File: fungw_cli.c

package info (click to toggle)
fungw 1.2.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,268 kB
  • sloc: ansic: 24,257; makefile: 500; sh: 32; awk: 9; perl: 8; tcl: 7; javascript: 7; ruby: 7; python: 6
file content (632 lines) | stat: -rw-r--r-- 14,852 bytes parent folder | download
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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
/*
    fungw - language-agnostic function gateway
    Copyright (C) 2018, 2019  Tibor 'Igor2' Palinkas

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

    This library 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
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 31 Milk Street, # 960789 Boston, MA 02196 USA

    Project page: http://repo.hu/projects/fungw
    Version control: svn://repo.hu/fungw/trunk
*/

#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <libfungw/fungw.h>
#include <libfungw/fungw_conv.h>

#include "os_dep.h"

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/signal.h>
#include <fcntl.h>
#include <errno.h>

typedef struct {
	const char *name;
	const char *shebang, *execflag;
	const char *head, *foot;
} fgws_cli_lang_t;

#include "sh_head.h"
static const char sh_foot[] = "\nfgw_main_loop\n";

static const fgws_cli_lang_t langs[] = {
	{"shell", "/bin/sh",          "-c",    sh_head_arr,    sh_foot},
	{"bash",  "/bin/bash",        "-c",    sh_head_arr,    sh_foot},
	{"dash",  "/bin/dash",        "-c",    sh_head_arr,    sh_foot},
	{"shell", "/usr/bin/sh",      "-c",    sh_head_arr,    sh_foot},
	{"bash",  "/usr/bin/bash",    "-c",    sh_head_arr,    sh_foot},
	{"dash",  "/usr/bin/dash",    "-c",    sh_head_arr,    sh_foot},
	{NULL,    NULL,               NULL,    NULL,           NULL}
};

typedef struct {
	fgw_obj_t *obj;
	int fd_c2s[2]; /* c->script pipe; c writes [1], script reads [0] */
	int fd_s2c[2]; /* c->script pipe; c reads [0], script writes [1] */
	pid_t pid;
	int running; /* whether the background process is running */

	/* read buffer */
	char buf[256];
	int buf_fill, bufp;

	/* name of the script being executed */
	char scr_name[L_tmpnam];
} cli_ctx_t;

static fgw_error_t fgws_cli_call_script(fgw_arg_t *res, int argc, fgw_arg_t *argv);

/* buffered read on the control pipe */
static int cli_getc(cli_ctx_t *ctx)
{
	if (ctx->bufp >= ctx->buf_fill) {
		ctx->buf_fill = read(ctx->fd_s2c[0], ctx->buf, sizeof(ctx->buf));
		if (ctx->buf_fill <= 0)
			return ctx->buf_fill;
		ctx->bufp = 0;
	}
	return ctx->buf[ctx->bufp++];
}

/* blocking write all buf */
static ssize_t cli_write_(int fd, const char *buf, ssize_t len)
{
	ssize_t orig = len;
	while(len > 0) {
		ssize_t l;
		l = write(fd, buf, len);
		if (l <= 0)
			return -1;
		buf += l;
		len -= l;
	}
	return orig;
}

static ssize_t cli_write(cli_ctx_t *ctx, const char *buf, ssize_t len)
{
	return cli_write_(ctx->fd_c2s[1], buf, len);
}


/* print small (<1k) formatted strings */
static void cli_printf(cli_ctx_t *ctx, const char *fmt, ...)
{
	char tmp[1024];
	size_t len;
	va_list ap;
	va_start(ap, fmt);
	len = vsprintf(tmp, fmt, ap);
	va_end(ap);
	cli_write(ctx, tmp, len);
}

static int cli_got_eof(cli_ctx_t *ctx, ssize_t len, int err_no)
{
/* later, for nonblocking:
	if ((len == 0) && (err_no == EAGAIN)) {
		usleep?
		return 0;
	}
*/

	if (len <= 0) {
		ctx->running = 0;
		return 1;
	}
	return 0;
}

static int cli_read_fgw_func_reg(cli_ctx_t *ctx, char *buf, int maxlen)
{
	int bl = 0;
	fgw_func_t *func;

	for(;;) {
		int c;

		/* read the function name */
		c = cli_getc(ctx);
		if (cli_got_eof(ctx, c, errno))
			return -1;
		if ((c == '\n') || (c == '\r'))
			break;
		buf[bl] = c;
		bl++;
		if (bl >= maxlen)
			return -1;
	}
	buf[bl] = '\0';

	func = fgw_func_reg(ctx->obj, buf, fgws_cli_call_script);
	if (func == NULL) {
		fgw_async_error(ctx->obj, "fgw_func_reg: failed to register function\n");
		fgw_async_error(ctx->obj, buf);
		fgw_async_error(ctx->obj, "\n");
		cli_write(ctx, "fr_err\n", 7);
	}
	cli_write(ctx, "fr_ok\n", 6);
	return 0;
}

static int cli_read_fgw_arg(cli_ctx_t *ctx, fgw_arg_t *arg)
{
	int used = 0, alloced = 256, grow = 2048, limit=1024*1024;

	arg->type = FGW_STR | FGW_DYN;
	arg->val.str = malloc(alloced);

	for(;;) {
		int c;

		/* read the function name */
		c = cli_getc(ctx);
		if (cli_got_eof(ctx, c, errno)) {
			free(arg->val.str);
			arg->type = 0;
			return -1;
		}
		if ((c == '\n') || (c == '\r'))
			break;
		if (used >= alloced) {
			alloced += grow;
			if (alloced > limit) {
				free(arg->val.str);
				arg->type = 0;
				return -1;
			}
			arg->val.str = realloc(arg->val.str, alloced+1);
		}
		arg->val.str[used] = c;
		used++;
	}
	arg->val.str[used] = '\0';
	return 0;
}

static int cli_read_fgw_int(cli_ctx_t *ctx, int *dst)
{
	long tmp = 0;
	int valid = 0;

	for(;;) {
		int c;

		/* read the function name */
		c = cli_getc(ctx);
		if (cli_got_eof(ctx, c, errno))
			return -1;
		if ((c == '\n') || (c == '\r'))
			break;
		if (isdigit(c)) {
			tmp *= 10;
			tmp += c - '0';
			valid = 1;
		}
		else {
			valid = 0;
			break;
		}
	}
	*dst = tmp;
	return !valid;
}

#define cli_wait_ok_free_arg() \
do { \
	int n; \
	if (argv != NULL) { \
		for (n = 1; n < argc; n++) {\
			if (argv[n].type == (FGW_STR | FGW_DYN)) \
				free(argv[n].val.str); \
			argv[n].type = 0; \
		} \
		free(argv); \
		argv = NULL; \
	} \
	argp = argc = -1; \
	argv_alloced = 0; \
} while(0)

static int cli_wait_ok(cli_ctx_t *ctx, fgw_arg_t *ret)
{
	char buf[1024];
	int bl = 0;
	int argp = -1, argc = -1;
	int argv_alloced = 0;
	fgw_arg_t *argv = NULL;

	for(;;) {
		int c;

		/* read the command */
		c = cli_getc(ctx);
		if (cli_got_eof(ctx, c, errno))
			return -1;
		if (isspace(c)) {
			buf[bl] = '\0';
			if (buf[0] == '\0')
				continue;
			if ((buf[0] == 'o') && (buf[1] == 'k')) {
				if (ret != NULL) {
					fprintf(stderr, "cli_wait_ok(): got 'ok' while waiting for a function return\n");
					goto err;
				}
				goto done;
			}
			else if (strcmp(buf, "call_begin") == 0) {
				if (cli_read_fgw_int(ctx, &argc) != 0) {
					fprintf(stderr, "cli_wait_ok(): invalid call_beign argc: %s\n", buf+11);
					goto err;
				}
				if (argc > 1024) {
					fprintf(stderr, "cli_wait_ok(): argc too high: %s\n", buf+11);
					goto err;
				}
				if (argc > argv_alloced) {
					argv_alloced = argc;
					argv = realloc(argv, argv_alloced * sizeof(fgw_arg_t));
				}
				argp = 1;
				bl = 0;
			}
			else if (strcmp(buf, "call_arg") == 0) {
				if (argc < 0) {
					fprintf(stderr, "cli_wait_ok(): invalid call_arg without call_begin\n");
					goto err;
				}
				if (argp >= argc) {
					fprintf(stderr, "cli_wait_ok(): invalid call_arg: too many arguments\n");
					goto err;
				}
				cli_read_fgw_arg(ctx, &argv[argp]);
				argp++;
				bl = 0;
			}
			else if (strcmp(buf, "call_end") == 0) {
				fgw_arg_t fn, res;
				fgw_func_t *func;
				fgw_error_t ferr;

				if (argp != argc) {
					fprintf(stderr, "cli_wait_ok(): invalid call_end: number of args mismatch: %d != %d\n", argp, argc);
					goto err;
				}
				cli_read_fgw_arg(ctx, &fn);
				func = fgw_func_lookup(ctx->obj->parent, fn.val.str);
				if (func == NULL) {
					fprintf(stderr, "cli_wait_ok(): invalid call_end: unknown function '%s'\n", fn.val.str);
					free(fn.val.str);
					goto err;
				}
				free(fn.val.str);
				argv[0].type = FGW_FUNC;
				argv[0].val.argv0.func = func;
				argv[0].val.argv0.user_call_ctx = ctx->obj->script_user_call_ctx;

				res.type = FGW_PTR;
				res.val.ptr_void = NULL;
				ferr = func->func(&res, argc, argv);
				fgw_argv_free(ctx->obj->parent, argc, argv);
				cli_wait_ok_free_arg();
				if ((ferr == 0) && (fgw_arg_conv(ctx->obj->parent, &res, FGW_STR | FGW_DYN) == 0)) {
					cli_write(ctx, "retok ", 6);
					cli_write(ctx, res.val.str, strlen(res.val.str));
					cli_write(ctx, "\n", 1);
				}
				else
					cli_write(ctx, "retfail\n", 8);
				if (res.type == (FGW_STR | FGW_DYN))
					free(res.val.str);
				bl = 0;
			}
			else if (strcmp(buf, "retok") == 0) {
				if (ret == NULL) {
					fprintf(stderr, "cli_wait_ok(): got 'retok' while NOT waiting for a function return\n");
					goto err;
				}
				if (cli_read_fgw_arg(ctx, ret) < 0)
					goto err;
				goto done;
			}
			else if (strcmp(buf, "retfail") == 0) {
				if (ret == NULL) {
					fprintf(stderr, "cli_wait_ok(): got 'retfail' while NOT waiting for a function return\n");
					goto err;
				}
				goto ret1;
			}
			else if (strcmp(buf, "fgw_func_reg") == 0) {
				if (cli_read_fgw_func_reg(ctx, buf, sizeof(buf)) < 0)
					goto err;
				bl = 0;
			}
			else {
				fprintf(stderr, "cli_wait_ok(): Invalid request from the script: '%s'\n", buf);
				goto err;
			}
		}
		else {
			buf[bl] = c;
			bl++;
			if (bl >= sizeof(buf))
				goto err;
		}
	}

	done:;
	cli_wait_ok_free_arg();
	return 0;

	ret1:;
	cli_wait_ok_free_arg();
	return 1;

	err:;
	cli_wait_ok_free_arg();
	return -1;
}

/* API: register an fgw function in the script, make the function visible/callable */
static void fgws_cli_reg_func(fgw_obj_t *obj, const char *name, fgw_func_t *f)
{
	/* Do not register functions in the script, in script->c direction fgw calls
	   are wrapped due to syntax limitations. */
}

/* API: fgw calls a cli function */
static fgw_error_t fgws_cli_call_script(fgw_arg_t *res, int argc, fgw_arg_t *argv)
{
	fgw_obj_t *obj = argv[0].val.func->obj;
	cli_ctx_t *ctx = obj->script_data;
	int n, rv;

	res->type = FGW_PTR;
	res->val.ptr_void = NULL;

	fgws_ucc_save(obj);
	cli_printf(ctx, "call_begin %d\n", argc-1);
	for(n = 1; n < argc; n++) {
		cli_write(ctx, "call_arg ", 9);
		fgw_arg_conv(obj->parent, &argv[n], FGW_STR | FGW_DYN);
#warning TODO: protect against \n
		cli_write(ctx, argv[n].val.str, strlen(argv[n].val.str));
		cli_write(ctx, "\n", 1);
	}
	cli_printf(ctx, "call_end %s\n", argv[0].val.func->name);
	rv = cli_wait_ok(ctx, res);
	fgws_ucc_restore(obj);
	for (n = 1; n < argc; n++) {
		if (argv[n].type == (FGW_STR | FGW_DYN)) {
			argv[n].type = 0;
			free(argv[n].val.str);
		}
	}
	if (rv == 0)
		return FGW_SUCCESS;
	if (res->type == (FGW_STR | FGW_DYN)) {
		res->type = 0;
		free(res->val.str);
	}
	return FGW_ERR_UNKNOWN;
}

/* API: unload the script */
static int fgws_cli_unload(fgw_obj_t *obj)
{
	cli_ctx_t *ctx = obj->script_data;
	if ((ctx->running) && (ctx->pid > 1))
		kill(ctx->pid, SIGTERM);

	if (*ctx->scr_name != '\0')
		remove(ctx->scr_name);

	close(ctx->fd_c2s[0]);
	close(ctx->fd_c2s[1]);
	close(ctx->fd_s2c[0]);
	close(ctx->fd_s2c[1]);

	free(ctx);

	return 0;
}

/* API: init the interpreter so that functions can be registered */
static int fgws_cli_init(fgw_obj_t *obj, const char *filename, const char *opts)
{
	cli_ctx_t *ctx = malloc(sizeof(cli_ctx_t));

	obj->script_data = ctx;
	ctx->obj = obj;

	ctx->pid = -1;
	ctx->buf_fill = ctx->bufp = 0;
	*ctx->scr_name = '\0';

	if (pipe(ctx->fd_c2s) != 0) {
		free(ctx);
		return -1;
	}
	if (pipe(ctx->fd_s2c) != 0) {
		close(ctx->fd_c2s[0]);
		close(ctx->fd_c2s[1]);
		free(ctx);
		return -1;
	}
	return 0;
}

/* API: load a script into an object  */
static int fgws_cli_load(fgw_obj_t *obj, const char *filename, const char *opts)
{
	cli_ctx_t *ctx = obj->script_data;
	char shebang[2048], *shb, buf[1024];
	FILE *f;
	const fgws_cli_lang_t *l;
	int fd;

	/* figure language from shebang */
	f = fopen(filename, "r");
	if (f == NULL) {
		fprintf(stderr, "fgws_cli_load: can't open '%s' for read\n", filename);
		return -1;
	}
	shb = fgets(shebang, sizeof(shebang)-1, f);
	if (shb == NULL) {
		fprintf(stderr, "fgws_cli_load: unable to load shebang from %s\n", filename);
		fclose(f);
		return -1;
	}
	if ((shb[0] != '#') && (shb[0] != '!')) {
		fprintf(stderr, "fgws_cli_load: invalid shebang prefix in %s\n", filename);
		fclose(f);
		return -1;
	}
	shb+=2;
	while(isspace(*shb)) shb++;

	for(l = langs; l->name != NULL; l++)
		if (strncmp(l->shebang, shb, strlen(l->shebang)) == 0)
			break;

	if (l->name == NULL) {
		fprintf(stderr, "fgws_cli_load: unrecognized shebang in %s: '%s'\n", filename, shb);
		fclose(f);
		return -1;
	}

	/* write the temp file with header, script and footer */
	/* NOTE: tmpnam is the only portable way to do this; O_EXCL below should
	   guarantee it's safe. There's a worse, unavoidable race when we later
	   exec the interpreter on the file, by name. */
	if (tmpnam(ctx->scr_name) == NULL) {
		fprintf(stderr, "fgws_cli_load: failed to create temp file\n");
		fclose(f);
		return -1;
	}

	fd = open(ctx->scr_name, O_WRONLY | O_EXCL | O_CREAT, 0600);
	if (fd < 0) {
		fprintf(stderr, "fgws_cli_load: failed to create temp file '%s'\n", ctx->scr_name);
		fclose(f);
		return -1;
	}
	cli_write_(fd, l->head, strlen(l->head));
	while(!feof(f)) {
		int len = fread(buf, 1, sizeof(buf), f);
		if (len > 0)
			cli_write_(fd, buf, len);
	}
	cli_write_(fd, l->foot, strlen(l->foot));
	close(fd);
	fclose(f);

	/* fork and execute the interpreter */
	ctx->pid = fork();
	if (ctx->pid == 0) {
		int fd;
		/* child */
		close(ctx->fd_c2s[1]);
		close(ctx->fd_s2c[0]);

		if (ctx->fd_c2s[0] != 3) {
			close(3);
			fd = dup2(ctx->fd_c2s[0], 3);
			if (fd != 3) {
				fprintf(stderr, "Can't dup2 script input on fd 3: %d %s\n", fd, strerror(errno));
				exit(1);
			}
		}
		if (ctx->fd_s2c[1] != 4) {
			close(4);
			fd = dup2(ctx->fd_s2c[1], 4);
			if (fd != 4) {
				fprintf(stderr, "Can't dup2 script input on fd 4: %d\n", fd);
				exit(1);
			}
		}

		for(fd = 5; fd < 1024; fd++)
			close(fd);

		execl(l->shebang, l->execflag, ctx->scr_name, NULL);
		exit(1);
	}
	ctx->running = 1;
	close(ctx->fd_c2s[0]);
	close(ctx->fd_s2c[1]);

	cli_wait_ok(ctx, NULL);

	return 0;
}

static int fgws_cli_test_parse(const char *filename, FILE *f)
{
	const char *exts[] = {".sh", ".bash", NULL };
	const char *shebang[] = {"sh", "bash", "dash", NULL };

	if (f != NULL) {
		char line[128], *s;
		const char **sh;

		s = fgets(line, sizeof(line), f);
		if ((s != NULL) && (s[0] == '#') && (s[1] == '!')) {
			s += 2;
			while(isspace(*s)) s++;
			if (strncmp(s, "/usr", 4) == 0) s += 4;
			if (strncmp(s, "/opt", 4) == 0) s += 4;
			if (strncmp(s, "/local", 6) == 0) s += 6;
			if (strncmp(s, "/bin", 4) == 0) s += 4;
			for(sh = shebang; *sh != NULL; sh++)
				if (strncmp(*sh, s, strlen(*sh)) == 0)
					return 1;
		}
	}
	return fgw_test_parse_fn(filename, exts);
}

/* API: engine registration */
static const fgw_eng_t fgw_cli_eng = {
	"cli",
	fgws_cli_call_script,
	fgws_cli_init,
	fgws_cli_load,
	fgws_cli_unload,
	fgws_cli_reg_func,
	NULL,
	fgws_cli_test_parse,
	".sh"
};

int pplg_check_ver_fungw_cli(int version_we_need)
{
	return 0;
}

int pplg_init_fungw_cli(void)
{
	(void)sh_head; /* suppress warning on unised var */
	fgw_eng_reg(&fgw_cli_eng);
	return 0;
}

void pplg_uninit_fungw_cli(void)
{
	fgw_eng_unreg(fgw_cli_eng.name);
}