http_recv: Trivial cleanup.
[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 "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 = write_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 = write_all(ct->scc.fd, (char *)challenge_hash, HASH_SIZE);
222                 if (ret < 0)
223                         goto out;
224                 ct->status = CL_SENT_CH_RESPONSE;
225                 return;
226                 }
227         case CL_SENT_CH_RESPONSE: /* read server response */
228                 {
229                 ret = client_recv_buffer(ct, &s->rfds, buf, sizeof(buf), &n);
230                 if (ret < 0 || n == 0)
231                         goto out;
232                 /* check if server has sent "Proceed" message */
233                 ret = -E_CLIENT_AUTH;
234                 if (n < PROCEED_MSG_LEN)
235                         goto out;
236                 if (!strstr(buf, PROCEED_MSG))
237                         goto out;
238                 ct->status = CL_RECEIVED_PROCEED;
239                 return;
240                 }
241         case CL_RECEIVED_PROCEED: /* concat args and send command */
242                 {
243                 int i;
244                 char *command = NULL;
245                 if (!FD_ISSET(ct->scc.fd, &s->wfds))
246                         return;
247                 for (i = 0; i < ct->conf.inputs_num; i++) {
248                         char *tmp = command;
249                         command = make_message("%s\n%s", command?
250                                 command : "", ct->conf.inputs[i]);
251                         free(tmp);
252                 }
253                 command = para_strcat(command, EOC_MSG "\n");
254                 PARA_DEBUG_LOG("--> %s\n", command);
255                 ret = sc_send_buffer(&ct->scc, command);
256                 free(command);
257                 if (ret < 0)
258                         goto out;
259                 ct->status = CL_SENT_COMMAND;
260                 return;
261                 }
262         case CL_SENT_COMMAND:
263                 {
264                 char *buf2;
265                 /* can not use "buf" here because we need a malloced buffer */
266                 buf2 = para_malloc(CLIENT_BUFSIZE);
267                 ret = client_recv_buffer(ct, &s->rfds, buf2, CLIENT_BUFSIZE, &n);
268                 if (n > 0) {
269                         if (strstr(buf2, AWAITING_DATA_MSG)) {
270                                 free(buf2);
271                                 ct->status = CL_SENDING;
272                                 return;
273                         }
274                         ct->status = CL_RECEIVING;
275                         btr_add_output(buf2, n, btrn);
276                 } else
277                         free(buf2);
278                 goto out;
279                 }
280         case CL_SENDING:
281                 {
282                 char *buf2;
283                 size_t sz;
284                 ret = btr_node_status(btrn, 0, BTR_NT_LEAF);
285                 if (ret < 0)
286                         goto out;
287                 if (ret == 0)
288                         return;
289                 if (!FD_ISSET(ct->scc.fd, &s->wfds))
290                         return;
291                 sz = btr_next_buffer(btrn, &buf2);
292                 ret = sc_send_bin_buffer(&ct->scc, buf2, sz);
293                 if (ret < 0)
294                         goto out;
295                 btr_consume(btrn, sz);
296                 return;
297                 }
298         case CL_RECEIVING:
299                 {
300                 char *buf2;
301                 ret = btr_node_status(btrn, 0, BTR_NT_ROOT);
302                 if (ret < 0)
303                         goto out;
304                 if (ret == 0)
305                         return;
306                 /*
307                  * The FD_ISSET() is not strictly necessary, but is allows us
308                  * to skip the malloc below if there is nothing to read anyway.
309                  */
310                 if (!FD_ISSET(ct->scc.fd, &s->rfds))
311                         return;
312                 buf2 = para_malloc(CLIENT_BUFSIZE);
313                 ret = client_recv_buffer(ct, &s->rfds, buf2, CLIENT_BUFSIZE, &n);
314                 if (n > 0) {
315                         buf2 = para_realloc(buf2, n);
316                         btr_add_output(buf2, n, btrn);
317                 } else
318                         free(buf2);
319                 goto out;
320                 }
321         }
322 out:
323         t->error = ret;
324         if (ret < 0) {
325                 if (ret != -E_SERVER_EOF && ret != -E_BTR_EOF)
326                         PARA_ERROR_LOG("%s\n", para_strerror(-t->error));
327                 btr_remove_node(btrn);
328         }
329 }
330
331 /**
332  * Connect to para_server and register the client task.
333  *
334  * \param ct The initialized client task structure.
335  * \param s The scheduler instance to register the client task to.
336  * \param parent The parent node of the client btr node.
337  * \param child The child node of the client node.
338  *
339  * The client task structure given by \a ct  must be allocated and initialized
340  * by \ref client_parse_config() before this function is called.
341  *
342  * \return Standard.
343  */
344 int client_connect(struct client_task *ct, struct sched *s,
345                 struct btr_node *parent, struct btr_node *child)
346 {
347         int ret;
348
349         PARA_NOTICE_LOG("connecting %s:%d\n", ct->conf.hostname_arg,
350                 ct->conf.server_port_arg);
351         ct->scc.fd = -1;
352         ret = para_connect_simple(IPPROTO_TCP, ct->conf.hostname_arg,
353                                                ct->conf.server_port_arg);
354         if (ret < 0)
355                 return ret;
356         ct->scc.fd = ret;
357         ret = mark_fd_nonblocking(ct->scc.fd);
358         if (ret < 0)
359                 goto err_out;
360         ct->status = CL_CONNECTED;
361         ct->btrn = btr_new_node(&(struct btr_node_description)
362                 EMBRACE(.name = "client", .parent = parent, .child = child));
363         ct->task.pre_select = client_pre_select;
364         ct->task.post_select = client_post_select;
365         ct->task.error = 0;
366         sprintf(ct->task.status, "client");
367         register_task(s, &ct->task);
368         return 1;
369 err_out:
370         close(ct->scc.fd);
371         ct->scc.fd = -1;
372         return ret;
373 }
374
375 /**
376  * Parse a client configuration.
377  *
378  * \param argc Usual argument count.
379  * \param argv Usual argument vector.
380  * \param ct_ptr Filled in by this function.
381  * \param loglevel If not \p NULL, the number of the loglevel is stored here.
382  *
383  * This checks the command line options given by \a argc and \a argv, sets
384  * default values for the user name and the name of the rsa key file and reads
385  * further options from the config file.
386  *
387  * Upon successful return, \a ct_ptr points to a dynamically allocated and
388  * initialized client task struct.
389  *
390  * \return The number of non-option arguments in \a argc/argv on success,
391  * negative on errors.
392  */
393 int client_parse_config(int argc, char *argv[], struct client_task **ct_ptr,
394                 int *loglevel)
395 {
396         char *home = para_homedir();
397         int ret;
398         struct client_task *ct = para_calloc(sizeof(struct client_task));
399
400         *ct_ptr = ct;
401         ct->scc.fd = -1;
402         ret = -E_CLIENT_SYNTAX;
403         if (client_cmdline_parser(argc, argv, &ct->conf))
404                 goto out;
405         HANDLE_VERSION_FLAG("client", ct->conf);
406
407         ct->config_file = ct->conf.config_file_given?
408                 para_strdup(ct->conf.config_file_arg) :
409                 make_message("%s/.paraslash/client.conf", home);
410         ret = file_exists(ct->config_file);
411         if (!ret && ct->conf.config_file_given) {
412                 ret = -E_NO_CONFIG;
413                 goto out;
414         }
415         if (ret) {
416                 struct client_cmdline_parser_params params = {
417                         .override = 0,
418                         .initialize = 0,
419                         .check_required = 0,
420                         .check_ambiguity = 0,
421                         .print_errors = 0
422                 };
423                 ret = -E_BAD_CONFIG;
424                 if (client_cmdline_parser_config_file(ct->config_file,
425                         &ct->conf, &params))
426                         goto out;
427         }
428         ct->user = ct->conf.user_given?
429                 para_strdup(ct->conf.user_arg) : para_logname();
430
431         if (ct->conf.key_file_given)
432                 ct->key_file = para_strdup(ct->conf.key_file_arg);
433         else {
434                 ct->key_file = make_message("%s/.paraslash/key.%s",
435                         home, ct->user);
436                 if (!file_exists(ct->key_file)) {
437                         free(ct->key_file);
438                         ct->key_file = make_message("%s/.ssh/id_rsa", home);
439                 }
440         }
441
442         if (loglevel)
443                 *loglevel = get_loglevel_by_name(ct->conf.loglevel_arg);
444         PARA_INFO_LOG("loglevel: %s\n", ct->conf.loglevel_arg);
445         PARA_INFO_LOG("config_file: %s\n", ct->config_file);
446         PARA_INFO_LOG("key_file: %s\n", ct->key_file);
447         ret = ct->conf.inputs_num;
448 out:
449         free(home);
450         if (ret < 0) {
451                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
452                 client_close(ct);
453                 *ct_ptr = NULL;
454         }
455         return ret;
456 }
457
458 /**
459  * Parse the client configuration and open a connection to para_server.
460  *
461  * \param argc See \ref client_parse_config.
462  * \param argv See \ref client_parse_config.
463  * \param ct_ptr See \ref client_parse_config.
464  * \param loglevel See \ref client_parse_config.
465  * \param parent See \ref client_connect().
466  * \param child See \ref client_connect().
467  * \param sched See \ref client_connect().
468  *
469  * This function combines client_parse_config() and client_connect(). It is
470  * considered a syntax error if no command was given, i.e. if the number
471  * of non-option arguments is zero.
472  *
473  * \return Standard.
474  */
475 int client_open(int argc, char *argv[], struct client_task **ct_ptr,
476                 int *loglevel, struct btr_node *parent, struct btr_node *child,
477                 struct sched *sched)
478 {
479         int ret = client_parse_config(argc, argv, ct_ptr, loglevel);
480
481         if (ret < 0)
482                 return ret;
483         if (ret == 0) {
484                 ret = -E_CLIENT_SYNTAX;
485                 goto fail;
486         }
487         ret = client_connect(*ct_ptr, sched, parent, child);
488         if (ret < 0)
489                 goto fail;
490         return 1;
491 fail:
492         client_close(*ct_ptr);
493         *ct_ptr = NULL;
494         return ret;
495 }