sync with main 0.9.11cvs2
[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 }
218
219 static gboolean session_timeout_cb(gpointer data)
220 {
221         Session *session = SESSION(data);
222
223         g_warning("session timeout.\n");
224
225         if (session->io_tag > 0) {
226                 g_source_remove(session->io_tag);
227                 session->io_tag = 0;
228         }
229
230         session->timeout_tag = 0;
231         session->state = SESSION_TIMEOUT;
232
233         return FALSE;
234 }
235
236 void session_set_recv_message_notify(Session *session,
237                                      RecvMsgNotify notify_func, gpointer data)
238 {
239         session->recv_msg_notify = notify_func;
240         session->recv_msg_notify_data = data;
241 }
242
243 void session_set_recv_data_progressive_notify
244                                         (Session *session,
245                                          RecvDataProgressiveNotify notify_func,
246                                          gpointer data)
247 {
248         session->recv_data_progressive_notify = notify_func,
249         session->recv_data_progressive_notify_data = data;
250 }
251
252 void session_set_recv_data_notify(Session *session, RecvDataNotify notify_func,
253                                   gpointer data)
254 {
255         session->recv_data_notify = notify_func;
256         session->recv_data_notify_data = data;
257 }
258
259 void session_set_send_data_progressive_notify
260                                         (Session *session,
261                                          SendDataProgressiveNotify notify_func,
262                                          gpointer data)
263 {
264         session->send_data_progressive_notify = notify_func;
265         session->send_data_progressive_notify_data = data;
266 }
267
268 void session_set_send_data_notify(Session *session, SendDataNotify notify_func,
269                                   gpointer data)
270 {
271         session->send_data_notify = notify_func;
272         session->send_data_notify_data = data;
273 }
274
275 /*!
276  *\brief        child and parent cleanup (child closes first)
277  *
278  *\param        session Contains session information
279  *
280  *\return        0 : success
281  */
282 static gint session_close(Session *session)
283 {
284         g_return_val_if_fail(session != NULL, -1);
285
286         if (session->conn_id > 0) {
287                 sock_connect_async_cancel(session->conn_id);
288                 session->conn_id = 0;
289                 debug_print("session (%p): connection cancelled\n", session);
290         }
291
292         session_set_timeout(session, 0);
293
294         if (session->io_tag > 0) {
295                 g_source_remove(session->io_tag);
296                 session->io_tag = 0;
297         }
298
299         if (session->sock) {
300                 sock_close(session->sock);
301                 session->sock = NULL;
302                 session->state = SESSION_DISCONNECTED;
303                 debug_print("session (%p): closed\n", session);
304         }
305
306         return 0;
307 }
308
309 #if USE_OPENSSL
310 gint session_start_tls(Session *session)
311 {
312         gboolean nb_mode;
313
314         nb_mode = sock_is_nonblocking_mode(session->sock);
315
316         if (nb_mode)
317                 sock_set_nonblocking_mode(session->sock, FALSE);
318
319         if (!ssl_init_socket_with_method(session->sock, SSL_METHOD_TLSv1)) {
320                 g_warning("can't start TLS session.\n");
321                 if (nb_mode)
322                         sock_set_nonblocking_mode(session->sock, TRUE);
323                 return -1;
324         }
325
326         if (nb_mode)
327                 sock_set_nonblocking_mode(session->sock, session->nonblocking);
328
329         return 0;
330 }
331 #endif
332
333 gint session_send_msg(Session *session, SessionMsgType type, const gchar *msg)
334 {
335         gboolean ret;
336
337         g_return_val_if_fail(session->write_buf == NULL, -1);
338         g_return_val_if_fail(msg != NULL, -1);
339         g_return_val_if_fail(msg[0] != '\0', -1);
340
341         session->state = SESSION_SEND;
342         session->write_buf = g_strconcat(msg, "\r\n", NULL);
343         session->write_buf_p = session->write_buf;
344         session->write_buf_len = strlen(msg) + 2;
345
346         ret = session_write_msg_cb(session->sock, G_IO_OUT, session);
347
348         if (ret == TRUE)
349                 session->io_tag = sock_add_watch(session->sock, G_IO_OUT,
350                                                  session_write_msg_cb, session);
351         else if (session->state == SESSION_ERROR)
352                 return -1;
353
354         return 0;
355 }
356
357 gint session_recv_msg(Session *session)
358 {
359         g_return_val_if_fail(session->read_msg_buf->len == 0, -1);
360
361         session->state = SESSION_RECV;
362
363         if (session->read_buf_len > 0)
364                 g_idle_add(session_recv_msg_idle_cb, session);
365         else
366                 session->io_tag = sock_add_watch(session->sock, G_IO_IN,
367                                                  session_read_msg_cb, session);
368
369         return 0;
370 }
371
372 static gboolean session_recv_msg_idle_cb(gpointer data)
373 {
374         Session *session = SESSION(data);
375         gboolean ret;
376
377         ret = session_read_msg_cb(session->sock, G_IO_IN, session);
378
379         if (ret == TRUE)
380                 session->io_tag = sock_add_watch(session->sock, G_IO_IN,
381                                                  session_read_msg_cb, session);
382
383         return FALSE;
384 }
385
386 /*!
387  *\brief        parent (child?): send data to other process
388  *
389  *\param        session Contains session information
390  *              data Data to send
391  *              size Bytes to send
392  *
393  *\return        0 : success
394  *              -1 : error
395  */
396 gint session_send_data(Session *session, const guchar *data, guint size)
397 {
398         gboolean ret;
399
400         g_return_val_if_fail(session->write_buf == NULL, -1);
401         g_return_val_if_fail(data != NULL, -1);
402         g_return_val_if_fail(size != 0, -1);
403
404         session->state = SESSION_SEND;
405
406         session->write_buf = g_malloc(size);
407         session->write_buf_p = session->write_buf;
408         memcpy(session->write_buf, data, size);
409         session->write_buf_len = size;
410         gettimeofday(&session->tv_prev, NULL);
411
412         ret = session_write_data_cb(session->sock, G_IO_OUT, session);
413
414         if (ret == TRUE)
415                 session->io_tag = sock_add_watch(session->sock, G_IO_OUT,
416                                                  session_write_data_cb,
417                                                  session);
418         else if (session->state == SESSION_ERROR)
419                 return -1;
420
421         return 0;
422 }
423
424 gint session_recv_data(Session *session, guint size, const gchar *terminator)
425 {
426         g_return_val_if_fail(session->read_data_buf->len == 0, -1);
427
428         session->state = SESSION_RECV;
429
430         g_free(session->read_data_terminator);
431         session->read_data_terminator = g_strdup(terminator);
432         gettimeofday(&session->tv_prev, NULL);
433
434         if (session->read_buf_len > 0)
435                 g_idle_add(session_recv_data_idle_cb, session);
436         else
437                 session->io_tag = sock_add_watch(session->sock, G_IO_IN,
438                                                  session_read_data_cb, session);
439
440         return 0;
441 }
442
443 static gboolean session_recv_data_idle_cb(gpointer data)
444 {
445         Session *session = SESSION(data);
446         gboolean ret;
447
448         ret = session_read_data_cb(session->sock, G_IO_IN, session);
449
450         if (ret == TRUE)
451                 session->io_tag = sock_add_watch(session->sock, G_IO_IN,
452                                                  session_read_data_cb, session);
453
454         return FALSE;
455 }
456
457 static gboolean session_read_msg_cb(SockInfo *source, GIOCondition condition,
458                                     gpointer data)
459 {
460         Session *session = SESSION(data);
461         gchar buf[SESSION_BUFFSIZE];
462         gint line_len;
463         gchar *newline;
464         gchar *msg;
465         gint ret;
466
467         g_return_val_if_fail(condition == G_IO_IN, FALSE);
468
469         session_set_timeout(session, session->timeout_interval);
470
471         if (session->read_buf_len == 0) {
472                 gint read_len;
473
474                 read_len = sock_read(session->sock, session->read_buf,
475                                      SESSION_BUFFSIZE - 1);
476
477                 if (read_len == 0) {
478                         g_warning("sock_read: received EOF\n");
479                         session->state = SESSION_EOF;
480                         return FALSE;
481                 }
482
483                 if (read_len < 0) {
484                         switch (errno) {
485                         case EAGAIN:
486                                 return TRUE;
487                         default:
488                                 g_warning("sock_read: %s\n", g_strerror(errno));
489                                 session->state = SESSION_ERROR;
490                                 return FALSE;
491                         }
492                 }
493
494                 session->read_buf_len = read_len;
495         }
496
497         if ((newline = memchr(session->read_buf_p, '\n', session->read_buf_len))
498                 != NULL)
499                 line_len = newline - session->read_buf_p + 1;
500         else
501                 line_len = session->read_buf_len;
502
503         if (line_len == 0)
504                 return TRUE;
505
506         memcpy(buf, session->read_buf_p, line_len);
507         buf[line_len] = '\0';
508
509         g_string_append(session->read_msg_buf, buf);
510
511         session->read_buf_len -= line_len;
512         if (session->read_buf_len == 0)
513                 session->read_buf_p = session->read_buf;
514         else
515                 session->read_buf_p += line_len;
516
517         /* incomplete read */
518         if (buf[line_len - 1] != '\n')
519                 return TRUE;
520
521         /* complete */
522         if (session->io_tag > 0) {
523                 g_source_remove(session->io_tag);
524                 session->io_tag = 0;
525         }
526
527         /* callback */
528         msg = g_strdup(session->read_msg_buf->str);
529         strretchomp(msg);
530         g_string_truncate(session->read_msg_buf, 0);
531
532         ret = session->recv_msg(session, msg);
533         session->recv_msg_notify(session, msg, session->recv_msg_notify_data);
534
535         g_free(msg);
536
537         if (ret < 0)
538                 session->state = SESSION_ERROR;
539
540         return FALSE;
541 }
542
543 static gboolean session_read_data_cb(SockInfo *source, GIOCondition condition,
544                                      gpointer data)
545 {
546         Session *session = SESSION(data);
547         GByteArray *data_buf;
548         gint terminator_len;
549         gboolean complete = FALSE;
550         guint data_len;
551         gint ret;
552
553         g_return_val_if_fail(condition == G_IO_IN, FALSE);
554
555         session_set_timeout(session, session->timeout_interval);
556
557         if (session->read_buf_len == 0) {
558                 gint read_len;
559
560                 read_len = sock_read(session->sock, session->read_buf,
561                                      SESSION_BUFFSIZE);
562
563                 if (read_len == 0) {
564                         g_warning("sock_read: received EOF\n");
565                         session->state = SESSION_EOF;
566                         return FALSE;
567                 }
568
569                 if (read_len < 0) {
570                         switch (errno) {
571                         case EAGAIN:
572                                 return TRUE;
573                         default:
574                                 g_warning("sock_read: %s\n", g_strerror(errno));
575                                 session->state = SESSION_ERROR;
576                                 return FALSE;
577                         }
578                 }
579
580                 session->read_buf_len = read_len;
581         }
582
583         data_buf = session->read_data_buf;
584         terminator_len = strlen(session->read_data_terminator);
585
586         if (session->read_buf_len == 0)
587                 return TRUE;
588
589         g_byte_array_append(data_buf, session->read_buf_p,
590                             session->read_buf_len);
591
592         session->read_buf_len = 0;
593         session->read_buf_p = session->read_buf;
594
595         /* check if data is terminated */
596         if (data_buf->len >= terminator_len) {
597                 if (memcmp(data_buf->data, session->read_data_terminator,
598                            terminator_len) == 0)
599                         complete = TRUE;
600                 else if (data_buf->len >= terminator_len + 2 &&
601                          memcmp(data_buf->data + data_buf->len -
602                                 (terminator_len + 2), "\r\n", 2) == 0 &&
603                          memcmp(data_buf->data + data_buf->len -
604                                 terminator_len, session->read_data_terminator,
605                                 terminator_len) == 0)
606                         complete = TRUE;
607         }
608
609         /* incomplete read */
610         if (!complete) {
611                 struct timeval tv_cur;
612
613                 gettimeofday(&tv_cur, NULL);
614                 if (tv_cur.tv_sec - session->tv_prev.tv_sec > 0 ||
615                     tv_cur.tv_usec - session->tv_prev.tv_usec >
616                     UI_REFRESH_INTERVAL) {
617                         session->recv_data_progressive_notify
618                                 (session, data_buf->len, 0,
619                                  session->recv_data_progressive_notify_data);
620                         gettimeofday(&session->tv_prev, NULL);
621                 }
622                 return TRUE;
623         }
624
625         /* complete */
626         if (session->io_tag > 0) {
627                 g_source_remove(session->io_tag);
628                 session->io_tag = 0;
629         }
630
631         data_len = data_buf->len - terminator_len;
632
633         /* callback */
634         ret = session->recv_data_finished(session, (gchar *)data_buf->data,
635                                           data_len);
636
637         g_byte_array_set_size(data_buf, 0);
638
639         session->recv_data_notify(session, data_len,
640                                   session->recv_data_notify_data);
641
642         if (ret < 0)
643                 session->state = SESSION_ERROR;
644
645         return FALSE;
646 }
647
648 static gint session_write_buf(Session *session)
649 {
650         gint write_len;
651         gint to_write_len;
652
653         g_return_val_if_fail(session->write_buf != NULL, -1);
654         g_return_val_if_fail(session->write_buf_p != NULL, -1);
655         g_return_val_if_fail(session->write_buf_len > 0, -1);
656
657         to_write_len = session->write_buf_len -
658                 (session->write_buf_p - session->write_buf);
659         to_write_len = MIN(to_write_len, SESSION_BUFFSIZE);
660
661         write_len = sock_write(session->sock, session->write_buf_p,
662                                to_write_len);
663
664         if (write_len < 0) {
665                 switch (errno) {
666                 case EAGAIN:
667                         write_len = 0;
668                         break;
669                 default:
670                         g_warning("sock_write: %s\n", g_strerror(errno));
671                         session->state = SESSION_ERROR;
672                         return -1;
673                 }
674         }
675
676         /* incomplete write */
677         if (session->write_buf_p - session->write_buf + write_len <
678             session->write_buf_len) {
679                 session->write_buf_p += write_len;
680                 return 1;
681         }
682
683         g_free(session->write_buf);
684         session->write_buf = NULL;
685         session->write_buf_p = NULL;
686         session->write_buf_len = 0;
687
688         return 0;
689 }
690
691 static gboolean session_write_msg_cb(SockInfo *source, GIOCondition condition,
692                                      gpointer data)
693 {
694         Session *session = SESSION(data);
695         gint ret;
696
697         g_return_val_if_fail(condition == G_IO_OUT, FALSE);
698         g_return_val_if_fail(session->write_buf != NULL, FALSE);
699         g_return_val_if_fail(session->write_buf_p != NULL, FALSE);
700         g_return_val_if_fail(session->write_buf_len > 0, FALSE);
701
702         ret = session_write_buf(session);
703
704         if (ret < 0) {
705                 session->state = SESSION_ERROR;
706                 return FALSE;
707         } else if (ret > 0)
708                 return TRUE;
709
710         if (session->io_tag > 0) {
711                 g_source_remove(session->io_tag);
712                 session->io_tag = 0;
713         }
714
715         session_recv_msg(session);
716
717         return FALSE;
718 }
719
720 static gboolean session_write_data_cb(SockInfo *source,
721                                       GIOCondition condition, gpointer data)
722 {
723         Session *session = SESSION(data);
724         guint write_buf_len;
725         gint ret;
726
727         g_return_val_if_fail(condition == G_IO_OUT, FALSE);
728         g_return_val_if_fail(session->write_buf != NULL, FALSE);
729         g_return_val_if_fail(session->write_buf_p != NULL, FALSE);
730         g_return_val_if_fail(session->write_buf_len > 0, FALSE);
731
732         write_buf_len = session->write_buf_len;
733
734         ret = session_write_buf(session);
735
736         if (ret < 0) {
737                 session->state = SESSION_ERROR;
738                 return FALSE;
739         } else if (ret > 0) {
740                 struct timeval tv_cur;
741
742                 gettimeofday(&tv_cur, NULL);
743                 if (tv_cur.tv_sec - session->tv_prev.tv_sec > 0 ||
744                     tv_cur.tv_usec - session->tv_prev.tv_usec >
745                     UI_REFRESH_INTERVAL) {
746                         session_set_timeout(session, session->timeout_interval);
747                         session->send_data_progressive_notify
748                                 (session,
749                                  session->write_buf_p - session->write_buf,
750                                  write_buf_len,
751                                  session->send_data_progressive_notify_data);
752                         gettimeofday(&session->tv_prev, NULL);
753                 }
754                 return TRUE;
755         }
756
757         if (session->io_tag > 0) {
758                 g_source_remove(session->io_tag);
759                 session->io_tag = 0;
760         }
761
762         /* callback */
763         ret = session->send_data_finished(session, write_buf_len);
764         session->send_data_notify(session, write_buf_len,
765                                   session->send_data_notify_data);
766
767         return FALSE;
768 }