kpty.cpp

00001 /*
00002 
00003    This file is part of the KDE libraries
00004    Copyright (C) 1997-2002 The Konsole Developers
00005    Copyright (C) 2002 Waldo Bastian <bastian@kde.org>
00006    Copyright (C) 2002-2003 Oswald Buddenhagen <ossi@kde.org>
00007 
00008    This library is free software; you can redistribute it and/or
00009    modify it under the terms of the GNU Library General Public
00010    License as published by the Free Software Foundation; either
00011    version 2 of the License, or (at your option) any later version.
00012 
00013    This library is distributed in the hope that it will be useful,
00014    but WITHOUT ANY WARRANTY; without even the implied warranty of
00015    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00016    Library General Public License for more details.
00017 
00018    You should have received a copy of the GNU Library General Public License
00019    along with this library; see the file COPYING.LIB.  If not, write to
00020    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
00021    Boston, MA 02110-1301, USA.
00022 */
00023 
00024 #include <config.h>
00025 
00026 #include "kpty.h"
00027 #include "kprocess.h"
00028 
00029 #ifdef __sgi
00030 #define __svr4__
00031 #endif
00032 
00033 #ifdef __osf__
00034 #define _OSF_SOURCE
00035 #include <float.h>
00036 #endif
00037 
00038 #ifdef _AIX
00039 #define _ALL_SOURCE
00040 #endif
00041 
00042 // __USE_XOPEN isn't defined by default in ICC
00043 // (needed for ptsname(), grantpt() and unlockpt())
00044 #ifdef __INTEL_COMPILER
00045 #  ifndef __USE_XOPEN
00046 #    define __USE_XOPEN
00047 #  endif
00048 #endif
00049 
00050 #include <sys/types.h>
00051 #include <sys/ioctl.h>
00052 #include <sys/time.h>
00053 #include <sys/resource.h>
00054 #include <sys/stat.h>
00055 #include <sys/param.h>
00056 
00057 #ifdef HAVE_SYS_STROPTS_H
00058 # include <sys/stropts.h>   // Defines I_PUSH
00059 # define _NEW_TTY_CTRL
00060 #endif
00061 
00062 #include <errno.h>
00063 #include <fcntl.h>
00064 #include <time.h>
00065 #include <stdlib.h>
00066 #include <stdio.h>
00067 #include <string.h>
00068 #include <unistd.h>
00069 #include <grp.h>
00070 
00071 #ifdef HAVE_LIBUTIL_H
00072 # include <libutil.h>
00073 # define USE_LOGIN
00074 #elif defined(HAVE_UTIL_H)
00075 # include <util.h>
00076 # define USE_LOGIN
00077 #endif
00078 
00079 #ifdef USE_LOGIN
00080 # include <utmp.h>
00081 #endif
00082 
00083 #ifdef HAVE_TERMIOS_H
00084 /* for HP-UX (some versions) the extern C is needed, and for other
00085    platforms it doesn't hurt */
00086 extern "C" {
00087 # include <termios.h>
00088 }
00089 #endif
00090 
00091 #if !defined(__osf__)
00092 # ifdef HAVE_TERMIO_H
00093 /* needed at least on AIX */
00094 #  include <termio.h>
00095 # endif
00096 #endif
00097 
00098 #if defined(HAVE_TCGETATTR)
00099 # define _tcgetattr(fd, ttmode) tcgetattr(fd, ttmode)
00100 #elif defined(TIOCGETA)
00101 # define _tcgetattr(fd, ttmode) ioctl(fd, TIOCGETA, (char *)ttmode)
00102 #elif defined(TCGETS)
00103 # define _tcgetattr(fd, ttmode) ioctl(fd, TCGETS, (char *)ttmode)
00104 #else
00105 # error
00106 #endif
00107 
00108 #if defined(HAVE_TCSETATTR) && defined(TCSANOW)
00109 # define _tcsetattr(fd, ttmode) tcsetattr(fd, TCSANOW, ttmode)
00110 #elif defined(TIOCSETA)
00111 # define _tcsetattr(fd, ttmode) ioctl(fd, TIOCSETA, (char *)ttmode)
00112 #elif defined(TCSETS)
00113 # define _tcsetattr(fd, ttmode) ioctl(fd, TCSETS, (char *)ttmode)
00114 #else
00115 # error
00116 #endif
00117 
00118 #if defined (_HPUX_SOURCE)
00119 # define _TERMIOS_INCLUDED
00120 # include <bsdtty.h>
00121 #endif
00122 
00123 #if defined(HAVE_PTY_H)
00124 # include <pty.h>
00125 #endif
00126 
00127 #include <kdebug.h>
00128 #include <kstandarddirs.h>  // locate
00129 
00130 // not defined on HP-UX for example
00131 #ifndef CTRL
00132 # define CTRL(x) ((x) & 037)
00133 #endif
00134 
00135 #define TTY_GROUP "tty"
00136 
00138 // private functions //
00140 
00141 #ifdef HAVE_UTEMPTER
00142 class KProcess_Utmp : public KProcess
00143 {
00144 public:
00145    int commSetupDoneC()
00146    {
00147      dup2(cmdFd, 0);
00148      dup2(cmdFd, 1);
00149      dup2(cmdFd, 3);
00150      return 1;
00151    }
00152    int cmdFd;
00153 };
00154 #endif
00155 
00156 #define BASE_CHOWN "kgrantpty"
00157 
00158 
00159 
00161 // private data //
00163 
00164 struct KPtyPrivate {
00165    KPtyPrivate() :
00166      xonXoff(false),
00167      utf8(false),
00168      logged(false),
00169      masterFd(-1), slaveFd(-1)
00170    {
00171      memset(&winSize, 0, sizeof(winSize));
00172      winSize.ws_row = 24;
00173      winSize.ws_col = 80;
00174    }
00175 
00176    bool xonXoff : 1;
00177    bool utf8    : 1;
00178    bool logged  : 1;
00179    int masterFd;
00180    int slaveFd;
00181    struct winsize winSize;
00182 
00183    QCString ttyName;
00184 };
00185 
00187 // public member functions //
00189 
00190 KPty::KPty()
00191 {
00192   d = new KPtyPrivate;
00193 }
00194 
00195 KPty::~KPty()
00196 {
00197   close();
00198   delete d;
00199 }
00200 
00201 bool KPty::open()
00202 {
00203   if (d->masterFd >= 0)
00204     return true;
00205 
00206   QCString ptyName;
00207 
00208   // Find a master pty that we can open ////////////////////////////////
00209 
00210   // Because not all the pty animals are created equal, they want to
00211   // be opened by several different methods.
00212 
00213   // We try, as we know them, one by one.
00214 
00215 #if defined(HAVE_PTSNAME) && defined(HAVE_GRANTPT)
00216 #ifdef _AIX
00217   d->masterFd = ::open("/dev/ptc",O_RDWR);
00218 #else
00219   d->masterFd = ::open("/dev/ptmx",O_RDWR);
00220 #endif
00221   if (d->masterFd >= 0)
00222   {
00223     char *ptsn = ptsname(d->masterFd);
00224     if (ptsn) {
00225         grantpt(d->masterFd);
00226         d->ttyName = ptsn;
00227         goto gotpty;
00228     } else {
00229        ::close(d->masterFd);
00230        d->masterFd = -1;
00231     }
00232   }
00233 #endif
00234 
00235   // Linux device names, FIXME: Trouble on other systems?
00236   for (const char* s3 = "pqrstuvwxyzabcdefghijklmno"; *s3; s3++)
00237   {
00238     for (const char* s4 = "0123456789abcdefghijklmnopqrstuvwxyz"; *s4; s4++)
00239     {
00240       ptyName.sprintf("/dev/pty%c%c", *s3, *s4);
00241       d->ttyName.sprintf("/dev/tty%c%c", *s3, *s4);
00242 
00243       d->masterFd = ::open(ptyName.data(), O_RDWR);
00244       if (d->masterFd >= 0)
00245       {
00246 #ifdef __sun
00247         /* Need to check the process group of the pty.
00248          * If it exists, then the slave pty is in use,
00249          * and we need to get another one.
00250          */
00251         int pgrp_rtn;
00252         if (ioctl(d->masterFd, TIOCGPGRP, &pgrp_rtn) == 0 || errno != EIO) {
00253           ::close(d->masterFd);
00254           d->masterFd = -1;
00255           continue;
00256         }
00257 #endif /* sun */
00258         if (!access(d->ttyName.data(),R_OK|W_OK)) // checks availability based on permission bits
00259         {
00260           if (!geteuid())
00261           {
00262             struct group* p = getgrnam(TTY_GROUP);
00263             if (!p)
00264               p = getgrnam("wheel");
00265             gid_t gid = p ? p->gr_gid : getgid ();
00266 
00267             chown(d->ttyName.data(), getuid(), gid);
00268             chmod(d->ttyName.data(), S_IRUSR|S_IWUSR|S_IWGRP);
00269           }
00270           goto gotpty;
00271         }
00272         ::close(d->masterFd);
00273         d->masterFd = -1;
00274       }
00275     }
00276   }
00277 
00278   kdWarning(175) << "Can't open a pseudo teletype" << endl;
00279   return false;
00280 
00281  gotpty:
00282   struct stat st;
00283   if (stat(d->ttyName.data(), &st))
00284     return false; // this just cannot happen ... *cough*  Yeah right, I just
00285                   // had it happen when pty #349 was allocated.  I guess
00286                   // there was some sort of leak?  I only had a few open.
00287   if (((st.st_uid != getuid()) ||
00288        (st.st_mode & (S_IRGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH))) &&
00289       !chownpty(true))
00290   {
00291     kdWarning(175)
00292       << "chownpty failed for device " << ptyName << "::" << d->ttyName
00293       << "\nThis means the communication can be eavesdropped." << endl;
00294   }
00295 
00296 #ifdef BSD
00297   revoke(d->ttyName.data());
00298 #endif
00299 
00300 #ifdef HAVE_UNLOCKPT
00301   unlockpt(d->masterFd);
00302 #endif
00303 
00304   d->slaveFd = ::open(d->ttyName.data(), O_RDWR | O_NOCTTY);
00305   if (d->slaveFd < 0)
00306   {
00307     kdWarning(175) << "Can't open slave pseudo teletype" << endl;
00308     ::close(d->masterFd);
00309     d->masterFd = -1;
00310     return false;
00311   }
00312 
00313 #if (defined(__svr4__) || defined(__sgi__))
00314   // Solaris
00315   ioctl(d->slaveFd, I_PUSH, "ptem");
00316   ioctl(d->slaveFd, I_PUSH, "ldterm");
00317 #endif
00318 
00319     // set xon/xoff & control keystrokes
00320   // without the '::' some version of HP-UX thinks, this declares
00321   // the struct in this class, in this method, and fails to find
00322   // the correct tc[gs]etattr
00323   struct ::termios ttmode;
00324 
00325   _tcgetattr(d->slaveFd, &ttmode);
00326 
00327   if (!d->xonXoff)
00328     ttmode.c_iflag &= ~(IXOFF | IXON);
00329   else
00330     ttmode.c_iflag |= (IXOFF | IXON);
00331 
00332 #ifdef IUTF8
00333   if (!d->utf8)
00334     ttmode.c_iflag &= ~IUTF8;
00335   else
00336     ttmode.c_iflag |= IUTF8;
00337 #endif
00338 
00339   ttmode.c_cc[VINTR] = CTRL('C' - '@');
00340   ttmode.c_cc[VQUIT] = CTRL('\\' - '@');
00341   ttmode.c_cc[VERASE] = 0177;
00342 
00343   _tcsetattr(d->slaveFd, &ttmode);
00344 
00345   // set screen size
00346   ioctl(d->slaveFd, TIOCSWINSZ, (char *)&d->winSize);
00347 
00348   fcntl(d->masterFd, F_SETFD, FD_CLOEXEC);
00349   fcntl(d->slaveFd, F_SETFD, FD_CLOEXEC);
00350 
00351   return true;
00352 }
00353 
00354 void KPty::close()
00355 {
00356    if (d->masterFd < 0)
00357       return;
00358    logout();
00359    // don't bother resetting unix98 pty, it will go away after closing master anyway.
00360    if (memcmp(d->ttyName.data(), "/dev/pts/", 9)) {
00361       if (!geteuid()) {
00362          struct stat st;
00363          if (!stat(d->ttyName.data(), &st)) {
00364             chown(d->ttyName.data(), 0, st.st_gid == getgid() ? 0 : -1);
00365             chmod(d->ttyName.data(), S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
00366      }
00367       } else {
00368          fcntl(d->masterFd, F_SETFD, 0);
00369          chownpty(false);
00370       }
00371    }
00372    ::close(d->slaveFd);
00373    ::close(d->masterFd);
00374    d->masterFd = d->slaveFd = -1;
00375 }
00376 
00377 void KPty::setCTty()
00378 {
00379     // Setup job control //////////////////////////////////
00380 
00381     // Become session leader, process group leader,
00382     // and get rid of the old controlling terminal.
00383     setsid();
00384 
00385     // make our slave pty the new controlling terminal.
00386 #ifdef TIOCSCTTY
00387     ioctl(d->slaveFd, TIOCSCTTY, 0);
00388 #else
00389     // SVR4 hack: the first tty opened after setsid() becomes controlling tty
00390     ::close(::open(d->ttyName, O_WRONLY, 0));
00391 #endif
00392 
00393     // make our new process group the foreground group on the pty
00394     int pgrp = getpid();
00395 #if defined(_POSIX_VERSION) || defined(__svr4__)
00396     tcsetpgrp (d->slaveFd, pgrp);
00397 #elif defined(TIOCSPGRP)
00398     ioctl(d->slaveFd, TIOCSPGRP, (char *)&pgrp);
00399 #endif
00400 }
00401 
00402 void KPty::login(const char *user, const char *remotehost)
00403 {
00404     if (d->logged)
00405         return; // print a warning?
00406     d->logged = true;
00407 #ifdef HAVE_UTEMPTER
00408     KProcess_Utmp utmp;
00409     utmp.cmdFd = d->masterFd;
00410     utmp << "/usr/sbin/utempter" << "-a" << d->ttyName << "";
00411     utmp.start(KProcess::Block);
00412     Q_UNUSED(user);
00413     Q_UNUSED(remotehost);
00414 #elif defined(USE_LOGIN)
00415     const char *str_ptr;
00416     struct utmp l_struct;
00417     memset(&l_struct, 0, sizeof(struct utmp));
00418     // note: strncpy without terminators _is_ correct here. man 4 utmp
00419 
00420     if (user)
00421       strncpy(l_struct.ut_name, user, UT_NAMESIZE);
00422 
00423     if (remotehost)
00424       strncpy(l_struct.ut_host, remotehost, UT_HOSTSIZE);
00425 
00426 # ifndef __GLIBC__
00427     str_ptr = d->ttyName.data();
00428     if (!memcmp(str_ptr, "/dev/", 5))
00429         str_ptr += 5;
00430     strncpy(l_struct.ut_line, str_ptr, UT_LINESIZE);
00431 # endif
00432 
00433     // Handle 64-bit time_t properly, where it may be larger
00434     // than the integral type of ut_time.
00435     {
00436         time_t ut_time_temp;
00437         time(&ut_time_temp);
00438         l_struct.ut_time=ut_time_temp;
00439     }
00440 
00441     ::login(&l_struct);
00442 #else
00443     Q_UNUSED(user);
00444     Q_UNUSED(remotehost);
00445 #endif
00446 }
00447 
00448 void KPty::logout()
00449 {
00450     if (!d->logged)
00451         return;
00452     d->logged = false;
00453 #ifdef HAVE_UTEMPTER
00454     KProcess_Utmp utmp;
00455     utmp.cmdFd = d->masterFd;
00456     utmp << "/usr/sbin/utempter" << "-d" << d->ttyName;
00457     utmp.start(KProcess::Block);
00458 #elif defined(USE_LOGIN)
00459     const char *str_ptr = d->ttyName.data();
00460     if (!memcmp(str_ptr, "/dev/", 5))
00461         str_ptr += 5;
00462 # ifdef __GLIBC__
00463     else {
00464         const char *sl_ptr = strrchr(str_ptr, '/');
00465         if (sl_ptr)
00466             str_ptr = sl_ptr + 1;
00467     }
00468 # endif
00469     ::logout(str_ptr);
00470 #endif
00471 }
00472 
00473 void KPty::setWinSize(int lines, int columns)
00474 {
00475   d->winSize.ws_row = (unsigned short)lines;
00476   d->winSize.ws_col = (unsigned short)columns;
00477   if (d->masterFd >= 0)
00478     ioctl( d->masterFd, TIOCSWINSZ, (char *)&d->winSize );
00479 }
00480 
00481 void KPty::setXonXoff(bool useXonXoff)
00482 {
00483   d->xonXoff = useXonXoff;
00484   if (d->masterFd >= 0) {
00485     // without the '::' some version of HP-UX thinks, this declares
00486     // the struct in this class, in this method, and fails to find
00487     // the correct tc[gs]etattr
00488     struct ::termios ttmode;
00489 
00490     _tcgetattr(d->masterFd, &ttmode);
00491 
00492     if (!useXonXoff)
00493       ttmode.c_iflag &= ~(IXOFF | IXON);
00494     else
00495       ttmode.c_iflag |= (IXOFF | IXON);
00496 
00497     _tcsetattr(d->masterFd, &ttmode);
00498   }
00499 }
00500 
00501 void KPty::setUtf8Mode(bool useUtf8)
00502 {
00503   d->utf8 = useUtf8;
00504 #ifdef IUTF8
00505   if (d->masterFd >= 0) {
00506     // without the '::' some version of HP-UX thinks, this declares
00507     // the struct in this class, in this method, and fails to find
00508     // the correct tc[gs]etattr
00509     struct ::termios ttmode;
00510 
00511     _tcgetattr(d->masterFd, &ttmode);
00512 
00513     if (!useUtf8)
00514       ttmode.c_iflag &= ~IUTF8;
00515     else
00516       ttmode.c_iflag |= IUTF8;
00517 
00518     _tcsetattr(d->masterFd, &ttmode);
00519   }
00520 #endif
00521 }
00522 
00523 const char *KPty::ttyName() const
00524 {
00525     return d->ttyName.data();
00526 }
00527 
00528 int KPty::masterFd() const
00529 {
00530     return d->masterFd;
00531 }
00532 
00533 int KPty::slaveFd() const
00534 {
00535     return d->slaveFd;
00536 }
00537 
00538 // private
00539 bool KPty::chownpty(bool grant)
00540 {
00541   KProcess proc;
00542   proc << locate("exe", BASE_CHOWN) << (grant?"--grant":"--revoke") << QString::number(d->masterFd);
00543   return proc.start(KProcess::Block) && proc.normalExit() && !proc.exitStatus();
00544 }
00545 
KDE Home | KDE Accessibility Home | Description of Access Keys