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