]> git.tuebingen.mpg.de Git - paraslash.git/blob - client_common.c
paraslash 0.7.3
[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_monitor(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                 sched_monitor_readfd(ct->scc.fd, s);
72                 return;
73
74         case CL_RECEIVED_WELCOME:
75         case CL_RECEIVED_PROCEED:
76         case CL_RECEIVED_CHALLENGE:
77                 sched_monitor_writefd(ct->scc.fd, s);
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                                 sched_monitor_writefd(ct->scc.fd, s);
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                                 sched_monitor_readfd(ct->scc.fd, s);
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, struct sb_buffer *result)
129 {
130         int ret;
131         size_t n;
132         sb_transformation trafo;
133         void *trafo_context;
134         struct iovec iov;
135
136         if (ct->status < CL_SENT_CH_RESPONSE)
137                 trafo = trafo_context = NULL;
138         else {
139                 trafo = sc_trafo;
140                 trafo_context = ct->scc.recv;
141         }
142         if (!ct->sbc[0])
143                 ct->sbc[0] = sb_new_recv(0, trafo, trafo_context);
144 again:
145         sb_get_recv_buffer(ct->sbc[0], &iov);
146         ret = read_nonblock(ct->scc.fd, iov.iov_base, iov.iov_len, &n);
147         if (ret < 0) {
148                 sb_free(ct->sbc[0]);
149                 ct->sbc[0] = NULL;
150                 return ret;
151         }
152         if (n == 0)
153                 return 0;
154         ret = sb_received(ct->sbc[0], n, result);
155         if (ret < 0)
156                 return ret;
157         if (ret == 0)
158                 goto again;
159         ct->sbc[0] = NULL;
160         return 1;
161 }
162
163
164 static char **parse_features(char *buf)
165 {
166         int i;
167         const char id[] = "\nFeatures: ";
168         char *p, *q, **features;
169
170         p = strstr(buf, id);
171         if (!p)
172                 return NULL;
173         p += strlen(id);
174         q = strchr(p, '\n');
175         if (!q)
176                 return NULL;
177         *q = '\0';
178         create_argv(p, ",", &features);
179         for (i = 0; features[i]; i++)
180                 PARA_INFO_LOG("server feature: %s\n", features[i]);
181         return features;
182 }
183
184 static int dispatch_sbb(struct client_task *ct, struct sb_buffer *sbb)
185 {
186         int ret;
187         const char *designator[] = {SB_DESIGNATORS_ARRAY};
188
189         if (!sbb)
190                 return 0;
191         if (sbb->band < NUM_SB_DESIGNATORS)
192                 PARA_DEBUG_LOG("band: %s\n", designator[sbb->band]);
193
194         switch (sbb->band) {
195         case SBD_AWAITING_DATA:
196                 ct->status = CL_SENDING;
197                 ret = 1;
198                 goto out;
199         case SBD_OUTPUT:
200                 if (iov_valid(&sbb->iov))
201                         btr_add_output(sbb->iov.iov_base, sbb->iov.iov_len,
202                                 ct->btrn[0]);
203                 ret = 1;
204                 goto out;
205         case SBD_DEBUG_LOG:
206         case SBD_INFO_LOG:
207         case SBD_NOTICE_LOG:
208         case SBD_WARNING_LOG:
209         case SBD_ERROR_LOG:
210         case SBD_CRIT_LOG:
211         case SBD_EMERG_LOG:
212                 if (iov_valid(&sbb->iov)) {
213                         int ll = sbb->band - SBD_DEBUG_LOG;
214                         para_log(ll, "remote: %s", (char *)sbb->iov.iov_base);
215                 }
216                 ret = 1;
217                 goto deallocate;
218         case SBD_EXIT__SUCCESS:
219                 ret = -E_SERVER_CMD_SUCCESS;
220                 goto deallocate;
221         case SBD_EXIT__FAILURE:
222                 ret = -E_SERVER_CMD_FAILURE;
223                 goto deallocate;
224         default:
225                 PARA_ERROR_LOG("invalid band %d\n", sbb->band);
226                 ret = -E_BAD_BAND;
227                 goto deallocate;
228         }
229 deallocate:
230         free(sbb->iov.iov_base);
231 out:
232         sbb->iov.iov_base = NULL;
233         return ret;
234 }
235
236 static int send_sb_command(struct client_task *ct)
237 {
238         int i;
239         char *command, *p;
240         size_t len = 0;
241         unsigned num_inputs = lls_num_inputs(ct->lpr);
242
243         if (ct->sbc[1])
244                 return send_sb(ct, 0, NULL, 0, 0, false);
245
246         for (i = 0; i < num_inputs; i++)
247                 len += strlen(lls_input(i, ct->lpr)) + 1;
248         p = command = alloc(len);
249         for (i = 0; i < num_inputs; i++) {
250                 const char *str = lls_input(i, ct->lpr);
251                 strcpy(p, str);
252                 p += strlen(str) + 1;
253         }
254         PARA_DEBUG_LOG("--> %s\n", command);
255         return send_sb(ct, 0, command, len, SBD_COMMAND, false);
256 }
257
258 /* Find out if the given string is contained in the features vector. */
259 static bool has_feature(const char *feature, struct client_task *ct)
260 {
261         if (!ct->features)
262                 return false;
263         for (int i = 0; ct->features[i]; i++)
264                 if (strcmp(feature, ct->features[i]) == 0)
265                         return i;
266         return false;
267 }
268
269 /*
270  * This function reads or writes to the socket file descriptor which
271  * corresponds to an established connection between the client and the server.
272  * It depends on the current state of the connection and on the readiness of
273  * the socket file descriptor which type of I/O is going to be performed.
274  * Besides the initial handshake and authentication, the function sends the
275  * server command and receives the output from the server, if any.
276  *
277  * The context pointer refers to a client task structure that was initialized
278  * earlier by client_open().
279  */
280 static int client_post_monitor(struct sched *s, void *context)
281 {
282         struct client_task *ct = context;
283         int ret = 0;
284         size_t n;
285         char buf[CLIENT_BUFSIZE];
286
287         ret = task_get_notification(ct->task);
288         if (ret < 0)
289                 goto out;
290         if (ct->scc.fd < 0)
291                 return 0;
292         switch (ct->status) {
293         case CL_CONNECTED: /* receive welcome message */
294                 ret = read_nonblock(ct->scc.fd, 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 0;
300         case CL_RECEIVED_WELCOME: /* send auth command */
301                 {
302                 /*
303                  * Use sha256 iff the server announced the feature. After 0.7.0
304                  * we may request and use the feature unconditionally. After
305                  * 0.8.0 we no longer need to request the feature.
306                  */
307                 bool has_sha256;
308                 if (!sched_write_ok(ct->scc.fd, s))
309                         return 0;
310                 has_sha256 = has_feature("sha256", ct);
311                 sprintf(buf, AUTH_REQUEST_MSG "%s%s", ct->user, has_sha256?
312                         " sha256" : "");
313                 PARA_INFO_LOG("--> %s\n", buf);
314                 ret = write_buffer(ct->scc.fd, buf);
315                 if (ret < 0)
316                         goto out;
317                 ct->status = CL_SENT_AUTH;
318                 return 0;
319                 }
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
330                 ret = recv_sb(ct, &sbb);
331                 if (ret <= 0)
332                         goto out;
333                 if (sbb.band != SBD_CHALLENGE) {
334                         ret = -E_BAD_BAND;
335                         free(sbb.iov.iov_base);
336                                 goto out;
337                 }
338                 n = sbb.iov.iov_len;
339                 PARA_INFO_LOG("<-- [challenge] (%zu bytes)\n", n);
340                 ret = apc_priv_decrypt(ct->key_file, crypt_buf,
341                         sbb.iov.iov_base, n);
342                 free(sbb.iov.iov_base);
343                 if (ret < 0)
344                         goto out;
345                 ct->challenge_hash = alloc(HASH2_SIZE);
346                 if (has_feature("sha256", ct)) {
347                         hash2_function((char *)crypt_buf, APC_CHALLENGE_SIZE, ct->challenge_hash);
348                         hash2_to_asc(ct->challenge_hash, buf);
349                 } else {
350                         hash_function((char *)crypt_buf, APC_CHALLENGE_SIZE, ct->challenge_hash);
351                         hash_to_asc(ct->challenge_hash, buf);
352                 }
353                 ct->scc.send = sc_new(crypt_buf + APC_CHALLENGE_SIZE, SESSION_KEY_LEN);
354                 ct->scc.recv = sc_new(crypt_buf + APC_CHALLENGE_SIZE + SESSION_KEY_LEN,
355                         SESSION_KEY_LEN);
356                 PARA_INFO_LOG("--> %s\n", buf);
357                 ct->status = CL_RECEIVED_CHALLENGE;
358                 return 0;
359                 }
360         case CL_RECEIVED_CHALLENGE:
361                 if (has_feature("sha256", ct))
362                         ret = send_sb(ct, 0, ct->challenge_hash, HASH2_SIZE,
363                                 SBD_CHALLENGE_RESPONSE, false);
364                 else
365                         ret = send_sb(ct, 0, ct->challenge_hash, HASH_SIZE,
366                                 SBD_CHALLENGE_RESPONSE, false);
367                 if (ret != 0)
368                         ct->challenge_hash = NULL;
369                 if (ret <= 0)
370                         goto out;
371                 ct->status = CL_SENT_CH_RESPONSE;
372                 goto out;
373         case CL_SENT_CH_RESPONSE: /* read server response */
374                 {
375                 struct sb_buffer sbb;
376                 ret = recv_sb(ct, &sbb);
377                 if (ret <= 0)
378                         goto out;
379                 free(sbb.iov.iov_base);
380                 if (sbb.band != SBD_PROCEED)
381                         ret = -E_BAD_BAND;
382                 else
383                         ct->status = CL_RECEIVED_PROCEED;
384                 goto out;
385                 }
386         case CL_RECEIVED_PROCEED: /* concat args and send command */
387                 {
388                 if (!sched_write_ok(ct->scc.fd, s))
389                         return 0;
390                 ret = send_sb_command(ct);
391                 if (ret <= 0)
392                         goto out;
393                 ct->status = CL_EXECUTING;
394                 return 0;
395                 }
396         case CL_SENDING:
397                 if (ct->btrn[1]) {
398                         char *buf2;
399                         size_t sz;
400                         ret = btr_node_status(ct->btrn[1], 0, BTR_NT_LEAF);
401                         if (ret == -E_BTR_EOF) {
402                                 /* empty blob data packet indicates EOF */
403                                 PARA_INFO_LOG("blob sent\n");
404                                 ret = send_sb(ct, 1, NULL, 0, SBD_BLOB_DATA, true);
405                                 if (ret >= 0)
406                                         ret = -E_BTR_EOF;
407                         }
408                         if (ret < 0)
409                                 goto close1;
410                         if (ret > 0 && sched_write_ok(ct->scc.fd, s)) {
411                                 sz = btr_next_buffer(ct->btrn[1], &buf2);
412                                 assert(sz);
413                                 ret = send_sb(ct, 1, buf2, sz, SBD_BLOB_DATA, true);
414                                 if (ret < 0)
415                                         goto close1;
416                                 if (ret > 0)
417                                         btr_consume(ct->btrn[1], sz);
418                         }
419                 }
420                 __attribute__ ((fallthrough));
421         case CL_EXECUTING:
422                 if (ct->btrn[0]) {
423                         ret = btr_node_status(ct->btrn[0], 0, BTR_NT_ROOT);
424                         if (ret < 0)
425                                 goto close0;
426                         if (ret > 0 && sched_read_ok(ct->scc.fd, s)) {
427                                 struct sb_buffer sbb;
428                                 ret = recv_sb(ct, &sbb);
429                                 if (ret < 0)
430                                         goto close0;
431                                 if (ret > 0) {
432                                         ret = dispatch_sbb(ct, &sbb);
433                                         if (ret < 0)
434                                                 goto close0;
435                                 }
436                         }
437                 }
438                 ret = 0;
439                 goto out;
440         }
441 close1:
442         PARA_INFO_LOG("channel 1: %s\n", para_strerror(-ret));
443         btr_remove_node(&ct->btrn[1]);
444         if (ct->btrn[0])
445                 return 0;
446         goto out;
447 close0:
448         PARA_INFO_LOG("channel 0: %s\n", para_strerror(-ret));
449         btr_remove_node(&ct->btrn[0]);
450         if (ct->btrn[1] && ct->status == CL_SENDING)
451                 return 0;
452 out:
453         if (ret >= 0)
454                 return 0;
455         btr_remove_node(&ct->btrn[0]);
456         btr_remove_node(&ct->btrn[1]);
457         PARA_NOTICE_LOG("closing connection (%s)\n", para_strerror(-ret));
458         if (ct->scc.fd >= 0) {
459                 close(ct->scc.fd);
460                 ct->scc.fd = -1;
461         }
462         free_argv(ct->features);
463         ct->features = NULL;
464         sc_free(ct->scc.recv);
465         ct->scc.recv = NULL;
466         sc_free(ct->scc.send);
467         ct->scc.send = NULL;
468         return ret;
469 }
470
471 /**
472  * Connect to para_server and register the client task.
473  *
474  * \param ct The initialized client task structure.
475  * \param s The scheduler instance to register the client task to.
476  * \param parent The parent node of the client btr node.
477  * \param child The child node of the client node.
478  *
479  * The client task structure given by \a ct  must be allocated and initialized
480  * by \ref client_parse_config() before this function is called.
481  *
482  * \return Standard.
483  */
484 int client_connect(struct client_task *ct, struct sched *s,
485                 struct btr_node *parent, struct btr_node *child)
486 {
487         int ret;
488         const char *host = CLIENT_OPT_STRING_VAL(HOSTNAME, ct->lpr);
489         uint32_t port = CLIENT_OPT_UINT32_VAL(SERVER_PORT, ct->lpr);
490
491         PARA_NOTICE_LOG("connecting %s:%u\n", host, port);
492         ct->scc.fd = -1;
493         ret = para_connect(IPPROTO_TCP, host, port);
494         if (ret < 0)
495                 return ret;
496         ct->scc.fd = ret;
497         ret = mark_fd_nonblocking(ct->scc.fd);
498         if (ret < 0)
499                 goto err_out;
500         ct->status = CL_CONNECTED;
501         ct->btrn[0] = btr_new_node(&(struct btr_node_description)
502                 EMBRACE(.name = "client recv", .parent = NULL, .child = child));
503         ct->btrn[1] = btr_new_node(&(struct btr_node_description)
504                 EMBRACE(.name = "client send", .parent = parent, .child = NULL));
505
506         ct->task = task_register(&(struct task_info) {
507                 .name = "client",
508                 .pre_monitor = client_pre_monitor,
509                 .post_monitor = client_post_monitor,
510                 .context = ct,
511         }, s);
512         return 1;
513 err_out:
514         close(ct->scc.fd);
515         ct->scc.fd = -1;
516         return ret;
517 }
518
519 static void handle_help_flag(struct lls_parse_result *lpr)
520 {
521         char *help;
522
523         if (CLIENT_OPT_GIVEN(DETAILED_HELP, lpr))
524                 help = lls_long_help(CLIENT_CMD_PTR);
525         else if (CLIENT_OPT_GIVEN(HELP, lpr))
526                 help = lls_short_help(CLIENT_CMD_PTR);
527         else
528                 return;
529         printf("%s\n", help);
530         free(help);
531         exit(EXIT_SUCCESS);
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         const struct lls_command *cmd = CLIENT_CMD_PTR;
556         struct lls_parse_result *lpr;
557         int ret, ll;
558         struct client_task *ct;
559         char *kf = NULL, *user, *errctx, *home = para_homedir();
560
561         ret = lls(lls_parse(argc, argv, cmd, &lpr, &errctx));
562         if (ret < 0)
563                 goto out;
564         version_handle_flag("client", CLIENT_OPT_GIVEN(VERSION, lpr));
565         handle_help_flag(lpr);
566
567         ret = lsu_merge_config_file_options(CLIENT_OPT_STRING_VAL(CONFIG_FILE, lpr),
568                 "client.conf", &lpr, cmd, client_suite, 0U /* default flags */);
569         if (ret < 0)
570                 goto out;
571         /* success */
572         ll = CLIENT_OPT_UINT32_VAL(LOGLEVEL, lpr);
573         if (loglevel)
574                 *loglevel = ll;
575         user = CLIENT_OPT_GIVEN(USER, lpr)?
576                 para_strdup(CLIENT_OPT_STRING_VAL(USER, lpr)) : para_logname();
577
578         if (CLIENT_OPT_GIVEN(KEY_FILE, lpr))
579                 kf = para_strdup(CLIENT_OPT_STRING_VAL(KEY_FILE, lpr));
580         else {
581                 kf = make_message("%s/.paraslash/key.%s", home, user);
582                 if (!file_exists(kf)) {
583                         free(kf);
584                         kf = make_message("%s/.ssh/id_rsa", home);
585                 }
586         }
587         PARA_INFO_LOG("user: %s\n", user);
588         PARA_INFO_LOG("key file: %s\n", kf);
589         PARA_INFO_LOG("loglevel: %d\n", ll);
590         ct = zalloc(sizeof(*ct));
591         ct->scc.fd = -1;
592         ct->lpr = lpr;
593         ct->key_file = kf;
594         ct->user = user;
595         *ct_ptr = ct;
596         ret = lls_num_inputs(lpr);
597 out:
598         free(home);
599         if (ret < 0) {
600                 if (errctx)
601                         PARA_ERROR_LOG("%s\n", errctx);
602                 free(errctx);
603                 lls_free_parse_result(lpr, cmd);
604                 free(kf);
605                 *ct_ptr = NULL;
606         }
607         return ret;
608 }
609
610 /**
611  * Parse the client configuration and open a connection to para_server.
612  *
613  * \param argc See \ref client_parse_config.
614  * \param argv See \ref client_parse_config.
615  * \param ct_ptr See \ref client_parse_config.
616  * \param loglevel See \ref client_parse_config.
617  * \param parent See \ref client_connect().
618  * \param child See \ref client_connect().
619  * \param sched See \ref client_connect().
620  *
621  * This function combines client_parse_config() and client_connect(). It is
622  * considered a syntax error if no command was given, i.e. if the number
623  * of non-option arguments is zero.
624  *
625  * \return Standard.
626  */
627 int client_open(int argc, char *argv[], struct client_task **ct_ptr,
628                 int *loglevel, struct btr_node *parent, struct btr_node *child,
629                 struct sched *sched)
630 {
631         int ret = client_parse_config(argc, argv, ct_ptr, loglevel);
632
633         if (ret < 0)
634                 return ret;
635         if (ret == 0) {
636                 ret = -E_CLIENT_SYNTAX;
637                 goto fail;
638         }
639         ret = client_connect(*ct_ptr, sched, parent, child);
640         if (ret < 0)
641                 goto fail;
642         return 1;
643 fail:
644         client_close(*ct_ptr);
645         *ct_ptr = NULL;
646         return ret;
647 }