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