]> git.tuebingen.mpg.de Git - paraslash.git/blob - client_common.c
f3cea05d45a3853c53840a66e5713fc681787ee3
[paraslash.git] / client_common.c
1 /*
2  * Copyright (C) 1997-2012 Andre Noll <maan@systemlinux.org>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file client_common.c Common functions of para_client and para_audiod. */
8
9 #include <regex.h>
10 #include <sys/types.h>
11
12 #include "para.h"
13 #include "error.h"
14 #include "list.h"
15 #include "sched.h"
16 #include "client.cmdline.h"
17 #include "crypt.h"
18 #include "net.h"
19 #include "fd.h"
20 #include "sideband.h"
21 #include "string.h"
22 #include "client.cmdline.h"
23 #include "client.h"
24 #include "buffer_tree.h"
25 #include "version.h"
26
27 /** The size of the receiving buffer. */
28 #define CLIENT_BUFSIZE 4000
29
30 /**
31  * Close the connection to para_server and deallocate per-command ressources.
32  *
33  * \param ct The client task.
34  *
35  * This frees all ressources of the current command but keeps the configuration
36  * in \p ct->conf.
37  *
38  * \sa \ref client_close().
39  */
40 void client_disconnect(struct client_task *ct)
41 {
42         if (!ct)
43                 return;
44         if (ct->scc.fd >= 0)
45                 close(ct->scc.fd);
46         free_argv(ct->features);
47         sc_free(ct->scc.recv);
48         ct->scc.recv = NULL;
49         sc_free(ct->scc.send);
50         ct->scc.send = NULL;
51         btr_free_node(ct->btrn);
52         ct->btrn = NULL;
53 }
54
55 /**
56  * Close the connection to para_server and free all resources.
57  *
58  * \param ct Pointer to the client data.
59  *
60  * \sa \ref client_open(), \ref client_disconnect().
61  */
62 void client_close(struct client_task *ct)
63 {
64         if (!ct)
65                 return;
66         client_disconnect(ct);
67         free(ct->user);
68         free(ct->config_file);
69         free(ct->key_file);
70         client_cmdline_parser_free(&ct->conf);
71         free(ct);
72 }
73
74 /**
75  * The preselect hook for server commands.
76  *
77  * \param s Pointer to the scheduler.
78  * \param t Pointer to the task struct for this command.
79  *
80  * The task pointer must contain a pointer to the initialized client data
81  * structure as it is returned by client_open().
82  *
83  * This function checks the state of the connection and adds the file descriptor
84  * of the connection to the read or write fd set of \a s accordingly.
85  *
86  * \sa register_task() client_open(), struct sched, struct task.
87  */
88 static void client_pre_select(struct sched *s, struct task *t)
89 {
90         int ret;
91         struct client_task *ct = container_of(t, struct client_task, task);
92         struct btr_node *btrn = ct->btrn;
93
94         if (ct->scc.fd < 0)
95                 return;
96         switch (ct->status) {
97         case CL_CONNECTED:
98         case CL_SENT_AUTH:
99         case CL_SENT_CH_RESPONSE:
100         case CL_SENT_COMMAND:
101                 para_fd_set(ct->scc.fd, &s->rfds, &s->max_fileno);
102                 return;
103
104         case CL_RECEIVED_WELCOME:
105         case CL_RECEIVED_PROCEED:
106                 para_fd_set(ct->scc.fd, &s->wfds, &s->max_fileno);
107                 return;
108
109         case CL_RECEIVING:
110                 ret = btr_node_status(btrn, 0, BTR_NT_ROOT);
111                 if (ret != 0) {
112                         if (ret < 0)
113                                 sched_min_delay(s);
114                         else
115                                 para_fd_set(ct->scc.fd, &s->rfds,
116                                         &s->max_fileno);
117                 }
118                 return;
119         case CL_SENDING:
120                 ret = btr_node_status(btrn, 0, BTR_NT_LEAF);
121                 if (ret != 0) {
122                         if (ret < 0)
123                                 sched_min_delay(s);
124                         else
125                                 para_fd_set(ct->scc.fd, &s->wfds,
126                                         &s->max_fileno);
127                 }
128                 return;
129         }
130 }
131
132 static int client_recv_buffer(struct client_task *ct, fd_set *rfds,
133                 char *buf, size_t sz, size_t *n)
134 {
135         int ret;
136
137         if (ct->status < CL_SENT_CH_RESPONSE)
138                 return read_nonblock(ct->scc.fd, buf, sz, rfds, n);
139
140         *n = 0;
141         ret = sc_recv_buffer(&ct->scc, buf, sz);
142         /*
143          * sc_recv_buffer is used with blocking fds elsewhere, so it
144          * does not use the nonblock-API. Therefore we need to
145          * check for EOF and EAGAIN.
146          */
147         if (ret == 0)
148                 return -E_SERVER_EOF;
149         if (ret == -ERRNO_TO_PARA_ERROR(EAGAIN))
150                 return 0;
151         if (ret < 0)
152                 return ret;
153         *n = ret;
154         return 0;
155 }
156
157 static int send_sb(struct client_task *ct, void *buf, size_t numbytes,
158                 enum sb_designator band, bool dont_free)
159 {
160         int ret, fd = ct->scc.fd;
161         struct iovec iov[2];
162
163         if (!ct->sbc) {
164                 struct sb_buffer sbb;
165                 sb_transformation trafo = ct->status < CL_RECEIVED_PROCEED?
166                         NULL : sc_trafo;
167                 sbb = (typeof(sbb))SBB_INIT(band, buf, numbytes);
168                 ct->sbc = sb_new_send(&sbb, dont_free, trafo, ct->scc.send);
169         }
170         ret = sb_get_send_buffers(ct->sbc, iov);
171         ret = xwritev(fd, iov, ret);
172         if (ret < 0) {
173                 sb_free(ct->sbc);
174                 ct->sbc = NULL;
175                 return ret;
176         }
177         if (sb_sent(ct->sbc, ret)) {
178                 ct->sbc = NULL;
179                 return 1;
180         }
181         return 0;
182 }
183
184 static int recv_sb(struct client_task *ct, fd_set *rfds,
185                 struct sb_buffer *result)
186 {
187         int ret;
188         size_t n;
189         sb_transformation trafo;
190         void *trafo_context;
191         struct iovec iov;
192
193         if (!FD_ISSET(ct->scc.fd, rfds))
194                 return 0;
195         if (ct->status < CL_SENT_CH_RESPONSE)
196                 trafo = trafo_context = NULL;
197         else {
198                 trafo = sc_trafo;
199                 trafo_context = ct->scc.recv;
200         }
201         if (!ct->sbc)
202                 ct->sbc = sb_new_recv(0, trafo, trafo_context);
203 again:
204         sb_get_recv_buffer(ct->sbc, &iov);
205         ret = read_nonblock(ct->scc.fd, iov.iov_base, iov.iov_len, rfds, &n);
206         if (ret < 0) {
207                 sb_free(ct->sbc);
208                 ct->sbc = NULL;
209                 return ret;
210         }
211         if (n == 0)
212                 return 0;
213         if (!sb_received(ct->sbc, n, result))
214                 goto again;
215         ct->sbc = NULL;
216         return 1;
217 }
218
219
220 static char **parse_features(char *buf)
221 {
222         int i;
223         const char id[] = "\nFeatures: ";
224         char *p, *q, **features;
225
226         p = strstr(buf, id);
227         if (!p)
228                 return NULL;
229         p += strlen(id);
230         q = strchr(p, '\n');
231         if (!q)
232                 return NULL;
233         *q = '\0';
234         create_argv(p, ",", &features);
235         for (i = 0; features[i]; i++)
236                 PARA_INFO_LOG("server feature: %s\n", features[i]);
237         return features;
238 }
239
240 static bool has_feature(const char *feature, struct client_task *ct)
241 {
242         return find_arg(feature, ct->features) >= 0? true : false;
243 }
244
245 /**
246  * The post select hook for client commands.
247  *
248  * \param s Pointer to the scheduler.
249  * \param t Pointer to the task struct for this command.
250  *
251  * Depending on the current state of the connection and the status of the read
252  * and write fd sets of \a s, this function performs the necessary steps to
253  * authenticate the connection, to send the command given by \a t->private_data
254  * and to receive para_server's output, if any.
255  *
256  * \sa struct sched, struct task.
257  */
258 static void client_post_select(struct sched *s, struct task *t)
259 {
260         struct client_task *ct = container_of(t, struct client_task, task);
261         struct btr_node *btrn = ct->btrn;
262         int ret = 0;
263         size_t n;
264         char buf[CLIENT_BUFSIZE];
265
266         t->error = 0;
267         if (ct->scc.fd < 0)
268                 return;
269         switch (ct->status) {
270         case CL_CONNECTED: /* receive welcome message */
271                 ret = client_recv_buffer(ct, &s->rfds, buf, sizeof(buf), &n);
272                 if (ret < 0 || n == 0)
273                         goto out;
274                 ct->features = parse_features(buf);
275                 ct->status = CL_RECEIVED_WELCOME;
276                 return;
277         case CL_RECEIVED_WELCOME: /* send auth command */
278                 if (!FD_ISSET(ct->scc.fd, &s->wfds))
279                         return;
280                 if (has_feature("sideband", ct)) {
281                         ct->use_sideband = true;
282                         sprintf(buf, AUTH_REQUEST_MSG "%s sideband", ct->user);
283                 } else
284                         sprintf(buf, AUTH_REQUEST_MSG "%s", ct->user);
285                 PARA_INFO_LOG("--> %s\n", buf);
286                 ret = write_buffer(ct->scc.fd, buf);
287                 if (ret < 0)
288                         goto out;
289                 ct->status = CL_SENT_AUTH;
290                 return;
291         case CL_SENT_AUTH:
292                 /*
293                  * Receive challenge and session keys, decrypt the challenge and
294                  * send back the hash of the decrypted challenge.
295                  */
296                 {
297                 /* decrypted challenge/session key buffer */
298                 unsigned char crypt_buf[1024];
299                 /* the SHA1 of the decrypted challenge */
300                 unsigned char challenge_hash[HASH_SIZE];
301
302                 if (ct->use_sideband) {
303                         struct sb_buffer sbb;
304                         ret = recv_sb(ct, &s->rfds, &sbb);
305                         if (ret <= 0)
306                                 goto out;
307                         if (sbb.band != SBD_CHALLENGE) {
308                                 ret = -E_BAD_BAND;
309                                 free(sbb.iov.iov_base);
310                                         goto out;
311                         }
312                         n = sbb.iov.iov_len;
313                         PARA_INFO_LOG("<-- [challenge] (%zu bytes)\n", n);
314                         ret = priv_decrypt(ct->key_file, crypt_buf,
315                                 sbb.iov.iov_base, n);
316                         free(sbb.iov.iov_base);
317                         if (ret < 0)
318                                 goto out;
319                 } else {
320                         ret = client_recv_buffer(ct, &s->rfds, buf, sizeof(buf), &n);
321                         if (ret < 0 || n == 0)
322                                 goto out;
323                         PARA_INFO_LOG("<-- [challenge] (%zu bytes)\n", n);
324                         ret = priv_decrypt(ct->key_file, crypt_buf,
325                                 (unsigned char *)buf, n);
326                         if (ret < 0)
327                                 goto out;
328                 }
329                 hash_function((char *)crypt_buf, CHALLENGE_SIZE, challenge_hash);
330                 ct->scc.send = sc_new(crypt_buf + CHALLENGE_SIZE, SESSION_KEY_LEN);
331                 ct->scc.recv = sc_new(crypt_buf + CHALLENGE_SIZE + SESSION_KEY_LEN,
332                         SESSION_KEY_LEN);
333                 hash_to_asc(challenge_hash, buf);
334                 PARA_INFO_LOG("--> %s\n", buf);
335                 ret = write_all(ct->scc.fd, (char *)challenge_hash, HASH_SIZE);
336                 if (ret < 0)
337                         goto out;
338                 ct->status = CL_SENT_CH_RESPONSE;
339                 return;
340                 }
341         case CL_SENT_CH_RESPONSE: /* read server response */
342                 {
343                 ret = client_recv_buffer(ct, &s->rfds, buf, sizeof(buf), &n);
344                 if (ret < 0 || n == 0)
345                         goto out;
346                 /* check if server has sent "Proceed" message */
347                 ret = -E_CLIENT_AUTH;
348                 if (n < PROCEED_MSG_LEN)
349                         goto out;
350                 if (!strstr(buf, PROCEED_MSG))
351                         goto out;
352                 ct->status = CL_RECEIVED_PROCEED;
353                 return;
354                 }
355         case CL_RECEIVED_PROCEED: /* concat args and send command */
356                 {
357                 int i;
358                 char *command = NULL;
359                 if (!FD_ISSET(ct->scc.fd, &s->wfds))
360                         return;
361                 for (i = 0; i < ct->conf.inputs_num; i++) {
362                         char *tmp = command;
363                         command = make_message("%s\n%s", command?
364                                 command : "", ct->conf.inputs[i]);
365                         free(tmp);
366                 }
367                 command = para_strcat(command, EOC_MSG "\n");
368                 PARA_DEBUG_LOG("--> %s\n", command);
369                 ret = sc_send_buffer(&ct->scc, command);
370                 free(command);
371                 if (ret < 0)
372                         goto out;
373                 ct->status = CL_SENT_COMMAND;
374                 return;
375                 }
376         case CL_SENT_COMMAND:
377                 {
378                 char *buf2;
379                 /* can not use "buf" here because we need a malloced buffer */
380                 buf2 = para_malloc(CLIENT_BUFSIZE);
381                 ret = client_recv_buffer(ct, &s->rfds, buf2, CLIENT_BUFSIZE, &n);
382                 if (n > 0) {
383                         if (strstr(buf2, AWAITING_DATA_MSG)) {
384                                 free(buf2);
385                                 ct->status = CL_SENDING;
386                                 return;
387                         }
388                         ct->status = CL_RECEIVING;
389                         btr_add_output(buf2, n, btrn);
390                 } else
391                         free(buf2);
392                 goto out;
393                 }
394         case CL_SENDING:
395                 {
396                 char *buf2;
397                 size_t sz;
398                 ret = btr_node_status(btrn, 0, BTR_NT_LEAF);
399                 if (ret < 0)
400                         goto out;
401                 if (ret == 0)
402                         return;
403                 if (!FD_ISSET(ct->scc.fd, &s->wfds))
404                         return;
405                 sz = btr_next_buffer(btrn, &buf2);
406                 ret = sc_send_bin_buffer(&ct->scc, buf2, sz);
407                 if (ret < 0)
408                         goto out;
409                 btr_consume(btrn, sz);
410                 return;
411                 }
412         case CL_RECEIVING:
413                 {
414                 char *buf2;
415                 ret = btr_node_status(btrn, 0, BTR_NT_ROOT);
416                 if (ret < 0)
417                         goto out;
418                 if (ret == 0)
419                         return;
420                 /*
421                  * The FD_ISSET() is not strictly necessary, but is allows us
422                  * to skip the malloc below if there is nothing to read anyway.
423                  */
424                 if (!FD_ISSET(ct->scc.fd, &s->rfds))
425                         return;
426                 buf2 = para_malloc(CLIENT_BUFSIZE);
427                 ret = client_recv_buffer(ct, &s->rfds, buf2, CLIENT_BUFSIZE, &n);
428                 if (n > 0) {
429                         buf2 = para_realloc(buf2, n);
430                         btr_add_output(buf2, n, btrn);
431                 } else
432                         free(buf2);
433                 goto out;
434                 }
435         }
436 out:
437         t->error = ret;
438         if (ret < 0) {
439                 if (ret != -E_SERVER_EOF && ret != -E_BTR_EOF && ret != -E_EOF)
440                         PARA_ERROR_LOG("%s\n", para_strerror(-t->error));
441                 btr_remove_node(btrn);
442         }
443 }
444
445 /**
446  * Connect to para_server and register the client task.
447  *
448  * \param ct The initialized client task structure.
449  * \param s The scheduler instance to register the client task to.
450  * \param parent The parent node of the client btr node.
451  * \param child The child node of the client node.
452  *
453  * The client task structure given by \a ct  must be allocated and initialized
454  * by \ref client_parse_config() before this function is called.
455  *
456  * \return Standard.
457  */
458 int client_connect(struct client_task *ct, struct sched *s,
459                 struct btr_node *parent, struct btr_node *child)
460 {
461         int ret;
462
463         PARA_NOTICE_LOG("connecting %s:%d\n", ct->conf.hostname_arg,
464                 ct->conf.server_port_arg);
465         ct->scc.fd = -1;
466         ret = para_connect_simple(IPPROTO_TCP, ct->conf.hostname_arg,
467                                                ct->conf.server_port_arg);
468         if (ret < 0)
469                 return ret;
470         ct->scc.fd = ret;
471         ret = mark_fd_nonblocking(ct->scc.fd);
472         if (ret < 0)
473                 goto err_out;
474         ct->status = CL_CONNECTED;
475         ct->btrn = btr_new_node(&(struct btr_node_description)
476                 EMBRACE(.name = "client", .parent = parent, .child = child));
477         ct->task.pre_select = client_pre_select;
478         ct->task.post_select = client_post_select;
479         ct->task.error = 0;
480         sprintf(ct->task.status, "client");
481         register_task(s, &ct->task);
482         return 1;
483 err_out:
484         close(ct->scc.fd);
485         ct->scc.fd = -1;
486         return ret;
487 }
488
489 /**
490  * Parse a client configuration.
491  *
492  * \param argc Usual argument count.
493  * \param argv Usual argument vector.
494  * \param ct_ptr Filled in by this function.
495  * \param loglevel If not \p NULL, the number of the loglevel is stored here.
496  *
497  * This checks the command line options given by \a argc and \a argv, sets
498  * default values for the user name and the name of the rsa key file and reads
499  * further options from the config file.
500  *
501  * Upon successful return, \a ct_ptr points to a dynamically allocated and
502  * initialized client task struct.
503  *
504  * \return The number of non-option arguments in \a argc/argv on success,
505  * negative on errors.
506  */
507 int client_parse_config(int argc, char *argv[], struct client_task **ct_ptr,
508                 int *loglevel)
509 {
510         char *home = para_homedir();
511         int ret;
512         struct client_task *ct = para_calloc(sizeof(struct client_task));
513
514         *ct_ptr = ct;
515         ct->scc.fd = -1;
516         ret = -E_CLIENT_SYNTAX;
517         if (client_cmdline_parser(argc, argv, &ct->conf))
518                 goto out;
519         HANDLE_VERSION_FLAG("client", ct->conf);
520
521         ct->config_file = ct->conf.config_file_given?
522                 para_strdup(ct->conf.config_file_arg) :
523                 make_message("%s/.paraslash/client.conf", home);
524         ret = file_exists(ct->config_file);
525         if (!ret && ct->conf.config_file_given) {
526                 ret = -E_NO_CONFIG;
527                 goto out;
528         }
529         if (ret) {
530                 struct client_cmdline_parser_params params = {
531                         .override = 0,
532                         .initialize = 0,
533                         .check_required = 0,
534                         .check_ambiguity = 0,
535                         .print_errors = 0
536                 };
537                 ret = -E_BAD_CONFIG;
538                 if (client_cmdline_parser_config_file(ct->config_file,
539                         &ct->conf, &params))
540                         goto out;
541         }
542         ct->user = ct->conf.user_given?
543                 para_strdup(ct->conf.user_arg) : para_logname();
544
545         if (ct->conf.key_file_given)
546                 ct->key_file = para_strdup(ct->conf.key_file_arg);
547         else {
548                 ct->key_file = make_message("%s/.paraslash/key.%s",
549                         home, ct->user);
550                 if (!file_exists(ct->key_file)) {
551                         free(ct->key_file);
552                         ct->key_file = make_message("%s/.ssh/id_rsa", home);
553                 }
554         }
555
556         if (loglevel)
557                 *loglevel = get_loglevel_by_name(ct->conf.loglevel_arg);
558         PARA_INFO_LOG("loglevel: %s\n", ct->conf.loglevel_arg);
559         PARA_INFO_LOG("config_file: %s\n", ct->config_file);
560         PARA_INFO_LOG("key_file: %s\n", ct->key_file);
561         ret = ct->conf.inputs_num;
562 out:
563         free(home);
564         if (ret < 0) {
565                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
566                 client_close(ct);
567                 *ct_ptr = NULL;
568         }
569         return ret;
570 }
571
572 /**
573  * Parse the client configuration and open a connection to para_server.
574  *
575  * \param argc See \ref client_parse_config.
576  * \param argv See \ref client_parse_config.
577  * \param ct_ptr See \ref client_parse_config.
578  * \param loglevel See \ref client_parse_config.
579  * \param parent See \ref client_connect().
580  * \param child See \ref client_connect().
581  * \param sched See \ref client_connect().
582  *
583  * This function combines client_parse_config() and client_connect(). It is
584  * considered a syntax error if no command was given, i.e. if the number
585  * of non-option arguments is zero.
586  *
587  * \return Standard.
588  */
589 int client_open(int argc, char *argv[], struct client_task **ct_ptr,
590                 int *loglevel, struct btr_node *parent, struct btr_node *child,
591                 struct sched *sched)
592 {
593         int ret = client_parse_config(argc, argv, ct_ptr, loglevel);
594
595         if (ret < 0)
596                 return ret;
597         if (ret == 0) {
598                 ret = -E_CLIENT_SYNTAX;
599                 goto fail;
600         }
601         ret = client_connect(*ct_ptr, sched, parent, child);
602         if (ret < 0)
603                 goto fail;
604         return 1;
605 fail:
606         client_close(*ct_ptr);
607         *ct_ptr = NULL;
608         return ret;
609 }