]> 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 true;
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,
348                                 ct->challenge_hash);
349                         hash2_to_asc(ct->challenge_hash, buf);
350                 } else {
351                         hash_function((char *)crypt_buf, APC_CHALLENGE_SIZE,
352                                 ct->challenge_hash);
353                         hash_to_asc(ct->challenge_hash, buf);
354                 }
355                 ct->scc.send = sc_new(crypt_buf + APC_CHALLENGE_SIZE,
356                          SESSION_KEY_LEN);
357                 ct->scc.recv = sc_new(crypt_buf + APC_CHALLENGE_SIZE
358                         + SESSION_KEY_LEN, SESSION_KEY_LEN);
359                 PARA_INFO_LOG("--> %s\n", buf);
360                 ct->status = CL_RECEIVED_CHALLENGE;
361                 return 0;
362                 }
363         case CL_RECEIVED_CHALLENGE:
364                 if (has_feature("sha256", ct))
365                         ret = send_sb(ct, 0, ct->challenge_hash, HASH2_SIZE,
366                                 SBD_CHALLENGE_RESPONSE, false);
367                 else
368                         ret = send_sb(ct, 0, ct->challenge_hash, HASH_SIZE,
369                                 SBD_CHALLENGE_RESPONSE, false);
370                 if (ret != 0)
371                         ct->challenge_hash = NULL;
372                 if (ret <= 0)
373                         goto out;
374                 ct->status = CL_SENT_CH_RESPONSE;
375                 goto out;
376         case CL_SENT_CH_RESPONSE: /* read server response */
377                 {
378                 struct sb_buffer sbb;
379                 ret = recv_sb(ct, &sbb);
380                 if (ret <= 0)
381                         goto out;
382                 free(sbb.iov.iov_base);
383                 if (sbb.band != SBD_PROCEED)
384                         ret = -E_BAD_BAND;
385                 else
386                         ct->status = CL_RECEIVED_PROCEED;
387                 goto out;
388                 }
389         case CL_RECEIVED_PROCEED: /* concat args and send command */
390                 {
391                 if (!sched_write_ok(ct->scc.fd, s))
392                         return 0;
393                 ret = send_sb_command(ct);
394                 if (ret <= 0)
395                         goto out;
396                 ct->status = CL_EXECUTING;
397                 return 0;
398                 }
399         case CL_SENDING:
400                 if (ct->btrn[1]) {
401                         char *buf2;
402                         size_t sz;
403                         ret = btr_node_status(ct->btrn[1], 0, BTR_NT_LEAF);
404                         if (ret == -E_EOF) {
405                                 /* empty blob data packet indicates EOF */
406                                 PARA_INFO_LOG("blob sent\n");
407                                 ret = send_sb(ct, 1, NULL, 0, SBD_BLOB_DATA, true);
408                                 if (ret >= 0)
409                                         ret = -E_EOF;
410                         }
411                         if (ret < 0)
412                                 goto close1;
413                         if (ret > 0 && sched_write_ok(ct->scc.fd, s)) {
414                                 sz = btr_next_buffer(ct->btrn[1], &buf2);
415                                 assert(sz);
416                                 ret = send_sb(ct, 1, buf2, sz, SBD_BLOB_DATA, true);
417                                 if (ret < 0)
418                                         goto close1;
419                                 if (ret > 0)
420                                         btr_consume(ct->btrn[1], sz);
421                         }
422                 }
423                 __attribute__ ((fallthrough));
424         case CL_EXECUTING:
425                 if (ct->btrn[0]) {
426                         ret = btr_node_status(ct->btrn[0], 0, BTR_NT_ROOT);
427                         if (ret < 0)
428                                 goto close0;
429                         if (ret > 0 && sched_read_ok(ct->scc.fd, s)) {
430                                 struct sb_buffer sbb;
431                                 ret = recv_sb(ct, &sbb);
432                                 if (ret < 0)
433                                         goto close0;
434                                 if (ret > 0) {
435                                         ret = dispatch_sbb(ct, &sbb);
436                                         if (ret < 0)
437                                                 goto close0;
438                                 }
439                         }
440                 }
441                 ret = 0;
442                 goto out;
443         }
444 close1:
445         PARA_INFO_LOG("channel 1: %s\n", para_strerror(-ret));
446         btr_remove_node(&ct->btrn[1]);
447         if (ct->btrn[0])
448                 return 0;
449         goto out;
450 close0:
451         PARA_INFO_LOG("channel 0: %s\n", para_strerror(-ret));
452         btr_remove_node(&ct->btrn[0]);
453         if (ct->btrn[1] && ct->status == CL_SENDING)
454                 return 0;
455 out:
456         if (ret >= 0)
457                 return 0;
458         btr_remove_node(&ct->btrn[0]);
459         btr_remove_node(&ct->btrn[1]);
460         PARA_NOTICE_LOG("closing connection (%s)\n", para_strerror(-ret));
461         if (ct->scc.fd >= 0) {
462                 close(ct->scc.fd);
463                 ct->scc.fd = -1;
464         }
465         free_argv(ct->features);
466         ct->features = NULL;
467         sc_free(ct->scc.recv);
468         ct->scc.recv = NULL;
469         sc_free(ct->scc.send);
470         ct->scc.send = NULL;
471         return ret;
472 }
473
474 /**
475  * Connect to para_server and register the client task.
476  *
477  * \param ct The initialized client task structure.
478  * \param s The scheduler instance to register the client task to.
479  * \param parent The parent node of the client btr node.
480  * \param child The child node of the client node.
481  *
482  * The client task structure given by \a ct  must be allocated and initialized
483  * by \ref client_parse_config() before this function is called.
484  *
485  * \return Standard.
486  */
487 int client_connect(struct client_task *ct, struct sched *s,
488                 struct btr_node *parent, struct btr_node *child)
489 {
490         int ret;
491         const char *host = CLIENT_OPT_STRING_VAL(HOSTNAME, ct->lpr);
492         uint32_t port = CLIENT_OPT_UINT32_VAL(SERVER_PORT, ct->lpr);
493
494         PARA_NOTICE_LOG("connecting %s:%u\n", host, port);
495         ct->scc.fd = -1;
496         ret = para_connect(IPPROTO_TCP, host, port);
497         if (ret < 0)
498                 return ret;
499         ct->scc.fd = ret;
500         ret = mark_fd_nonblocking(ct->scc.fd);
501         if (ret < 0)
502                 goto err_out;
503         ct->status = CL_CONNECTED;
504         ct->btrn[0] = btr_new_node(&(struct btr_node_description)
505                 EMBRACE(.name = "client recv", .parent = NULL, .child = child));
506         ct->btrn[1] = btr_new_node(&(struct btr_node_description)
507                 EMBRACE(.name = "client send", .parent = parent, .child = NULL));
508
509         ct->task = task_register(&(struct task_info) {
510                 .name = "client",
511                 .pre_monitor = client_pre_monitor,
512                 .post_monitor = client_post_monitor,
513                 .context = ct,
514         }, s);
515         return 1;
516 err_out:
517         close(ct->scc.fd);
518         ct->scc.fd = -1;
519         return ret;
520 }
521
522 static void handle_help_flag(struct lls_parse_result *lpr)
523 {
524         char *help;
525
526         if (CLIENT_OPT_GIVEN(DETAILED_HELP, lpr))
527                 help = lls_long_help(CLIENT_CMD_PTR);
528         else if (CLIENT_OPT_GIVEN(HELP, lpr))
529                 help = lls_short_help(CLIENT_CMD_PTR);
530         else
531                 return;
532         printf("%s\n", help);
533         free(help);
534         exit(EXIT_SUCCESS);
535 }
536
537 /**
538  * Parse a client configuration.
539  *
540  * \param argc Usual argument count.
541  * \param argv Usual argument vector.
542  * \param ct_ptr Filled in by this function.
543  * \param loglevel If not \p NULL, the number of the loglevel is stored here.
544  *
545  * This checks the command line options given by \a argc and \a argv, sets
546  * default values for the user name and the name of the rsa key file and reads
547  * further options from the config file.
548  *
549  * Upon successful return, \a ct_ptr points to a dynamically allocated and
550  * initialized client task struct.
551  *
552  * \return The number of non-option arguments in \a argc/argv on success,
553  * negative on errors.
554  */
555 int client_parse_config(int argc, char *argv[], struct client_task **ct_ptr,
556                 int *loglevel)
557 {
558         const struct lls_command *cmd = CLIENT_CMD_PTR;
559         struct lls_parse_result *lpr;
560         int ret, ll;
561         struct client_task *ct;
562         char *kf = NULL, *user, *errctx, *home = para_homedir();
563
564         ret = lls(lls_parse(argc, argv, cmd, &lpr, &errctx));
565         if (ret < 0)
566                 goto out;
567         version_handle_flag("client", CLIENT_OPT_GIVEN(VERSION, lpr));
568         handle_help_flag(lpr);
569
570         ret = lsu_merge_config_file_options(CLIENT_OPT_STRING_VAL(CONFIG_FILE, lpr),
571                 "client.conf", &lpr, cmd, client_suite, 0U /* default flags */);
572         if (ret < 0)
573                 goto out;
574         /* success */
575         ll = CLIENT_OPT_UINT32_VAL(LOGLEVEL, lpr);
576         if (loglevel)
577                 *loglevel = ll;
578         user = CLIENT_OPT_GIVEN(USER, lpr)?
579                 para_strdup(CLIENT_OPT_STRING_VAL(USER, lpr)) : para_logname();
580
581         if (CLIENT_OPT_GIVEN(KEY_FILE, lpr))
582                 kf = para_strdup(CLIENT_OPT_STRING_VAL(KEY_FILE, lpr));
583         else {
584                 struct stat statbuf;
585                 kf = make_message("%s/.paraslash/key.%s", home, user);
586                 if (stat(kf, &statbuf) != 0) { /* assume file does not exist */
587                         free(kf);
588                         kf = make_message("%s/.ssh/id_rsa", home);
589                 }
590         }
591         PARA_INFO_LOG("user: %s\n", user);
592         PARA_INFO_LOG("key file: %s\n", kf);
593         PARA_INFO_LOG("loglevel: %d\n", ll);
594         ct = zalloc(sizeof(*ct));
595         ct->scc.fd = -1;
596         ct->lpr = lpr;
597         ct->key_file = kf;
598         ct->user = user;
599         *ct_ptr = ct;
600         ret = lls_num_inputs(lpr);
601 out:
602         free(home);
603         if (ret < 0) {
604                 if (errctx)
605                         PARA_ERROR_LOG("%s\n", errctx);
606                 free(errctx);
607                 lls_free_parse_result(lpr, cmd);
608                 free(kf);
609                 *ct_ptr = NULL;
610         }
611         return ret;
612 }
613
614 /**
615  * Parse the client configuration and open a connection to para_server.
616  *
617  * \param argc See \ref client_parse_config.
618  * \param argv See \ref client_parse_config.
619  * \param ct_ptr See \ref client_parse_config.
620  * \param loglevel See \ref client_parse_config.
621  * \param parent See \ref client_connect().
622  * \param child See \ref client_connect().
623  * \param sched See \ref client_connect().
624  *
625  * This function combines client_parse_config() and client_connect(). It is
626  * considered a syntax error if no command was given, i.e. if the number
627  * of non-option arguments is zero.
628  *
629  * \return Standard.
630  */
631 int client_open(int argc, char *argv[], struct client_task **ct_ptr,
632                 int *loglevel, struct btr_node *parent, struct btr_node *child,
633                 struct sched *sched)
634 {
635         int ret = client_parse_config(argc, argv, ct_ptr, loglevel);
636
637         if (ret < 0)
638                 return ret;
639         if (ret == 0) {
640                 ret = -E_CLIENT_SYNTAX;
641                 goto fail;
642         }
643         ret = client_connect(*ct_ptr, sched, parent, child);
644         if (ret < 0)
645                 goto fail;
646         return 1;
647 fail:
648         client_close(*ct_ptr);
649         *ct_ptr = NULL;
650         return ret;
651 }