More null pointer dereference fixes
[claws.git] / src / plugins / managesieve / managesieve.c
1 /*
2  * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2015 the Claws Mail Team
4  * Copyright (C) 2014-2015 Charles Lehner
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program. If not, see <http://www.gnu.org/licenses/>.
18  * 
19  */
20
21 #include <glib.h>
22 #include <glib/gi18n.h>
23 #include <ctype.h>
24 #include <errno.h>
25
26 #include "claws.h"
27 #include "account.h"
28 #include "gtk/inputdialog.h"
29 #include "md5.h"
30 #include "utils.h"
31 #include "log.h"
32 #include "session.h"
33
34 #include "managesieve.h"
35 #include "sieve_editor.h"
36 #include "sieve_prefs.h"
37
38 GSList *sessions = NULL;
39
40 static void sieve_session_destroy(Session *session);
41 static gint sieve_pop_send_queue(SieveSession *session);
42 static void sieve_session_reset(SieveSession *session);
43 static void command_free(SieveCommand *cmd);
44 static void command_abort(SieveCommand *cmd);
45 static void command_cb(SieveCommand *cmd, gpointer result);
46 static gint sieve_session_recv_chunk(SieveSession *, guint len);
47 static void sieve_read_chunk(SieveSession *, gchar *data, guint len);
48 static gint sieve_read_chunk_done(SieveSession *session);
49
50 void sieve_sessions_close()
51 {
52         if (sessions) {
53                 GSList *list = sessions;
54                 sessions = NULL;
55                 g_slist_free_full(list, (GDestroyNotify)session_destroy);
56         }
57 }
58
59 /* remove all command callbacks with a given data pointer */
60 void sieve_sessions_discard_callbacks(gpointer user_data)
61 {
62         GSList *item;
63         GSList *queue;
64         GSList *prev = NULL;
65         SieveSession *session;
66         SieveCommand *cmd;
67
68         for (item = sessions; item; item = item->next) {
69                 session = (SieveSession *)item->data;
70                 cmd = session->current_cmd;
71                 /* abort current command handler */
72                 if (cmd && cmd->data == user_data) {
73                         command_abort(cmd);
74                         session->current_cmd = NULL;
75                 }
76                 /* abort queued command handlers */
77                 for (queue = session->send_queue; queue; queue = queue->next) {
78                         cmd = (SieveCommand *)queue->data;
79                         if (cmd && cmd->data == user_data) {
80                                 if (prev)
81                                         prev->next = queue->next;
82                                 else
83                                         session->send_queue = NULL;
84                                 command_abort(cmd);
85                                 g_slist_free_1(queue);
86                         } else {
87                                 prev = queue;
88                         }
89                 }
90         }
91 }
92
93 static void command_cb(SieveCommand *cmd, gpointer result)
94 {
95         if (cmd)
96                 cmd->cb(cmd->session, FALSE, result, cmd->data);
97 }
98
99 static void command_abort(SieveCommand *cmd)
100 {
101         cmd->cb(cmd->session, TRUE, NULL, cmd->data);
102         g_free(cmd->msg);
103         g_free(cmd);
104 }
105
106 static void command_free(SieveCommand *cmd)
107 {
108         g_free(cmd->msg);
109         g_free(cmd);
110 }
111
112 void sieve_session_handle_status(SieveSession *session,
113                 sieve_session_error_cb_fn on_error,
114                 sieve_session_connected_cb_fn on_connected,
115                 gpointer data)
116 {
117         session->on_error = on_error;
118         session->on_connected = on_connected;
119         session->cb_data = data;
120 }
121
122 static void sieve_error(SieveSession *session, const gchar *msg)
123 {
124         if (session->on_error)
125                 session->on_error(session, msg, session->cb_data);
126 }
127
128 static void sieve_connected(SieveSession *session, gboolean connected)
129 {
130         if (session->on_connected)
131                 session->on_connected(session, connected, session->cb_data);
132 }
133
134 static gboolean sieve_read_chunk_cb(SockInfo *source,
135                 GIOCondition condition, gpointer data)
136 {
137         SieveSession *sieve_session = SIEVE_SESSION(data);
138         Session *session = &sieve_session->session;
139         gint data_len;
140         gint ret;
141
142         cm_return_val_if_fail(condition == G_IO_IN, FALSE);
143
144         session_set_timeout(session, session->timeout_interval);
145
146         if (session->read_buf_len == 0) {
147                 gint read_len = -1;
148
149                 if (session->sock)
150                         read_len = sock_read(session->sock,
151                                         session->read_buf,
152                                         SESSION_BUFFSIZE - 1);
153
154                 if (read_len == -1 &&
155                                 session->state == SESSION_DISCONNECTED) {
156                         g_warning ("sock_read: session disconnected");
157                         if (session->io_tag > 0) {
158                                 g_source_remove(session->io_tag);
159                                 session->io_tag = 0;
160                         }
161                         return FALSE;
162                 }
163
164                 if (read_len == 0) {
165                         g_warning("sock_read: received EOF");
166                         session->state = SESSION_EOF;
167                         return FALSE;
168                 }
169
170                 if (read_len < 0) {
171                         switch (errno) {
172                         case EAGAIN:
173                                 return TRUE;
174                         default:
175                                 g_warning("sock_read: %s",
176                                                 g_strerror(errno));
177                                 session->state = SESSION_ERROR;
178                                 return FALSE;
179                         }
180                 }
181
182                 session->read_buf_len = read_len;
183         }
184
185         data_len = MIN(session->read_buf_len,
186                         sieve_session->octets_remaining);
187         sieve_session->octets_remaining -= data_len;
188         session->read_buf_len -= data_len;
189         session->read_buf_p[data_len] = '\0';
190
191         /* progress callback */
192         sieve_read_chunk(sieve_session, session->read_buf_p, data_len);
193
194         if (session->read_buf_len == 0) {
195                 session->read_buf_p = session->read_buf;
196         } else {
197                 session->read_buf_p += data_len;
198         }
199
200         /* incomplete read */
201         if (sieve_session->octets_remaining > 0)
202                 return TRUE;
203
204         /* complete */
205         if (session->io_tag > 0) {
206                 g_source_remove(session->io_tag);
207                 session->io_tag = 0;
208         }
209
210         /* completion callback */
211         ret = sieve_read_chunk_done(sieve_session);
212
213         if (ret < 0)
214                 session->state = SESSION_ERROR;
215
216         return FALSE;
217 }
218
219 static gboolean sieve_read_chunk_idle_cb(gpointer data)
220 {
221         Session *session = SESSION(data);
222         gboolean ret;
223
224         ret = sieve_read_chunk_cb(session->sock, G_IO_IN, session);
225
226         if (ret == TRUE)
227                 session->io_tag = sock_add_watch(session->sock, G_IO_IN,
228                                 sieve_read_chunk_cb, session);
229
230         return FALSE;
231 }
232
233 /* Get data of specified length.
234  * If needed elsewhere, this should be put in session.c */
235 static gint sieve_session_recv_chunk(SieveSession *sieve_session,
236                 guint bytes)
237 {
238         Session *session = &sieve_session->session;
239         cm_return_val_if_fail(session->read_msg_buf->len == 0, -1);
240
241         session->state = SESSION_RECV;
242         sieve_session->octets_remaining = bytes;
243
244         if (session->read_buf_len > 0)
245                 g_idle_add(sieve_read_chunk_idle_cb, session);
246         else
247                 session->io_tag = sock_add_watch(session->sock, G_IO_IN,
248                                                  sieve_read_chunk_cb, session);
249         return 0;
250 }
251
252
253 static gint sieve_auth_recv(SieveSession *session, const gchar *msg)
254 {
255         gchar buf[MESSAGEBUFSIZE], *tmp;
256
257         switch (session->auth_type) {
258         case SIEVEAUTH_LOGIN:
259                 session->state = SIEVE_AUTH_LOGIN_USER;
260
261                 if (strstr(msg, "VXNlcm5hbWU6")) {
262                         tmp = g_base64_encode(session->user, strlen(session->user));
263                         g_snprintf(buf, sizeof(buf), "\"%s\"", tmp);
264
265                         if (session_send_msg(SESSION(session), SESSION_MSG_NORMAL, buf) < 0) {
266                                 g_free(tmp);
267                                 return SE_ERROR;
268                         }
269                         g_free(tmp);
270                         log_print(LOG_PROTOCOL, "Sieve> [USERID]\n");
271                 } else {
272                         /* Server rejects AUTH */
273                         if (session_send_msg(SESSION(session), SESSION_MSG_NORMAL,
274                                          "\"*\"") < 0)
275                                 return SE_ERROR;
276                         log_print(LOG_PROTOCOL, "Sieve> *\n");
277                 }
278                 break;
279         case SIEVEAUTH_CRAM_MD5:
280                 session->state = SIEVE_AUTH_CRAM_MD5;
281
282                 if (msg[0] == '"') {
283                         gchar *response;
284                         gchar *response64;
285                         gchar *challenge, *tmp;
286                         gsize challengelen;
287                         guchar hexdigest[33];
288
289                         tmp = g_base64_decode(msg + 1, &challengelen);
290                         challenge = g_strndup(tmp, challengelen);
291                         g_free(tmp);
292                         log_print(LOG_PROTOCOL, "Sieve< [Decoded: %s]\n", challenge);
293
294                         g_snprintf(buf, sizeof(buf), "%s", session->pass);
295                         md5_hex_hmac(hexdigest, challenge, challengelen,
296                                      buf, strlen(session->pass));
297                         g_free(challenge);
298
299                         response = g_strdup_printf
300                                 ("%s %s", session->user, hexdigest);
301                         log_print(LOG_PROTOCOL, "Sieve> [Encoded: %s]\n", response);
302
303                         response64 = g_base64_encode(response, strlen(response));
304                         g_free(response);
305
306                         response = g_strdup_printf("\"%s\"", response64);
307                         g_free(response64);
308
309                         if (session_send_msg(SESSION(session), SESSION_MSG_NORMAL,
310                                          response) < 0) {
311                                 g_free(response);
312                                 return SE_ERROR;
313                         }
314                         log_print(LOG_PROTOCOL, "Sieve> %s\n", response);
315                         g_free(response);
316                 } else {
317                         /* Server rejects AUTH */
318                         if (session_send_msg(SESSION(session), SESSION_MSG_NORMAL,
319                                          "\"*\"") < 0)
320                                 return SE_ERROR;
321                         log_print(LOG_PROTOCOL, "Sieve> *\n");
322                 }
323                 break;
324         default:
325                 /* stop sieve_auth when no correct authtype */
326                 if (session_send_msg(SESSION(session), SESSION_MSG_NORMAL, "*") < 0)
327                         return SE_ERROR;
328                 log_print(LOG_PROTOCOL, "Sieve> *\n");
329                 break;
330         }
331
332         return SE_OK;
333 }
334
335 static gint sieve_auth_login_user_recv(SieveSession *session, const gchar *msg)
336 {
337         gchar *tmp, *tmp2;
338
339         session->state = SIEVE_AUTH_LOGIN_PASS;
340         
341         if (strstr(msg, "UGFzc3dvcmQ6")) {
342                 tmp2 = g_base64_encode(session->pass, strlen(session->pass));
343                 tmp = g_strdup_printf("\"%s\"", tmp2);
344                 g_free(tmp2);
345         } else {
346                 /* Server rejects AUTH */
347                 tmp = g_strdup("\"*\"");
348         }
349
350         if (session_send_msg(SESSION(session), SESSION_MSG_NORMAL, tmp) < 0) {
351                 g_free(tmp);
352                 return SE_ERROR;
353         }
354         g_free(tmp);
355
356         log_print(LOG_PROTOCOL, "Sieve> [PASSWORD]\n");
357
358         return SE_OK;
359 }
360
361
362 static gint sieve_auth_cram_md5(SieveSession *session)
363 {
364         session->state = SIEVE_AUTH;
365         session->auth_type = SIEVEAUTH_CRAM_MD5;
366
367         if (session_send_msg(SESSION(session), SESSION_MSG_NORMAL,
368                                 "Authenticate \"CRAM-MD5\"") < 0)
369                 return SE_ERROR;
370         log_print(LOG_PROTOCOL, "Sieve> Authenticate CRAM-MD5\n");
371
372         return SE_OK;
373 }
374
375 static gint sieve_auth_plain(SieveSession *session)
376 {
377         gchar buf[MESSAGEBUFSIZE], *b64buf, *out;
378         gint len;
379
380         session->state = SIEVE_AUTH_PLAIN;
381         session->auth_type = SIEVEAUTH_PLAIN;
382
383         memset(buf, 0, sizeof buf);
384
385         /* "\0user\0password" */
386         len = sprintf(buf, "%c%s%c%s", '\0', session->user, '\0', session->pass);
387         b64buf = g_base64_encode(buf, len);
388         out = g_strconcat("Authenticate \"PLAIN\" \"", b64buf, "\"", NULL);
389         g_free(b64buf);
390
391         if (session_send_msg(SESSION(session), SESSION_MSG_NORMAL, out) < 0) {
392                 g_free(out);
393                 return SE_ERROR;
394         }
395
396         g_free(out);
397
398         log_print(LOG_PROTOCOL, "Sieve> [Authenticate PLAIN]\n");
399
400         return SE_OK;
401 }
402
403 static gint sieve_auth_login(SieveSession *session)
404 {
405         session->state = SIEVE_AUTH;
406         session->auth_type = SIEVEAUTH_LOGIN;
407
408         if (session_send_msg(SESSION(session), SESSION_MSG_NORMAL,
409                                 "Authenticate \"LOGIN\"") < 0)
410                 return SE_ERROR;
411         log_print(LOG_PROTOCOL, "Sieve> Authenticate LOGIN\n");
412
413         return SE_OK;
414 }
415
416 static gint sieve_auth(SieveSession *session)
417 {
418         SieveAuthType forced_auth_type = session->forced_auth_type;
419
420         if (!session->use_auth) {
421                 session->state = SIEVE_READY;
422                 sieve_connected(session, TRUE);
423                 return SE_OK;
424         }
425
426         session->state = SIEVE_AUTH;
427         sieve_error(session, _("Authenticating..."));
428
429         if ((forced_auth_type == SIEVEAUTH_CRAM_MD5 || forced_auth_type == 0) &&
430              (session->avail_auth_type & SIEVEAUTH_CRAM_MD5) != 0)
431                 return sieve_auth_cram_md5(session);
432         else if ((forced_auth_type == SIEVEAUTH_LOGIN || forced_auth_type == 0) &&
433                   (session->avail_auth_type & SIEVEAUTH_LOGIN) != 0)
434                 return sieve_auth_login(session);
435         else if ((forced_auth_type == SIEVEAUTH_PLAIN || forced_auth_type == 0) &&
436                   (session->avail_auth_type & SIEVEAUTH_PLAIN) != 0)
437                 return sieve_auth_plain(session);
438         else if (forced_auth_type == 0) {
439                 log_warning(LOG_PROTOCOL, _("No Sieve auth method available\n"));
440                 session->state = SIEVE_RETRY_AUTH;
441                 return SE_AUTHFAIL;
442         } else {
443                 log_warning(LOG_PROTOCOL, _("Selected Sieve auth method not available\n"));
444                 session->state = SIEVE_RETRY_AUTH;
445                 return SE_AUTHFAIL;
446         }
447
448         return SE_OK;
449 }
450
451 static void sieve_session_putscript_cb(SieveSession *session, SieveResult *result)
452 {
453         /* Remove script name from the beginning the response,
454          * which is added by Dovecot/Pigeonhole */
455         gchar *start, *desc = result->description;
456         gchar *end = NULL;
457         if (!desc) {
458                 /* callback just for the status */
459                 command_cb(session->current_cmd, result);
460         }
461         while (desc && desc[0]) {
462                 if ((end = strchr(desc, '\r')) ||
463                     (end = strchr(desc, '\n')))
464                         while (*end == '\n' || *end == '\r')
465                                 *end++ = '\0';
466                 if (g_str_has_prefix(desc, "NULL_") && (start = strchr(desc+5, ':'))) {
467                         desc = start+1;
468                         while (*desc == ' ')
469                                 desc++;
470                 /* TODO: match against known script name, in case it contains
471                  * weird text like ": line " */
472                 } else if ((start = strstr(desc, ": line ")) ||
473                                 (start = strstr(desc, ": error"))) {
474                         desc = start+2;
475                 }
476                 result->description = desc;
477                 command_cb(session->current_cmd, result);
478                 desc = end;
479         }
480 }
481
482 static inline gboolean response_is_ok(const char *msg)
483 {
484         return !strncmp(msg, "OK", 2) && (!msg[2] || msg[2] == ' ');
485 }
486
487 static inline gboolean response_is_no(const char *msg)
488 {
489         return !strncmp(msg, "NO", 2) && (!msg[2] || msg[2] == ' ');
490 }
491
492 static inline gboolean response_is_bye(const char *msg)
493 {
494         return !strncmp(msg, "BYE", 3) && (!msg[3] || msg[3] == ' ');
495 }
496
497 static void sieve_got_capability(SieveSession *session, gchar *cap_name,
498                 gchar *cap_value)
499 {
500         if (strcmp(cap_name, "SASL") == 0) {
501                 SieveAuthType auth_type = 0;
502                 gchar *auth, *end;
503                 for (auth = cap_value; auth && auth[0]; auth = end) {
504                         if ((end = strchr(auth, ' ')))
505                                 *end++ = '\0';
506                         if (strcmp(auth, "PLAIN") == 0) {
507                                 auth_type |= SIEVEAUTH_PLAIN;
508                         } else if (strcmp(auth, "CRAM-MD5") == 0) {
509                                 auth_type |= SIEVEAUTH_CRAM_MD5;
510                         } else if (strcmp(auth, "LOGIN") == 0) {
511                                 auth_type |= SIEVEAUTH_LOGIN;
512                         }
513                 }
514                 session->avail_auth_type = auth_type;
515
516         } else if (strcmp(cap_name, "STARTTLS") == 0) {
517                 session->capability.starttls = TRUE;
518         }
519 }
520
521 static void log_send(SieveSession *session, SieveCommand *cmd)
522 {
523         gchar *end, *msg = cmd->msg;
524         if (cmd->next_state == SIEVE_PUTSCRIPT && (end = strchr(msg, '\n'))) {
525                 /* Don't log the script data */
526                 msg = g_strndup(msg, end - msg);
527                 log_print(LOG_PROTOCOL, "Sieve> %s\n", msg);
528                 g_free(msg);
529                 msg = "[Data]";
530         }
531         log_print(LOG_PROTOCOL, "Sieve> %s\n", msg);
532 }
533
534 static gint sieve_pop_send_queue(SieveSession *session)
535 {
536         SieveCommand *cmd;
537         GSList *send_queue = session->send_queue;
538
539         if (session->current_cmd) {
540                 command_free(session->current_cmd);
541                 session->current_cmd = NULL;
542         }
543
544         if (!send_queue)
545                 return SE_OK;
546
547         cmd = (SieveCommand *)send_queue->data;
548         session->send_queue = g_slist_next(send_queue);
549         g_slist_free_1(send_queue);
550
551         log_send(session, cmd);
552         session->state = cmd->next_state;
553         session->current_cmd = cmd;
554         if (session_send_msg(SESSION(session), SESSION_SEND, cmd->msg) < 0)
555                 return SE_ERROR;
556
557         return SE_OK;
558 }
559
560 static void parse_split(gchar *line, gchar **first_word, gchar **second_word)
561 {
562         gchar *first = line;
563         gchar *second;
564         gchar *end;
565
566         /* get first */
567         if (line[0] == '"' && ((second = strchr(line + 1, '"')))) {
568                 *second++ = '\0';
569                 first++;
570                 if (second[0] == ' ')
571                         second++;
572         } else if ((second = strchr(line, ' '))) {
573                 *second++ = '\0';
574         }
575
576         /* unquote second */
577         if (second && second[0] == '"' &&
578                         ((end = strchr(second + 1, '"')))) {
579                 second++;
580                 *end = '\0';
581         }
582
583         *first_word = first;
584         *second_word = second;
585 }
586
587 static void unquote_inplace(gchar *str)
588 {
589         gchar *src, *dest;
590         if (*str != '"')
591                 return;
592         for (src = str+1, dest = str; src && *src && *src != '"'; src++) {
593                 if (*src == '\\') {
594                         src++;
595                 }
596                 *dest++ = *src;
597         }
598         *dest = '\0';
599 }
600
601 static void parse_response(gchar *msg, SieveResult *result)
602 {
603         gchar *end;
604
605         cm_return_if_fail(msg != NULL);
606
607         /* response status */
608         if (isalpha(msg[0])) {
609                 end = strchr(msg, ' ');
610                 if (end) {
611                         *end++ = '\0';
612                         while (*end == ' ')
613                                 end++;
614                 }
615                 result->success = strcmp(msg, "OK") == 0;
616                 result->has_status = TRUE;
617                 msg = end;
618         } else {
619                 result->has_status = FALSE;
620         }
621
622         /* response code */
623         if (msg && msg[0] == '(' && (end = strchr(msg, ')'))) {
624                 msg++;
625                 *end++ = '\0';
626                 result->code =
627                         strcmp(msg, "WARNINGS") == 0 ? SIEVE_CODE_WARNINGS :
628                         strcmp(msg, "TRYLATER") == 0 ? SIEVE_CODE_TRYLATER :
629                         SIEVE_CODE_UNKNOWN;
630                 while (*end == ' ')
631                         end++;
632                 msg = end;
633         } else {
634                 result->code = SIEVE_CODE_NONE;
635         }
636
637         /* s2c octets */
638         if (msg && msg[0] == '{' && (end = strchr(msg, '}'))) {
639                 msg++;
640                 *end++ = '\0';
641                 if (msg[0] == '0' && msg+1 == end) {
642                         result->has_octets = TRUE;
643                         result->octets = 0;
644                 } else {
645                         result->has_octets =
646                                 (result->octets = g_ascii_strtoll(msg, NULL, 10)) != 0;
647                 }
648                 while (*end == ' ')
649                         end++;
650                 msg = end;
651         } else {
652                 result->has_octets = FALSE;
653                 result->octets = 0;
654         }
655
656         /* text */
657         if (msg && *msg) {
658                 unquote_inplace(msg);
659                 result->description = msg;
660         } else {
661                 result->description = NULL;
662         }
663 }
664
665 static gint sieve_session_recv_msg(Session *session, const gchar *msg)
666 {
667         SieveSession *sieve_session = SIEVE_SESSION(session);
668         SieveResult result;
669         gint ret = SE_OK;
670
671         log_print(LOG_PROTOCOL, "Sieve< %s\n", msg);
672         if (response_is_bye(msg)) {
673                 gchar *status;
674                 parse_response((gchar *)msg, &result);
675                 if (!result.description)
676                         status = g_strdup(_("Disconnected"));
677                 else if (g_str_has_prefix(result.description, "Disconnected"))
678                         status = g_strdup(result.description);
679                 else
680                         status = g_strdup_printf(_("Disconnected: %s"), result.description);
681                 sieve_session->error = SE_ERROR;
682                 sieve_error(sieve_session, status);
683                 sieve_session->state = SIEVE_DISCONNECTED;
684                 g_free(status);
685                 return -1;
686         }
687
688         switch (sieve_session->state) {
689         case SIEVE_CAPABILITIES:
690                 if (response_is_ok(msg)) {
691                         /* capabilities list done */
692
693 #ifdef USE_GNUTLS
694                         if (sieve_session->tls_init_done == FALSE &&
695                                         sieve_session->config->tls_type != SIEVE_TLS_NO) {
696                                 if (sieve_session->capability.starttls) {
697                                         log_print(LOG_PROTOCOL, "Sieve> STARTTLS\n");
698                                         session_send_msg(session, SESSION_SEND, "STARTTLS");
699                                         sieve_session->state = SIEVE_STARTTLS;
700                                 } else if (sieve_session->config->tls_type == SIEVE_TLS_YES) {
701                                         log_warning(LOG_PROTOCOL, "Sieve: does not support STARTTLS\n");
702                                         sieve_session->state = SIEVE_ERROR;
703                                 } else {
704                                         log_warning(LOG_PROTOCOL, "Sieve: continuing without TLS\n");
705                                         sieve_session->state = SIEVE_READY;
706                                 }
707                                 break;
708                         }
709 #endif
710                         /* authenticate after getting capabilities */
711                         if (!sieve_session->authenticated) {
712                                 ret = sieve_auth(sieve_session);
713                         } else {
714                                 sieve_session->state = SIEVE_READY;
715                                 sieve_connected(sieve_session, TRUE);
716                         }
717                 } else {
718                         /* got a capability */
719                         gchar *cap_name, *cap_value;
720                         parse_split((gchar *)msg, &cap_name, &cap_value);
721                         sieve_got_capability(sieve_session, cap_name, cap_value);
722                 }
723                 break;
724         case SIEVE_READY:
725                 if (!msg[0])
726                         break;
727                 log_warning(LOG_PROTOCOL,
728                                 _("unhandled message on Sieve session: %s\n"), msg);
729                 break;
730         case SIEVE_STARTTLS:
731 #ifdef USE_GNUTLS
732                 if (session_start_tls(session) < 0) {
733                         sieve_session->state = SIEVE_ERROR;
734                         sieve_session->error = SE_ERROR;
735                         sieve_error(sieve_session, _("TLS failed"));
736                         return -1;
737                 }
738                 sieve_session->tls_init_done = TRUE;
739                 sieve_session->state = SIEVE_CAPABILITIES;
740 #endif
741                 break;
742         case SIEVE_AUTH:
743                 ret = sieve_auth_recv(sieve_session, msg);
744                 break;
745         case SIEVE_AUTH_LOGIN_USER:
746                 ret = sieve_auth_login_user_recv(sieve_session, msg);
747                 break;
748         case SIEVE_AUTH_PLAIN:
749         case SIEVE_AUTH_LOGIN_PASS:
750         case SIEVE_AUTH_CRAM_MD5:
751                 if (response_is_no(msg)) {
752                         log_print(LOG_PROTOCOL, "Sieve auth failed\n");
753                         session->state = SIEVE_RETRY_AUTH;
754                         ret = SE_AUTHFAIL;
755                 } else if (response_is_ok(msg)) {
756                         log_print(LOG_PROTOCOL, "Sieve auth completed\n");
757                         sieve_error(sieve_session, "");
758                         sieve_session->authenticated = TRUE;
759                         sieve_session->state = SIEVE_READY;
760                         sieve_connected(sieve_session, TRUE);
761                 }
762                 break;
763         case SIEVE_NOOP:
764                 if (!response_is_ok(msg)) {
765                         sieve_session->state = SIEVE_ERROR;
766                 }
767                 sieve_session->state = SIEVE_READY;
768                 break;
769         case SIEVE_LISTSCRIPTS:
770                 if (response_is_no(msg)) {
771                         /* got an error. probably not authenticated. */
772                         command_cb(sieve_session->current_cmd, NULL);
773                         sieve_session->state = SIEVE_READY;
774                 } else if (response_is_ok(msg)) {
775                         /* end of list */
776                         sieve_session->state = SIEVE_READY;
777                         sieve_session->error = SE_OK;
778                         command_cb(sieve_session->current_cmd,
779                                         (gpointer)&(SieveScript){0});
780                 } else {
781                         /* got a script name */
782                         SieveScript script;
783                         gchar *script_status;
784
785                         parse_split((gchar *)msg, &script.name, &script_status);
786                         script.active = (script_status &&
787                                         strcasecmp(script_status, "active") == 0);
788
789                         command_cb(sieve_session->current_cmd,
790                                         (gpointer)&script);
791                 }
792                 break;
793         case SIEVE_RENAMESCRIPT:
794                 if (response_is_no(msg)) {
795                         /* error */
796                         command_cb(sieve_session->current_cmd, NULL);
797                 } else if (response_is_ok(msg)) {
798                         command_cb(sieve_session->current_cmd, (void*)TRUE);
799                 } else {
800                         log_warning(LOG_PROTOCOL, _("error occurred on SIEVE session\n"));
801                 }
802                 sieve_session->state = SIEVE_READY;
803                 break;
804         case SIEVE_SETACTIVE:
805                 parse_response((gchar *)msg, &result);
806                 if (result.success) {
807                         /* clear status possibly set when setting another
808                          * script active. TODO: give textual feedback */
809                         sieve_error(sieve_session, "");
810
811                         command_cb(sieve_session->current_cmd, NULL);
812                 } else if (result.description) {
813                         command_cb(sieve_session->current_cmd,
814                                         result.description);
815                 } else {
816                         log_warning(LOG_PROTOCOL, _("error occurred on SIEVE session\n"));
817                 }
818                 if (result.has_octets) {
819                         return sieve_session_recv_chunk(sieve_session,
820                                         result.octets);
821                 } else {
822                         sieve_session->state = SIEVE_READY;
823                 }
824                 break;
825         case SIEVE_GETSCRIPT:
826                 if (response_is_no(msg)) {
827                         command_cb(sieve_session->current_cmd, (void *)-1);
828                         sieve_session->state = SIEVE_READY;
829                 } else {
830                         parse_response((gchar *)msg, &result);
831                         sieve_session->state = SIEVE_GETSCRIPT_DATA;
832                         return sieve_session_recv_chunk(sieve_session,
833                                         result.octets);
834                 }
835                 break;
836         case SIEVE_GETSCRIPT_DATA:
837                 if (!msg[0])
838                         break;
839                 sieve_session->state = SIEVE_READY;
840                 if (response_is_ok(msg)) {
841                         command_cb(sieve_session->current_cmd, NULL);
842                 } else if (msg[0]) {
843                         log_warning(LOG_PROTOCOL, _("error occurred on SIEVE session\n"));
844                 }
845                 break;
846         case SIEVE_PUTSCRIPT:
847                 if (!msg[0])
848                         break;
849                 parse_response((gchar *)msg, &result);
850                 sieve_session_putscript_cb(sieve_session, &result);
851                 if (result.has_octets) {
852                         return sieve_session_recv_chunk(sieve_session,
853                                         result.octets);
854                 } else {
855                         sieve_session->state = SIEVE_READY;
856                 }
857                 break;
858         case SIEVE_DELETESCRIPT:
859                 parse_response((gchar *)msg, &result);
860                 if (!result.success) {
861                         command_cb(sieve_session->current_cmd,
862                                         result.description);
863                 } else {
864                         command_cb(sieve_session->current_cmd, NULL);
865                 }
866                 sieve_session->state = SIEVE_READY;
867                 break;
868         case SIEVE_ERROR:
869                 log_warning(LOG_PROTOCOL, _("error occurred on Sieve session. data: %s\n"), msg);
870                 sieve_session->error = SE_ERROR;
871                 break;
872         case SIEVE_RETRY_AUTH:
873                 log_warning(LOG_PROTOCOL, _("unhandled message on Sieve session: %s\n"),
874                                         msg);
875                 ret = sieve_auth(sieve_session);
876                 break;
877         default:
878                 log_warning(LOG_PROTOCOL, _("unhandled message on Sieve session: %d\n"),
879                                         sieve_session->state);
880                 sieve_session->error = SE_ERROR;
881                 return -1;
882         }
883
884         if (ret == SE_OK && sieve_session->state == SIEVE_READY)
885                 ret = sieve_pop_send_queue(sieve_session);
886
887         if (ret == SE_OK) {
888                 return session_recv_msg(session);
889         } else if (ret == SE_AUTHFAIL) {
890                 sieve_error(sieve_session, _("Auth failed"));
891                 sieve_session->state = SIEVE_ERROR;
892                 sieve_session->error = SE_ERROR;
893         }
894
895         return 0;
896 }
897
898 static gint sieve_recv_message(Session *session, const gchar *msg,
899                 gpointer user_data)
900 {
901         return 0;
902 }
903
904 static void sieve_read_chunk(SieveSession *session, gchar *data, guint len)
905 {
906         log_print(LOG_PROTOCOL, "Sieve< [%u bytes]\n", len);
907
908         switch (session->state) {
909         case SIEVE_GETSCRIPT_DATA:
910                 command_cb(session->current_cmd, (gchar *)data);
911                 break;
912         case SIEVE_SETACTIVE:
913                 /* Dovecot shows a script's warnings when making it active */
914                 /* TODO: append message in case it is very long*/
915                 strretchomp(data);
916                 sieve_error(session, data);
917                 break;
918         case SIEVE_PUTSCRIPT: {
919                 SieveResult result = {.description = (gchar *)data};
920                 sieve_session_putscript_cb(session, &result);
921                 break;
922         }
923         default:
924                 log_warning(LOG_PROTOCOL,
925                                 _("error occurred on SIEVE session\n"));
926         }
927 }
928
929 static gint sieve_read_chunk_done(SieveSession *session)
930 {
931         gint ret = SE_OK;
932
933         switch (session->state) {
934         case SIEVE_GETSCRIPT_DATA:
935                 /* wait for ending "OK" response */
936                 break;
937         case SIEVE_SETACTIVE:
938         case SIEVE_PUTSCRIPT:
939                 session->state = SIEVE_READY;
940                 break;
941         default:
942                 log_warning(LOG_PROTOCOL,
943                                 _("error occurred on SIEVE session\n"));
944         }
945
946         if (ret == SE_OK && session->state == SIEVE_READY)
947                 ret = sieve_pop_send_queue(session);
948
949         if (ret == SE_OK)
950                 return session_recv_msg(SESSION(session));
951
952         return 0;
953 }
954
955 static gint sieve_cmd_noop(SieveSession *session)
956 {
957         log_print(LOG_PROTOCOL, "Sieve> NOOP\n");
958         session->state = SIEVE_NOOP;
959         if (session_send_msg(SESSION(session), SESSION_SEND, "NOOP") < 0) {
960                 session->state = SIEVE_ERROR;
961                 session->error = SE_ERROR;
962                 return 1;
963         }
964         return 0;
965 }
966
967 static gboolean sieve_ping(gpointer data)
968 {
969         Session *session = SESSION(data);
970         SieveSession *sieve_session = SIEVE_SESSION(session);
971
972         if (sieve_session->state == SIEVE_ERROR || session->state == SESSION_ERROR)
973                 return FALSE;
974         if (sieve_session->state != SIEVE_READY)
975                 return TRUE;
976
977         return sieve_cmd_noop(sieve_session) == 0;
978 }
979
980 static void sieve_session_destroy(Session *session)
981 {
982         SieveSession *sieve_session = SIEVE_SESSION(session);
983         g_free(sieve_session->pass);
984         if (sieve_session->current_cmd)
985                 command_abort(sieve_session->current_cmd);
986         sessions = g_slist_remove(sessions, (gconstpointer)session);
987         g_slist_free_full(sieve_session->send_queue,
988                         (GDestroyNotify)command_abort);
989 }
990
991 static void sieve_connect_finished(Session *session, gboolean success)
992 {
993         if (!success) {
994                 sieve_connected(SIEVE_SESSION(session), FALSE);
995         }
996 }
997
998 static gint sieve_session_connect(SieveSession *session)
999 {
1000         session->state = SIEVE_CAPABILITIES;
1001         session->authenticated = FALSE;
1002 #ifdef USE_GNUTLS
1003         session->tls_init_done = FALSE;
1004 #endif
1005         return session_connect(SESSION(session), session->host,
1006                         session->port);
1007 }
1008
1009 static SieveSession *sieve_session_new(PrefsAccount *account)
1010 {
1011         SieveSession *session;
1012         session = g_new0(SieveSession, 1);
1013         session_init(SESSION(session), account, FALSE);
1014
1015         session->account = account;
1016
1017         SESSION(session)->recv_msg = sieve_session_recv_msg;
1018         SESSION(session)->destroy = sieve_session_destroy;
1019         SESSION(session)->connect_finished = sieve_connect_finished;
1020         session_set_recv_message_notify(SESSION(session), sieve_recv_message, NULL);
1021
1022         sieve_session_reset(session);
1023         return session;
1024 }
1025
1026 static void sieve_session_reset(SieveSession *session)
1027 {
1028         PrefsAccount *account = session->account;
1029         SieveAccountConfig *config = sieve_prefs_account_get_config(account);
1030         gboolean reuse_auth = (config->auth == SIEVEAUTH_REUSE);
1031
1032         g_slist_free_full(session->send_queue, (GDestroyNotify)command_abort);
1033
1034         session_disconnect(SESSION(session));
1035
1036         SESSION(session)->ssl_cert_auto_accept = account->ssl_certs_auto_accept;
1037         SESSION(session)->nonblocking = account->use_nonblocking_ssl;
1038         session->authenticated = FALSE;
1039         session->current_cmd = NULL;
1040         session->send_queue = NULL;
1041         session->state = SIEVE_CAPABILITIES;
1042 #ifdef USE_GNUTLS
1043         session->tls_init_done = FALSE;
1044 #endif
1045         session->avail_auth_type = 0;
1046         session->auth_type = 0;
1047         session->config = config;
1048         session->host = config->use_host ? config->host : account->recv_server;
1049         session->port = config->use_port ? config->port : SIEVE_PORT;
1050         session->user = reuse_auth ? account->userid : session->config->userid;
1051         session->forced_auth_type = config->auth_type;
1052         session_register_ping(SESSION(session), sieve_ping);
1053
1054         if (session->pass)
1055                 g_free(session->pass);
1056         if (config->auth == SIEVEAUTH_NONE) {
1057                 session->pass = NULL;
1058         } else if (reuse_auth && account->passwd) {
1059                 session->pass = g_strdup(account->passwd);
1060         } else if (config->passwd && config->passwd[0]) {
1061                 session->pass = g_strdup(config->passwd);
1062         } else if (password_get(session->user, session->host, "sieve",
1063                                 session->port, &session->pass)) {
1064         } else {
1065                 session->pass = input_dialog_query_password_keep(session->host,
1066                                 session->user, &(session->pass));
1067         }
1068         if (!session->pass) {
1069                 session->pass = g_strdup("");
1070                 session->use_auth = FALSE;
1071         } else {
1072                 session->use_auth = TRUE;
1073         }
1074
1075 #ifdef USE_GNUTLS
1076         SESSION(session)->ssl_type =
1077                 (config->tls_type == SIEVE_TLS_NO) ? SSL_NONE : SSL_STARTTLS;
1078 #endif
1079 }
1080
1081 /* When an account config is changed, reset associated sessions. */
1082 void sieve_account_prefs_updated(PrefsAccount *account)
1083 {
1084         GSList *item;
1085         SieveSession *session;
1086
1087         for (item = sessions; item; item = item->next) {
1088                 session = (SieveSession *)item->data;
1089                 if (session->account == account) {
1090                         log_print(LOG_PROTOCOL, "Sieve: resetting session\n");
1091                         sieve_session_reset(session);
1092                 }
1093         }
1094 }
1095
1096 SieveSession *sieve_session_get_for_account(PrefsAccount *account)
1097 {
1098         SieveSession *session;
1099         GSList *item;
1100
1101         /* find existing */
1102         for (item = sessions; item; item = item->next) {
1103                 session = (SieveSession *)item->data;
1104                 if (session->account == account) {
1105                         return session;
1106                 }
1107         }
1108
1109         /* create new */
1110         session = sieve_session_new(account);
1111         sessions = g_slist_prepend(sessions, session);
1112
1113         return session;
1114 }
1115
1116 static void sieve_queue_send(SieveSession *session, SieveState next_state,
1117                 gchar *msg, sieve_session_data_cb_fn cb, gpointer data)
1118 {
1119         gboolean queue = FALSE;
1120         SieveCommand *cmd = g_new0(SieveCommand, 1);
1121         cmd->session = session;
1122         cmd->next_state = next_state;
1123         cmd->msg = msg;
1124         cmd->data = data;
1125         cmd->cb = cb;
1126
1127         if (!session_is_connected(SESSION(session))) {
1128                 log_print(LOG_PROTOCOL, "Sieve: connecting to %s:%hu\n",
1129                                 session->host, session->port);
1130                 if (sieve_session_connect(session) < 0) {
1131                         sieve_connect_finished(SESSION(session), FALSE);
1132                 }
1133                 queue = TRUE;
1134         } else if (session->state == SIEVE_RETRY_AUTH) {
1135                 log_print(LOG_PROTOCOL, _("Sieve: retrying auth\n"));
1136                 if (sieve_auth(session) == SE_AUTHFAIL)
1137                         sieve_error(session, _("Auth method not available"));
1138                 queue = TRUE;
1139         } else if (session->state != SIEVE_READY) {
1140                 log_print(LOG_PROTOCOL, "Sieve: in state %d\n", session->state);
1141                 queue = TRUE;
1142         }
1143
1144         if (queue) {
1145                 session->send_queue = g_slist_prepend(session->send_queue, cmd);
1146         } else {
1147                 if (session->current_cmd)
1148                         command_free(session->current_cmd);
1149                 session->current_cmd = cmd;
1150                 session->state = next_state;
1151                 log_send(session, cmd);
1152                 if (session_send_msg(SESSION(session), SESSION_SEND, cmd->msg) < 0) {
1153                         /* error */
1154                 }
1155         }
1156 }
1157
1158 void sieve_session_list_scripts(SieveSession *session,
1159                 sieve_session_data_cb_fn cb, gpointer data)
1160 {
1161         gchar *msg = g_strdup("LISTSCRIPTS");
1162         sieve_queue_send(session, SIEVE_LISTSCRIPTS, msg, cb, data);
1163 }
1164
1165 void sieve_session_set_active_script(SieveSession *session,
1166                 const gchar *filter_name,
1167                 sieve_session_data_cb_fn cb, gpointer data)
1168 {
1169         gchar *msg = g_strdup_printf("SETACTIVE \"%s\"",
1170                         filter_name ? filter_name : "");
1171         if (!msg) {
1172                 cb(session, FALSE, (void*)FALSE, data);
1173                 return;
1174         }
1175
1176         sieve_queue_send(session, SIEVE_SETACTIVE, msg, cb, data);
1177 }
1178
1179 void sieve_session_rename_script(SieveSession *session,
1180                 const gchar *name_old, const char *name_new,
1181                 sieve_session_data_cb_fn cb, gpointer data)
1182 {
1183         gchar *msg = g_strdup_printf("RENAMESCRIPT \"%s\" \"%s\"",
1184                         name_old, name_new);
1185
1186         sieve_queue_send(session, SIEVE_RENAMESCRIPT, msg, cb, data);
1187 }
1188
1189 void sieve_session_get_script(SieveSession *session, const gchar *filter_name,
1190                 sieve_session_data_cb_fn cb, gpointer data)
1191 {
1192         gchar *msg = g_strdup_printf("GETSCRIPT \"%s\"",
1193                         filter_name);
1194
1195         sieve_queue_send(session, SIEVE_GETSCRIPT, msg, cb, data);
1196 }
1197
1198 void sieve_session_put_script(SieveSession *session, const gchar *filter_name,
1199                 gint len, const gchar *script_contents,
1200                 sieve_session_data_cb_fn cb, gpointer data)
1201 {
1202         /* TODO: refactor so don't have to copy the whole script here */
1203         gchar *msg = g_strdup_printf("PUTSCRIPT \"%s\" {%u+}%s%s",
1204                         filter_name, len, len > 0 ? "\r\n" : "",
1205                         script_contents);
1206
1207         sieve_queue_send(session, SIEVE_PUTSCRIPT, msg, cb, data);
1208 }
1209
1210 void sieve_session_check_script(SieveSession *session,
1211                 gint len, const gchar *script_contents,
1212                 sieve_session_data_cb_fn cb, gpointer data)
1213 {
1214         gchar *msg = g_strdup_printf("CHECKSCRIPT {%u+}%s%s",
1215                         len, len > 0 ? "\r\n" : "", script_contents);
1216
1217         sieve_queue_send(session, SIEVE_PUTSCRIPT, msg, cb, data);
1218 }
1219
1220 void sieve_session_delete_script(SieveSession *session,
1221                 const gchar *filter_name,
1222                 sieve_session_data_cb_fn cb, gpointer data)
1223 {
1224         gchar *msg = g_strdup_printf("DELETESCRIPT \"%s\"",
1225                         filter_name);
1226
1227         sieve_queue_send(session, SIEVE_DELETESCRIPT, msg, cb, data);
1228 }