source: src-qt4/PCDM/src/pcdm-xprocess.cpp @ 72c9698

9.2-releasereleng/10.0releng/10.0.1releng/10.0.2releng/10.0.3
Last change on this file since 72c9698 was 72c9698, checked in by Ken Moore <ken@…>, 11 months ago

Fix up PCDM compilation on 10.x

  • Property mode set to 100644
File size: 9.4 KB
Line 
1/* PCDM Login Manager:
2*  Written by Ken Moore (ken@pcbsd.org) 2012/2013
3*  Modified by Kris Moore (kris@pcbsd.org) 2013
4*  Copyright(c) 2013 by the PC-BSD Project
5*  Available under the 3-clause BSD license
6*/
7
8#include <sys/types.h>
9#include <sys/wait.h>
10#include <unistd.h>
11#include <pwd.h>
12#include <login_cap.h>
13#include <QMessageBox>
14
15/*
16Sub-classed QProcess for starting an XSession Process
17*/
18
19#include "pcdm-xprocess.h"
20
21XProcess::XProcess() : QProcess(0) {
22  //initialize the variables
23  xuser.clear();
24  xcmd.clear();
25  xhome.clear();
26  xpwd.clear();
27  xshell.clear();
28  pam_started = FALSE;
29  pam_session_open = FALSE;
30  //Setup the finished signal/slot
31  connect( this, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(slotCleanup()) );
32}
33
34XProcess::~XProcess(){
35  if( isRunning() ){
36    this->terminate();
37  }
38  this->close();
39}
40
41void XProcess::loginToXSession(QString username, QString password, QString desktop){
42  //Setup the variables
43  xuser = username;
44  xpwd = password;
45  xhome = Backend::getUserHomeDir(xuser);
46  xcmd = Backend::getDesktopBinary(desktop);
47  xshell = Backend::getUserShell(xuser);
48  xde = desktop;
49  //Now start the login process
50  startXSession();
51}
52
53bool XProcess::isRunning(){
54  if(this->state() != QProcess::NotRunning){ return TRUE; }
55  else{ return FALSE; }
56}
57
58void XProcess::waitForSessionClosed(){
59  // CAUTION!!
60  // This function will pause the calling program to wait for the session to end!
61  if( isRunning() ){ this->waitForFinished(-1); }
62
63}
64
65/*
66 ========== SESSION STARTUP ==========
67*/
68
69bool XProcess::startXSession(){
70  //Check that the necessary info to start the session is available
71  if( xuser.isEmpty() || xcmd.isEmpty() || xhome.isEmpty() || xde.isEmpty() ){
72    emit InvalidLogin();  //Make sure the GUI knows that it was a failure
73    return FALSE;
74  }
75  //Backend::log("Starting up Desktop environment ("+xcmd+") as user ("+xuser+")");
76 
77  //Check for PAM username/password validity
78  if( !pam_checkPW() ){ emit InvalidLogin(); pam_shutdown(); return FALSE; }
79
80
81  //Save the current user/desktop as the last login
82  Backend::saveLoginInfo(Backend::getDisplayNameFromUsername(xuser),xde);
83
84  // Get the users uid/gid information
85  struct passwd *pw;
86  int uid;
87  char *ok;
88
89  if (!(pw = getpwnam(xuser.toLatin1()))) {
90      uid = strtol(xuser.toLatin1(), &ok, 10);
91      if (!(pw = getpwuid(uid))) {
92          emit InvalidLogin();  //Make sure the GUI knows that it was a failure
93          return FALSE;
94      }
95  }
96
97  // Get the environment before we drop priv
98  this->setProcessEnvironment( QProcessEnvironment::systemEnvironment() ); //current environment
99  //Now allow this user access to the Xserver
100  QString xhostcmd = "xhost si:localuser:"+xuser;
101  system(xhostcmd.toUtf8());
102 
103  //QWidget *wid = new QWidget();
104  if (setgid(pw->pw_gid) < 0) {
105      qDebug() << "setgid() failed!";
106      emit InvalidLogin();  //Make sure the GUI knows that it was a failure
107      return FALSE;
108  }
109
110  // Setup our other groups
111  if (initgroups(xuser.toLatin1(), pw->pw_gid) < 0) {
112      qDebug() << "initgroups() failed!";
113      emit InvalidLogin();  //Make sure the GUI knows that it was a failure
114      setgid(0);
115      return FALSE;
116  }
117
118  // Lets drop to user privs
119  if (setuid(pw->pw_uid) < 0) {
120      qDebug() << "setuid() failed!";
121      emit InvalidLogin();  //Make sure the GUI knows that it was a failure
122      return FALSE;
123  }
124
125  //Startup the PAM session
126  if( !pam_startSession() ){ pam_shutdown(); return FALSE; }
127  pam_session_open = TRUE; //flag that pam has an open session
128 
129  QString cmd;
130  // Configure the DE startup command
131
132  //  - Add the DE startup command to the end
133  cmd.append("dbus-launch --exit-with-session "+xcmd);
134  //cmd.append(xcmd);
135  //cmd.append("; kill -l KILL"); //to clean up the session afterwards
136 
137  //Backend::log("Startup command: "+cmd);
138  // Setup the process environment
139  setupSessionEnvironment();
140 
141  //Log the DE startup outputs as well
142  this->setStandardOutputFile(xhome+"/.pcdm-startup.log",QIODevice::Truncate);
143  this->setStandardErrorFile(xhome+"/.pcdm-startup.err",QIODevice::Truncate);
144  // Startup the process(s)
145   //  - Setup to run the user's <home-dir>/.xprofile startup script
146  if(QFile::exists(xhome+"/.xprofile")){
147    disconnect(SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(slotCleanup(int, QProcess::ExitStatus)) );
148    this->start("sh "+xhome+"/.xprofile &");//make sure to start it in parallel
149    if(!this->waitForFinished(30000) ){
150      //If it still has not finished this after 30 seconds, kill it
151      this->terminate();
152    }
153    connect( this, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(slotCleanup(int, QProcess::ExitStatus)) );
154  }
155  this->start(cmd);
156  return TRUE;
157}
158
159void XProcess::slotCleanup(){
160  pam_shutdown(); //make sure that PAM shuts down properly
161  //Now remove this user's access to the Xserver
162  QString xhostcmd = "xhost -si:localuser:"+xuser;
163  system(xhostcmd.toUtf8());
164}
165
166void XProcess::setupSessionEnvironment(){
167  // Setup any specialized environment variables
168  QProcessEnvironment environ = this->processEnvironment();
169  // Get the current locale code
170  QLocale mylocale;
171  QString langCode = mylocale.name();
172  if( langCode.toLower() == "c" ){ langCode = "en_US"; } // default to the US english (PCDM code default), LANG=C causes problems
173  if(!environ.value("MM_CHARSET").isEmpty() ){ langCode.append( "."+environ.value("MM_CHARSET") ); }
174  else{ langCode.append(".UTF-8"); }
175  // USER, HOME, and SHELL are set by the "su" login
176  environ.insert("LOGNAME",xuser); //Login name
177  environ.insert("USERNAME",xuser); // Username
178  environ.insert("USER",xuser); // Username
179  environ.insert("PATH",environ.value("PATH")+":"+xhome+"/bin"); // Append the user's home dir to the path
180  environ.insert("LANG",langCode); //Set the proper localized language
181  environ.insert("MAIL","/var/mail/"+xuser); //Set the mail variable
182  environ.insert("GROUP",xuser); //Set the proper group id
183  environ.insert("SHLVL","0"); //Set the proper shell level
184  environ.insert("HOME",xhome); //Set the users home directory
185  environ.insert("SHELL",xshell); //Set the user's default shell
186  this->setProcessEnvironment(environ);
187  this->setWorkingDirectory(xhome); //set the current directory to the user's home directory
188}
189
190//Stand-alone function to check a username/password combination for validity
191void XProcess::checkPW(QString user, QString pwd){
192  xuser = Backend::getUsernameFromDisplayname(user); 
193  xpwd = pwd;
194  bool ok = pam_checkPW();
195  pam_shutdown();
196  xuser.clear();
197  xpwd.clear();
198  if(ok){ emit ValidLogin(); }
199  else{ emit InvalidLogin(); }
200}
201
202/*
203 ========== PAM FUNCTIONS ==========
204*/
205static struct pam_conv pamc = { openpam_nullconv, NULL };
206
207bool XProcess::pam_checkPW(){
208 //Requires internal "xuser" and "xpwd" variables to be set
209       
210//Convert the inputs to C character arrays for use in PAM
211  QByteArray tmp = xuser.toUtf8();
212  char* cUser = tmp.data();
213  QByteArray tmp2 = xpwd.toUtf8();
214  char* cPassword = tmp2.data();
215  //initialize variables
216  bool result = FALSE;
217  int ret;
218  //Initialize PAM
219  ret = pam_start("login", cUser, &pamc, &pamh);
220  if( ret == PAM_SUCCESS ){
221    pam_started = TRUE; //flag that pam is started
222    //Place the user-supplied password into the structure
223    ret = pam_set_item(pamh, PAM_AUTHTOK, cPassword);
224    //Set the TTY
225    //ret = pam_set_item(pamh, PAM_TTY, "pcdm-terminal");
226    //Authenticate with PAM
227    ret = pam_authenticate(pamh,0);
228    if( ret == PAM_SUCCESS ){
229      //Check for valid, unexpired account and verify access restrictions
230      ret = pam_acct_mgmt(pamh,0);
231      if( ret == PAM_SUCCESS ){ result = TRUE; }
232   
233    }else{
234      pam_logFailure(ret);
235    }
236  }
237  //return verification result
238  return result;       
239}
240
241bool XProcess::pam_startSession(){
242  //This should only be run if pam_checkPW was successful
243  int ret = pam_open_session(pamh,0);
244  bool ok = FALSE;
245  if(ret == PAM_SUCCESS){ ok = TRUE; }
246  else{ pam_logFailure(ret); }
247 
248  return ok;
249}
250
251bool XProcess::pam_stopSession(){
252  //This should only be run if pam_startSession was successful
253  int ret = pam_close_session(pamh,0);
254  bool ok = FALSE;
255  if(ret == PAM_SUCCESS){ ok = TRUE; }
256  else{ pam_logFailure(ret); }
257 
258  return ok;
259}
260
261void XProcess::pam_logFailure(int ret){
262  //Interpret a PAM error message and log it
263  Backend::log("PAM Error: " + QString::number(ret));
264  switch( ret ){
265  case PAM_ABORT:
266    Backend::log(" - PAM abort error");
267    break;
268  case PAM_AUTHINFO_UNAVAIL:
269    Backend::log(" - Authentication info unavailable");
270    break;
271  case PAM_AUTH_ERR:
272    Backend::log(" - Authentication error");
273    break;
274  case PAM_BUF_ERR:
275    Backend::log(" - Buffer error");
276    break;
277  case PAM_CONV_ERR:
278    Backend::log(" - Conversion error");
279    break;
280  case PAM_CRED_INSUFFICIENT:
281    Backend::log(" - Credentials insufficient");
282    break;
283  case PAM_MAXTRIES:
284    Backend::log(" - Maximum number of tries exceeded");
285    break;
286  case PAM_PERM_DENIED:
287    Backend::log(" - Permission denied");
288    break;
289  case PAM_SERVICE_ERR:
290    Backend::log(" - Service error");
291    break;
292  case PAM_SYMBOL_ERR:
293    Backend::log(" - Symbol error");
294    break;
295  case PAM_SYSTEM_ERR:
296    Backend::log(" - System error");
297    break;
298  case PAM_USER_UNKNOWN:
299    Backend::log(" - Unknown user");
300    break;
301  default:
302    Backend::log(" - Unrecognized authentication error");
303  }
304       
305}
306
307void XProcess::pam_shutdown(){
308  if(pam_session_open){
309    pam_stopSession();
310    pam_session_open = FALSE;
311  }
312  if(pam_started){
313    pam_end(pamh,0);
314    pam_started = FALSE;
315  }
316}
Note: See TracBrowser for help on using the repository browser.