summaryrefslogtreecommitdiffstats
path: root/languages/cpp/debugger/stty.cpp
blob: cdf4c81e33fe59f2392f8b6b9ecebd64a9863bb3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
/***************************************************************************
    begin                : Mon Sep 13 1999
    copyright            : (C) 1999 by John Birch
    email                : jbb@kdevelop.org

  This code was originally written by Judin Maxim, from the
	KDEStudio project.

  It was then updated with later code from konsole (KDE).

	It has also been enhanced with an idea from the code in kdbg
	written by Johannes Sixt<Johannes.Sixt@telecom.at>

 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#ifdef __osf__
#define _XOPEN_SOURCE_EXTENDED
#define O_NDELAY O_NONBLOCK
#endif

#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/time.h>
#include <sys/resource.h>

#ifdef HAVE_SYS_STROPTS_H
#include <sys/stropts.h>
#define _NEW_TTY_CTRL
#endif

#include <assert.h>
#include <fcntl.h>
#include <grp.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <termios.h>
#include <time.h>
#include <unistd.h>
#include <errno.h>

#if defined (_HPUX_SOURCE)
#define _TERMIOS_INCLUDED
#include <bsdtty.h>
#endif

#include <tqintdict.h>
#include <tqsocketnotifier.h>
#include <tqstring.h>
#include <tqfile.h>

#include <klocale.h>
#include <kstandarddirs.h>
#include <kapplication.h>

#include "stty.h"

#define PTY_FILENO 3
#define BASE_CHOWN "konsole_grantpty"

namespace GDBDebugger
{

static int chownpty(int fd, int grant)
// param fd: the fd of a master pty.
// param grant: 1 to grant, 0 to revoke
// returns 1 on success 0 on fail
{
    void(*tmp)(int) = signal(SIGCHLD,SIG_DFL);
    pid_t pid = fork();
    if (pid < 0) {
        signal(SIGCHLD,tmp);
        return 0;
    }
    if (pid == 0) {
        /* We pass the master pseudo terminal as file descriptor PTY_FILENO. */
        if (fd != PTY_FILENO && dup2(fd, PTY_FILENO) < 0)
            ::exit(1);

        TQString path = locate("exe", BASE_CHOWN);
        execle(TQFile::encodeName(path), BASE_CHOWN, grant?"--grant":"--revoke", (void *)0, NULL);
        ::exit(1); // should not be reached
    }
    if (pid > 0) {
        int w;
        //  retry:
        int rc = waitpid (pid, &w, 0);
        if (rc != pid)
            ::exit(1);

        //    { // signal from other child, behave like catchChild.
        //      // guess this gives quite some control chaos...
        //      Shell* sh = shells.find(rc);
        //      if (sh) { shells.remove(rc); sh->doneShell(w); }
        //      goto retry;
        //    }
        signal(SIGCHLD,tmp);
        return (rc != -1 && WIFEXITED(w) && WEXITSTATUS(w) == 0);
    }
    signal(SIGCHLD,tmp);
    return 0; //dummy.
}

// **************************************************************************

STTY::STTY(bool ext, const TQString &termAppName)
    : TQObject(),
      out(0),
      ttySlave(""),
      pid_(0),
      external_(ext)
{
    if (ext) {
        findExternalTTY(termAppName);
    } else {
        fout = findTTY();
        if (fout >= 0) {
            ttySlave = TQString(tty_slave);
            out = new TQSocketNotifier(fout, TQSocketNotifier::Read, this);
            connect( out, TQT_SIGNAL(activated(int)), this, TQT_SLOT(OutReceived(int)) );
        }
    }
}

// **************************************************************************

STTY::~STTY()
{
    if (pid_)
        ::kill(pid_, SIGTERM);

    if (out) {
        ::close(fout);
        delete out;
    }
}

// **************************************************************************

int STTY::findTTY()
{
    int ptyfd = -1;
    bool needGrantPty = TRUE;

    // Find a master pty that we can open ////////////////////////////////

#ifdef __sgi__
    ptyfd = open("/dev/ptmx",O_RDWR);
    if (ptyfd < 0) {
        perror("Can't open a pseudo teletype");
        return(-1);
    }
    strncpy(tty_slave, ptsname(ptyfd), 50);
    grantpt(ptyfd);
    unlockpt(ptyfd);
    needGrantPty = FALSE;
#endif

    // first we try UNIX PTY's
#ifdef TIOCGPTN
    strcpy(pty_master,"/dev/ptmx");
    strcpy(tty_slave,"/dev/pts/");
    ptyfd = open(pty_master,O_RDWR);
    if (ptyfd >= 0) { // got the master pty
        int ptyno;
        if (ioctl(ptyfd, TIOCGPTN, &ptyno) == 0) {
            struct stat sbuf;
            sprintf(tty_slave,"/dev/pts/%d",ptyno);
            if (stat(tty_slave,&sbuf) == 0 && S_ISCHR(sbuf.st_mode))
                needGrantPty = FALSE;
            else {
                close(ptyfd);
                ptyfd = -1;
            }
        } else {
            close(ptyfd);
            ptyfd = -1;
        }
    }
#endif

#if defined(_SCO_DS) || defined(__USLC__) /* SCO OSr5 and UnixWare */
    if (ptyfd < 0) {
        for (int idx = 0; idx < 256; idx++)
            { sprintf(pty_master, "/dev/ptyp%d", idx);
            sprintf(tty_slave, "/dev/ttyp%d", idx);
            if (access(tty_slave, F_OK) < 0) { idx = 256; break; }
            if ((ptyfd = open (pty_master, O_RDWR)) >= 0)
                { if (access (tty_slave, R_OK|W_OK) == 0) break;
                close(ptyfd); ptyfd = -1;
                }
            }
    }
#endif
    if (ptyfd < 0) { /// \FIXME Linux, Trouble on other systems?
        for (const char* s3 = "pqrstuvwxyzabcde"; *s3 != 0; s3++) {
            for (const char* s4 = "0123456789abcdef"; *s4 != 0; s4++) {
                sprintf(pty_master,"/dev/pty%c%c",*s3,*s4);
                sprintf(tty_slave,"/dev/tty%c%c",*s3,*s4);
                if ((ptyfd = open(pty_master, O_RDWR)) >= 0) {
                    if (geteuid() == 0 || access(tty_slave, R_OK|W_OK) == 0)
                        break;

                    close(ptyfd);
                    ptyfd = -1;
                }
            }

            if (ptyfd >= 0)
                break;
        }
    }

    if (ptyfd >= 0) {
        if (needGrantPty && !chownpty(ptyfd, TRUE)) {
            fprintf(stderr,"kdevelop: chownpty failed for device %s::%s.\n",pty_master,tty_slave);
            fprintf(stderr,"        : This means the session can be eavesdroped.\n");
            fprintf(stderr,"        : Make sure konsole_grantpty is installed and setuid root.\n");
        }

        ::fcntl(ptyfd, F_SETFL, O_NDELAY);
#ifdef TIOCSPTLCK
        int flag = 0;
        ioctl(ptyfd, TIOCSPTLCK, &flag); // unlock pty
#endif
    }

    return ptyfd;
}

// **************************************************************************

void STTY::OutReceived(int f)
{
    char buf[1024];
    int n;

    // read until socket is empty. We shouldn't be receiving a continuous
    // stream of data, so the loop is unlikely to cause problems.
    while ((n = ::read(f, buf, sizeof(buf)-1)) > 0) {
        *(buf+n) = 0;         // a standard string
        emit OutOutput(buf);
    }
    // Note: for some reason, n can be 0 here.
    // I can understand that non-blocking read returns 0,
    // but I don't understand how OutRecieved can be even
    // called when there's no input.
    if (n == 0 /* eof */
        || (n == -1 && errno != EAGAIN))
    {
        // Found eof or error. Disable socket notifier, otherwise Qt
        // will repeatedly call this method, eating CPU
        // cycles.
        out->setEnabled(false);
    }
    
}

void STTY::readRemaining()
{
    if (!external_)
        OutReceived(fout);
}

// **************************************************************************

#define FIFO_FILE "/tmp/debug_tty.XXXXXX"

bool STTY::findExternalTTY(const TQString &termApp)
{
    TQString appName(termApp.isEmpty() ? TQString("xterm") : termApp);

    if ( KStandardDirs::findExe( termApp ).isEmpty() )
    {
        return false;
    }

    char fifo[] = FIFO_FILE;
    int fifo_fd;
    if ((fifo_fd = mkstemp(fifo)) == -1)
        return false;

    ::close(fifo_fd);
    ::unlink(fifo);

    // create a fifo that will pass in the tty name
#ifdef HAVE_MKFIFO
    if (::mkfifo(fifo, S_IRUSR|S_IWUSR) < 0)
#else
        if (::mknod(fifo, S_IFIFO | S_IRUSR|S_IWUSR, 0) < 0)
#endif
            return false;

    int pid = ::fork();
    if (pid < 0) {             // No process
        ::unlink(fifo);
        return false;
    }

    if (pid == 0) {            // child process
        /*
         * Spawn a console that in turn runs a shell script that passes us
         * back the terminal name and then only sits and waits.
         */

        const char* prog      = appName.latin1();
        TQString script = TQString("tty>") + TQString(fifo) +
            TQString(";"                  // fifo name
                    "trap \"\" INT QUIT TSTP;"	  // ignore various signals
                    "exec<&-;exec>&-;"		        // close stdin and stdout
                    "while :;do sleep 3600;done");
        const char* scriptStr = script.latin1();
        const char* end       = 0;

        if ( termApp == "konsole" )
        {
            ::execlp( prog,       prog,
                  "-caption", i18n("kdevelop: Debug application console").local8Bit().data(),
                  "-e",       "sh",
                  "-c",       scriptStr,
                  end);
        }
        else
        {        
            ::execlp( prog,       prog,
                  "-e",       "sh",
                  "-c",       scriptStr,
                  end);
        }

        // Should not get here, as above should always work
        ::exit(1);
    }

    // parent process
    if (pid <= 0)
        ::exit(1);

    // Open the communication between us (the parent) and the
    // child (the process running on a tty console)
    fifo_fd = ::open(fifo, O_RDONLY);
    if (fifo_fd < 0)
        return false;

    // Get the ttyname from the fifo buffer that the child process
    // has sent.
    char ttyname[50];
    int n = ::read(fifo_fd, ttyname, sizeof(ttyname)-sizeof(char));

    ::close(fifo_fd);
    ::unlink(fifo);

    // No name??
    if (n <= 0)
        return false;

    // remove whitespace
    ttyname[n] = 0;
    if (char* newline = strchr(ttyname, '\n'))
        *newline = 0;      // clobber the new line

    ttySlave = ttyname;
    pid_ = pid;

    return true;
}

}

// **************************************************************************
#include "stty.moc"