sync with 0.9.11cvs17 HEAD
[claws.git] / src / common / session.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2004 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_timeout_cb      (gpointer        data);
46
47 static gboolean session_recv_msg_idle_cb        (gpointer        data);
48 static gboolean session_recv_data_idle_cb       (gpointer        data);
49
50 static gboolean session_read_msg_cb     (SockInfo       *source,
51                                          GIOCondition    condition,
52                                          gpointer        data);
53 static gboolean session_read_data_cb    (SockInfo       *source,
54                                          GIOCondition    condition,
55                                          gpointer        data);
56 static gboolean session_write_msg_cb    (SockInfo       *source,
57                                          GIOCondition    condition,
58                                          gpointer        data);
59 static gboolean session_write_data_cb   (SockInfo       *source,
60                                          GIOCondition    condition,
61                                          gpointer        data);
62
63
64 void session_init(Session *session)
65 {
66         session->type = SESSION_UNKNOWN;
67         session->sock = NULL;
68         session->server = NULL;
69         session->port = 0;
70 #if USE_OPENSSL
71         session->ssl_type = SSL_NONE;
72 #endif
73         session->nonblocking = TRUE;
74         session->state = SESSION_READY;
75         session->last_access_time = time(NULL);
76
77         gettimeofday(&session->tv_prev, NULL);
78
79         session->conn_id = 0;
80
81         session->io_tag = 0;
82
83         session->read_buf_p = session->read_buf;
84         session->read_buf_len = 0;
85
86         session->read_msg_buf = g_string_sized_new(1024);
87         session->read_data_buf = g_byte_array_new();
88
89         session->write_buf = NULL;
90         session->write_buf_p = NULL;
91         session->write_buf_len = 0;
92
93         session->timeout_tag = 0;
94         session->timeout_interval = 0;
95
96         session->data = NULL;
97 }
98
99 /*!
100  *\brief        Set up parent and child process
101  *              Childloop: Read commands from parent,
102  *              send to server, get answer, pass to parent
103  *
104  *\param        session Contains session information
105  *              server to connect to
106  *              port to connect to
107  *
108  *\return        0 : success
109  *              -1 : pipe / fork errors (parent)
110  *               1 : connection error (child)
111  */
112 gint session_connect(Session *session, const gchar *server, gushort port)
113 {
114         session->server = g_strdup(server);
115         session->port = port;
116
117         session->conn_id = sock_connect_async(server, port, session_connect_cb,
118                                               session);
119         if (session->conn_id < 0) {
120                 g_warning("can't connect to server.");
121                 session_close(session);
122                 return -1;
123         }
124
125         return 0;
126 }
127
128 static gint session_connect_cb(SockInfo *sock, gpointer data)
129 {
130         Session *session = SESSION(data);
131
132         session->conn_id = 0;
133
134         if (!sock) {
135                 g_warning("can't connect to server.");
136                 session->state = SESSION_ERROR;
137                 return -1;
138         }
139
140         session->sock = sock;
141
142 #if USE_OPENSSL
143         if (session->ssl_type == SSL_TUNNEL) {
144                 sock_set_nonblocking_mode(sock, FALSE);
145                 if (!ssl_init_socket(sock)) {
146                         g_warning("can't initialize SSL.");
147                         session->state = SESSION_ERROR;
148                         return -1;
149                 }
150         }
151 #endif
152
153         sock_set_nonblocking_mode(sock, session->nonblocking);
154
155         debug_print("session (%p): connected\n", session);
156
157         session->state = SESSION_RECV;
158         session->io_tag = sock_add_watch(session->sock, G_IO_IN,
159                                          session_read_msg_cb,
160                                          session);
161
162         return 0;
163 }
164
165 /*!
166  *\brief        child and parent: send DISCONNECT message to other process
167  *
168  *\param        session Contains session information
169  *
170  *\return        0 : success
171  */
172 gint session_disconnect(Session *session)
173 {
174         session_close(session);
175         return 0;
176 }
177
178 /*!
179  *\brief        parent ?
180  *
181  *\param        session Contains session information
182  */
183 void session_destroy(Session *session)
184 {
185         g_return_if_fail(session != NULL);
186         g_return_if_fail(session->destroy != NULL);
187
188         session_close(session);
189         session->destroy(session);
190         g_free(session->server);
191         g_string_free(session->read_msg_buf, TRUE);
192         g_byte_array_free(session->read_data_buf, TRUE);
193         g_free(session->read_data_terminator);
194         g_free(session->write_buf);
195
196         debug_print("session (%p): destroyed\n", session);
197
198         g_free(session);
199 }
200
201 gboolean session_is_connected(Session *session)
202 {
203         return (session->state == SESSION_READY ||
204                 session->state == SESSION_SEND ||
205                 session->state == SESSION_RECV);
206 }
207
208 void session_set_timeout(Session *session, guint interval)
209 {
210         if (session->timeout_tag > 0)
211                 g_source_remove(session->timeout_tag);
212
213         session->timeout_interval = interval;
214         if (interval > 0)
215                 session->timeout_tag =
216                         g_timeout_add(interval, session_timeout_cb, session);
217         else
218                 session->timeout_tag = 0;
219 }
220
221 static gboolean session_timeout_cb(gpointer data)
222 {
223         Session *session = SESSION(data);
224
225         g_warning("session timeout.\n");
226
227         if (session->io_tag > 0) {
228                 g_source_remove(session->io_tag);
229                 session->io_tag = 0;
230         }
231
232         session->timeout_tag = 0;
233         session->state = SESSION_TIMEOUT;
234
235         return FALSE;
236 }
237
238 void session_set_recv_message_notify(Session *session,
239                                      RecvMsgNotify notify_func, gpointer data)
240 {
241         session->recv_msg_notify = notify_func;
242         session->recv_msg_notify_data = data;
243 }
244
245 void session_set_recv_data_progressive_notify
246                                         (Session *session,
247                                          RecvDataProgressiveNotify notify_func,
248                                          gpointer data)
249 {
250         session->recv_data_progressive_notify = notify_func,
251         session->recv_data_progressive_notify_data = data;
252 }
253
254 void session_set_recv_data_notify(Session *session, RecvDataNotify notify_func,
255                                   gpointer data)
256 {
257         session->recv_data_notify = notify_func;
258         session->recv_data_notify_data = data;
259 }
260
261 void session_set_send_data_progressive_notify
262                                         (Session *session,
263                                          SendDataProgressiveNotify notify_func,
264                                          gpointer data)
265 {
266         session->send_data_progressive_notify = notify_func;
267         session->send_data_progressive_notify_data = data;
268 }
269
270 void session_set_send_data_notify(Session *session, SendDataNotify notify_func,
271                                   gpointer data)
272 {
273         session->send_data_notify = notify_func;
274         session->send_data_notify_data = data;
275 }
276
277 /*!
278  *\brief        child and parent cleanup (child closes first)
279  *
280  *\param        session Contains session information
281  *
282  *\return        0 : success
283  */
284 static gint session_close(Session *session)
285 {
286         g_return_val_if_fail(session != NULL, -1);
287
288         if (session->conn_id > 0) {
289                 sock_connect_async_cancel(session->conn_id);
290                 session->conn_id = 0;
291                 debug_print("session (%p): connection cancelled\n", session);
292         }
293
294         session_set_timeout(session, 0);
295
296         if (session->io_tag > 0) {
297                 g_source_remove(session->io_tag);
298                 session->io_tag = 0;
299         }
300
301         if (session->sock) {
302                 sock_close(session->sock);
303                 session->sock = NULL;
304                 session->state = SESSION_DISCONNECTED;
305                 debug_print("session (%p): closed\n", session);
306         }
307
308         return 0;
309 }
310
311 #if USE_OPENSSL
312 gint session_start_tls(Session *session)
313 {
314         gboolean nb_mode;
315
316         nb_mode = sock_is_nonblocking_mode(session->sock);
317
318         if (nb_mode)
319                 sock_set_nonblocking_mode(session->sock, FALSE);
320
321         if (!ssl_init_socket_with_method(session->sock, SSL_METHOD_TLSv1)) {
322                 g_warning("can't start TLS session.\n");
323                 if (nb_mode)
324                         sock_set_nonblocking_mode(session->sock, TRUE);
325                 return -1;
326         }
327
328         if (nb_mode)
329                 sock_set_nonblocking_mode(session->sock, session->nonblocking);
330
331         return 0;
332 }
333 #endif
334
335 gint session_send_msg(Session *session, SessionMsgType type, const gchar *msg)
336 {
337         gboolean ret;
338
339         g_return_val_if_fail(session->write_buf == NULL, -1);
340         g_return_val_if_fail(msg != NULL, -1);
341         g_return_val_if_fail(msg[0] != '\0', -1);
342
343         session->state = SESSION_SEND;
344         session->write_buf = g_strconcat(msg, "\r\n", NULL);
345         session->write_buf_p = session->write_buf;
346         session->write_buf_len = strlen(msg) + 2;
347
348         ret = session_write_msg_cb(session->sock, G_IO_OUT, session);
349
350         if (ret == TRUE)
351                 session->io_tag = sock_add_watch(session->sock, G_IO_OUT,
352                                                  session_write_msg_cb, session);
353         else if (session->state == SESSION_ERROR)
354                 return -1;
355
356         return 0;
357 }
358
359 gint session_recv_msg(Session *session)
360 {
361         g_return_val_if_fail(session->read_msg_buf->len == 0, -1);
362
363         session->state = SESSION_RECV;
364
365         if (session->read_buf_len > 0)
366                 g_idle_add(session_recv_msg_idle_cb, session);
367         else
368                 session->io_tag = sock_add_watch(session->sock, G_IO_IN,
369                                                  session_read_msg_cb, session);
370
371         return 0;
372 }
373
374 static gboolean session_recv_msg_idle_cb(gpointer data)
375 {
376         Session *session = SESSION(data);
377         gboolean ret;
378
379         ret = session_read_msg_cb(session->sock, G_IO_IN, session);
380
381         if (ret == TRUE)
382                 session->io_tag = sock_add_watch(session->sock, G_IO_IN,
383                                                  session_read_msg_cb, session);
384
385         return FALSE;
386 }
387
388 /*!
389  *\brief        parent (child?): send data to other process
390  *
391  *\param        session Contains session information
392  *              data Data to send
393  *              size Bytes to send
394  *
395  *\return        0 : success
396  *              -1 : error
397  */
398 gint session_send_data(Session *session, const guchar *data, guint size)
399 {
400         gboolean ret;
401
402         g_return_val_if_fail(session->write_buf == NULL, -1);
403         g_return_val_if_fail(data != NULL, -1);
404         g_return_val_if_fail(size != 0, -1);
405
406         session->state = SESSION_SEND;
407
408         session->write_buf = g_malloc(size);
409         session->write_buf_p = session->write_buf;
410         memcpy(session->write_buf, data, size);
411         session->write_buf_len = size;
412         gettimeofday(&session->tv_prev, NULL);
413
414         ret = session_write_data_cb(session->sock, G_IO_OUT, session);
415
416         if (ret == TRUE)
417                 session->io_tag = sock_add_watch(session->sock, G_IO_OUT,
418                                                  session_write_data_cb,
419                                                  session);
420         else if (session->state == SESSION_ERROR)
421                 return -1;
422
423         return 0;
424 }
425
426 gint session_recv_data(Session *session, guint size, const gchar *terminator)
427 {
428         g_return_val_if_fail(session->read_data_buf->len == 0, -1);
429
430         session->state = SESSION_RECV;
431
432         g_free(session->read_data_terminator);
433         session->read_data_terminator = g_strdup(terminator);
434         gettimeofday(&session->tv_prev, NULL);
435
436         if (session->read_buf_len > 0)
437                 g_idle_add(session_recv_data_idle_cb, session);
438         else
439                 session->io_tag = sock_add_watch(session->sock, G_IO_IN,
440                                                  session_read_data_cb, session);
441
442         return 0;
443 }
444
445 static gboolean session_recv_data_idle_cb(gpointer data)
446 {
447         Session *session = SESSION(data);
448         gboolean ret;
449
450         ret = session_read_data_cb(session->sock, G_IO_IN, session);
451
452         if (ret == TRUE)
453                 session->io_tag = sock_add_watch(session->sock, G_IO_IN,
454                                                  session_read_data_cb, session);
455
456         return FALSE;
457 }
458
459 static gboolean session_read_msg_cb(SockInfo *source, GIOCondition condition,
460                                     gpointer data)
461 {
462         Session *session = SESSION(data);
463         gchar buf[SESSION_BUFFSIZE];
464         gint line_len;
465         gchar *newline;
466         gchar *msg;
467         gint ret;
468
469         g_return_val_if_fail(condition == G_IO_IN, FALSE);
470
471         session_set_timeout(session, session->timeout_interval);
472
473         if (session->read_buf_len == 0) {
474                 gint read_len;
475
476                 read_len = sock_read(session->sock, session->read_buf,
477                                      SESSION_BUFFSIZE - 1);
478
479                 if (read_len == -1 && session->state == SESSION_DISCONNECTED) {
480                         g_warning ("sock_read: session disconnected\n");
481                         if (session->io_tag > 0) {
482                                 g_source_remove(session->io_tag);
483                                 session->io_tag = 0;
484                         }
485                         return FALSE;
486                 }
487                 
488                 if (read_len == 0) {
489                         g_warning("sock_read: received EOF\n");
490                         session->state = SESSION_EOF;
491                         return FALSE;
492                 }
493
494                 if (read_len < 0) {
495                         switch (errno) {
496                         case EAGAIN:
497                                 return TRUE;
498                         default:
499                                 g_warning("sock_read: %s\n", g_strerror(errno));
500                                 session->state = SESSION_ERROR;
501                                 return FALSE;
502                         }
503                 }
504
505                 session->read_buf_len = read_len;
506         }
507
508         if ((newline = memchr(session->read_buf_p, '\n', session->read_buf_len))
509                 != NULL)
510                 line_len = newline - session->read_buf_p + 1;
511         else
512                 line_len = session->read_buf_len;
513
514         if (line_len == 0)
515                 return TRUE;
516
517         memcpy(buf, session->read_buf_p, line_len);
518         buf[line_len] = '\0';
519
520         g_string_append(session->read_msg_buf, buf);
521
522         session->read_buf_len -= line_len;
523         if (session->read_buf_len == 0)
524                 session->read_buf_p = session->read_buf;
525         else
526                 session->read_buf_p += line_len;
527
528         /* incomplete read */
529         if (buf[line_len - 1] != '\n')
530                 return TRUE;
531
532         /* complete */
533         if (session->io_tag > 0) {
534                 g_source_remove(session->io_tag);
535                 session->io_tag = 0;
536         }
537
538         /* callback */
539         msg = g_strdup(session->read_msg_buf->str);
540         strretchomp(msg);
541         g_string_truncate(session->read_msg_buf, 0);
542
543         ret = session->recv_msg(session, msg);
544         session->recv_msg_notify(session, msg, session->recv_msg_notify_data);
545
546         g_free(msg);
547
548         if (ret < 0)
549                 session->state = SESSION_ERROR;
550
551         return FALSE;
552 }
553
554 static gboolean session_read_data_cb(SockInfo *source, GIOCondition condition,
555                                      gpointer data)
556 {
557         Session *session = SESSION(data);
558         GByteArray *data_buf;
559         gint terminator_len;
560         gboolean complete = FALSE;
561         guint data_len;
562         gint ret;
563
564         g_return_val_if_fail(condition == G_IO_IN, FALSE);
565
566         session_set_timeout(session, session->timeout_interval);
567
568         if (session->read_buf_len == 0) {
569                 gint read_len;
570
571                 read_len = sock_read(session->sock, session->read_buf,
572                                      SESSION_BUFFSIZE);
573
574                 if (read_len == 0) {
575                         g_warning("sock_read: received EOF\n");
576                         session->state = SESSION_EOF;
577                         return FALSE;
578                 }
579
580                 if (read_len < 0) {
581                         switch (errno) {
582                         case EAGAIN:
583                                 return TRUE;
584                         default:
585                                 g_warning("sock_read: %s\n", g_strerror(errno));
586                                 session->state = SESSION_ERROR;
587                                 return FALSE;
588                         }
589                 }
590
591                 session->read_buf_len = read_len;
592         }
593
594         data_buf = session->read_data_buf;
595         terminator_len = strlen(session->read_data_terminator);
596
597         if (session->read_buf_len == 0)
598                 return TRUE;
599
600         g_byte_array_append(data_buf, session->read_buf_p,
601                             session->read_buf_len);
602
603         session->read_buf_len = 0;
604         session->read_buf_p = session->read_buf;
605
606         /* check if data is terminated */
607         if (data_buf->len >= terminator_len) {
608                 if (memcmp(data_buf->data, session->read_data_terminator,
609                            terminator_len) == 0)
610                         complete = TRUE;
611                 else if (data_buf->len >= terminator_len + 2 &&
612                          memcmp(data_buf->data + data_buf->len -
613                                 (terminator_len + 2), "\r\n", 2) == 0 &&
614                          memcmp(data_buf->data + data_buf->len -
615                                 terminator_len, session->read_data_terminator,
616                                 terminator_len) == 0)
617                         complete = TRUE;
618         }
619
620         /* incomplete read */
621         if (!complete) {
622                 struct timeval tv_cur;
623
624                 gettimeofday(&tv_cur, NULL);
625                 if (tv_cur.tv_sec - session->tv_prev.tv_sec > 0 ||
626                     tv_cur.tv_usec - session->tv_prev.tv_usec >
627                     UI_REFRESH_INTERVAL) {
628                         session->recv_data_progressive_notify
629                                 (session, data_buf->len, 0,
630                                  session->recv_data_progressive_notify_data);
631                         gettimeofday(&session->tv_prev, NULL);
632                 }
633                 return TRUE;
634         }
635
636         /* complete */
637         if (session->io_tag > 0) {
638                 g_source_remove(session->io_tag);
639                 session->io_tag = 0;
640         }
641
642         data_len = data_buf->len - terminator_len;
643
644         /* callback */
645         ret = session->recv_data_finished(session, (gchar *)data_buf->data,
646                                           data_len);
647
648         g_byte_array_set_size(data_buf, 0);
649
650         session->recv_data_notify(session, data_len,
651                                   session->recv_data_notify_data);
652
653         if (ret < 0)
654                 session->state = SESSION_ERROR;
655
656         return FALSE;
657 }
658
659 static gint session_write_buf(Session *session)
660 {
661         gint write_len;
662         gint to_write_len;
663
664         g_return_val_if_fail(session->write_buf != NULL, -1);
665         g_return_val_if_fail(session->write_buf_p != NULL, -1);
666         g_return_val_if_fail(session->write_buf_len > 0, -1);
667
668         to_write_len = session->write_buf_len -
669                 (session->write_buf_p - session->write_buf);
670         to_write_len = MIN(to_write_len, SESSION_BUFFSIZE);
671
672         write_len = sock_write(session->sock, session->write_buf_p,
673                                to_write_len);
674
675         if (write_len < 0) {
676                 switch (errno) {
677                 case EAGAIN:
678                         write_len = 0;
679                         break;
680                 default:
681                         g_warning("sock_write: %s\n", g_strerror(errno));
682                         session->state = SESSION_ERROR;
683                         return -1;
684                 }
685         }
686
687         /* incomplete write */
688         if (session->write_buf_p - session->write_buf + write_len <
689             session->write_buf_len) {
690                 session->write_buf_p += write_len;
691                 return 1;
692         }
693
694         g_free(session->write_buf);
695         session->write_buf = NULL;
696         session->write_buf_p = NULL;
697         session->write_buf_len = 0;
698
699         return 0;
700 }
701
702 static gboolean session_write_msg_cb(SockInfo *source, GIOCondition condition,
703                                      gpointer data)
704 {
705         Session *session = SESSION(data);
706         gint ret;
707
708         g_return_val_if_fail(condition == G_IO_OUT, FALSE);
709         g_return_val_if_fail(session->write_buf != NULL, FALSE);
710         g_return_val_if_fail(session->write_buf_p != NULL, FALSE);
711         g_return_val_if_fail(session->write_buf_len > 0, FALSE);
712
713         ret = session_write_buf(session);
714
715         if (ret < 0) {
716                 session->state = SESSION_ERROR;
717                 return FALSE;
718         } else if (ret > 0)
719                 return TRUE;
720
721         if (session->io_tag > 0) {
722                 g_source_remove(session->io_tag);
723                 session->io_tag = 0;
724         }
725
726         session_recv_msg(session);
727
728         return FALSE;
729 }
730
731 static gboolean session_write_data_cb(SockInfo *source,
732                                       GIOCondition condition, gpointer data)
733 {
734         Session *session = SESSION(data);
735         guint write_buf_len;
736         gint ret;
737
738         g_return_val_if_fail(condition == G_IO_OUT, FALSE);
739         g_return_val_if_fail(session->write_buf != NULL, FALSE);
740         g_return_val_if_fail(session->write_buf_p != NULL, FALSE);
741         g_return_val_if_fail(session->write_buf_len > 0, FALSE);
742
743         write_buf_len = session->write_buf_len;
744
745         ret = session_write_buf(session);
746
747         if (ret < 0) {
748                 session->state = SESSION_ERROR;
749                 return FALSE;
750         } else if (ret > 0) {
751                 struct timeval tv_cur;
752
753                 gettimeofday(&tv_cur, NULL);
754                 if (tv_cur.tv_sec - session->tv_prev.tv_sec > 0 ||
755                     tv_cur.tv_usec - session->tv_prev.tv_usec >
756                     UI_REFRESH_INTERVAL) {
757                         session_set_timeout(session, session->timeout_interval);
758                         session->send_data_progressive_notify
759                                 (session,
760                                  session->write_buf_p - session->write_buf,
761                                  write_buf_len,
762                                  session->send_data_progressive_notify_data);
763                         gettimeofday(&session->tv_prev, NULL);
764                 }
765                 return TRUE;
766         }
767
768         if (session->io_tag > 0) {
769                 g_source_remove(session->io_tag);
770                 session->io_tag = 0;
771         }
772
773         /* callback */
774         ret = session->send_data_finished(session, write_buf_len);
775         session->send_data_notify(session, write_buf_len,
776                                   session->send_data_notify_data);
777
778         return FALSE;
779 }