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