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