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