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