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