Merge branch 'refs/heads/t/ll'
[paraslash.git] / client.c
1 /* Copyright (C) 1997 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
2
3 /** \file client.c The client program used to connect to para_server. */
4
5 #include <regex.h>
6 #include <signal.h>
7 #include <lopsub.h>
8
9 #include "client.lsg.h"
10 #include "para.h"
11 #include "list.h"
12 #include "sched.h"
13 #include "crypt.h"
14 #include "string.h"
15 #include "stdin.h"
16 #include "stdout.h"
17 #include "client.h"
18 #include "buffer_tree.h"
19 #include "error.h"
20 #include "version.h"
21
22 /** Array of error strings. */
23 DEFINE_PARA_ERRLIST;
24
25 static struct sched sched;
26 static struct client_task *ct;
27 static struct stdin_task sit;
28 static struct stdout_task sot;
29
30 static int client_loglevel = LL_ERROR;
31 DEFINE_STDERR_LOGGER(stderr_log, client_loglevel);
32 __printf_2_3 void (*para_log)(int, const char*, ...) = stderr_log;
33
34 #ifdef HAVE_READLINE
35 #include "interactive.h"
36 #include "server_cmd.lsg.h"
37
38 struct exec_task {
39         struct task *task;
40         struct btr_node *btrn;
41         char *result_buf;
42         size_t result_size;
43 };
44
45 static void exec_pre_monitor(struct sched *s, void *context)
46 {
47         struct exec_task *et = context;
48         int ret = btr_node_status(et->btrn, 0, BTR_NT_LEAF);
49
50         if (ret != 0)
51                 sched_min_delay(s);
52 }
53
54 static int exec_post_monitor(__a_unused struct sched *s, void *context)
55 {
56         struct exec_task *et = context;
57         struct btr_node *btrn = et->btrn;
58         char *buf;
59         size_t sz;
60         int ret;
61
62         ret = btr_node_status(btrn, 0, BTR_NT_LEAF);
63         if (ret <= 0)
64                 return ret;
65         sz = btr_next_buffer(btrn, &buf);
66         if (sz <= 1)
67                 goto out;
68         et->result_buf = para_realloc(et->result_buf, et->result_size + sz - 1);
69         memcpy(et->result_buf + et->result_size - 1, buf, sz -  1);
70         et->result_size += sz - 1;
71         et->result_buf[et->result_size - 1] = '\0';
72 out:
73         btr_consume(btrn, sz);
74         return 0;
75 }
76
77 /* Called from the line handler and the completers. This overwrites ct->lpr. */
78 static int create_merged_lpr(const char *line)
79 {
80         const struct lls_command *cmd = CLIENT_CMD_PTR;
81         int argc, ret;
82         char *cmdline, **argv, *errctx;
83         struct lls_parse_result *argv_lpr;
84         static struct lls_parse_result *orig_lpr;
85
86         if (!orig_lpr)
87                 orig_lpr = ct->lpr;
88         ct->lpr = NULL;
89         cmdline = make_message("-- %s", line);
90         ret = create_shifted_argv(cmdline, " ", &argv);
91         free(cmdline);
92         if (ret < 0)
93                 return ret;
94         argc = ret;
95         if (argc == 2) { /* no words (only blanks in line) */
96                 free_argv(argv);
97                 return 0;
98         }
99         argv[0] = para_strdup("--");
100         /*
101          * The original lpr for the interactive session has no non-option
102          * arguments. We create a fresh lpr from the words in "line" and merge
103          * it with the original lpr.
104          */
105         ret = lls(lls_parse(argc, argv, cmd, &argv_lpr, &errctx));
106         free_argv(argv);
107         if (ret < 0)
108                 goto fail;
109         ret = lls(lls_merge(orig_lpr, argv_lpr, cmd, &ct->lpr, &errctx));
110         lls_free_parse_result(argv_lpr, cmd);
111         if (ret < 0)
112                 goto fail;
113         return 1;
114 fail:
115         if (errctx)
116                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
117         free(errctx);
118         assert(ret < 0);
119         return ret;
120 }
121
122 /* called from completers */
123 static int execute_client_command(const char *cmd, char **result)
124 {
125         int ret;
126         struct sched command_sched = {.default_timeout = 1000};
127         struct exec_task exec_task = {
128                 .result_buf = para_strdup(""),
129                 .result_size = 1,
130         };
131         struct lls_parse_result *old_lpr = ct->lpr;
132
133         *result = NULL;
134         ret = create_merged_lpr(cmd);
135         if (ret <= 0)
136                 goto out;
137         exec_task.btrn = btr_new_node(&(struct btr_node_description)
138                 EMBRACE(.name = "exec_collect"));
139         exec_task.task = task_register(&(struct task_info) {
140                 .name = "client exec",
141                 .pre_monitor = exec_pre_monitor,
142                 .post_monitor = exec_post_monitor,
143                 .context = &exec_task,
144         }, &command_sched);
145         ret = client_connect(ct, &command_sched, NULL, exec_task.btrn);
146         if (ret < 0)
147                 goto out;
148         schedule(&command_sched);
149         sched_shutdown(&command_sched);
150         lls_free_parse_result(ct->lpr, CLIENT_CMD_PTR);
151         ct->lpr = old_lpr;
152         *result = exec_task.result_buf;
153         btr_remove_node(&exec_task.btrn);
154         ret = 1;
155 out:
156         btr_remove_node(&exec_task.btrn);
157         if (ret < 0)
158                 free(exec_task.result_buf);
159         return ret;
160 }
161
162 static int extract_matches_from_command(const char *word, char *cmd,
163                 char ***matches)
164 {
165         char *buf, **sl;
166         int ret;
167
168         ret = execute_client_command(cmd, &buf);
169         if (ret < 0)
170                 return ret;
171         ret = create_argv(buf, "\n", &sl);
172         free(buf);
173         if (ret < 0)
174                 return ret;
175         ret = i9e_extract_completions(word, sl, matches);
176         free_argv(sl);
177         return ret;
178 }
179
180 static int complete_attributes(const char *word, char ***matches)
181 {
182         return extract_matches_from_command(word, "lsatt", matches);
183 }
184
185 static void complete_addblob(__a_unused const char *blob_type,
186                 __a_unused struct i9e_completion_info *ci,
187                 __a_unused struct i9e_completion_result *cr)
188 {
189         cr->filename_completion_desired = true;
190 }
191
192 static void generic_blob_complete(const char *blob_type,
193                 struct i9e_completion_info *ci,
194                 struct i9e_completion_result *cr)
195 {
196         char cmd[20];
197         sprintf(cmd, "ls%s", blob_type);
198         extract_matches_from_command(ci->word, cmd, &cr->matches);
199 }
200
201 static void complete_catblob(const char *blob_type,
202                 struct i9e_completion_info *ci,
203                 struct i9e_completion_result *cr)
204 {
205         generic_blob_complete(blob_type, ci, cr);
206 }
207
208 static void complete_lsblob(const char *blob_type,
209                 struct i9e_completion_info *ci,
210                 struct i9e_completion_result *cr)
211 {
212         char *opts[] = {LSG_SERVER_CMD_LSIMG_OPTS, NULL};
213
214         if (ci->word[0] == '-')
215                 return i9e_complete_option(opts, ci, cr);
216         generic_blob_complete(blob_type, ci, cr);
217 }
218
219 static void complete_rmblob(const char *blob_type,
220                 struct i9e_completion_info *ci,
221                 struct i9e_completion_result *cr)
222 {
223         generic_blob_complete(blob_type, ci, cr);
224 }
225
226 static void complete_mvblob(const char *blob_type,
227                 struct i9e_completion_info *ci,
228                 struct i9e_completion_result *cr)
229 {
230         generic_blob_complete(blob_type, ci, cr);
231 }
232
233 /* these don't need any completions */
234 I9E_DUMMY_COMPLETER(ff);
235 I9E_DUMMY_COMPLETER(hup);
236 I9E_DUMMY_COMPLETER(jmp);
237 I9E_DUMMY_COMPLETER(next);
238 I9E_DUMMY_COMPLETER(nomore);
239 I9E_DUMMY_COMPLETER(pause);
240 I9E_DUMMY_COMPLETER(play);
241 I9E_DUMMY_COMPLETER(si);
242 I9E_DUMMY_COMPLETER(term);
243 I9E_DUMMY_COMPLETER(stop);
244 I9E_DUMMY_COMPLETER(addatt);
245 I9E_DUMMY_COMPLETER(init);
246
247 static struct i9e_completer completers[];
248
249 static void ll_completer(struct i9e_completion_info *ci,
250                 struct i9e_completion_result *cr)
251 {
252         i9e_ll_completer(ci, cr);
253 }
254
255 static void help_completer(struct i9e_completion_info *ci,
256                 struct i9e_completion_result *cr)
257 {
258         char *opts[] = {LSG_SERVER_CMD_HELP_OPTS, NULL};
259
260         if (ci->word[0] == '-') {
261                 i9e_complete_option(opts, ci, cr);
262                 return;
263         }
264         cr->matches = i9e_complete_commands(ci->word, completers);
265 }
266
267 static void stat_completer(struct i9e_completion_info *ci,
268                 struct i9e_completion_result *cr)
269 {
270         char *opts[] = {LSG_SERVER_CMD_STAT_OPTS, NULL};
271         i9e_complete_option(opts, ci, cr);
272 }
273
274 static void version_completer(struct i9e_completion_info *ci,
275                 struct i9e_completion_result *cr)
276 {
277         char *opts[] = {LSG_SERVER_CMD_VERSION_OPTS, NULL};
278         i9e_complete_option(opts, ci, cr);
279 }
280
281 static void sender_completer(struct i9e_completion_info *ci,
282                 struct i9e_completion_result *cr)
283 {
284         char *senders[] = {"http", "dccp", "udp", NULL};
285         char *http_cmds[] = {"on", "off", "allow", "deny", "help", NULL};
286         char *dccp_cmds[] = {"on", "off", "allow", "deny", "help", NULL};
287         char *udp_cmds[] ={"on", "off", "add", "delete", "help", NULL};
288         char *sender;
289         char **cmds;
290
291         //PARA_CRIT_LOG("wn: %d\n", ci->word_num);
292         if (ci->word_num == 0 || ci->word_num > 3)
293                 return;
294         if (ci->word_num == 1 || (ci->word_num == 2 && *ci->word != '\0')) {
295                 i9e_extract_completions(ci->word, senders, &cr->matches);
296                 return;
297         }
298         sender = ci->argv[1];
299         //PARA_CRIT_LOG("sender: %s\n", sender);
300         if (strcmp(sender, "http") == 0)
301                 cmds = http_cmds;
302         else if (strcmp(sender, "dccp") == 0)
303                 cmds = dccp_cmds;
304         else if (strcmp(sender, "udp") == 0)
305                 cmds = udp_cmds;
306         else
307                 return;
308         i9e_extract_completions(ci->word, cmds, &cr->matches);
309 }
310
311 static void add_completer(struct i9e_completion_info *ci,
312                 struct i9e_completion_result *cr)
313 {
314         char *opts[] = {LSG_SERVER_CMD_ADD_OPTS, NULL};
315
316         if (ci->word[0] == '-')
317                 i9e_complete_option(opts, ci, cr);
318         cr->filename_completion_desired = true;
319 }
320
321 static void ls_completer(struct i9e_completion_info *ci,
322                 struct i9e_completion_result *cr)
323 {
324         char *opts[] = {LSG_SERVER_CMD_LS_OPTS, NULL};
325         if (ci->word[0] == '-')
326                 i9e_complete_option(opts, ci, cr);
327         cr->filename_completion_desired = true;
328 }
329
330 static void setatt_completer(struct i9e_completion_info *ci,
331                 struct i9e_completion_result *cr)
332 {
333         char *buf, **sl;
334         int i, ret, num_atts;
335
336         if (ci->word_num == 0)
337                 return;
338
339         if (*ci->word == '/' || *ci->word == '\0')
340                 cr->filename_completion_desired = true;
341         if (*ci->word == '/')
342                 return;
343         ret = execute_client_command("lsatt", &buf);
344         if (ret < 0)
345                 return;
346         ret = create_argv(buf, "\n", &sl);
347         if (ret < 0)
348                 goto out;
349         num_atts = ret;
350         sl = para_realloc(sl, (2 * num_atts + 1) * sizeof(char *));
351         for (i = 0; i < num_atts; i++) {
352                 char *orig = sl[i];
353                 sl[i] = make_message("%s+", orig);
354                 sl[num_atts + i] = make_message("%s-", orig);
355                 free(orig);
356         }
357         sl[2 * num_atts] = NULL;
358         i9e_extract_completions(ci->word, sl, &cr->matches);
359 out:
360         free(buf);
361         free_argv(sl);
362 }
363
364 static void lsatt_completer(struct i9e_completion_info *ci,
365                 struct i9e_completion_result *cr)
366 {
367         char *opts[] = {LSG_SERVER_CMD_LSATT_OPTS, NULL};
368         i9e_complete_option(opts, ci, cr);
369 }
370
371 static void mvatt_completer(struct i9e_completion_info *ci,
372                 struct i9e_completion_result *cr)
373 {
374         complete_attributes(ci->word, &cr->matches);
375 }
376
377 static void rmatt_completer(struct i9e_completion_info *ci,
378                 struct i9e_completion_result *cr)
379 {
380         complete_attributes(ci->word, &cr->matches);
381 }
382
383 static void check_completer(struct i9e_completion_info *ci,
384                 struct i9e_completion_result *cr)
385 {
386         char *opts[] = {LSG_SERVER_CMD_CHECK_OPTS, NULL};
387         i9e_complete_option(opts, ci, cr);
388 }
389
390 static void rm_completer(struct i9e_completion_info *ci,
391                 struct i9e_completion_result *cr)
392 {
393         char *opts[] = {LSG_SERVER_CMD_RM_OPTS, NULL};
394
395         if (ci->word[0] == '-') {
396                 i9e_complete_option(opts, ci, cr);
397                 return;
398         }
399         cr->filename_completion_desired = true;
400 }
401
402 static void touch_completer(struct i9e_completion_info *ci,
403                 struct i9e_completion_result *cr)
404 {
405         char *opts[] = {LSG_SERVER_CMD_TOUCH_OPTS, NULL};
406
407         if (ci->word[0] == '-')
408                 i9e_complete_option(opts, ci, cr);
409         cr->filename_completion_desired = true;
410 }
411
412 static void cpsi_completer(struct i9e_completion_info *ci,
413                 struct i9e_completion_result *cr)
414 {
415         char *opts[] = {LSG_SERVER_CMD_CPSI_OPTS, NULL};
416
417         if (ci->word[0] == '-')
418                 i9e_complete_option(opts, ci, cr);
419         cr->filename_completion_desired = true;
420 }
421
422 static void select_completer(struct i9e_completion_info *ci,
423                 struct i9e_completion_result *cr)
424 {
425         char *mood_buf, *pl_buf, **moods, **playlists, **mops;
426         int num_moods, num_pl, i, n, ret;
427
428         ret = execute_client_command("lsmood", &mood_buf);
429         if (ret < 0)
430                 return;
431         ret = execute_client_command("lspl", &pl_buf);
432         if (ret < 0)
433                 goto free_mood_buf;
434
435         ret = create_argv(mood_buf, "\n", &moods);
436         if (ret < 0)
437                 goto free_pl_buf;
438         num_moods = ret;
439         ret = create_argv(pl_buf, "\n", &playlists);
440         if (ret < 0)
441                 goto free_moods;
442         num_pl = ret;
443         n = num_moods + num_pl;
444         mops = para_malloc((n + 1) * sizeof(char *));
445         for (i = 0; i < num_moods; i++)
446                 mops[i] = make_message("m/%s", moods[i]);
447         for (i = 0; i < num_pl; i++)
448                 mops[num_moods + i] = make_message("p/%s", playlists[i]);
449         mops[n] = NULL;
450         i9e_extract_completions(ci->word, mops, &cr->matches);
451         free_argv(mops);
452         free_argv(playlists);
453 free_moods:
454         free_argv(moods);
455 free_pl_buf:
456         free(pl_buf);
457 free_mood_buf:
458         free(mood_buf);
459 }
460
461 #define DEFINE_BLOB_COMPLETER(cmd, blob_type) \
462         static void cmd ## blob_type ## _completer( \
463                 struct i9e_completion_info *ci, \
464                 struct i9e_completion_result *cr) \
465         {complete_ ## cmd ## blob(#blob_type, ci, cr);}
466
467 DEFINE_BLOB_COMPLETER(add, mood)
468 DEFINE_BLOB_COMPLETER(add, lyr)
469 DEFINE_BLOB_COMPLETER(add, img)
470 DEFINE_BLOB_COMPLETER(add, pl)
471 DEFINE_BLOB_COMPLETER(cat, mood)
472 DEFINE_BLOB_COMPLETER(cat, lyr)
473 DEFINE_BLOB_COMPLETER(cat, img)
474 DEFINE_BLOB_COMPLETER(cat, pl)
475 DEFINE_BLOB_COMPLETER(ls, mood)
476 DEFINE_BLOB_COMPLETER(ls, lyr)
477 DEFINE_BLOB_COMPLETER(ls, img)
478 DEFINE_BLOB_COMPLETER(ls, pl)
479 DEFINE_BLOB_COMPLETER(rm, mood)
480 DEFINE_BLOB_COMPLETER(rm, lyr)
481 DEFINE_BLOB_COMPLETER(rm, img)
482 DEFINE_BLOB_COMPLETER(rm, pl)
483 DEFINE_BLOB_COMPLETER(mv, mood)
484 DEFINE_BLOB_COMPLETER(mv, lyr)
485 DEFINE_BLOB_COMPLETER(mv, img)
486 DEFINE_BLOB_COMPLETER(mv, pl)
487
488 static int client_i9e_line_handler(char *line)
489 {
490         int ret;
491         static bool first = true;
492
493         if (first)
494                 first = false;
495         else
496                 lls_free_parse_result(ct->lpr, CLIENT_CMD_PTR);
497         ret = create_merged_lpr(line);
498         if (ret <= 0)
499                 return ret;
500         ret = client_connect(ct, &sched, NULL, NULL);
501         if (ret < 0)
502                 return ret;
503         i9e_attach_to_stdout(ct->btrn[0]);
504         return 1;
505 }
506
507 static struct i9e_completer completers[] = {
508 #define LSG_SERVER_CMD_CMD(_name) {.name = #_name, \
509         .completer = _name ## _completer}
510         LSG_SERVER_CMD_SUBCOMMANDS
511 #undef LSG_SERVER_CMD_CMD
512         {.name = NULL}
513 };
514
515 __noreturn static void interactive_session(void)
516 {
517         int ret;
518         struct sigaction act;
519         struct i9e_client_info ici = {
520                 .fds = {0, 1, 2},
521                 .prompt = "para_client> ",
522                 .line_handler = client_i9e_line_handler,
523                 .loglevel = client_loglevel,
524                 .completers = completers,
525         };
526
527         PARA_NOTICE_LOG("\n%s\n", version_text("client"));
528         if (CLIENT_OPT_GIVEN(HISTORY_FILE, ct->lpr))
529                 ici.history_file = para_strdup(CLIENT_OPT_STRING_VAL(
530                         HISTORY_FILE, ct->lpr));
531         else {
532                 char *home = para_homedir();
533                 ici.history_file = make_message("%s/.paraslash/client.history",
534                         home);
535                 free(home);
536         }
537         act.sa_handler = i9e_signal_dispatch;
538         sigemptyset(&act.sa_mask);
539         act.sa_flags = 0;
540         sigaction(SIGINT, &act, NULL);
541         sched.poll_function = i9e_poll;
542
543         ret = i9e_open(&ici, &sched);
544         if (ret < 0)
545                 goto out;
546         para_log = i9e_log;
547         ret = schedule(&sched);
548         sched_shutdown(&sched);
549         i9e_close();
550         para_log = stderr_log;
551 out:
552         if (ret < 0)
553                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
554         exit(ret < 0? EXIT_FAILURE : EXIT_SUCCESS);
555         //client_close(ct);
556 }
557
558 __noreturn static void print_completions(void)
559 {
560         int ret;
561
562         ret = i9e_print_completions(completers);
563         exit(ret <= 0? EXIT_FAILURE : EXIT_SUCCESS);
564 }
565
566 #else /* HAVE_READLINE */
567
568 __noreturn static void interactive_session(void)
569 {
570         PARA_EMERG_LOG("interactive sessions not available\n");
571         exit(EXIT_FAILURE);
572 }
573
574 __noreturn static void print_completions(void)
575 {
576         PARA_EMERG_LOG("command completion not available\n");
577         exit(EXIT_FAILURE);
578 }
579
580 #endif /* HAVE_READLINE */
581
582 struct supervisor_task {
583         bool stdout_task_started;
584         struct task *task;
585 };
586
587 static int supervisor_post_monitor(struct sched *s, void *context)
588 {
589         struct supervisor_task *svt = context;
590         int ret = task_status(ct->task);
591
592         if (ret < 0)
593                 return ret;
594         if (!svt->stdout_task_started && ct->status == CL_EXECUTING) {
595                 stdout_task_register(&sot, s);
596                 svt->stdout_task_started = true;
597                 return 1;
598         }
599         if (ct->status == CL_SENDING) {
600                 stdin_task_register(&sit, s);
601                 return -E_TASK_STARTED;
602         }
603         return 0;
604 }
605
606 static struct supervisor_task supervisor_task;
607
608 /**
609  * The client program to connect to para_server.
610  *
611  * \param argc Usual argument count.
612  * \param argv Usual argument vector.
613  *
614  * When called without a paraslash command, an interactive session is started.
615  * Otherwise, the client task and the supervisor task are started. The former
616  * communicates with para_server while the latter monitors whether the client
617  * task intends to read from stdin or write to stdout.
618  *
619  * Once it has been determined whether the client command corresponds to a
620  * stdin command (addmood, addimg, ..), either the stdin task or the stdout
621  * task is set up to replace the supervisor task.
622  *
623  * \return EXIT_SUCCESS or EXIT_FAILURE
624  *
625  * \sa \ref client_open(), \ref stdin.c, \ref stdout.c, para_client(1),
626  * para_server(1).
627  */
628 int main(int argc, char *argv[])
629 {
630         int ret;
631
632         crypt_init();
633         sched.default_timeout = 1000;
634
635         ret = client_parse_config(argc, argv, &ct, &client_loglevel);
636         if (ret < 0)
637                 goto out;
638         if (CLIENT_OPT_GIVEN(COMPLETE, ct->lpr))
639                 print_completions();
640         if (ret == 0)
641                 interactive_session(); /* does not return */
642
643         /*
644          * We add buffer tree nodes for stdin and stdout even though
645          * only one of them will be needed. This simplifies the code
646          * a bit wrt. to the buffer tree setup.
647          */
648         sit.btrn = btr_new_node(&(struct btr_node_description)
649                 EMBRACE(.name = "stdin"));
650         ret = client_connect(ct, &sched, sit.btrn, NULL);
651         if (ret < 0)
652                 goto out;
653         sot.btrn = btr_new_node(&(struct btr_node_description)
654                 EMBRACE(.name = "stdout", .parent = ct->btrn[0]));
655         supervisor_task.task = task_register(&(struct task_info) {
656                 .name = "supervisor",
657                 .post_monitor = supervisor_post_monitor,
658                 .context = &supervisor_task,
659         }, &sched);
660
661         ret = schedule(&sched);
662         if (ret >= 0) {
663                 ret = task_status(ct->task);
664                 if (ret < 0) {
665                         switch (ret) {
666                         /* these are not errors */
667                         case -E_SERVER_CMD_SUCCESS:
668                         case -E_EOF:
669                         case -E_SERVER_EOF:
670                         case -E_BTR_EOF:
671                                 ret = 0;
672                                 break;
673                         default: ret = -E_SERVER_CMD_FAILURE;
674                         }
675                 }
676         }
677         sched_shutdown(&sched);
678         crypt_shutdown();
679 out:
680         if (ret < 0)
681                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
682         client_close(ct);
683         btr_remove_node(&sit.btrn);
684         btr_remove_node(&sot.btrn);
685         return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;
686 }