aboutsummaryrefslogtreecommitdiff
path: root/mfd/bi_io.m4
blob: 81693532f904c861737b292dc43759f249fb9c14 (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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
/* This file is part of Mailfromd.             -*- c -*-
   Copyright (C) 2006, 2007, 2008, 2009 Sergey Poznyakoff

   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 3, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>. */

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>

#define NSTREAMS 1024

struct io_stream {
	char *name;
	mu_locker_t lock;
	int fd[2];
	pid_t pid;
	char *buf;
	size_t bufsize;
	void (*cleanup)(void*);
	void *cleanup_data;
};

#define IFD(s) ((s).fd[0])
#define OFD(s) ((s).fd[1] == -1 ? (s).fd[0] : (s).fd[1])

static void
flush_stream(struct io_stream *str)
{
	/*FIXME*/
}

static void
close_stream(struct io_stream *str)
{
	if (OFD(*str) == -1)
		return;
	flush_stream(str);
	close(OFD(*str));
	if (IFD(*str) != -1)
		close(IFD(*str));
	if (str->pid) {
		int status;
		waitpid(str->pid, &status, 0);
	}
	str->fd[0] = -1;
	str->fd[1] = -1;
	str->pid = 0;
	if (str->cleanup)
		str->cleanup(str->cleanup_data);
	str->cleanup = NULL;
	str->cleanup_data = NULL;
}

/* Read bytes from the stream STR into its buffer, until
   DELIM is encountered. Return number of bytes read. */
static int
read_stream_delim(struct io_stream *str, int delim)
{
	int fd = IFD(*str);
	size_t i = 0;
	int rc;

	for (i = 0; ; i++) {
		if (str->bufsize == i) {
			if (str->bufsize == 0) 
				str->bufsize = 16;
			str->buf = x2nrealloc(str->buf, &str->bufsize,
					      sizeof str->buf[1]);
		}
		rc = read(fd, str->buf + i, 1);
		if (rc == -1)
			return -1;
		else if (rc == 0)
			return 0;
		if ((unsigned char) str->buf[i] == delim) {
			/* NOTE: We're leaving the loop, so
			   we must increment the counter here: */
			str->buf[i++] = 0;
			break;
		}
	}
	return i;
}

#define REDIRECT_STDIN_P(f) ((f) & (O_WRONLY|O_RDWR))
#define REDIRECT_STDOUT_P(f) ((f) == O_RDONLY || ((f) & (O_RDONLY|O_RDWR)))

static int
open_program_stream(eval_environ_t env,
		    struct io_stream *str, const char *cmdline, int flags)
{
	int rightp[2], leftp[2];
	int i;
	int rc = 0;
	pid_t pid;
	int argc;
	char **argv;
	
	if (REDIRECT_STDIN_P(flags))
		pipe(leftp);
	if (REDIRECT_STDOUT_P(flags))
		pipe(rightp);

	switch (pid = fork()) {
		/* The child branch.  */
	case 0:
		/* attach the pipes */

		/* Right-end */
		if (REDIRECT_STDOUT_P(flags)) {
			if (rightp[1] != 1) {
				close(1);
				dup2(rightp[1], 1);
			}
			close(rightp[0]);
		}

		/* Left-end */
		if (REDIRECT_STDIN_P(flags)) {
			if (leftp[0] != 0) {
				close(0);
				dup2(leftp[0], 0);
			}
			close(leftp[1]);
		}
      
		/* FIXME: Error output */
#if 0
		if (errfile) {
			i = open (errfile, O_CREAT|O_WRONLY|O_APPEND, 0644);
			if (i > 0 && i != 2) {
				dup2(i, 2);
				close(i);
			}
		}
#endif	
		/* Close unneded descripitors */
		for (i = getmaxfd(); i > 2; i--)
			close(i);

		debug1(10, "running %s", cmdline);
		rc = mu_argcv_get(cmdline, "", NULL, &argc, &argv);
		if (rc) {
			mu_error(_("Cannot parse command line %s: %s"),
				 cmdline, mu_strerror(rc));
			exit(127);
		}			
		execvp(argv[0], argv);
		mu_error(_("Cannot run %s: %s"),
			 cmdline, mu_strerror(rc));
		exit(127);
		/********************/

		/* Parent branches: */
	case -1:
		/* Fork has failed */
		/* Restore things */
		rc = errno;
		if (REDIRECT_STDOUT_P(flags)) {
			close(rightp[0]);
			close(rightp[1]);
		}
		if (REDIRECT_STDIN_P(flags)) {
			close(leftp[0]);
			close(leftp[1]);
		}
		break;
		
	default:
		str->pid = pid;
		if (REDIRECT_STDOUT_P(flags)) {
			str->fd[0] = rightp[0];
			close(rightp[1]);
		} else
			str->fd[0] = -1;

		if (REDIRECT_STDIN_P(flags)) {
			str->fd[1] = leftp[1];
			close(leftp[0]);
		} else
			str->fd[1] = -1;
	}
	return rc;
}


static int
open_file_stream(eval_environ_t env,
		 struct io_stream *str, const char *file, int flags)
{
	str->fd[0] = open(file, flags, 0644); /* FIXME: mode? */
	if (str->fd[0] == -1)
		return errno;
	return 0;
}



static int
open_parsed_inet_stream(eval_environ_t env,
			struct io_stream *str,
			const char *cstr,
			char *proto, char *port, char *path,
			int flags)
{
	struct timeval start, connect_tv;
	union {
		struct sockaddr sa;
		struct sockaddr_in s_in;
		struct sockaddr_un s_un;
	} addr;

	int socklen;
	int fd;

	if (!proto
	    || strcmp(proto, "unix") == 0 || strcmp(proto, "local") == 0) {
		struct stat st;
		
		MF_ASSERT(port == NULL,
			  mfe_failure,
			  _("invalid connection type: %s; "
			    "port is meaningless for UNIX sockets"),
			  cstr);
		
		MF_ASSERT(strlen(path) <= sizeof addr.s_un.sun_path,
			  mfe_range,
			  _("%s: UNIX socket name too long"),
			  path);
		
		addr.sa.sa_family = PF_UNIX;
		socklen = sizeof(addr.s_un);
		strcpy(addr.s_un.sun_path, path);
		
		if (stat(path, &st)) {
			MF_THROW(mfe_failure,
				 _("%s: cannot stat socket: %s"),
				 path, strerror(errno));
		} else {
			/* FIXME: Check permissions? */
			MF_ASSERT(S_ISSOCK(st.st_mode),
				  mfe_failure,
				  _("%s: not a socket"),
				  path);
		}

	} else if (strcmp(proto, "inet") == 0) {
		short pnum;
		long num;
		char *p;
		
		addr.sa.sa_family = PF_INET;
		socklen = sizeof(addr.s_in);

		MF_ASSERT(port != NULL,
			  mfe_failure,
			  _("invalid connection type: %s; "
			    "missing port number"),
			  cstr);

		num = pnum = strtol(port, &p, 0);
		if (*p == 0) {
			MF_ASSERT(num == pnum,
				  mfe_range,
				  _("invalid connection type: "
				    "%s; bad port number"),
				  cstr);
			pnum = htons(pnum);
		} else {
			struct servent *sp = getservbyname(port, "tcp");

			MF_ASSERT(sp != NULL,
				  mfe_failure,
				  _("invalid connection type: "
				    "%s; unknown port name"),
				  cstr);
			pnum = sp->s_port;
		}
		
		if (!path)
			addr.s_in.sin_addr.s_addr = INADDR_ANY;
		else {
			struct hostent *hp = gethostbyname(path);
			MF_ASSERT(hp != NULL,
				  mfe_failure,
				  _("Unknown host name %s"),
				  path);
			addr.sa.sa_family = hp->h_addrtype;
			switch (hp->h_addrtype) {
			case AF_INET:
				memmove(&addr.s_in.sin_addr, hp->h_addr, 4);
				addr.s_in.sin_port = pnum;
				break;

			default:
				MF_THROW(mfe_range,
					 _("invalid connection type: "
					   "%s; unsupported address family"),
					 cstr);
			}
		}
	} else {
		MF_THROW(mfe_range,
			 _("unsupported protocol: %s"),
			 proto);
	}

	fd = socket(addr.sa.sa_family, SOCK_STREAM, 0);
	MF_ASSERT(fd != -1,
		  mfe_failure,
		  _("Unable to create new socket: %s"),
		  strerror(errno));

	/* FIXME: Bind to the source ? */

	connect_tv.tv_sec = 5;
	connect_tv.tv_usec = 0;
	
	gettimeofday(&start, NULL);
	for (;;) {
		int rc = connect(fd, &addr.sa, socklen);
		if (rc == 0)
			break;
		else if (errno == ECONNREFUSED) {
			struct timeval tv, now;
			fd_set rset, wset, xset;
			
			gettimeofday(&now, NULL);
			timersub(&now, &start, &tv);
			
			if (timercmp(&tv, &connect_tv, < )) {
				FD_ZERO(&rset);
				FD_SET(fd, &rset);
				FD_ZERO(&wset);
				FD_SET(fd, &wset);
				FD_ZERO(&xset);
				FD_SET(fd, &xset);
				select(fd + 1, &rset, &wset, &xset, &tv);
				continue;
			}
		}
		
		close(fd);
		MF_THROW(mfe_failure,
			 _("Cannot connect to %s: %s"),
			 cstr, strerror(errno));
	}
	
	str->fd[0] = fd;
	return 0;
}

static int
open_inet_stream(eval_environ_t env,
		 struct io_stream *str, const char *addr, int flags)
{
	int rc;
	char *proto, *port, *path;

	if (gacopyz_parse_connection(addr, &proto, &port, &path)
	    != MI_SUCCESS) 
		rc = ENOMEM; /* FIXME: or EINVAL? */
	else {
		rc = open_parsed_inet_stream(env,
					     str, addr,
					     proto, port, path, flags);
		free(proto);
		free(port);
		free(path);
	}
	return rc;
}


static void *
alloc_streams()
{
	struct io_stream *p, *stab = xcalloc(NSTREAMS, sizeof *stab);
	for (p = stab; p < stab + NSTREAMS; p++) 
		p->fd[0] = p->fd[1] = -1;
	return stab;
}

static void
destroy_streams(void *data)
{
	struct io_stream *stab = data;
	struct io_stream *p;
	for (p = stab; p < stab + NSTREAMS; p++) {
		close_stream(p);
		free(p->buf);
	}
	free(stab);
}
		
MF_DECLARE_DATA(IO, alloc_streams, destroy_streams)


MF_DEFUN(open, NUMBER, STRING name)
{
	int i, rc;
	int flags = 0;
	int (*opf)(eval_environ_t env,
		   struct io_stream *, const char *, int) = open_file_stream;
	struct io_stream *iotab = MF_GET_DATA;
	
	for (i = 0; i < NSTREAMS; i++) {
		if (iotab[i].fd[0] == -1) 
			break;
	}
	MF_ASSERT(i < NSTREAMS,
		  mfe_failure,
		  _("No more files available"));

	debug1(10, "opening stream %s", name);
	iotab[i].name = name;
	if (*name == '>') {
		flags |= O_RDWR|O_CREAT;
		name++;
		if (*name == '>') {
			flags |= O_APPEND;
			name++;
		} else
			flags |= O_TRUNC;
	} else if (*name == '|') {
		opf = open_program_stream;
		flags = O_WRONLY;
		name++;
		if (*name == '&') {
			flags = O_RDWR;
			name++;
		}
	} else if (*name == '@') {
		name++;
		opf = open_inet_stream;
		flags = O_RDWR;
	} else
		flags = O_RDWR;
	
	for (;*name && c_isspace(*name); name++)
		;
	
	rc = opf(env, &iotab[i], name, flags);
	
	MF_ASSERT(rc == 0,
		  mfe_failure,
		  _("Cannot open stream %s: %s"), name,
		  mu_strerror(rc));
	debug2(10, "open(%s) = %d", name, i);
	MF_RETURN(i);
}
END

MF_DEFUN(close, VOID, NUMBER fd)
{
	struct io_stream *iotab = MF_GET_DATA;

	MF_ASSERT(fd >= 0 && fd < NSTREAMS,
		  mfe_range,
		  _("Invalid file descriptor"));
	close_stream(&iotab[fd]);
}
END	

MF_DEFUN(write, VOID, NUMBER fd, STRING str, OPTIONAL, NUMBER n)
{
	struct io_stream *iotab = MF_GET_DATA;
	int rc;
	
	debug2(10, "writing %s to %d", str, fd);
	MF_ASSERT(fd >= 0 && fd < NSTREAMS && OFD(iotab[fd]),
		  mfe_range,
		  _("Invalid file descriptor"));
	if (!MF_DEFINED(n))
		n = strlen (str);
	rc = write(OFD(iotab[fd]), str, n);
	MF_ASSERT(n == rc,
		  mfe_io,
		  _("Write error on %s: %s"),
		  iotab[fd].name, mu_strerror(errno));
}
END

MF_DEFUN(read, STRING, NUMBER fd, NUMBER size)
{
	struct io_stream *iotab = MF_GET_DATA;
	int rc;
	size_t off;
	char *s = MF_ALLOC_HEAP(off, size + 1);

	MF_ASSERT(fd >= 0 && fd < NSTREAMS && IFD(iotab[fd]),
		  mfe_range,
		  _("Invalid file descriptor"));
	
	rc = read(IFD(iotab[fd]), s, size);
	if (rc == 0)
		MF_THROW(mfe_eof,
			 _("EOF on %s"), iotab[fd].name);
	MF_ASSERT(rc == size,
		  mfe_io,
		  _("Read error on %s: %s"),
		  iotab[fd].name, mu_strerror(errno));
	s[size] = 0;
	MF_RETURN(off);
}	
END

/* FIXME: only first char of delim is used */
MF_DEFUN(getdelim, STRING, NUMBER fd, STRING delim)
{
	struct io_stream *iotab = MF_GET_DATA;
	int rc;

	MF_ASSERT(fd >= 0 && fd < NSTREAMS && IFD(iotab[fd]),
		  mfe_range,
		  _("Invalid file descriptor"));
	rc = read_stream_delim(&iotab[fd], delim[0]); 
	if (rc == 0)
		MF_THROW(mfe_eof,
			 _("EOF on %s"), iotab[fd].name);
	MF_ASSERT(rc > 0,
		  mfe_io,
		  _("Read error on %s: %s"),
		  iotab[fd].name, mu_strerror(errno));
	MF_RETURN_STRING(iotab[fd].buf);
}	
END

MF_DEFUN(getline, STRING, NUMBER fd)
{
	struct io_stream *iotab = MF_GET_DATA;
	int rc;

	MF_ASSERT(fd >= 0 && fd < NSTREAMS && IFD(iotab[fd]),
		  mfe_range,
		  _("Invalid file descriptor"));
	rc = read_stream_delim(&iotab[fd], '\n');
	if (rc == 0)
		MF_THROW(mfe_eof,
			 _("EOF on %s"), iotab[fd].name);
	MF_ASSERT(rc > 0,
		  mfe_io,
		  _("Read error on %s: %s"),
		  iotab[fd].name, mu_strerror(errno));
	MF_RETURN_STRING(iotab[fd].buf);
}	
END

MF_INIT

Return to:

Send suggestions and report system problems to the System administrator.