7ecc57332f92f21febd3b8da90211517ee2cccdf
[claws.git] / src / common / session.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2003 Hiroyuki Yamamoto
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #include <glib.h>
27
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <sys/types.h>
32 #include <unistd.h>
33 #include <sys/signal.h>
34 #include <sys/wait.h>
35 #include <sys/time.h>
36 #include <errno.h>
37
38 #include "session.h"
39 #include "utils.h"
40
41 static gint session_connect_cb          (SockInfo       *sock,
42                                          gpointer        data);
43 static gint session_close               (Session        *session);
44
45 static gboolean session_read_msg_cb     (GIOChannel     *source,
46                                          GIOCondition    condition,
47                                          gpointer        data);
48 static gboolean session_read_data_cb    (GIOChannel     *source,
49                                          GIOCondition    condition,
50                                          gpointer        data);
51 static gboolean session_write_msg_cb    (GIOChannel     *source,
52                                          GIOCondition    condition,
53                                          gpointer        data);
54 static gboolean session_write_data_cb   (GIOChannel     *source,
55                                          GIOCondition    condition,
56                                          gpointer        data);
57
58
59 void session_init(Session *session)
60 {
61         session->type = SESSION_UNKNOWN;
62         session->sock = NULL;
63         session->server = NULL;
64         session->port = 0;
65 #if USE_OPENSSL
66         session->ssl_type = SSL_NONE;
67 #endif
68         session->state = SESSION_READY;
69         session->last_access_time = time(NULL);
70
71         gettimeofday(&session->tv_prev, NULL);
72
73         session->conn_id = 0;
74
75         session->sock_ch = NULL;
76         session->io_tag = 0;
77
78         session->read_buf = g_string_sized_new(1024);
79         session->read_data_buf = g_byte_array_new();
80         session->write_buf = NULL;
81         session->write_buf_p = NULL;
82         session->write_buf_len = 0;
83
84         session->data = NULL;
85 }
86
87 /*!
88  *\brief        Set up parent and child process
89  *              Childloop: Read commands from parent,
90  *              send to server, get answer, pass to parent
91  *
92  *\param        session Contains session information
93  *              server to connect to
94  *              port to connect to
95  *
96  *\return        0 : success
97  *              -1 : pipe / fork errors (parent)
98  *               1 : connection error (child)
99  */
100 gint session_connect(Session *session, const gchar *server, gushort port)
101 {
102         session->server = g_strdup(server);
103         session->port = port;
104
105         session->conn_id = sock_connect_async(server, port, session_connect_cb,
106                                               session);
107         if (session->conn_id < 0) {
108                 g_warning("can't connect to server.");
109                 session_close(session);
110                 return -1;
111         }
112
113         return 0;
114 }
115
116 static gint session_connect_cb(SockInfo *sock, gpointer data)
117 {
118         Session *session = SESSION(data);
119
120         session->conn_id = 0;
121
122         if (!sock) {
123                 g_warning("can't connect to server.");
124                 session->state = SESSION_ERROR;
125                 return -1;
126         }
127
128         session->sock = sock;
129
130 #if USE_OPENSSL
131         sock_set_nonblocking_mode(sock, FALSE);
132         if (session->ssl_type == SSL_TUNNEL && !ssl_init_socket(sock)) {
133                 g_warning("can't initialize SSL.");
134                 session->state = SESSION_ERROR;
135                 return -1;
136         }
137 #endif
138
139         debug_print("session: child: connected\n");
140
141         debug_print("session: connected\n");
142
143         session->state = SESSION_RECV;
144         session->sock_ch = g_io_channel_unix_new(sock->sock);
145         session->io_tag = g_io_add_watch(session->sock_ch, G_IO_IN,
146                                          session_read_msg_cb,
147                                          session);
148
149         return 0;
150 }
151
152 /*!
153  *\brief        child and parent: send DISCONNECT message to other process
154  *
155  *\param        session Contains session information
156  *
157  *\return        0 : success
158  */
159 gint session_disconnect(Session *session)
160 {
161         session_close(session);
162         return 0;
163 }
164
165 /*!
166  *\brief        parent ?
167  *
168  *\param        session Contains session information
169  */
170 void session_destroy(Session *session)
171 {
172         g_return_if_fail(session != NULL);
173         g_return_if_fail(session->destroy != NULL);
174
175         debug_print("session: session_destroy()\n");
176         session_close(session);
177         session->destroy(session);
178         g_free(session->server);
179         g_string_free(session->read_buf, TRUE);
180         g_byte_array_free(session->read_data_buf, TRUE);
181         g_free(session->read_data_terminator);
182         g_free(session->write_buf);
183         g_free(session);
184 }
185
186 void session_set_recv_message_notify(Session *session,
187                                      RecvMsgNotify notify_func, gpointer data)
188 {
189         session->recv_msg_notify = notify_func;
190         session->recv_msg_notify_data = data;
191 }
192
193 void session_set_recv_data_progressive_notify
194                                         (Session *session,
195                                          RecvDataProgressiveNotify notify_func,
196                                          gpointer data)
197 {
198         session->recv_data_progressive_notify = notify_func,
199         session->recv_data_progressive_notify_data = data;
200 }
201
202 void session_set_recv_data_notify(Session *session, RecvDataNotify notify_func,
203                                   gpointer data)
204 {
205         session->recv_data_notify = notify_func;
206         session->recv_data_notify_data = data;
207 }
208
209 void session_set_send_data_progressive_notify
210                                         (Session *session,
211                                          SendDataProgressiveNotify notify_func,
212                                          gpointer data)
213 {
214         session->send_data_progressive_notify = notify_func;
215         session->send_data_progressive_notify_data = data;
216 }
217
218 void session_set_send_data_notify(Session *session, SendDataNotify notify_func,
219                                   gpointer data)
220 {
221         session->send_data_notify = notify_func;
222         session->send_data_notify_data = data;
223 }
224
225 /*!
226  *\brief        child and parent cleanup (child closes first)
227  *
228  *\param        session Contains session information
229  *
230  *\return        0 : success
231  */
232 static gint session_close(Session *session)
233 {
234         g_return_val_if_fail(session != NULL, -1);
235
236         debug_print("session_close\n");
237
238         if (session->conn_id > 0) {
239                 sock_connect_async_cancel(session->conn_id);
240                 session->conn_id = 0;
241         }
242
243         if (session->io_tag > 0) {
244                 g_source_remove(session->io_tag);
245                 session->io_tag = 0;
246         }
247
248         if (session->sock_ch) {
249                 g_io_channel_unref(session->sock_ch);
250                 session->sock_ch = NULL;
251         }
252
253         if (session->sock) {
254                 sock_close(session->sock);
255                 session->sock = NULL;
256                 session->state = SESSION_DISCONNECTED;
257         }
258
259         return 0;
260 }
261
262 #if USE_OPENSSL
263 gint session_start_tls(Session *session)
264 {
265         gboolean nb_mode;
266
267         nb_mode = sock_is_nonblocking_mode(session->sock);
268
269         if (nb_mode)
270                 sock_set_nonblocking_mode(session->sock, FALSE);
271
272         if (!ssl_init_socket_with_method(session->sock, SSL_METHOD_TLSv1)) {
273                 g_warning("can't start TLS session.\n");
274                 if (nb_mode)
275                         sock_set_nonblocking_mode(session->sock, TRUE);
276                 return -1;
277         }
278
279         if (nb_mode)
280                 sock_set_nonblocking_mode(session->sock, TRUE);
281
282         return 0;
283 }
284 #endif
285
286 gint session_send_msg(Session *session, SessionMsgType type, const gchar *msg)
287 {
288         gboolean ret;
289
290         g_return_val_if_fail(session->write_buf == NULL, -1);
291         g_return_val_if_fail(msg != NULL, -1);
292         g_return_val_if_fail(msg[0] != '\0', -1);
293
294         session->state = SESSION_SEND;
295         session->write_buf = g_strconcat(msg, "\r\n", NULL);
296         session->write_buf_p = session->write_buf;
297         session->write_buf_len = strlen(msg) + 2;
298
299         ret = session_write_msg_cb(session->sock_ch, G_IO_OUT, session);
300
301         if (ret == TRUE)
302                 session->io_tag = g_io_add_watch(session->sock_ch, G_IO_OUT,
303                                                  session_write_msg_cb, session);
304         else if (session->state == SESSION_ERROR)
305                 return -1;
306
307         return 0;
308 }
309
310 gint session_recv_msg(Session *session)
311 {
312         g_return_val_if_fail(session->read_buf->len == 0, -1);
313
314         session->state = SESSION_RECV;
315
316         session->io_tag = g_io_add_watch(session->sock_ch, G_IO_IN,
317                                          session_read_msg_cb, session);
318
319         return 0;
320 }
321
322 /*!
323  *\brief        parent (child?): send data to other process
324  *
325  *\param        session Contains session information
326  *              data Data to send
327  *              size Bytes to send
328  *
329  *\return        0 : success
330  *              -1 : error
331  */
332 gint session_send_data(Session *session, const guchar *data, guint size)
333 {
334         gboolean ret;
335
336         g_return_val_if_fail(session->write_buf == NULL, -1);
337         g_return_val_if_fail(data != NULL, -1);
338         g_return_val_if_fail(size != 0, -1);
339
340         session->state = SESSION_SEND;
341
342         session->write_buf = g_malloc(size);
343         session->write_buf_p = session->write_buf;
344         memcpy(session->write_buf, data, size);
345         session->write_buf_len = size;
346         gettimeofday(&session->tv_prev, NULL);
347
348         ret = session_write_data_cb(session->sock_ch, G_IO_OUT, session);
349
350         if (ret == TRUE)
351                 session->io_tag = g_io_add_watch(session->sock_ch, G_IO_OUT,
352                                                  session_write_data_cb,
353                                                  session);
354         else if (session->state == SESSION_ERROR)
355                 return -1;
356
357         return 0;
358 }
359
360 gint session_recv_data(Session *session, guint size, const gchar *terminator)
361 {
362         g_return_val_if_fail(session->read_data_buf->len == 0, -1);
363
364         session->state = SESSION_RECV;
365
366         g_free(session->read_data_terminator);
367         session->read_data_terminator = g_strdup(terminator);
368         gettimeofday(&session->tv_prev, NULL);
369
370         session->io_tag = g_io_add_watch(session->sock_ch, G_IO_IN,
371                                          session_read_data_cb, session);
372
373         return 0;
374 }
375
376 static gboolean session_read_msg_cb(GIOChannel *source, GIOCondition condition,
377                                     gpointer data)
378 {
379         Session *session = SESSION(data);
380         gchar buf[SESSION_BUFFSIZE];
381         gint read_len;
382         gint to_read_len;
383         gchar *newline;
384         gchar *msg;
385         gint ret;
386
387         g_return_val_if_fail(condition == G_IO_IN, FALSE);
388
389         read_len = sock_peek(session->sock, buf, sizeof(buf) - 1);
390
391         if (read_len < 0) {
392                 switch (errno) {
393                 case EAGAIN:
394                         g_print("session_read_msg_cb: %s\n", g_strerror(errno));
395                         return TRUE;
396                 default:
397                         g_warning("sock_peek: %s\n", g_strerror(errno));
398                         session->state = SESSION_ERROR;
399                         return FALSE;
400                 }
401         }
402
403         if ((newline = memchr(buf, '\n', read_len)) != NULL)
404                 to_read_len = newline - buf + 1;
405         else
406                 to_read_len = read_len;
407
408         read_len = sock_read(session->sock, buf, to_read_len);
409
410         /* this should always succeed */
411         if (read_len < 0) {
412                 switch (errno) {
413                 case EAGAIN:
414                         g_print("session_read_msg_cb: %s\n", g_strerror(errno));
415                         return TRUE;
416                 default:
417                         g_warning("sock_read: %s\n", g_strerror(errno));
418                         session->state = SESSION_ERROR;
419                         return FALSE;
420                 }
421         }
422
423         buf[read_len] = '\0';
424
425         /* incomplete read */
426         if (read_len == 0 || buf[read_len - 1] != '\n') {
427                 g_string_append(session->read_buf, buf);
428                 return TRUE;
429         }
430
431         /* complete */
432         strretchomp(buf);
433         g_string_append(session->read_buf, buf);
434
435         if (session->io_tag > 0) {
436                 g_source_remove(session->io_tag);
437                 session->io_tag = 0;
438         }
439
440         /* callback */
441         msg = g_strdup(session->read_buf->str);
442         g_string_truncate(session->read_buf, 0);
443
444         ret = session->recv_msg(session, msg);
445         session->recv_msg_notify(session, msg, session->recv_msg_notify_data);
446
447         g_free(msg);
448
449         if (ret < 0)
450                 session->state = SESSION_ERROR;
451
452         return FALSE;
453 }
454
455 static gboolean session_read_data_cb(GIOChannel *source, GIOCondition condition,
456                                      gpointer data)
457 {
458         Session *session = SESSION(data);
459         gchar buf[SESSION_BUFFSIZE];
460         GByteArray *data_buf;
461         gint read_len;
462         gint terminator_len;
463         gboolean complete = FALSE;
464         gint ret;
465
466         g_return_val_if_fail(condition == G_IO_IN, FALSE);
467
468         read_len = sock_read(session->sock, buf, sizeof(buf));
469
470         if (read_len < 0) {
471                 switch (errno) {
472                 case EAGAIN:
473                         g_print("session_read_data_cb: %s\n", g_strerror(errno));
474                         return TRUE;
475                 default:
476                         g_warning("sock_read: %s\n", g_strerror(errno));
477                         session->state = SESSION_ERROR;
478                         return FALSE;
479                 }
480         }
481
482         data_buf = session->read_data_buf;
483
484         g_byte_array_append(data_buf, buf, read_len);
485         terminator_len = strlen(session->read_data_terminator);
486
487         /* check if data is terminated */
488         if (read_len > 0 && data_buf->len >= terminator_len) {
489                 if (memcmp(data_buf->data, session->read_data_terminator,
490                            terminator_len) == 0)
491                         complete = TRUE;
492                 else if (data_buf->len >= terminator_len + 2 &&
493                          memcmp(data_buf->data + data_buf->len -
494                                 (terminator_len + 2), "\r\n", 2) == 0 &&
495                          memcmp(data_buf->data + data_buf->len -
496                                 terminator_len, session->read_data_terminator,
497                                 terminator_len) == 0)
498                         complete = TRUE;
499         }
500
501         /* incomplete read */
502         if (!complete) {
503                 struct timeval tv_cur;
504
505                 gettimeofday(&tv_cur, NULL);
506                 if (tv_cur.tv_sec - session->tv_prev.tv_sec > 0 ||
507                     tv_cur.tv_usec - session->tv_prev.tv_usec >
508                     UI_REFRESH_INTERVAL) {
509                         session->recv_data_progressive_notify
510                                 (session, data_buf->len, 0,
511                                  session->recv_data_progressive_notify_data);
512                         gettimeofday(&session->tv_prev, NULL);
513                 }
514                 return TRUE;
515         }
516
517         /* complete */
518         if (session->io_tag > 0) {
519                 g_source_remove(session->io_tag);
520                 session->io_tag = 0;
521         }
522
523         /* callback */
524         ret = session->recv_data_finished(session, data_buf->data,
525                                           data_buf->len - terminator_len);
526         session->recv_data_notify(session, data_buf->len - terminator_len,
527                                   session->recv_data_notify_data);
528
529         g_byte_array_set_size(data_buf, 0);
530
531         if (ret < 0)
532                 session->state = SESSION_ERROR;
533
534         return FALSE;
535 }
536
537 static gint session_write_buf(Session *session)
538 {
539         gint write_len;
540         gint to_write_len;
541
542         g_return_val_if_fail(session->write_buf != NULL, -1);
543         g_return_val_if_fail(session->write_buf_p != NULL, -1);
544         g_return_val_if_fail(session->write_buf_len > 0, -1);
545
546         to_write_len = session->write_buf_len -
547                 (session->write_buf_p - session->write_buf);
548         to_write_len = MIN(to_write_len, SESSION_BUFFSIZE);
549
550         write_len = sock_write(session->sock, session->write_buf_p,
551                                to_write_len);
552
553         if (write_len < 0) {
554                 switch (errno) {
555                 case EAGAIN:
556                         g_print("session_write_cb: %s\n", g_strerror(errno));
557                         write_len = 0;
558                         break;
559                 default:
560                         g_warning("sock_write: %s\n", g_strerror(errno));
561                         session->state = SESSION_ERROR;
562                         return -1;
563                 }
564         }
565
566         /* incomplete write */
567         if (session->write_buf_p - session->write_buf + write_len <
568             session->write_buf_len) {
569                 session->write_buf_p += write_len;
570                 return 1;
571         }
572
573         g_free(session->write_buf);
574         session->write_buf = NULL;
575         session->write_buf_p = NULL;
576         session->write_buf_len = 0;
577
578         return 0;
579 }
580
581 static gboolean session_write_msg_cb(GIOChannel *source, GIOCondition condition,
582                                      gpointer data)
583 {
584         Session *session = SESSION(data);
585         gint ret;
586
587         g_return_val_if_fail(condition == G_IO_OUT, FALSE);
588         g_return_val_if_fail(session->write_buf != NULL, FALSE);
589         g_return_val_if_fail(session->write_buf_p != NULL, FALSE);
590         g_return_val_if_fail(session->write_buf_len > 0, FALSE);
591
592         ret = session_write_buf(session);
593
594         if (ret < 0) {
595                 session->state = SESSION_ERROR;
596                 return FALSE;
597         } else if (ret > 0)
598                 return TRUE;
599
600         if (session->io_tag > 0) {
601                 g_source_remove(session->io_tag);
602                 session->io_tag = 0;
603         }
604
605         session_recv_msg(session);
606
607         return FALSE;
608 }
609
610 static gboolean session_write_data_cb(GIOChannel *source,
611                                       GIOCondition condition, gpointer data)
612 {
613         Session *session = SESSION(data);
614         guint write_buf_len;
615         gint ret;
616
617         g_return_val_if_fail(condition == G_IO_OUT, FALSE);
618         g_return_val_if_fail(session->write_buf != NULL, FALSE);
619         g_return_val_if_fail(session->write_buf_p != NULL, FALSE);
620         g_return_val_if_fail(session->write_buf_len > 0, FALSE);
621
622         write_buf_len = session->write_buf_len;
623
624         ret = session_write_buf(session);
625
626         if (ret < 0) {
627                 session->state = SESSION_ERROR;
628                 return FALSE;
629         } else if (ret > 0) {
630                 struct timeval tv_cur;
631
632                 gettimeofday(&tv_cur, NULL);
633                 if (tv_cur.tv_sec - session->tv_prev.tv_sec > 0 ||
634                     tv_cur.tv_usec - session->tv_prev.tv_usec >
635                     UI_REFRESH_INTERVAL) {
636                         session->send_data_progressive_notify
637                                 (session,
638                                  session->write_buf_p - session->write_buf,
639                                  write_buf_len,
640                                  session->send_data_progressive_notify_data);
641                         gettimeofday(&session->tv_prev, NULL);
642                 }
643                 return TRUE;
644         }
645
646         if (session->io_tag > 0) {
647                 g_source_remove(session->io_tag);
648                 session->io_tag = 0;
649         }
650
651         /* callback */
652         ret = session->send_data_finished(session, write_buf_len);
653         session->send_data_notify(session, write_buf_len,
654                                   session->send_data_notify_data);
655
656         return FALSE;
657 }