aboutsummaryrefslogtreecommitdiffstats
path: root/beam.c
blob: cff503da6fab64cd80ecd7d767adcd11a0fc1667 (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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
/*
 *  beam.c  --  code to beam texts across the TCP connection following a
 *              special protocol
 *
 *  Copyright (C) 1998 by Massimiliano Ghilardi
 *
 *  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.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <arpa/telnet.h>

#include "defines.h"
#include "main.h"
#include "utils.h"
#include "beam.h"
#include "map.h"
#include "tcp.h"
#include "tty.h"
#include "edit.h"
#include "eval.h"

editsess *edit_sess;	/* head of session list */

char edit_start[BUFSIZE]; /* messages to send to host when starting */
char edit_end[BUFSIZE];   /* or leaving editing sessions */

static void write_message(char *s)
{
    clear_input_line(opt_compact);
    if (!opt_compact) {
	tty_putc('\n');
	status(1);
    }
    tty_puts(s);
}

/*
 * Process editing protocol message from buf with len remaining chars.
 * Return number of characters used in the message.
 */
int process_message(char *buf, int len)
{
    int msglen, i, l, used;
    char *text, *from, *to;
    char msg[BUFSIZE];
    int got_iac;

    status(1);

    msglen = atoi(buf + 1);
    for (i = 1; i < len && isdigit(buf[i]); i++)
      ;

    if (i < len && buf[i] == '\r') i++;
    if (i >= len || buf[i] != '\n') {
	write_message ("#warning: MPI protocol error\n");
	return 0;
    }

    l = len - ++i;

    text = (char *)malloc(msglen);
    if (!text) {
	errmsg("malloc");
	return i;
    }

    /* only doing trivial (IAC IAC) processing; this should all be
     * rewritten */
    got_iac = 0;
    from = buf + i;
    to = text;
    for (i = 0; i < l && (to - text) < msglen; ++i) {
        if (got_iac) {
            if (*from != (char)IAC)
                errmsg("got IAC in MPI message; treating as IAC IAC");
            else
                ++from;
            got_iac = 0;
        } else {
            got_iac = (*to++ = *from++) == (char)IAC;
        }
    }
    i = to - text;
    used = from - buf;

    while (i < msglen) {
	/* read() might block here, but it should't be long */
	while ((l = read(tcp_fd, text + i, msglen - i)) == -1 && errno == EINTR)
	    ;
	if (l == -1) {
	    errmsg("read message from socket");
	    return used > len ? len : used;
	}
        from = to = text + i;
        for (i = 0; i < l; ++i) {
            if (got_iac) {
                if (*from != (char)IAC)
                    errmsg("got IAC in MPI message; treating as IAC IAC");
                else
                    ++from;
                got_iac = 0;
            } else {
                got_iac = (*to++ = *from++) == (char)IAC;
            }
        }
        i = to - text;
	tty_printf("\rgot %d chars out of %d", i, msglen);
	tty_flush();
    }
    tty_printf("\rread all %d chars.%s\n", msglen, tty_clreoln);

    switch(*buf) {
    case 'E':
        message_edit(text, msglen, 0, 0);
        break;
    case 'V':
        message_edit(text, msglen, 1, 0);
        break;
    default:
        sprintf(msg, "#warning: received a funny message (0x%x)\n", *buf);
        write_message(msg);
        free(text);
        break;
    }

    return used;
}

/*
 * abort an editing session when
 * the MUD socket it comes from gets closed
 */
void abort_edit_fd(int fd)
{
    editsess **sp, *p;

    if (fd < 0)
	return;

    for (sp = &edit_sess; *sp; sp = &(*sp)->next) {
	p = *sp;
	if (p->fd != fd)
	    continue;

	if (kill(p->pid, SIGKILL) < 0) {       /* Editicide */
	    errmsg("kill editor child");
	    continue;
	}

	PRINTF("#aborted \"%s\" (%u)\n", p->descr, p->key);
	p->cancel = 1;
    }
}

/*
 * cancel an editing session; does not free anything
 * (the child death signal handler will remove the session from the list)
 */
void cancel_edit(editsess *sp)
{
    char buf[BUFSIZE];
    char keystr[16];

    if (kill(sp->pid, SIGKILL) < 0) {       /* Editicide */
	errmsg("kill editor child");
	return;
    }
    PRINTF("#killed \"%s\" (%u)\n", sp->descr, sp->key);
    sprintf(keystr, "C%u\n", sp->key);
    sprintf(buf, "%sE%d\n%s", MPI, (int)strlen(keystr), keystr);
    tcp_write(sp->fd, buf);
    sp->cancel = 1;
}

static ssize_t read_file(int fd, void *buf, size_t count)
{
    size_t result = 0;
    while (count > 0) {
        int r;
        do {
            r = read(fd, buf, count);
        } while (r < 0 && errno == EINTR);
        if (r < 0)
            return -1;
        if (r == 0)
            break;
        result += r;
        buf += r;
        count -= r;
    }
    return result;
}

/*
 * send back edited text to server, or cancel the editing session if the
 * file was not changed.
 */
static void finish_edit(editsess *sp)
{
    char *realtext = NULL, *text;
    int fd, txtlen, hdrlen;
    struct stat sbuf;
    char keystr[16], buf[256], hdr[65];

    if (sp->fd == -1)
	goto cleanup_file;

    fd = open(sp->file, O_RDONLY);
    if (fd == -1) {
	errmsg("open edit file");
	goto cleanup_file;
    }
    if (fstat(fd, &sbuf) == -1) {
	errmsg("fstat edit file");
	goto cleanup_fd;
    }

    txtlen = sbuf.st_size;

    if (!sp->cancel && (sbuf.st_mtime > sp->ctime || txtlen != sp->oldsize)) {
	/* file was changed by editor: send back result to server */

	realtext = (char *)malloc(txtlen + 65);
	/* +1 is for possible LF, +64 for header */
	if (!realtext) {
	    errmsg("malloc");
	    goto cleanup_fd;
	}

	text = realtext + 64;
        txtlen = read_file(fd, text, txtlen);
        if (txtlen < 0)
	    goto cleanup_text;

	if (txtlen && text[txtlen - 1] != '\n') {
	    /* If the last line isn't LF-terminated, add an LF;
	     * however, empty files must remain empty */
	    text[txtlen] = '\n';
	    txtlen++;
	}

	sprintf(keystr, "E%u\n", sp->key);

	sprintf(hdr, "%sE%d\n%s", MPI, (int)(txtlen + strlen(keystr)), keystr);

	text -= (hdrlen = strlen(hdr));
	memcpy(text, hdr, hdrlen);

	/* text[hdrlen + txtlen] = '\0'; */
	tcp_write_escape_iac(sp->fd, text, hdrlen + txtlen);

	sprintf(buf, "#completed session %s (%u)\n", sp->descr, sp->key);
	write_message(buf);
    } else {
	/* file wasn't changed, cancel editing session */
	sprintf(keystr, "C%u\n", sp->key);
	sprintf(hdr, "%sE%d\n%s", MPI, (int) strlen(keystr), keystr);

	tcp_raw_write(sp->fd, hdr, strlen(hdr));

	sprintf(buf, "#cancelled session %s (%u)\n", sp->descr, sp->key);
	write_message(buf);
    }

cleanup_text: if (realtext) free(realtext);
cleanup_fd:   close(fd);
cleanup_file: if (unlink(sp->file) < 0)
		errmsg("unlink edit file");
}

/*
 * start an editing session: process the EDIT/VIEW message
 * if view == 1, text will be viewed, else edited
 */
void message_edit(char *text, int msglen, char view, char builtin)
{
    char tmpname[BUFSIZE], command_str[BUFSIZE], buf[BUFSIZE];
    char *errdesc = "#warning: protocol error (message_edit, no %s)\n";
    int tmpfd, i, childpid;
    unsigned int key;
    editsess *s;
    char *editor, *descr;
    char *args[4];
    int waitforeditor;

    status(1);

    args[0] = "/bin/sh"; args[1] = "-c";
    args[2] = command_str; args[3] = 0;

    if (view) {
	key = (unsigned int)-1;
	i = 0;
    } else {
	if (msglen < 1 || text[0] != 'M') {
	    tty_printf(errdesc, "M");
	    free(text);
	    return;
	}
	for (i = 1; i < msglen && isdigit(text[i]); i++)
	    ;
	if (text[i++] != '\n' || i >= msglen) {
	    tty_printf(errdesc, "\\n");
	    free(text);
	    return;
	}
	key = strtoul(text + 1, NULL, 10);
    }
    descr = text + i;
    while (i < msglen && text[i] != '\n') i++;
    if (i >= msglen) {
	tty_printf(errdesc, "desc");
	free(text);
	return;
    }
    text[i++] = '\0';

    sprintf(tmpname, "/tmp/powwow.%u.%d%d", key, getpid(), abs(rand()) >> 8);
    if ((tmpfd = open(tmpname, O_WRONLY | O_CREAT, 0600)) < 0) {
	errmsg("create temp edit file");
	free(text);
	return;
    }
    if (write(tmpfd, text + i, msglen - i) < msglen - i) {
	errmsg("write to temp edit file");
	free(text);
	close(tmpfd);
	return;
    }
    close(tmpfd);

    s = (editsess*)malloc(sizeof(editsess));
    if (!s) {
	errmsg("malloc");
	return;
    }
    s->ctime = time((time_t*)NULL);
    s->oldsize = msglen - i;
    s->key = key;
    s->fd = (view || builtin) ? -1 : tcp_fd; /* MUME doesn't expect a reply. */
    s->cancel = 0;
    s->descr = my_strdup(descr);
    s->file = my_strdup(tmpname);
    free(text);

    /* send a edit_start message (if wanted) */
    if ((!edit_sess) && (*edit_start)) {
	error = 0;
	parse_instruction(edit_start, 0, 0, 1);
	history_done = 0;
    }

    if (view) {
	if (!(editor = getenv("POWWOWPAGER")) && !(editor = getenv("PAGER")))
	    editor = "more";
    } else {
	if (!(editor = getenv("POWWOWEDITOR")) && !(editor = getenv("EDITOR")))
	    editor = "emacs";
    }

    if (editor[0] == '&') {
	waitforeditor = 0;
	editor++;
    } else
	waitforeditor = 1;

    if (waitforeditor) {
	tty_quit();
	/* ignore SIGINT since interrupting the child would interrupt us too,
	 if we are in the same tty group */
	sig_permanent(SIGINT, SIG_IGN);
	sig_permanent(SIGCHLD, SIG_DFL);
    }

    switch(childpid = fork()) {		/* let's get schizophrenic */
      case 0:
	sprintf(command_str, "%s %s", editor, s->file);
	sprintf(buf, "TITLE=%s", s->descr);
	putenv(buf);
	/*	   setenv("TITLE", s->descr, 1);*/
	execvp((char *)args[0], (char **)args);
	syserr("execve");
	break;
      case -1:
	errmsg("fork");
	free(s->descr);
	free(s->file);
	free(s);
	return;
    }
    s->pid = childpid;
    if (waitforeditor) {
	while ((i = waitpid(childpid, (int*)NULL, 0)) == -1 && errno == EINTR)
	    ;

	signal_start();		/* reset SIGINT and SIGCHLD handlers */
	tty_start();

	if (s->fd != -1) {
	    tty_gotoxy(0, lines - 1);
	    tty_putc('\n');
	}

	if (i == -1)
	    errmsg("waitpid");
	else
	    finish_edit(s);

	free(s->descr);
	free(s->file);
	if (i != -1 && !edit_sess && *edit_end) {
	    error = 0;
	    parse_instruction(edit_end, 0, 0, 1);
	    history_done = 0;
	}

	free(s);

    } else {
	s->next = edit_sess;
	edit_sess = s;
    }
}

/*
 * Our child has snuffed it. check if it was an editor, and update the
 * session list if that is the case.
 */
void sig_chld_bottomhalf(void)
{
    int fd, pid, ret;
    editsess **sp, *p;

    /* GH: while() instead of just one check */
    while ((pid = waitpid(-1, &ret, WNOHANG)) > 0) {

	/* GH: check for WIFSTOPPED unnecessary since no */
	/* WUNTRACED to waitpid()			 */
	for (sp = &edit_sess; *sp && (*sp)->pid != pid; sp = &(*sp)->next)
	    ;
	if (*sp) {
	    finish_edit(*sp);
	    p = *sp; *sp = p->next;
	    fd = p->fd;
	    free(p->descr);
	    free(p->file);
	    free(p);

	    /* GH: only send message if found matching session */

	    /* send the edit_end message if this is the last editor... */
	    if ((!edit_sess) && (*edit_end)) {
		int otcp_fd = tcp_fd;  /* backup current socket fd */
		tcp_fd = fd;
		error = 0;
		parse_instruction(edit_end, 0, 0, 1);
		history_done = 0;
		tcp_fd = otcp_fd;
	    }
	}
    }
}