• Skip to content
  • Skip to link menu
Trinity API Reference
  • Trinity API Reference
  • tdecore
 

tdecore

  • tdecore
kpty.cpp
1 /*
2 
3  This file is part of the KDE libraries
4  Copyright (C) 1997-2002 The Konsole Developers
5  Copyright (C) 2002 Waldo Bastian <bastian@kde.org>
6  Copyright (C) 2002-2003 Oswald Buddenhagen <ossi@kde.org>
7 
8  This library is free software; you can redistribute it and/or
9  modify it under the terms of the GNU Library General Public
10  License as published by the Free Software Foundation; either
11  version 2 of the License, or (at your option) any later version.
12 
13  This library is distributed in the hope that it will be useful,
14  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  Library General Public License for more details.
17 
18  You should have received a copy of the GNU Library General Public License
19  along with this library; see the file COPYING.LIB. If not, write to
20  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21  Boston, MA 02110-1301, USA.
22 */
23 
24 #include <config.h>
25 
26 #include "kpty.h"
27 #include "kprocess.h"
28 
29 #ifdef _AIX
30 #define _ALL_SOURCE
31 #endif
32 
33 // __USE_XOPEN isn't defined by default in ICC
34 // (needed for ptsname(), grantpt() and unlockpt())
35 #ifdef __INTEL_COMPILER
36 # ifndef __USE_XOPEN
37 # define __USE_XOPEN
38 # endif
39 #endif
40 
41 #include <sys/types.h>
42 #include <sys/ioctl.h>
43 #include <sys/time.h>
44 #include <sys/resource.h>
45 #include <sys/stat.h>
46 #include <sys/param.h>
47 
48 #ifdef HAVE_SYS_STROPTS_H
49 # include <sys/stropts.h> // Defines I_PUSH
50 # define _NEW_TTY_CTRL
51 #endif
52 
53 #include <errno.h>
54 #include <fcntl.h>
55 #include <time.h>
56 #include <stdlib.h>
57 #include <stdio.h>
58 #include <string.h>
59 #include <unistd.h>
60 #include <grp.h>
61 
62 #if defined(HAVE_LIBUTIL_H)
63 # include <libutil.h>
64 # if (!defined(__FreeBSD__) || __FreeBSD_version < 900007)
65 # define USE_LOGIN
66 # endif
67 #endif
68 #if defined(HAVE_UTIL_H)
69 # include <util.h>
70 # define USE_LOGIN
71 #endif
72 
73 #ifdef USE_LOGIN
74 # include <utmp.h>
75 #endif
76 
77 #ifdef HAVE_TERMIOS_H
78 extern "C" {
79 # include <termios.h>
80 }
81 #endif
82 
83 #ifdef HAVE_TERMIO_H
84 /* needed at least on AIX */
85 # include <termio.h>
86 #endif
87 
88 #if defined(HAVE_TCGETATTR)
89 # define _tcgetattr(fd, ttmode) tcgetattr(fd, ttmode)
90 #elif defined(TIOCGETA)
91 # define _tcgetattr(fd, ttmode) ioctl(fd, TIOCGETA, (char *)ttmode)
92 #elif defined(TCGETS)
93 # define _tcgetattr(fd, ttmode) ioctl(fd, TCGETS, (char *)ttmode)
94 #else
95 # error
96 #endif
97 
98 #if defined(HAVE_TCSETATTR) && defined(TCSANOW)
99 # define _tcsetattr(fd, ttmode) tcsetattr(fd, TCSANOW, ttmode)
100 #elif defined(TIOCSETA)
101 # define _tcsetattr(fd, ttmode) ioctl(fd, TIOCSETA, (char *)ttmode)
102 #elif defined(TCSETS)
103 # define _tcsetattr(fd, ttmode) ioctl(fd, TCSETS, (char *)ttmode)
104 #else
105 # error
106 #endif
107 
108 #if defined(HAVE_PTY_H)
109 # include <pty.h>
110 #endif
111 
112 #include <kdebug.h>
113 #include <kstandarddirs.h> // locate
114 
115 #ifndef CINTR
116 #define CINTR 0x03
117 #endif
118 #ifndef CQUIT
119 #define CQUIT 0x1c
120 #endif
121 #ifndef CERASE
122 #define CERASE 0x7f
123 #endif
124 
125 #define TTY_GROUP "tty"
126 
128 // private functions //
130 
131 #ifdef HAVE_UTEMPTER
132 class TDEProcess_Utmp : public TDEProcess
133 {
134 public:
135  int commSetupDoneC()
136  {
137  dup2(cmdFd, 0);
138  dup2(cmdFd, 1);
139  dup2(cmdFd, 3);
140  return 1;
141  }
142  int cmdFd;
143 };
144 #endif
145 
146 #define BASE_CHOWN "kgrantpty"
147 
148 
149 
151 // private data //
153 
154 struct KPtyPrivate {
155  KPtyPrivate() :
156  xonXoff(false),
157  utf8(false),
158  masterFd(-1), slaveFd(-1)
159  {
160  memset(&winSize, 0, sizeof(winSize));
161  winSize.ws_row = 24;
162  winSize.ws_col = 80;
163  }
164 
165  bool xonXoff : 1;
166  bool utf8 : 1;
167  int masterFd;
168  int slaveFd;
169  struct winsize winSize;
170 
171  TQCString ttyName;
172 };
173 
175 // public member functions //
177 
178 KPty::KPty()
179 {
180  d = new KPtyPrivate;
181 }
182 
183 KPty::~KPty()
184 {
185  close();
186  delete d;
187 }
188 
189 bool KPty::setPty(int pty_master)
190 {
191  // a pty is already open
192  if(d->masterFd >= 0) {
193  kdWarning(175) << "KPty::setPty(): " << "d->masterFd >= 0" << endl;
194  return false;
195  }
196  d->masterFd = pty_master;
197  return _attachPty(pty_master);
198 }
199 
200 bool KPty::_attachPty(int pty_master)
201 {
202  if (d->slaveFd < 0 ) {
203 
204  kdDebug(175) << "KPty::_attachPty(): " << pty_master << endl;
205 #if defined(HAVE_PTSNAME)
206  char *ptsn = ptsname(d->masterFd);
207  if (ptsn) {
208  d->ttyName = ptsn;
209  } else {
210  ::close(d->masterFd);
211  d->masterFd = -1;
212  return false;
213  }
214 #endif
215 
216 #if defined(HAVE_GRANTPT)
217  if (grantpt(d->masterFd)) {
218  return false;
219  }
220 #else
221  struct stat st;
222  if (stat(d->ttyName.data(), &st))
223  return false; // this just cannot happen ... *cough* Yeah right, I just
224  // had it happen when pty #349 was allocated. I guess
225  // there was some sort of leak? I only had a few open.
226  if (((st.st_uid != getuid()) ||
227  (st.st_mode & (S_IRGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH))) &&
228  !chownpty(true))
229  {
230  kdWarning(175)
231  << "KPty::_attachPty(): " << "chownpty failed for device " << d->ttyName << endl
232  << "KPty::_attachPty(): " << "This means the communication can be eavesdropped." << endl;
233  }
234 #endif
235 
236 #ifdef BSD
237  revoke(d->ttyName.data());
238 #endif
239 
240 #ifdef HAVE_UNLOCKPT
241  unlockpt(d->masterFd);
242 #endif
243 
244  d->slaveFd = ::open(d->ttyName.data(), O_RDWR | O_NOCTTY);
245  if (d->slaveFd < 0)
246  {
247  kdWarning(175) << "KPty::_attachPty(): " << "Can't open slave pseudo teletype" << endl;
248  ::close(d->masterFd);
249  d->masterFd = -1;
250  return false;
251  }
252 #ifdef HAVE_OPENPTY
253  // set screen size
254  ioctl(d->slaveFd, TIOCSWINSZ, (char *)&d->winSize);
255 #endif
256  }
257 
258 #if defined(__svr4__)
259  // Solaris
260  ioctl(d->slaveFd, I_PUSH, "ptem");
261  ioctl(d->slaveFd, I_PUSH, "ldterm");
262 #endif
263 
264  // set xon/xoff & control keystrokes
265  // without the '::' some old system thinks, this declares
266  // the struct in this class, in this method, and fails to find
267  // the correct tc[gs]etattr
268  struct ::termios ttmode;
269 
270  _tcgetattr(d->slaveFd, &ttmode);
271 
272  if (!d->xonXoff)
273  ttmode.c_iflag &= ~(IXOFF | IXON);
274  else
275  ttmode.c_iflag |= (IXOFF | IXON);
276 
277 #ifdef IUTF8
278  if (!d->utf8)
279  ttmode.c_iflag &= ~IUTF8;
280  else
281  ttmode.c_iflag |= IUTF8;
282 #endif
283 
284  ttmode.c_cc[VINTR] = CINTR;
285  ttmode.c_cc[VQUIT] = CQUIT;
286  ttmode.c_cc[VERASE] = CERASE;
287 
288  _tcsetattr(d->slaveFd, &ttmode);
289 
290 #ifndef HAVE_OPENPTY
291  // set screen size
292  ioctl(d->slaveFd, TIOCSWINSZ, (char *)&d->winSize);
293 #endif
294 
295  fcntl(d->masterFd, F_SETFD, FD_CLOEXEC);
296  fcntl(d->slaveFd, F_SETFD, FD_CLOEXEC);
297 
298  return true;
299 }
300 
301 bool KPty::open()
302 {
303  if (d->masterFd >= 0)
304  return true;
305 
306 #if defined(HAVE_OPENPTY)
307  char cpty[16];
308 
309  if (openpty(&d->masterFd, &d->slaveFd, cpty, NULL, &d->winSize) == 0) {
310  d->ttyName = cpty;
311  } else {
312  kdWarning(175) << "Can't open slave pseudo teletype" << endl;
313  return false;
314  }
315 #else
316 
317  TQCString ptyName;
318 
319  // Find a master pty that we can open ////////////////////////////////
320 
321  // Because not all the pty animals are created equal, they want to
322  // be opened by several different methods.
323 
324  // We try, as we know them, one by one.
325 
326 #if defined(HAVE_PTSNAME) && defined(HAVE_GRANTPT)
327 #if defined(HAVE_GETPT)
328  d->masterFd = ::getpt();
329 #elif defined(HAVE_POSIX_OPENPT)
330  d->masterFd = ::posix_openpt(O_RDWR);
331 #elif defined(_AIX)
332  d->masterFd = ::open("/dev/ptc",O_RDWR);
333 #else
334  d->masterFd = ::open("/dev/ptmx",O_RDWR);
335 #endif
336  if (d->masterFd >= 0)
337  {
338  char *ptsn = ptsname(d->masterFd);
339  if (ptsn) {
340  grantpt(d->masterFd);
341  d->ttyName = ptsn;
342  goto gotpty;
343  } else {
344  ::close(d->masterFd);
345  d->masterFd = -1;
346  }
347  }
348 #endif
349 
350  // Linux device names, FIXME: Trouble on other systems?
351  for (const char* s3 = "pqrstuvwxyzabcdefghijklmno"; *s3; s3++)
352  {
353  for (const char* s4 = "0123456789abcdefghijklmnopqrstuvwxyz"; *s4; s4++)
354  {
355  ptyName.sprintf("/dev/pty%c%c", *s3, *s4);
356  d->ttyName.sprintf("/dev/tty%c%c", *s3, *s4);
357 
358  d->masterFd = ::open(ptyName.data(), O_RDWR);
359  if (d->masterFd >= 0)
360  {
361 #ifdef __sun
362  /* Need to check the process group of the pty.
363  * If it exists, then the slave pty is in use,
364  * and we need to get another one.
365  */
366  int pgrp_rtn;
367  if (ioctl(d->masterFd, TIOCGPGRP, &pgrp_rtn) == 0 || errno != EIO) {
368  ::close(d->masterFd);
369  d->masterFd = -1;
370  continue;
371  }
372 #endif /* sun */
373  if (!access(d->ttyName.data(),R_OK|W_OK)) // checks availability based on permission bits
374  {
375  if (!geteuid())
376  {
377  struct group* p = getgrnam(TTY_GROUP);
378  if (!p)
379  p = getgrnam("wheel");
380  gid_t gid = p ? p->gr_gid : getgid ();
381 
382  chown(d->ttyName.data(), getuid(), gid);
383  chmod(d->ttyName.data(), S_IRUSR|S_IWUSR|S_IWGRP);
384  }
385  goto gotpty;
386  }
387  ::close(d->masterFd);
388  d->masterFd = -1;
389  }
390  }
391  }
392 
393  kdWarning(175) << "KPty::open(): " << "Can't open a pseudo teletype" << endl;
394  return false;
395 #endif
396 
397  gotpty:
398  return _attachPty(d->masterFd);
399 
400  return true;
401 }
402 
403 void KPty::close()
404 {
405  if (d->masterFd < 0)
406  return;
407  // don't bother resetting unix98 pty, it will go away after closing master anyway.
408  if (memcmp(d->ttyName.data(), "/dev/pts/", 9)) {
409  if (!geteuid()) {
410  struct stat st;
411  if (!stat(d->ttyName.data(), &st)) {
412  chown(d->ttyName.data(), 0, st.st_gid == getgid() ? 0 : -1);
413  chmod(d->ttyName.data(), S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
414  }
415  } else {
416  fcntl(d->masterFd, F_SETFD, 0);
417  chownpty(false);
418  }
419  }
420  ::close(d->slaveFd);
421  ::close(d->masterFd);
422  d->masterFd = d->slaveFd = -1;
423 }
424 
425 void KPty::setCTty()
426 {
427  // Setup job control //////////////////////////////////
428 
429  // Become session leader, process group leader,
430  // and get rid of the old controlling terminal.
431  setsid();
432 
433  // make our slave pty the new controlling terminal.
434 #ifdef TIOCSCTTY
435  ioctl(d->slaveFd, TIOCSCTTY, 0);
436 #else
437  // SVR4 hack: the first tty opened after setsid() becomes controlling tty
438  ::close(::open(d->ttyName, O_WRONLY, 0));
439 #endif
440 
441  // make our new process group the foreground group on the pty
442  int pgrp = getpid();
443 #if defined(_POSIX_VERSION) || defined(__svr4__)
444  tcsetpgrp (d->slaveFd, pgrp);
445 #elif defined(TIOCSPGRP)
446  ioctl(d->slaveFd, TIOCSPGRP, (char *)&pgrp);
447 #endif
448 }
449 
450 void KPty::login(const char *user, const char *remotehost)
451 {
452 #ifdef HAVE_UTEMPTER
453  TDEProcess_Utmp utmp;
454  utmp.cmdFd = d->masterFd;
455  utmp << UTEMPTER_HELPER << "add";
456  if (remotehost)
457  utmp << remotehost;
458  utmp.start(TDEProcess::Block);
459  Q_UNUSED(user);
460  Q_UNUSED(remotehost);
461 #elif defined(USE_LOGIN)
462  const char *str_ptr;
463  struct utmp l_struct;
464  memset(&l_struct, 0, sizeof(struct utmp));
465  // note: strncpy without terminators _is_ correct here. man 4 utmp
466 
467  if (user)
468  strncpy(l_struct.ut_name, user, UT_NAMESIZE);
469 
470  if (remotehost)
471  strncpy(l_struct.ut_host, remotehost, UT_HOSTSIZE);
472 
473 # ifndef __GLIBC__
474  str_ptr = d->ttyName.data();
475  if (!memcmp(str_ptr, "/dev/", 5))
476  str_ptr += 5;
477  strncpy(l_struct.ut_line, str_ptr, UT_LINESIZE);
478 # endif
479 
480  // Handle 64-bit time_t properly, where it may be larger
481  // than the integral type of ut_time.
482  {
483  time_t ut_time_temp;
484  time(&ut_time_temp);
485  l_struct.ut_time=ut_time_temp;
486  }
487 
488  ::login(&l_struct);
489 #else
490  Q_UNUSED(user);
491  Q_UNUSED(remotehost);
492 #endif
493 }
494 
495 void KPty::logout()
496 {
497 #ifdef HAVE_UTEMPTER
498  TDEProcess_Utmp utmp;
499  utmp.cmdFd = d->masterFd;
500  utmp << UTEMPTER_HELPER << "del";
501  utmp.start(TDEProcess::Block);
502 #elif defined(USE_LOGIN)
503  const char *str_ptr = d->ttyName.data();
504  if (!memcmp(str_ptr, "/dev/", 5))
505  str_ptr += 5;
506 # ifdef __GLIBC__
507  else {
508  const char *sl_ptr = strrchr(str_ptr, '/');
509  if (sl_ptr)
510  str_ptr = sl_ptr + 1;
511  }
512 # endif
513  ::logout(str_ptr);
514 #endif
515 }
516 
517 void KPty::setWinSize(int lines, int columns)
518 {
519  d->winSize.ws_row = (unsigned short)lines;
520  d->winSize.ws_col = (unsigned short)columns;
521  if (d->masterFd >= 0)
522  ioctl( d->masterFd, TIOCSWINSZ, (char *)&d->winSize );
523 }
524 
525 void KPty::setXonXoff(bool useXonXoff)
526 {
527  d->xonXoff = useXonXoff;
528  if (d->masterFd >= 0) {
529  // without the '::' some old system thinks, this declares
530  // the struct in this class, in this method, and fails to find
531  // the correct tc[gs]etattr
532  struct ::termios ttmode;
533 
534  _tcgetattr(d->masterFd, &ttmode);
535 
536  if (!useXonXoff)
537  ttmode.c_iflag &= ~(IXOFF | IXON);
538  else
539  ttmode.c_iflag |= (IXOFF | IXON);
540 
541  _tcsetattr(d->masterFd, &ttmode);
542  }
543 }
544 
545 void KPty::setUtf8Mode(bool useUtf8)
546 {
547  d->utf8 = useUtf8;
548 #ifdef IUTF8
549  if (d->masterFd >= 0) {
550  // without the '::' some old system thinks, this declares
551  // the struct in this class, in this method, and fails to find
552  // the correct tc[gs]etattr
553  struct ::termios ttmode;
554 
555  _tcgetattr(d->masterFd, &ttmode);
556 
557  if (!useUtf8)
558  ttmode.c_iflag &= ~IUTF8;
559  else
560  ttmode.c_iflag |= IUTF8;
561 
562  _tcsetattr(d->masterFd, &ttmode);
563  }
564 #endif
565 }
566 
567 const char *KPty::ttyName() const
568 {
569  return d->ttyName.data();
570 }
571 
572 int KPty::masterFd() const
573 {
574  return d->masterFd;
575 }
576 
577 int KPty::slaveFd() const
578 {
579  return d->slaveFd;
580 }
581 
582 // private
583 bool KPty::chownpty(bool grant)
584 {
585 #if !defined(__OpenBSD__) && !defined(__FreeBSD__)
586  TDEProcess proc;
587  proc << locate("exe", BASE_CHOWN) << (grant?"--grant":"--revoke") << TQString::number(d->masterFd);
588  return proc.start(TDEProcess::Block) && proc.normalExit() && !proc.exitStatus();
589 #endif
590 }
591 
KPty::setPty
bool setPty(int pty_master)
Attach a existing pty master.
Definition: kpty.cpp:189
KPty::~KPty
~KPty()
Destructor:
Definition: kpty.cpp:183
KPty::setXonXoff
void setXonXoff(bool useXonXoff)
Set whether the pty should honor Xon/Xoff flow control.
Definition: kpty.cpp:525
KPty::setCTty
void setCTty()
Creates a new session and process group and makes this pty the controlling tty.
Definition: kpty.cpp:425
KPty::masterFd
int masterFd() const
Definition: kpty.cpp:572
KPty::setWinSize
void setWinSize(int lines, int columns)
Change the logical (screen) size of the pty.
Definition: kpty.cpp:517
KPty::login
void login(const char *user=0, const char *remotehost=0)
Creates an utmp entry for the tty.
Definition: kpty.cpp:450
KPty::open
bool open()
Create a pty master/slave pair.
Definition: kpty.cpp:301
KPty::setUtf8Mode
void setUtf8Mode(bool useUtf8)
Set the pty in utf8 mode on systems that support it.
Definition: kpty.cpp:545
KPty::logout
void logout()
Removes the utmp entry for this tty.
Definition: kpty.cpp:495
KPty::ttyName
const char * ttyName() const
Definition: kpty.cpp:567
KPty::KPty
KPty()
Constructor.
Definition: kpty.cpp:178
KPty::slaveFd
int slaveFd() const
Definition: kpty.cpp:577
KPty::close
void close()
Close the pty master/slave pair.
Definition: kpty.cpp:403
TDEProcess
Child process invocation, monitoring and control.
Definition: kprocess.h:131
TDEProcess::commSetupDoneC
virtual int commSetupDoneC()
Called right after a (successful) fork(), but before an exec() on the child process' side.
Definition: kprocess.cpp:978
TDEProcess::start
virtual bool start(RunMode runmode=NotifyOnExit, Communication comm=NoCommunication)
Starts the process.
Definition: kprocess.cpp:289
TDEProcess::exitStatus
int exitStatus() const
Returns the exit status of the process.
Definition: kprocess.cpp:607
TDEProcess::Block
@ Block
The application is suspended until the started process is finished.
Definition: kprocess.h:182
TDEProcess::normalExit
bool normalExit() const
Checks whether the process exited cleanly.
Definition: kprocess.cpp:585
endl
kndbgstream & endl(kndbgstream &s)
Does nothing.
Definition: kdebug.h:583

tdecore

Skip menu "tdecore"
  • Main Page
  • Modules
  • Namespace List
  • Class Hierarchy
  • Alphabetical List
  • Class List
  • File List
  • Namespace Members
  • Class Members
  • Related Pages

tdecore

Skip menu "tdecore"
  • arts
  • dcop
  • dnssd
  • interfaces
  •   kspeech
  •     interface
  •     library
  •   tdetexteditor
  • kate
  • kded
  • kdoctools
  • kimgio
  • kjs
  • libtdemid
  • libtdescreensaver
  • tdeabc
  • tdecmshell
  • tdecore
  • tdefx
  • tdehtml
  • tdeinit
  • tdeio
  •   bookmarks
  •   httpfilter
  •   kpasswdserver
  •   kssl
  •   tdefile
  •   tdeio
  •   tdeioexec
  • tdeioslave
  •   http
  • tdemdi
  •   tdemdi
  • tdenewstuff
  • tdeparts
  • tdeprint
  • tderandr
  • tderesources
  • tdespell2
  • tdesu
  • tdeui
  • tdeunittest
  • tdeutils
  • tdewallet
Generated for tdecore by doxygen 1.9.1
This website is maintained by Timothy Pearson.