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