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 (__FreeBSD__) || defined (__NetBSD__) || defined (__OpenBSD__) || defined (__bsdi__) || defined(__APPLE__) || defined (__DragonFly__)
00099 # define _tcgetattr(fd, ttmode) ioctl(fd, TIOCGETA, (char *)ttmode)
00100 #else
00101 # if defined(_HPUX_SOURCE) || defined(__Lynx__) || defined (__CYGWIN__)
00102 #  define _tcgetattr(fd, ttmode) tcgetattr(fd, ttmode)
00103 # else
00104 #  define _tcgetattr(fd, ttmode) ioctl(fd, TCGETS, (char *)ttmode)
00105 # endif
00106 #endif
00107 
00108 #if defined (__FreeBSD__) || defined (__NetBSD__) || defined (__OpenBSD__) || defined (__bsdi__) || defined(__APPLE__) || defined (__DragonFly__)
00109 # define _tcsetattr(fd, ttmode) ioctl(fd, TIOCSETA, (char *)ttmode)
00110 #else
00111 # if defined(_HPUX_SOURCE) || defined(__CYGWIN__)
00112 #  define _tcsetattr(fd, ttmode) tcsetattr(fd, TCSANOW, ttmode) 
00113 # else
00114 #  define _tcsetattr(fd, ttmode) ioctl(fd, TCSETS, (char *)ttmode)
00115 # endif
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      masterFd(-1), slaveFd(-1)
00169    {
00170      memset(&winSize, 0, sizeof(winSize));
00171      winSize.ws_row = 24;
00172      winSize.ws_col = 80;
00173    }
00174 
00175    bool xonXoff : 1;
00176    bool utf8    : 1;
00177    int masterFd;
00178    int slaveFd;
00179    struct winsize winSize;
00180 
00181    QCString ttyName;
00182 };
00183 
00185 // public member functions //
00187 
00188 KPty::KPty()
00189 {
00190   d = new KPtyPrivate;
00191 }
00192 
00193 KPty::~KPty()
00194 {
00195   close();
00196   delete d;
00197 }
00198 
00199 bool KPty::open()
00200 {
00201   if (d->masterFd >= 0)
00202     return true;
00203 
00204   QCString ptyName;
00205 
00206   // Find a master pty that we can open ////////////////////////////////
00207 
00208   // Because not all the pty animals are created equal, they want to
00209   // be opened by several different methods.
00210 
00211   // We try, as we know them, one by one.
00212 
00213 #if defined(HAVE_PTSNAME) && defined(HAVE_GRANTPT)
00214 #ifdef _AIX
00215   d->masterFd = ::open("/dev/ptc",O_RDWR);
00216 #else
00217   d->masterFd = ::open("/dev/ptmx",O_RDWR);
00218 #endif
00219   if (d->masterFd >= 0)
00220   {
00221     char *ptsn = ptsname(d->masterFd);
00222     if (ptsn) {
00223         grantpt(d->masterFd);
00224         d->ttyName = ptsn;
00225         goto gotpty;
00226     } else {
00227        ::close(d->masterFd);
00228        d->masterFd = -1;
00229     }
00230   }
00231 #endif
00232 
00233   // Linux device names, FIXME: Trouble on other systems?
00234   for (const char* s3 = "pqrstuvwxyzabcdefghijklmno"; *s3; s3++)
00235   {
00236     for (const char* s4 = "0123456789abcdefghijklmnopqrstuvwxyz"; *s4; s4++)
00237     {
00238       ptyName.sprintf("/dev/pty%c%c", *s3, *s4);
00239       d->ttyName.sprintf("/dev/tty%c%c", *s3, *s4);
00240 
00241       d->masterFd = ::open(ptyName.data(), O_RDWR);
00242       if (d->masterFd >= 0)
00243       {
00244 #ifdef __sun
00245         /* Need to check the process group of the pty.
00246          * If it exists, then the slave pty is in use,
00247          * and we need to get another one.
00248          */
00249         int pgrp_rtn;
00250         if (ioctl(d->masterFd, TIOCGPGRP, &pgrp_rtn) == 0 || errno != EIO) {
00251           ::close(d->masterFd);
00252           d->masterFd = -1;
00253           continue;
00254         }
00255 #endif /* sun */
00256         if (!access(d->ttyName.data(),R_OK|W_OK)) // checks availability based on permission bits
00257         {
00258           if (!geteuid())
00259           {
00260             struct group* p = getgrnam(TTY_GROUP);
00261             if (!p)
00262               p = getgrnam("wheel");
00263             gid_t gid = p ? p->gr_gid : getgid ();
00264 
00265             chown(d->ttyName.data(), getuid(), gid);
00266             chmod(d->ttyName.data(), S_IRUSR|S_IWUSR|S_IWGRP);
00267           }
00268           goto gotpty;
00269         }
00270         ::close(d->masterFd);
00271         d->masterFd = -1;
00272       }
00273     }
00274   }
00275 
00276   kdWarning(175) << "Can't open a pseudo teletype" << endl;
00277   return false;
00278 
00279  gotpty:
00280   struct stat st;
00281   if (stat(d->ttyName.data(), &st))
00282     return false; // this just cannot happen ... *cough*  Yeah right, I just
00283                   // had it happen when pty #349 was allocated.  I guess
00284                   // there was some sort of leak?  I only had a few open.
00285   if (((st.st_uid != getuid()) ||
00286        (st.st_mode & (S_IRGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH))) &&
00287       !chownpty(true))
00288   {
00289     kdWarning(175)
00290       << "chownpty failed for device " << ptyName << "::" << d->ttyName
00291       << "\nThis means the communication can be eavesdropped." << endl;
00292   }
00293 
00294 #ifdef BSD
00295   revoke(d->ttyName.data());
00296 #endif
00297 
00298 #ifdef HAVE_UNLOCKPT
00299   unlockpt(d->masterFd);
00300 #endif
00301 
00302   d->slaveFd = ::open(d->ttyName.data(), O_RDWR | O_NOCTTY);
00303   if (d->slaveFd < 0)
00304   {
00305     kdWarning(175) << "Can't open slave pseudo teletype" << endl;
00306     ::close(d->masterFd);
00307     d->masterFd = -1;
00308     return false;
00309   }
00310 
00311 #if (defined(__svr4__) || defined(__sgi__))
00312   // Solaris
00313   ioctl(d->slaveFd, I_PUSH, "ptem");
00314   ioctl(d->slaveFd, I_PUSH, "ldterm");
00315 #endif
00316 
00317     // set xon/xoff & control keystrokes
00318   // without the '::' some version of HP-UX thinks, this declares
00319   // the struct in this class, in this method, and fails to find
00320   // the correct tc[gs]etattr
00321   struct ::termios ttmode;
00322 
00323   _tcgetattr(d->slaveFd, &ttmode);
00324 
00325   if (!d->xonXoff)
00326     ttmode.c_iflag &= ~(IXOFF | IXON);
00327   else
00328     ttmode.c_iflag |= (IXOFF | IXON);
00329 
00330 #ifdef IUTF8
00331   if (!d->utf8)
00332     ttmode.c_iflag &= ~IUTF8;
00333   else
00334     ttmode.c_iflag |= IUTF8;
00335 #endif
00336 
00337   ttmode.c_cc[VINTR] = CTRL('C' - '@');
00338   ttmode.c_cc[VQUIT] = CTRL('\\' - '@');
00339   ttmode.c_cc[VERASE] = 0177;
00340 
00341   _tcsetattr(d->slaveFd, &ttmode);
00342 
00343   // set screen size
00344   ioctl(d->slaveFd, TIOCSWINSZ, (char *)&d->winSize);
00345 
00346   fcntl(d->masterFd, F_SETFD, FD_CLOEXEC);
00347   fcntl(d->slaveFd, F_SETFD, FD_CLOEXEC);
00348 
00349   return true;
00350 }
00351 
00352 void KPty::close()
00353 {
00354    if (d->masterFd < 0)
00355       return;
00356    // don't bother resetting unix98 pty, it will go away after closing master anyway.
00357    if (memcmp(d->ttyName.data(), "/dev/pts/", 9)) {
00358       if (!geteuid()) {
00359          struct stat st;
00360          if (!stat(d->ttyName.data(), &st)) {
00361             chown(d->ttyName.data(), 0, st.st_gid == getgid() ? 0 : -1);
00362             chmod(d->ttyName.data(), S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
00363          }
00364       } else {
00365          fcntl(d->masterFd, F_SETFD, 0);
00366          chownpty(false);
00367       }
00368    }
00369    ::close(d->slaveFd);
00370    ::close(d->masterFd);
00371    d->masterFd = d->slaveFd = -1;
00372 }
00373 
00374 void KPty::setCTty()
00375 {
00376     // Setup job control //////////////////////////////////
00377 
00378     // Become session leader, process group leader,
00379     // and get rid of the old controlling terminal.
00380     setsid();
00381 
00382     // make our slave pty the new controlling terminal.
00383 #ifdef TIOCSCTTY
00384     ioctl(d->slaveFd, TIOCSCTTY, 0);
00385 #else
00386     // SVR4 hack: the first tty opened after setsid() becomes controlling tty
00387     ::close(::open(d->ttyName, O_WRONLY, 0));
00388 #endif
00389 
00390     // make our new process group the foreground group on the pty
00391     int pgrp = getpid();
00392 #if defined(_POSIX_VERSION) || defined(__svr4__)
00393     tcsetpgrp (d->slaveFd, pgrp);
00394 #elif defined(TIOCSPGRP)
00395     ioctl(d->slaveFd, TIOCSPGRP, (char *)&pgrp);
00396 #endif
00397 }
00398 
00399 void KPty::login(const char *user, const char *remotehost)
00400 {
00401 #ifdef HAVE_UTEMPTER
00402     KProcess_Utmp utmp;
00403     utmp.cmdFd = d->masterFd;
00404     utmp << "/usr/sbin/utempter" << "-a" << d->ttyName << "";
00405     utmp.start(KProcess::Block);
00406     Q_UNUSED(user);
00407     Q_UNUSED(remotehost);
00408 #elif defined(USE_LOGIN)
00409     const char *str_ptr;
00410     struct utmp l_struct;
00411     memset(&l_struct, 0, sizeof(struct utmp));
00412     // note: strncpy without terminators _is_ correct here. man 4 utmp
00413 
00414     if (user)
00415       strncpy(l_struct.ut_name, user, UT_NAMESIZE);
00416 
00417     if (remotehost)
00418       strncpy(l_struct.ut_host, remotehost, UT_HOSTSIZE);
00419 
00420 # ifndef __GLIBC__
00421     str_ptr = d->ttyName.data();
00422     if (!memcmp(str_ptr, "/dev/", 5))
00423         str_ptr += 5;
00424     strncpy(l_struct.ut_line, str_ptr, UT_LINESIZE);
00425 # endif
00426 
00427     // Handle 64-bit time_t properly, where it may be larger
00428     // than the integral type of ut_time.
00429     {
00430         time_t ut_time_temp;
00431         time(&ut_time_temp);
00432         l_struct.ut_time=ut_time_temp;
00433     }
00434 
00435     ::login(&l_struct);
00436 #else
00437     Q_UNUSED(user);
00438     Q_UNUSED(remotehost);
00439 #endif
00440 }
00441 
00442 void KPty::logout()
00443 {
00444 #ifdef HAVE_UTEMPTER
00445     KProcess_Utmp utmp;
00446     utmp.cmdFd = d->masterFd;
00447     utmp << "/usr/sbin/utempter" << "-d" << d->ttyName;
00448     utmp.start(KProcess::Block);
00449 #elif defined(USE_LOGIN)
00450     const char *str_ptr = d->ttyName.data();
00451     if (!memcmp(str_ptr, "/dev/", 5))
00452         str_ptr += 5;
00453 # ifdef __GLIBC__
00454     else {
00455         const char *sl_ptr = strrchr(str_ptr, '/');
00456         if (sl_ptr)
00457             str_ptr = sl_ptr + 1;
00458     }
00459 # endif
00460     ::logout(str_ptr);
00461 #endif
00462 }
00463 
00464 void KPty::setWinSize(int lines, int columns)
00465 {
00466   d->winSize.ws_row = (unsigned short)lines;
00467   d->winSize.ws_col = (unsigned short)columns;
00468   if (d->masterFd >= 0)
00469     ioctl( d->masterFd, TIOCSWINSZ, (char *)&d->winSize );
00470 }
00471 
00472 void KPty::setXonXoff(bool useXonXoff)
00473 {
00474   d->xonXoff = useXonXoff;
00475   if (d->masterFd >= 0) {
00476     // without the '::' some version of HP-UX thinks, this declares
00477     // the struct in this class, in this method, and fails to find
00478     // the correct tc[gs]etattr
00479     struct ::termios ttmode;
00480 
00481     _tcgetattr(d->masterFd, &ttmode);
00482 
00483     if (!useXonXoff)
00484       ttmode.c_iflag &= ~(IXOFF | IXON);
00485     else
00486       ttmode.c_iflag |= (IXOFF | IXON);
00487 
00488     _tcsetattr(d->masterFd, &ttmode);
00489   }
00490 }
00491 
00492 void KPty::setUtf8Mode(bool useUtf8)
00493 {
00494   d->utf8 = useUtf8;
00495 #ifdef IUTF8
00496   if (d->masterFd >= 0) {
00497     // without the '::' some version of HP-UX thinks, this declares
00498     // the struct in this class, in this method, and fails to find
00499     // the correct tc[gs]etattr
00500     struct ::termios ttmode;
00501 
00502     _tcgetattr(d->masterFd, &ttmode);
00503 
00504     if (!useUtf8)
00505       ttmode.c_iflag &= ~IUTF8;
00506     else
00507       ttmode.c_iflag |= IUTF8;
00508 
00509     _tcsetattr(d->masterFd, &ttmode);
00510   }
00511 #endif
00512 }
00513 
00514 const char *KPty::ttyName() const
00515 {
00516     return d->ttyName.data();
00517 }
00518 
00519 int KPty::masterFd() const
00520 {
00521     return d->masterFd;
00522 }
00523 
00524 int KPty::slaveFd() const
00525 {
00526     return d->slaveFd;
00527 }
00528 
00529 // private
00530 bool KPty::chownpty(bool grant)
00531 {
00532   KProcess proc;
00533   proc << locate("exe", BASE_CHOWN) << (grant?"--grant":"--revoke") << QString::number(d->masterFd);
00534   return proc.start(KProcess::Block) && proc.normalExit() && !proc.exitStatus();
00535 }
00536 
KDE Home | KDE Accessibility Home | Description of Access Keys