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