paraslash 0.4.9
[paraslash.git] / client_common.c
1 /*
2  * Copyright (C) 1997-2011 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 "string.h"
21 #include "client.cmdline.h"
22 #include "client.h"
23 #include "buffer_tree.h"
24 #include "version.h"
25
26 /** The size of the receiving buffer. */
27 #define CLIENT_BUFSIZE 4000
28
29 /**
30  * Close the connection to para_server and deallocate per-command ressources.
31  *
32  * \param ct The client task.
33  *
34  * This frees all ressources of the current command but keeps the configuration
35  * in \p ct->conf.
36  *
37  * \sa \ref client_close().
38  */
39 void client_disconnect(struct client_task *ct)
40 {
41         if (!ct)
42                 return;
43         if (ct->scc.fd >= 0)
44                 close(ct->scc.fd);
45         sc_free(ct->scc.recv);
46         ct->scc.recv = NULL;
47         sc_free(ct->scc.send);
48         ct->scc.send = NULL;
49         btr_free_node(ct->btrn);
50         ct->btrn = NULL;
51 }
52
53 /**
54  * Close the connection to para_server and free all resources.
55  *
56  * \param ct Pointer to the client data.
57  *
58  * \sa \ref client_open(), \ref client_disconnect().
59  */
60 void client_close(struct client_task *ct)
61 {
62         if (!ct)
63                 return;
64         client_disconnect(ct);
65         free(ct->user);
66         free(ct->config_file);
67         free(ct->key_file);
68         client_cmdline_parser_free(&ct->conf);
69         free(ct);
70 }
71
72 /**
73  * The preselect hook for server commands.
74  *
75  * \param s Pointer to the scheduler.
76  * \param t Pointer to the task struct for this command.
77  *
78  * The task pointer must contain a pointer to the initialized client data
79  * structure as it is returned by client_open().
80  *
81  * This function checks the state of the connection and adds the file descriptor
82  * of the connection to the read or write fd set of \a s accordingly.
83  *
84  * \sa register_task() client_open(), struct sched, struct task.
85  */
86 static void client_pre_select(struct sched *s, struct task *t)
87 {
88         int ret;
89         struct client_task *ct = container_of(t, struct client_task, task);
90         struct btr_node *btrn = ct->btrn;
91
92         if (ct->scc.fd < 0)
93                 return;
94         switch (ct->status) {
95         case CL_CONNECTED:
96         case CL_SENT_AUTH:
97         case CL_SENT_CH_RESPONSE:
98         case CL_SENT_COMMAND:
99                 para_fd_set(ct->scc.fd, &s->rfds, &s->max_fileno);
100                 return;
101
102         case CL_RECEIVED_WELCOME:
103         case CL_RECEIVED_PROCEED:
104                 para_fd_set(ct->scc.fd, &s->wfds, &s->max_fileno);
105                 return;
106
107         case CL_RECEIVING:
108                 ret = btr_node_status(btrn, 0, BTR_NT_ROOT);
109                 if (ret != 0) {
110                         if (ret < 0)
111                                 sched_min_delay(s);
112                         else
113                                 para_fd_set(ct->scc.fd, &s->rfds,
114                                         &s->max_fileno);
115                 }
116                 return;
117         case CL_SENDING:
118                 ret = btr_node_status(btrn, 0, BTR_NT_LEAF);
119                 if (ret != 0) {
120                         if (ret < 0)
121                                 sched_min_delay(s);
122                         else
123                                 para_fd_set(ct->scc.fd, &s->wfds,
124                                         &s->max_fileno);
125                 }
126                 return;
127         }
128 }
129
130 static int client_recv_buffer(struct client_task *ct, fd_set *rfds,
131                 char *buf, size_t sz, size_t *n)
132 {
133         int ret;
134
135         if (ct->status < CL_SENT_CH_RESPONSE)
136                 return read_nonblock(ct->scc.fd, buf, sz, rfds, n);
137
138         *n = 0;
139         ret = sc_recv_buffer(&ct->scc, buf, sz);
140         /*
141          * sc_recv_buffer is used with blocking fds elsewhere, so it
142          * does not use the nonblock-API. Therefore we need to
143          * check for EOF and EAGAIN.
144          */
145         if (ret == 0)
146                 return -E_SERVER_EOF;
147         if (ret == -ERRNO_TO_PARA_ERROR(EAGAIN))
148                 return 0;
149         if (ret < 0)
150                 return ret;
151         *n = ret;
152         return 0;
153 }
154
155 /**
156  * The post select hook for client commands.
157  *
158  * \param s Pointer to the scheduler.
159  * \param t Pointer to the task struct for this command.
160  *
161  * Depending on the current state of the connection and the status of the read
162  * and write fd sets of \a s, this function performs the necessary steps to
163  * authenticate the connection, to send the command given by \a t->private_data
164  * and to receive para_server's output, if any.
165  *
166  * \sa struct sched, struct task.
167  */
168 static void client_post_select(struct sched *s, struct task *t)
169 {
170         struct client_task *ct = container_of(t, struct client_task, task);
171         struct btr_node *btrn = ct->btrn;
172         int ret = 0;
173         size_t n;
174         char buf[CLIENT_BUFSIZE];
175
176         t->error = 0;
177         if (ct->scc.fd < 0)
178                 return;
179         switch (ct->status) {
180         case CL_CONNECTED: /* receive welcome message */
181                 ret = client_recv_buffer(ct, &s->rfds, buf, sizeof(buf), &n);
182                 if (ret < 0 || n == 0)
183                         goto out;
184                 ct->status = CL_RECEIVED_WELCOME;
185                 return;
186         case CL_RECEIVED_WELCOME: /* send auth command */
187                 sprintf(buf, AUTH_REQUEST_MSG "%s", ct->user);
188                 PARA_INFO_LOG("--> %s\n", buf);
189                 if (!FD_ISSET(ct->scc.fd, &s->wfds))
190                         return;
191                 ret = send_buffer(ct->scc.fd, buf);
192                 if (ret < 0)
193                         goto out;
194                 ct->status = CL_SENT_AUTH;
195                 return;
196         case CL_SENT_AUTH:
197                 /*
198                  * Receive challenge and session keys, decrypt the challenge and
199                  * send back the hash of the decrypted challenge.
200                  */
201                 {
202                 /* decrypted challenge/session key buffer */
203                 unsigned char crypt_buf[1024];
204                 /* the SHA1 of the decrypted challenge */
205                 unsigned char challenge_hash[HASH_SIZE];
206
207                 ret = client_recv_buffer(ct, &s->rfds, buf, sizeof(buf), &n);
208                 if (ret < 0 || n == 0)
209                         goto out;
210                 PARA_INFO_LOG("<-- [challenge] (%zu bytes)\n", n);
211                 ret = priv_decrypt(ct->key_file, crypt_buf,
212                         (unsigned char *)buf, n);
213                 if (ret < 0)
214                         goto out;
215                 hash_function((char *)crypt_buf, CHALLENGE_SIZE, challenge_hash);
216                 ct->scc.send = sc_new(crypt_buf + CHALLENGE_SIZE, SESSION_KEY_LEN);
217                 ct->scc.recv = sc_new(crypt_buf + CHALLENGE_SIZE + SESSION_KEY_LEN,
218                         SESSION_KEY_LEN);
219                 hash_to_asc(challenge_hash, buf);
220                 PARA_INFO_LOG("--> %s\n", buf);
221                 ret = send_bin_buffer(ct->scc.fd, (char *)challenge_hash,
222                         HASH_SIZE);
223                 if (ret < 0)
224                         goto out;
225                 ct->status = CL_SENT_CH_RESPONSE;
226                 return;
227                 }
228         case CL_SENT_CH_RESPONSE: /* read server response */
229                 {
230                 ret = client_recv_buffer(ct, &s->rfds, buf, sizeof(buf), &n);
231                 if (ret < 0 || n == 0)
232                         goto out;
233                 /* check if server has sent "Proceed" message */
234                 ret = -E_CLIENT_AUTH;
235                 if (n < PROCEED_MSG_LEN)
236                         goto out;
237                 if (!strstr(buf, PROCEED_MSG))
238                         goto out;
239                 ct->status = CL_RECEIVED_PROCEED;
240                 return;
241                 }
242         case CL_RECEIVED_PROCEED: /* concat args and send command */
243                 {
244                 int i;
245                 char *command = NULL;
246                 if (!FD_ISSET(ct->scc.fd, &s->wfds))
247                         return;
248                 for (i = 0; i < ct->conf.inputs_num; i++) {
249                         char *tmp = command;
250                         command = make_message("%s\n%s", command?
251                                 command : "", ct->conf.inputs[i]);
252                         free(tmp);
253                 }
254                 command = para_strcat(command, EOC_MSG "\n");
255                 PARA_DEBUG_LOG("--> %s\n", command);
256                 ret = sc_send_buffer(&ct->scc, command);
257                 free(command);
258                 if (ret < 0)
259                         goto out;
260                 ct->status = CL_SENT_COMMAND;
261                 return;
262                 }
263         case CL_SENT_COMMAND:
264                 {
265                 char *buf2;
266                 /* can not use "buf" here because we need a malloced buffer */
267                 buf2 = para_malloc(CLIENT_BUFSIZE);
268                 ret = client_recv_buffer(ct, &s->rfds, buf2, CLIENT_BUFSIZE, &n);
269                 if (n > 0) {
270                         if (strstr(buf2, AWAITING_DATA_MSG)) {
271                                 free(buf2);
272                                 ct->status = CL_SENDING;
273                                 return;
274                         }
275                         ct->status = CL_RECEIVING;
276                         btr_add_output(buf2, n, btrn);
277                 } else
278                         free(buf2);
279                 goto out;
280                 }
281         case CL_SENDING:
282                 {
283                 char *buf2;
284                 size_t sz;
285                 ret = btr_node_status(btrn, 0, BTR_NT_LEAF);
286                 if (ret < 0)
287                         goto out;
288                 if (ret == 0)
289                         return;
290                 if (!FD_ISSET(ct->scc.fd, &s->wfds))
291                         return;
292                 sz = btr_next_buffer(btrn, &buf2);
293                 ret = sc_send_bin_buffer(&ct->scc, buf2, sz);
294                 if (ret < 0)
295                         goto out;
296                 btr_consume(btrn, sz);
297                 return;
298                 }
299         case CL_RECEIVING:
300                 {
301                 char *buf2;
302                 ret = btr_node_status(btrn, 0, BTR_NT_ROOT);
303                 if (ret < 0)
304                         goto out;
305                 if (ret == 0)
306                         return;
307                 /*
308                  * The FD_ISSET() is not strictly necessary, but is allows us
309                  * to skip the malloc below if there is nothing to read anyway.
310                  */
311                 if (!FD_ISSET(ct->scc.fd, &s->rfds))
312                         return;
313                 buf2 = para_malloc(CLIENT_BUFSIZE);
314                 ret = client_recv_buffer(ct, &s->rfds, buf2, CLIENT_BUFSIZE, &n);
315                 if (n > 0) {
316                         buf2 = para_realloc(buf2, n);
317                         btr_add_output(buf2, n, btrn);
318                 } else
319                         free(buf2);
320                 goto out;
321                 }
322         }
323 out:
324         t->error = ret;
325         if (ret < 0) {
326                 if (ret != -E_SERVER_EOF && ret != -E_BTR_EOF)
327                         PARA_ERROR_LOG("%s\n", para_strerror(-t->error));
328                 btr_remove_node(btrn);
329         }
330 }
331
332 /**
333  * Connect to para_server and register the client task.
334  *
335  * \param ct The initialized client task structure.
336  * \param s The scheduler instance to register the client task to.
337  * \param parent The parent node of the client btr node.
338  * \param child The child node of the client node.
339  *
340  * The client task structure given by \a ct  must be allocated and initialized
341  * by \ref client_parse_config() before this function is called.
342  *
343  * \return Standard.
344  */
345 int client_connect(struct client_task *ct, struct sched *s,
346                 struct btr_node *parent, struct btr_node *child)
347 {
348         int ret;
349
350         PARA_NOTICE_LOG("connecting %s:%d\n", ct->conf.hostname_arg,
351                 ct->conf.server_port_arg);
352         ct->scc.fd = -1;
353         ret = para_connect_simple(IPPROTO_TCP, ct->conf.hostname_arg,
354                                                ct->conf.server_port_arg);
355         if (ret < 0)
356                 return ret;
357         ct->scc.fd = ret;
358         ret = mark_fd_nonblocking(ct->scc.fd);
359         if (ret < 0)
360                 goto err_out;
361         ct->status = CL_CONNECTED;
362         ct->btrn = btr_new_node(&(struct btr_node_description)
363                 EMBRACE(.name = "client", .parent = parent, .child = child));
364         ct->task.pre_select = client_pre_select;
365         ct->task.post_select = client_post_select;
366         ct->task.error = 0;
367         sprintf(ct->task.status, "client");
368         register_task(s, &ct->task);
369         return 1;
370 err_out:
371         close(ct->scc.fd);
372         ct->scc.fd = -1;
373         return ret;
374 }
375
376 /**
377  * Parse a client configuration.
378  *
379  * \param argc Usual argument count.
380  * \param argv Usual argument vector.
381  * \param ct_ptr Filled in by this function.
382  * \param loglevel If not \p NULL, the number of the loglevel is stored here.
383  *
384  * This checks the command line options given by \a argc and \a argv, sets
385  * default values for the user name and the name of the rsa key file and reads
386  * further options from the config file.
387  *
388  * Upon successful return, \a ct_ptr points to a dynamically allocated and
389  * initialized client task struct.
390  *
391  * \return The number of non-option arguments in \a argc/argv on success,
392  * negative on errors.
393  */
394 int client_parse_config(int argc, char *argv[], struct client_task **ct_ptr,
395                 int *loglevel)
396 {
397         char *home = para_homedir();
398         int ret;
399         struct client_task *ct = para_calloc(sizeof(struct client_task));
400
401         *ct_ptr = ct;
402         ct->scc.fd = -1;
403         ret = -E_CLIENT_SYNTAX;
404         if (client_cmdline_parser(argc, argv, &ct->conf))
405                 goto out;
406         HANDLE_VERSION_FLAG("client", ct->conf);
407
408         ct->config_file = ct->conf.config_file_given?
409                 para_strdup(ct->conf.config_file_arg) :
410                 make_message("%s/.paraslash/client.conf", home);
411         ret = file_exists(ct->config_file);
412         if (!ret && ct->conf.config_file_given) {
413                 ret = -E_NO_CONFIG;
414                 goto out;
415         }
416         if (ret) {
417                 struct client_cmdline_parser_params params = {
418                         .override = 0,
419                         .initialize = 0,
420                         .check_required = 0,
421                         .check_ambiguity = 0,
422                         .print_errors = 0
423                 };
424                 ret = -E_BAD_CONFIG;
425                 if (client_cmdline_parser_config_file(ct->config_file,
426                         &ct->conf, &params))
427                         goto out;
428         }
429         ct->user = ct->conf.user_given?
430                 para_strdup(ct->conf.user_arg) : para_logname();
431
432         if (ct->conf.key_file_given)
433                 ct->key_file = para_strdup(ct->conf.key_file_arg);
434         else {
435                 ct->key_file = make_message("%s/.paraslash/key.%s",
436                         home, ct->user);
437                 if (!file_exists(ct->key_file)) {
438                         free(ct->key_file);
439                         ct->key_file = make_message("%s/.ssh/id_rsa", home);
440                 }
441         }
442
443         if (loglevel)
444                 *loglevel = get_loglevel_by_name(ct->conf.loglevel_arg);
445         PARA_INFO_LOG("loglevel: %s\n", ct->conf.loglevel_arg);
446         PARA_INFO_LOG("config_file: %s\n", ct->config_file);
447         PARA_INFO_LOG("key_file: %s\n", ct->key_file);
448         ret = ct->conf.inputs_num;
449 out:
450         free(home);
451         if (ret < 0) {
452                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
453                 client_close(ct);
454                 *ct_ptr = NULL;
455         }
456         return ret;
457 }
458
459 /**
460  * Parse the client configuration and open a connection to para_server.
461  *
462  * \param argc See \ref client_parse_config.
463  * \param argv See \ref client_parse_config.
464  * \param ct_ptr See \ref client_parse_config.
465  * \param loglevel See \ref client_parse_config.
466  * \param parent See \ref client_connect().
467  * \param child See \ref client_connect().
468  * \param sched See \ref client_connect().
469  *
470  * This function combines client_parse_config() and client_connect(). It is
471  * considered a syntax error if no command was given, i.e. if the number
472  * of non-option arguments is zero.
473  *
474  * \return Standard.
475  */
476 int client_open(int argc, char *argv[], struct client_task **ct_ptr,
477                 int *loglevel, struct btr_node *parent, struct btr_node *child,
478                 struct sched *sched)
479 {
480         int ret = client_parse_config(argc, argv, ct_ptr, loglevel);
481
482         if (ret < 0)
483                 return ret;
484         if (ret == 0) {
485                 ret = -E_CLIENT_SYNTAX;
486                 goto fail;
487         }
488         ret = client_connect(*ct_ptr, sched, parent, child);
489         if (ret < 0)
490                 goto fail;
491         return 1;
492 fail:
493         client_close(*ct_ptr);
494         *ct_ptr = NULL;
495         return ret;
496 }