]> 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 = para_malloc(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 static bool has_feature(const char *feature, struct client_task *ct)
259 {
260         return find_arg(feature, ct->features) >= 0? true : false;
261 }
262
263 /*
264  * This function reads or writes to the socket file descriptor which
265  * corresponds to an established connection between the client and the server.
266  * It depends on the current state of the connection and on the readiness of
267  * the socket file descriptor which type of I/O is going to be performed.
268  * Besides the initial handshake and authentication, the function sends the
269  * server command and receives the output from the server, if any.
270  *
271  * The context pointer refers to a client task structure that was initialized
272  * earlier by client_open().
273  */
274 static int client_post_monitor(struct sched *s, void *context)
275 {
276         struct client_task *ct = context;
277         int ret = 0;
278         size_t n;
279         char buf[CLIENT_BUFSIZE];
280
281         ret = task_get_notification(ct->task);
282         if (ret < 0)
283                 goto out;
284         if (ct->scc.fd < 0)
285                 return 0;
286         switch (ct->status) {
287         case CL_CONNECTED: /* receive welcome message */
288                 ret = read_nonblock(ct->scc.fd, buf, sizeof(buf), &n);
289                 if (ret < 0 || n == 0)
290                         goto out;
291                 ct->features = parse_features(buf);
292                 ct->status = CL_RECEIVED_WELCOME;
293                 return 0;
294         case CL_RECEIVED_WELCOME: /* send auth command */
295                 {
296                 /*
297                  * Use sha256 iff the server announced the feature. After 0.7.0
298                  * we may request and use the feature unconditionally. After
299                  * 0.8.0 we no longer need to request the feature.
300                  */
301                 bool has_sha256;
302                 if (!sched_write_ok(ct->scc.fd, s))
303                         return 0;
304                 has_sha256 = has_feature("sha256", ct);
305                 sprintf(buf, AUTH_REQUEST_MSG "%s%s", ct->user, has_sha256?
306                         " sha256" : "");
307                 PARA_INFO_LOG("--> %s\n", buf);
308                 ret = write_buffer(ct->scc.fd, buf);
309                 if (ret < 0)
310                         goto out;
311                 ct->status = CL_SENT_AUTH;
312                 return 0;
313                 }
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                 struct sb_buffer sbb;
323
324                 ret = recv_sb(ct, &sbb);
325                 if (ret <= 0)
326                         goto out;
327                 if (sbb.band != SBD_CHALLENGE) {
328                         ret = -E_BAD_BAND;
329                         free(sbb.iov.iov_base);
330                                 goto out;
331                 }
332                 n = sbb.iov.iov_len;
333                 PARA_INFO_LOG("<-- [challenge] (%zu bytes)\n", n);
334                 ret = apc_priv_decrypt(ct->key_file, crypt_buf,
335                         sbb.iov.iov_base, n);
336                 free(sbb.iov.iov_base);
337                 if (ret < 0)
338                         goto out;
339                 ct->challenge_hash = para_malloc(HASH2_SIZE);
340
341                 if (has_feature("sha256", ct)) {
342                         hash2_function((char *)crypt_buf, APC_CHALLENGE_SIZE, ct->challenge_hash);
343                         hash2_to_asc(ct->challenge_hash, buf);
344                 } else {
345                         hash_function((char *)crypt_buf, APC_CHALLENGE_SIZE, ct->challenge_hash);
346                         hash_to_asc(ct->challenge_hash, buf);
347                 }
348                 ct->scc.send = sc_new(crypt_buf + APC_CHALLENGE_SIZE, SESSION_KEY_LEN);
349                 ct->scc.recv = sc_new(crypt_buf + APC_CHALLENGE_SIZE + SESSION_KEY_LEN,
350                         SESSION_KEY_LEN);
351                 PARA_INFO_LOG("--> %s\n", buf);
352                 ct->status = CL_RECEIVED_CHALLENGE;
353                 return 0;
354                 }
355         case CL_RECEIVED_CHALLENGE:
356                 if (has_feature("sha256", ct))
357                         ret = send_sb(ct, 0, ct->challenge_hash, HASH2_SIZE,
358                                 SBD_CHALLENGE_RESPONSE, false);
359                 else
360                         ret = send_sb(ct, 0, ct->challenge_hash, HASH_SIZE,
361                                 SBD_CHALLENGE_RESPONSE, false);
362                 if (ret != 0)
363                         ct->challenge_hash = NULL;
364                 if (ret <= 0)
365                         goto out;
366                 ct->status = CL_SENT_CH_RESPONSE;
367                 goto out;
368         case CL_SENT_CH_RESPONSE: /* read server response */
369                 {
370                 struct sb_buffer sbb;
371                 ret = recv_sb(ct, &sbb);
372                 if (ret <= 0)
373                         goto out;
374                 free(sbb.iov.iov_base);
375                 if (sbb.band != SBD_PROCEED)
376                         ret = -E_BAD_BAND;
377                 else
378                         ct->status = CL_RECEIVED_PROCEED;
379                 goto out;
380                 }
381         case CL_RECEIVED_PROCEED: /* concat args and send command */
382                 {
383                 if (!sched_write_ok(ct->scc.fd, s))
384                         return 0;
385                 ret = send_sb_command(ct);
386                 if (ret <= 0)
387                         goto out;
388                 ct->status = CL_EXECUTING;
389                 return 0;
390                 }
391         case CL_SENDING:
392                 if (ct->btrn[1]) {
393                         char *buf2;
394                         size_t sz;
395                         ret = btr_node_status(ct->btrn[1], 0, BTR_NT_LEAF);
396                         if (ret == -E_BTR_EOF) {
397                                 /* empty blob data packet indicates EOF */
398                                 PARA_INFO_LOG("blob sent\n");
399                                 ret = send_sb(ct, 1, NULL, 0, SBD_BLOB_DATA, true);
400                                 if (ret >= 0)
401                                         ret = -E_BTR_EOF;
402                         }
403                         if (ret < 0)
404                                 goto close1;
405                         if (ret > 0 && sched_write_ok(ct->scc.fd, s)) {
406                                 sz = btr_next_buffer(ct->btrn[1], &buf2);
407                                 assert(sz);
408                                 ret = send_sb(ct, 1, buf2, sz, SBD_BLOB_DATA, true);
409                                 if (ret < 0)
410                                         goto close1;
411                                 if (ret > 0)
412                                         btr_consume(ct->btrn[1], sz);
413                         }
414                 }
415                 __attribute__ ((fallthrough));
416         case CL_EXECUTING:
417                 if (ct->btrn[0]) {
418                         ret = btr_node_status(ct->btrn[0], 0, BTR_NT_ROOT);
419                         if (ret < 0)
420                                 goto close0;
421                         if (ret > 0 && sched_read_ok(ct->scc.fd, s)) {
422                                 struct sb_buffer sbb;
423                                 ret = recv_sb(ct, &sbb);
424                                 if (ret < 0)
425                                         goto close0;
426                                 if (ret > 0) {
427                                         ret = dispatch_sbb(ct, &sbb);
428                                         if (ret < 0)
429                                                 goto close0;
430                                 }
431                         }
432                 }
433                 ret = 0;
434                 goto out;
435         }
436 close1:
437         PARA_INFO_LOG("channel 1: %s\n", para_strerror(-ret));
438         btr_remove_node(&ct->btrn[1]);
439         if (ct->btrn[0])
440                 return 0;
441         goto out;
442 close0:
443         PARA_INFO_LOG("channel 0: %s\n", para_strerror(-ret));
444         btr_remove_node(&ct->btrn[0]);
445         if (ct->btrn[1] && ct->status == CL_SENDING)
446                 return 0;
447 out:
448         if (ret >= 0)
449                 return 0;
450         btr_remove_node(&ct->btrn[0]);
451         btr_remove_node(&ct->btrn[1]);
452         PARA_NOTICE_LOG("closing connection (%s)\n", para_strerror(-ret));
453         if (ct->scc.fd >= 0) {
454                 close(ct->scc.fd);
455                 ct->scc.fd = -1;
456         }
457         free_argv(ct->features);
458         ct->features = NULL;
459         sc_free(ct->scc.recv);
460         ct->scc.recv = NULL;
461         sc_free(ct->scc.send);
462         ct->scc.send = NULL;
463         return ret;
464 }
465
466 /**
467  * Connect to para_server and register the client task.
468  *
469  * \param ct The initialized client task structure.
470  * \param s The scheduler instance to register the client task to.
471  * \param parent The parent node of the client btr node.
472  * \param child The child node of the client node.
473  *
474  * The client task structure given by \a ct  must be allocated and initialized
475  * by \ref client_parse_config() before this function is called.
476  *
477  * \return Standard.
478  */
479 int client_connect(struct client_task *ct, struct sched *s,
480                 struct btr_node *parent, struct btr_node *child)
481 {
482         int ret;
483         const char *host = CLIENT_OPT_STRING_VAL(HOSTNAME, ct->lpr);
484         uint32_t port = CLIENT_OPT_UINT32_VAL(SERVER_PORT, ct->lpr);
485
486         PARA_NOTICE_LOG("connecting %s:%u\n", host, port);
487         ct->scc.fd = -1;
488         ret = para_connect_simple(IPPROTO_TCP, host, port);
489         if (ret < 0)
490                 return ret;
491         ct->scc.fd = ret;
492         ret = mark_fd_nonblocking(ct->scc.fd);
493         if (ret < 0)
494                 goto err_out;
495         ct->status = CL_CONNECTED;
496         ct->btrn[0] = btr_new_node(&(struct btr_node_description)
497                 EMBRACE(.name = "client recv", .parent = NULL, .child = child));
498         ct->btrn[1] = btr_new_node(&(struct btr_node_description)
499                 EMBRACE(.name = "client send", .parent = parent, .child = NULL));
500
501         ct->task = task_register(&(struct task_info) {
502                 .name = "client",
503                 .pre_monitor = client_pre_monitor,
504                 .post_monitor = client_post_monitor,
505                 .context = ct,
506         }, s);
507         return 1;
508 err_out:
509         close(ct->scc.fd);
510         ct->scc.fd = -1;
511         return ret;
512 }
513
514 static void handle_help_flag(struct lls_parse_result *lpr)
515 {
516         char *help;
517
518         if (CLIENT_OPT_GIVEN(DETAILED_HELP, lpr))
519                 help = lls_long_help(CLIENT_CMD_PTR);
520         else if (CLIENT_OPT_GIVEN(HELP, lpr))
521                 help = lls_short_help(CLIENT_CMD_PTR);
522         else
523                 return;
524         printf("%s\n", help);
525         free(help);
526         exit(EXIT_SUCCESS);
527 }
528
529 /**
530  * Parse a client configuration.
531  *
532  * \param argc Usual argument count.
533  * \param argv Usual argument vector.
534  * \param ct_ptr Filled in by this function.
535  * \param loglevel If not \p NULL, the number of the loglevel is stored here.
536  *
537  * This checks the command line options given by \a argc and \a argv, sets
538  * default values for the user name and the name of the rsa key file and reads
539  * further options from the config file.
540  *
541  * Upon successful return, \a ct_ptr points to a dynamically allocated and
542  * initialized client task struct.
543  *
544  * \return The number of non-option arguments in \a argc/argv on success,
545  * negative on errors.
546  */
547 int client_parse_config(int argc, char *argv[], struct client_task **ct_ptr,
548                 int *loglevel)
549 {
550         const struct lls_command *cmd = CLIENT_CMD_PTR;
551         struct lls_parse_result *lpr;
552         int ret, ll;
553         struct client_task *ct;
554         char *kf = NULL, *user, *errctx, *home = para_homedir();
555
556         ret = lls(lls_parse(argc, argv, cmd, &lpr, &errctx));
557         if (ret < 0)
558                 goto out;
559         version_handle_flag("client", CLIENT_OPT_GIVEN(VERSION, lpr));
560         handle_help_flag(lpr);
561
562         ret = lsu_merge_config_file_options(CLIENT_OPT_STRING_VAL(CONFIG_FILE, lpr),
563                 "client.conf", &lpr, cmd, client_suite, 0U /* default flags */);
564         if (ret < 0)
565                 goto out;
566         /* success */
567         ll = CLIENT_OPT_UINT32_VAL(LOGLEVEL, lpr);
568         if (loglevel)
569                 *loglevel = ll;
570         user = CLIENT_OPT_GIVEN(USER, lpr)?
571                 para_strdup(CLIENT_OPT_STRING_VAL(USER, lpr)) : para_logname();
572
573         if (CLIENT_OPT_GIVEN(KEY_FILE, lpr))
574                 kf = para_strdup(CLIENT_OPT_STRING_VAL(KEY_FILE, lpr));
575         else {
576                 kf = make_message("%s/.paraslash/key.%s", home, user);
577                 if (!file_exists(kf)) {
578                         free(kf);
579                         kf = make_message("%s/.ssh/id_rsa", home);
580                 }
581         }
582         PARA_INFO_LOG("user: %s\n", user);
583         PARA_INFO_LOG("key file: %s\n", kf);
584         PARA_INFO_LOG("loglevel: %d\n", ll);
585         ct = para_calloc(sizeof(*ct));
586         ct->scc.fd = -1;
587         ct->lpr = lpr;
588         ct->key_file = kf;
589         ct->user = user;
590         *ct_ptr = ct;
591         ret = lls_num_inputs(lpr);
592 out:
593         free(home);
594         if (ret < 0) {
595                 if (errctx)
596                         PARA_ERROR_LOG("%s\n", errctx);
597                 free(errctx);
598                 lls_free_parse_result(lpr, cmd);
599                 free(kf);
600                 *ct_ptr = NULL;
601         }
602         return ret;
603 }
604
605 /**
606  * Parse the client configuration and open a connection to para_server.
607  *
608  * \param argc See \ref client_parse_config.
609  * \param argv See \ref client_parse_config.
610  * \param ct_ptr See \ref client_parse_config.
611  * \param loglevel See \ref client_parse_config.
612  * \param parent See \ref client_connect().
613  * \param child See \ref client_connect().
614  * \param sched See \ref client_connect().
615  *
616  * This function combines client_parse_config() and client_connect(). It is
617  * considered a syntax error if no command was given, i.e. if the number
618  * of non-option arguments is zero.
619  *
620  * \return Standard.
621  */
622 int client_open(int argc, char *argv[], struct client_task **ct_ptr,
623                 int *loglevel, struct btr_node *parent, struct btr_node *child,
624                 struct sched *sched)
625 {
626         int ret = client_parse_config(argc, argv, ct_ptr, loglevel);
627
628         if (ret < 0)
629                 return ret;
630         if (ret == 0) {
631                 ret = -E_CLIENT_SYNTAX;
632                 goto fail;
633         }
634         ret = client_connect(*ct_ptr, sched, parent, child);
635         if (ret < 0)
636                 goto fail;
637         return 1;
638 fail:
639         client_close(*ct_ptr);
640         *ct_ptr = NULL;
641         return ret;
642 }