opus_afh: Use custom header API to strip comment packet.
[paraslash.git] / client_common.c
1 /*
2  * Copyright (C) 1997 Andre Noll <maan@tuebingen.mpg.de>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file client_common.c Common functions of para_client and para_audiod. */
8
9 #include <netinet/in.h>
10 #include <sys/socket.h>
11 #include <regex.h>
12 #include <sys/types.h>
13 #include <arpa/inet.h>
14 #include <sys/un.h>
15 #include <netdb.h>
16 #include <lopsub.h>
17
18 #include "client.lsg.h"
19 #include "para.h"
20 #include "error.h"
21 #include "list.h"
22 #include "sched.h"
23 #include "crypt.h"
24 #include "net.h"
25 #include "fd.h"
26 #include "sideband.h"
27 #include "string.h"
28 #include "client.h"
29 #include "buffer_tree.h"
30 #include "version.h"
31
32 /** The size of the receiving buffer. */
33 #define CLIENT_BUFSIZE 4000
34
35 /**
36  * Close the connection to para_server and free all resources.
37  *
38  * \param ct Pointer to the client data.
39  *
40  * \sa \ref client_open().
41  */
42 void client_close(struct client_task *ct)
43 {
44         if (!ct)
45                 return;
46         free(ct->user);
47         free(ct->config_file);
48         free(ct->key_file);
49         lls_free_parse_result(ct->lpr, CLIENT_CMD_PTR);
50         free(ct->challenge_hash);
51         sb_free(ct->sbc[0]);
52         sb_free(ct->sbc[1]);
53         free(ct);
54 }
55
56 /*
57  * The preselect hook for server commands.
58  *
59  * The task pointer must contain a pointer to the initialized client data
60  * structure as it is returned by client_open().
61  *
62  * This function checks the state of the connection and adds the file descriptor
63  * of the connection to the read or write fd set of s accordingly.
64  */
65 static void client_pre_select(struct sched *s, void *context)
66 {
67         int ret;
68         struct client_task *ct = context;
69
70         if (ct->scc.fd < 0)
71                 return;
72         switch (ct->status) {
73         case CL_CONNECTED:
74         case CL_SENT_AUTH:
75         case CL_SENT_CH_RESPONSE:
76                 para_fd_set(ct->scc.fd, &s->rfds, &s->max_fileno);
77                 return;
78
79         case CL_RECEIVED_WELCOME:
80         case CL_RECEIVED_PROCEED:
81         case CL_RECEIVED_CHALLENGE:
82                 para_fd_set(ct->scc.fd, &s->wfds, &s->max_fileno);
83                 return;
84
85         case CL_SENDING:
86                 if (ct->btrn[1]) {
87                         ret = btr_node_status(ct->btrn[1], 0, BTR_NT_LEAF);
88                         if (ret < 0)
89                                 sched_min_delay(s);
90                         else if (ret > 0)
91                                 para_fd_set(ct->scc.fd, &s->wfds, &s->max_fileno);
92                 }
93                 /* fallthrough */
94         case CL_EXECUTING:
95                 if (ct->btrn[0]) {
96                         ret = btr_node_status(ct->btrn[0], 0, BTR_NT_ROOT);
97                         if (ret < 0)
98                                 sched_min_delay(s);
99                         else if (ret > 0)
100                                 para_fd_set(ct->scc.fd, &s->rfds, &s->max_fileno);
101                 }
102                 return;
103         }
104 }
105
106 static int send_sb(struct client_task *ct, int channel, void *buf, size_t numbytes,
107                 enum sb_designator band, bool dont_free)
108 {
109         int ret, fd = ct->scc.fd;
110         struct iovec iov[2];
111
112         if (!ct->sbc[channel]) {
113                 struct sb_buffer sbb;
114                 sb_transformation trafo = ct->status < CL_RECEIVED_PROCEED?
115                         NULL : sc_trafo;
116                 sbb = (typeof(sbb))SBB_INIT(band, buf, numbytes);
117                 ct->sbc[channel] = sb_new_send(&sbb, dont_free, trafo, ct->scc.send);
118         }
119         ret = sb_get_send_buffers(ct->sbc[channel], iov);
120         ret = xwritev(fd, iov, ret);
121         if (ret < 0) {
122                 sb_free(ct->sbc[channel]);
123                 ct->sbc[channel] = NULL;
124                 return ret;
125         }
126         if (sb_sent(ct->sbc[channel], ret)) {
127                 ct->sbc[channel] = NULL;
128                 return 1;
129         }
130         return 0;
131 }
132
133 static int recv_sb(struct client_task *ct, fd_set *rfds,
134                 struct sb_buffer *result)
135 {
136         int ret;
137         size_t n;
138         sb_transformation trafo;
139         void *trafo_context;
140         struct iovec iov;
141
142         if (!FD_ISSET(ct->scc.fd, rfds))
143                 return 0;
144         if (ct->status < CL_SENT_CH_RESPONSE)
145                 trafo = trafo_context = NULL;
146         else {
147                 trafo = sc_trafo;
148                 trafo_context = ct->scc.recv;
149         }
150         if (!ct->sbc[0])
151                 ct->sbc[0] = sb_new_recv(0, trafo, trafo_context);
152 again:
153         sb_get_recv_buffer(ct->sbc[0], &iov);
154         ret = read_nonblock(ct->scc.fd, iov.iov_base, iov.iov_len, rfds, &n);
155         if (ret < 0) {
156                 sb_free(ct->sbc[0]);
157                 ct->sbc[0] = NULL;
158                 return ret;
159         }
160         if (n == 0)
161                 return 0;
162         ret = sb_received(ct->sbc[0], n, result);
163         if (ret < 0)
164                 return ret;
165         if (ret == 0)
166                 goto again;
167         ct->sbc[0] = NULL;
168         return 1;
169 }
170
171
172 static char **parse_features(char *buf)
173 {
174         int i;
175         const char id[] = "\nFeatures: ";
176         char *p, *q, **features;
177
178         p = strstr(buf, id);
179         if (!p)
180                 return NULL;
181         p += strlen(id);
182         q = strchr(p, '\n');
183         if (!q)
184                 return NULL;
185         *q = '\0';
186         create_argv(p, ",", &features);
187         for (i = 0; features[i]; i++)
188                 PARA_INFO_LOG("server feature: %s\n", features[i]);
189         return features;
190 }
191
192 static int dispatch_sbb(struct client_task *ct, struct sb_buffer *sbb)
193 {
194         int ret;
195         const char *designator[] = {SB_DESIGNATORS_ARRAY};
196
197         if (!sbb)
198                 return 0;
199         if (sbb->band < NUM_SB_DESIGNATORS)
200                 PARA_DEBUG_LOG("band: %s\n", designator[sbb->band]);
201
202         switch (sbb->band) {
203         case SBD_AWAITING_DATA:
204                 ct->status = CL_SENDING;
205                 ret = 1;
206                 goto out;
207         case SBD_OUTPUT:
208                 if (iov_valid(&sbb->iov))
209                         btr_add_output(sbb->iov.iov_base, sbb->iov.iov_len,
210                                 ct->btrn[0]);
211                 ret = 1;
212                 goto out;
213         case SBD_DEBUG_LOG:
214         case SBD_INFO_LOG:
215         case SBD_NOTICE_LOG:
216         case SBD_WARNING_LOG:
217         case SBD_ERROR_LOG:
218         case SBD_CRIT_LOG:
219         case SBD_EMERG_LOG:
220                 if (iov_valid(&sbb->iov)) {
221                         int ll = sbb->band - SBD_DEBUG_LOG;
222                         para_log(ll, "remote: %s", (char *)sbb->iov.iov_base);
223                 }
224                 ret = 1;
225                 goto deallocate;
226         case SBD_EXIT__SUCCESS:
227                 ret = -E_SERVER_CMD_SUCCESS;
228                 goto deallocate;
229         case SBD_EXIT__FAILURE:
230                 ret = -E_SERVER_CMD_FAILURE;
231                 goto deallocate;
232         default:
233                 PARA_ERROR_LOG("invalid band %d\n", sbb->band);
234                 ret = -E_BAD_BAND;
235                 goto deallocate;
236         }
237 deallocate:
238         free(sbb->iov.iov_base);
239 out:
240         sbb->iov.iov_base = NULL;
241         return ret;
242 }
243
244 static int send_sb_command(struct client_task *ct)
245 {
246         int i;
247         char *command, *p;
248         size_t len = 0;
249         unsigned num_inputs = lls_num_inputs(ct->lpr);
250
251         if (ct->sbc[1])
252                 return send_sb(ct, 0, NULL, 0, 0, false);
253
254         for (i = 0; i < num_inputs; i++)
255                 len += strlen(lls_input(i, ct->lpr)) + 1;
256         p = command = para_malloc(len);
257         for (i = 0; i < num_inputs; i++) {
258                 const char *str = lls_input(i, ct->lpr);
259                 strcpy(p, str);
260                 p += strlen(str) + 1;
261         }
262         PARA_DEBUG_LOG("--> %s\n", command);
263         return send_sb(ct, 0, command, len, SBD_COMMAND, false);
264 }
265
266 /*
267  * The post select hook for client commands.
268  *
269  * Depending on the current state of the connection and the status of the read
270  * and write fd sets of s, this function performs the necessary steps to
271  * authenticate the connection, to send the command given by t->private_data
272  * and to receive para_server's output, if any.
273  */
274 static int client_post_select(struct sched *s, void *context)
275 {
276         struct client_task *ct = context;
277         int ret = 0;
278         size_t n;
279         char buf[CLIENT_BUFSIZE];
280
281         ret = task_get_notification(ct->task);
282         if (ret < 0)
283                 goto out;
284         if (ct->scc.fd < 0)
285                 return 0;
286         switch (ct->status) {
287         case CL_CONNECTED: /* receive welcome message */
288                 ret = read_nonblock(ct->scc.fd, buf, sizeof(buf), &s->rfds, &n);
289                 if (ret < 0 || n == 0)
290                         goto out;
291                 ct->features = parse_features(buf);
292                 ct->status = CL_RECEIVED_WELCOME;
293                 return 0;
294         case CL_RECEIVED_WELCOME: /* send auth command */
295                 if (!FD_ISSET(ct->scc.fd, &s->wfds))
296                         return 0;
297                 sprintf(buf, AUTH_REQUEST_MSG "%s sideband,aes_ctr128",
298                         ct->user);
299                 PARA_INFO_LOG("--> %s\n", buf);
300                 ret = write_buffer(ct->scc.fd, buf);
301                 if (ret < 0)
302                         goto out;
303                 ct->status = CL_SENT_AUTH;
304                 return 0;
305         case CL_SENT_AUTH:
306                 /*
307                  * Receive challenge and session keys, decrypt the challenge and
308                  * send back the hash of the decrypted challenge.
309                  */
310                 {
311                 /* decrypted challenge/session key buffer */
312                 unsigned char crypt_buf[1024];
313                 struct sb_buffer sbb;
314
315                 ret = recv_sb(ct, &s->rfds, &sbb);
316                 if (ret <= 0)
317                         goto out;
318                 if (sbb.band != SBD_CHALLENGE) {
319                         ret = -E_BAD_BAND;
320                         free(sbb.iov.iov_base);
321                                 goto out;
322                 }
323                 n = sbb.iov.iov_len;
324                 PARA_INFO_LOG("<-- [challenge] (%zu bytes)\n", n);
325                 ret = priv_decrypt(ct->key_file, crypt_buf,
326                         sbb.iov.iov_base, n);
327                 free(sbb.iov.iov_base);
328                 if (ret < 0)
329                         goto out;
330                 ct->challenge_hash = para_malloc(HASH_SIZE);
331                 hash_function((char *)crypt_buf, CHALLENGE_SIZE, ct->challenge_hash);
332                 ct->scc.send = sc_new(crypt_buf + CHALLENGE_SIZE, SESSION_KEY_LEN);
333                 ct->scc.recv = sc_new(crypt_buf + CHALLENGE_SIZE + SESSION_KEY_LEN,
334                         SESSION_KEY_LEN);
335                 hash_to_asc(ct->challenge_hash, buf);
336                 PARA_INFO_LOG("--> %s\n", buf);
337                 ct->status = CL_RECEIVED_CHALLENGE;
338                 return 0;
339                 }
340         case CL_RECEIVED_CHALLENGE:
341                 ret = send_sb(ct, 0, ct->challenge_hash, HASH_SIZE,
342                         SBD_CHALLENGE_RESPONSE, false);
343                 if (ret != 0)
344                         ct->challenge_hash = NULL;
345                 if (ret <= 0)
346                         goto out;
347                 ct->status = CL_SENT_CH_RESPONSE;
348                 goto out;
349         case CL_SENT_CH_RESPONSE: /* read server response */
350                 {
351                 struct sb_buffer sbb;
352                 ret = recv_sb(ct, &s->rfds, &sbb);
353                 if (ret <= 0)
354                         goto out;
355                 free(sbb.iov.iov_base);
356                 if (sbb.band != SBD_PROCEED)
357                         ret = -E_BAD_BAND;
358                 else
359                         ct->status = CL_RECEIVED_PROCEED;
360                 goto out;
361                 }
362         case CL_RECEIVED_PROCEED: /* concat args and send command */
363                 {
364                 if (!FD_ISSET(ct->scc.fd, &s->wfds))
365                         return 0;
366                 ret = send_sb_command(ct);
367                 if (ret <= 0)
368                         goto out;
369                 ct->status = CL_EXECUTING;
370                 return 0;
371                 }
372         case CL_SENDING:
373                 if (ct->btrn[1]) {
374                         char *buf2;
375                         size_t sz;
376                         ret = btr_node_status(ct->btrn[1], 0, BTR_NT_LEAF);
377                         if (ret == -E_BTR_EOF) {
378                                 /* empty blob data packet indicates EOF */
379                                 PARA_INFO_LOG("blob sent\n");
380                                 ret = send_sb(ct, 1, NULL, 0, SBD_BLOB_DATA, true);
381                                 if (ret >= 0)
382                                         ret = -E_BTR_EOF;
383                         }
384                         if (ret < 0)
385                                 goto close1;
386                         if (ret > 0 && FD_ISSET(ct->scc.fd, &s->wfds)) {
387                                 sz = btr_next_buffer(ct->btrn[1], &buf2);
388                                 assert(sz);
389                                 ret = send_sb(ct, 1, buf2, sz, SBD_BLOB_DATA, true);
390                                 if (ret < 0)
391                                         goto close1;
392                                 if (ret > 0)
393                                         btr_consume(ct->btrn[1], sz);
394                         }
395                 }
396                 /* fall through */
397         case CL_EXECUTING:
398                 if (ct->btrn[0]) {
399                         ret = btr_node_status(ct->btrn[0], 0, BTR_NT_ROOT);
400                         if (ret < 0)
401                                 goto close0;
402                         if (ret > 0 && FD_ISSET(ct->scc.fd, &s->rfds)) {
403                                 struct sb_buffer sbb;
404                                 ret = recv_sb(ct, &s->rfds, &sbb);
405                                 if (ret < 0)
406                                         goto close0;
407                                 if (ret > 0) {
408                                         ret = dispatch_sbb(ct, &sbb);
409                                         if (ret < 0)
410                                                 goto close0;
411                                 }
412                         }
413                 }
414                 ret = 0;
415                 goto out;
416         }
417 close1:
418         PARA_INFO_LOG("channel 1: %s\n", para_strerror(-ret));
419         btr_remove_node(&ct->btrn[1]);
420         if (ct->btrn[0])
421                 return 0;
422         goto out;
423 close0:
424         PARA_INFO_LOG("channel 0: %s\n", para_strerror(-ret));
425         btr_remove_node(&ct->btrn[0]);
426         if (ct->btrn[1] && ct->status == CL_SENDING)
427                 return 0;
428 out:
429         if (ret >= 0)
430                 return 0;
431         btr_remove_node(&ct->btrn[0]);
432         btr_remove_node(&ct->btrn[1]);
433         if (ret != -E_SERVER_CMD_SUCCESS && ret != -E_SERVER_CMD_FAILURE)
434                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
435         if (ct->scc.fd >= 0) {
436                 close(ct->scc.fd);
437                 ct->scc.fd = -1;
438         }
439         free_argv(ct->features);
440         ct->features = NULL;
441         sc_free(ct->scc.recv);
442         ct->scc.recv = NULL;
443         sc_free(ct->scc.send);
444         ct->scc.send = NULL;
445         return ret;
446 }
447
448 /**
449  * Connect to para_server and register the client task.
450  *
451  * \param ct The initialized client task structure.
452  * \param s The scheduler instance to register the client task to.
453  * \param parent The parent node of the client btr node.
454  * \param child The child node of the client node.
455  *
456  * The client task structure given by \a ct  must be allocated and initialized
457  * by \ref client_parse_config() before this function is called.
458  *
459  * \return Standard.
460  */
461 int client_connect(struct client_task *ct, struct sched *s,
462                 struct btr_node *parent, struct btr_node *child)
463 {
464         int ret;
465         const char *host = CLIENT_OPT_STRING_VAL(HOSTNAME, ct->lpr);
466         uint32_t port = CLIENT_OPT_UINT32_VAL(SERVER_PORT, ct->lpr);
467
468         PARA_NOTICE_LOG("connecting %s:%u\n", host, port);
469         ct->scc.fd = -1;
470         ret = para_connect_simple(IPPROTO_TCP, host, port);
471         if (ret < 0)
472                 return ret;
473         ct->scc.fd = ret;
474         ret = mark_fd_nonblocking(ct->scc.fd);
475         if (ret < 0)
476                 goto err_out;
477         ct->status = CL_CONNECTED;
478         ct->btrn[0] = btr_new_node(&(struct btr_node_description)
479                 EMBRACE(.name = "client recv", .parent = NULL, .child = child));
480         ct->btrn[1] = btr_new_node(&(struct btr_node_description)
481                 EMBRACE(.name = "client send", .parent = parent, .child = NULL));
482
483         ct->task = task_register(&(struct task_info) {
484                 .name = "client",
485                 .pre_select = client_pre_select,
486                 .post_select = client_post_select,
487                 .context = ct,
488         }, s);
489         return 1;
490 err_out:
491         close(ct->scc.fd);
492         ct->scc.fd = -1;
493         return ret;
494 }
495
496 static void handle_help_flag(struct lls_parse_result *lpr)
497 {
498         char *help;
499
500         if (CLIENT_OPT_GIVEN(DETAILED_HELP, lpr))
501                 help = lls_long_help(CLIENT_CMD_PTR);
502         else if (CLIENT_OPT_GIVEN(HELP, lpr))
503                 help = lls_short_help(CLIENT_CMD_PTR);
504         else
505                 return;
506         printf("%s\n", help);
507         free(help);
508         exit(EXIT_SUCCESS);
509 }
510
511 /**
512  * Parse a client configuration.
513  *
514  * \param argc Usual argument count.
515  * \param argv Usual argument vector.
516  * \param ct_ptr Filled in by this function.
517  * \param loglevel If not \p NULL, the number of the loglevel is stored here.
518  *
519  * This checks the command line options given by \a argc and \a argv, sets
520  * default values for the user name and the name of the rsa key file and reads
521  * further options from the config file.
522  *
523  * Upon successful return, \a ct_ptr points to a dynamically allocated and
524  * initialized client task struct.
525  *
526  * \return The number of non-option arguments in \a argc/argv on success,
527  * negative on errors.
528  */
529 int client_parse_config(int argc, char *argv[], struct client_task **ct_ptr,
530                 int *loglevel)
531 {
532         const struct lls_command *cmd = CLIENT_CMD_PTR;
533         void *map;
534         size_t sz;
535         struct lls_parse_result *lpr;
536         int ret, ll;
537         struct client_task *ct;
538         char *cf = NULL, *kf = NULL, *user, *errctx, *home = para_homedir();
539
540         ret = lls(lls_parse(argc, argv, cmd, &lpr, &errctx));
541         if (ret < 0)
542                 goto out;
543         ll = CLIENT_OPT_UINT32_VAL(LOGLEVEL, lpr);
544         version_handle_flag("client", CLIENT_OPT_GIVEN(VERSION, lpr));
545         handle_help_flag(lpr);
546
547         if (CLIENT_OPT_GIVEN(CONFIG_FILE, lpr))
548                 cf = para_strdup(CLIENT_OPT_STRING_VAL(CONFIG_FILE, lpr));
549         else
550                 cf = make_message("%s/.paraslash/client.conf", home);
551         ret = mmap_full_file(cf, O_RDONLY, &map, &sz, NULL);
552         if (ret < 0) {
553                 if (ret != -E_EMPTY && ret != -ERRNO_TO_PARA_ERROR(ENOENT))
554                         goto out;
555                 if (ret == -ERRNO_TO_PARA_ERROR(ENOENT) &&
556                                 CLIENT_OPT_GIVEN(CONFIG_FILE, lpr))
557                         goto out;
558         } else {
559                 int cf_argc;
560                 char **cf_argv;
561                 struct lls_parse_result *cf_lpr, *merged_lpr;
562                 ret = lls(lls_convert_config(map, sz, NULL, &cf_argv, &errctx));
563                 para_munmap(map, sz);
564                 if (ret < 0)
565                         goto out;
566                 cf_argc = ret;
567                 ret = lls(lls_parse(cf_argc, cf_argv, cmd, &cf_lpr, &errctx));
568                 lls_free_argv(cf_argv);
569                 if (ret < 0)
570                         goto out;
571                 ret = lls(lls_merge(lpr, cf_lpr, cmd, &merged_lpr,
572                         &errctx));
573                 lls_free_parse_result(cf_lpr, cmd);
574                 if (ret < 0)
575                         goto out;
576                 lls_free_parse_result(lpr, cmd);
577                 lpr = merged_lpr;
578         }
579         /* success */
580         user = CLIENT_OPT_GIVEN(USER, lpr)?
581                 para_strdup(CLIENT_OPT_STRING_VAL(USER, lpr)) : para_logname();
582
583         if (CLIENT_OPT_GIVEN(KEY_FILE, lpr))
584                 kf = para_strdup(CLIENT_OPT_STRING_VAL(KEY_FILE, lpr));
585         else {
586                 kf = make_message("%s/.paraslash/key.%s", home, user);
587                 if (!file_exists(kf)) {
588                         free(kf);
589                         kf = make_message("%s/.ssh/id_rsa", home);
590                 }
591         }
592         PARA_INFO_LOG("user: %s\n", user);
593         PARA_INFO_LOG("config file: %s\n", cf);
594         PARA_INFO_LOG("key file: %s\n", kf);
595         PARA_INFO_LOG("loglevel: %d\n", ll);
596         ct = para_calloc(sizeof(*ct));
597         ct->scc.fd = -1;
598         ct->lpr = lpr;
599         ct->key_file = kf;
600         ct->config_file = cf;
601         ct->user = user;
602         *ct_ptr = ct;
603         if (loglevel)
604                 *loglevel = ll;
605         ret = lls_num_inputs(lpr);
606 out:
607         free(home);
608         if (ret < 0) {
609                 if (errctx)
610                         PARA_ERROR_LOG("%s\n", errctx);
611                 free(errctx);
612                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
613                 lls_free_parse_result(lpr, cmd);
614                 free(cf);
615                 free(kf);
616                 *ct_ptr = NULL;
617         }
618         return ret;
619 }
620
621 /**
622  * Parse the client configuration and open a connection to para_server.
623  *
624  * \param argc See \ref client_parse_config.
625  * \param argv See \ref client_parse_config.
626  * \param ct_ptr See \ref client_parse_config.
627  * \param loglevel See \ref client_parse_config.
628  * \param parent See \ref client_connect().
629  * \param child See \ref client_connect().
630  * \param sched See \ref client_connect().
631  *
632  * This function combines client_parse_config() and client_connect(). It is
633  * considered a syntax error if no command was given, i.e. if the number
634  * of non-option arguments is zero.
635  *
636  * \return Standard.
637  */
638 int client_open(int argc, char *argv[], struct client_task **ct_ptr,
639                 int *loglevel, struct btr_node *parent, struct btr_node *child,
640                 struct sched *sched)
641 {
642         int ret = client_parse_config(argc, argv, ct_ptr, loglevel);
643
644         if (ret < 0)
645                 return ret;
646         if (ret == 0) {
647                 ret = -E_CLIENT_SYNTAX;
648                 goto fail;
649         }
650         ret = client_connect(*ct_ptr, sched, parent, child);
651         if (ret < 0)
652                 goto fail;
653         return 1;
654 fail:
655         client_close(*ct_ptr);
656         *ct_ptr = NULL;
657         return ret;
658 }