Fix warnings all over citserver; handle function replies; remove unused code.
[citadel.git] / citadel / modules / managesieve / serv_managesieve.c
1 /*
2  * This module is an managesieve implementation for the Citadel system.
3  * It is compliant with all of the following:
4  *
5  * http://tools.ietf.org/html/draft-martin-managesieve-06
6  * as this draft expires with this writing, you might need to search for
7  * the new one.
8  *
9  * Copyright (c) 2007-2009 by the citadel.org team
10  *
11  *  This program is free software; you can redistribute it and/or modify
12  *  it under the terms of the GNU General Public License as published by
13  *  the Free Software Foundation; either version 3 of the License, or
14  *  (at your option) any later version.
15  *
16  *  This program is distributed in the hope that it will be useful,
17  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
18  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  *  GNU General Public License for more details.
20  *
21  *  You should have received a copy of the GNU General Public License
22  *  along with this program; if not, write to the Free Software
23  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
24  */
25
26 #include "sysdep.h"
27 #include <stdlib.h>
28 #include <unistd.h>
29 #include <stdio.h>
30 #include <fcntl.h>
31 #include <signal.h>
32 #include <pwd.h>
33 #include <errno.h>
34 #include <sys/types.h>
35 #include <syslog.h>
36
37 #if TIME_WITH_SYS_TIME
38 # include <sys/time.h>
39 # include <time.h>
40 #else
41 # if HAVE_SYS_TIME_H
42 #  include <sys/time.h>
43 # else
44 #  include <time.h>
45 # endif
46 #endif
47
48 #include <sys/wait.h>
49 #include <ctype.h>
50 #include <string.h>
51 #include <limits.h>
52 #include <sys/socket.h>
53 #include <netinet/in.h>
54 #include <arpa/inet.h>
55 #include <libcitadel.h>
56 #include "citadel.h"
57 #include "server.h"
58 #include "citserver.h"
59 #include "support.h"
60 #include "config.h"
61 #include "control.h"
62 #include "user_ops.h"
63 #include "database.h"
64 #include "msgbase.h"
65 #include "internet_addressing.h"
66 #include "genstamp.h"
67 #include "domain.h"
68 #include "clientsocket.h"
69 #include "locate_host.h"
70 #include "citadel_dirs.h"
71
72 #ifndef HAVE_SNPRINTF
73 #include "snprintf.h"
74 #endif
75
76
77 #include "ctdl_module.h"
78 #include "serv_sieve.h"
79
80
81 /**
82  * http://tools.ietf.org/html/draft-martin-managesieve-06
83  *
84  * this is the draft this code tries to implement.
85  */
86
87
88 struct citmgsve {               
89         int command_state;             /**< Information about the current session */
90         char *transmitted_message;
91         size_t transmitted_length;
92         char *imap_format_outstring;
93         int imap_outstring_length;
94 };
95
96 enum {  /** Command states for login authentication */
97         mgsve_command,
98         mgsve_tls,
99         mgsve_user,
100         mgsve_password,
101         mgsve_plain
102 };
103
104 #define MGSVE          ((struct citmgsve *)CC->session_specific_data)
105
106 int old_imap_parameterize(char** args, char *in)
107 {
108         char* out = in;
109         int num = 0;
110
111         for (;;)
112         {
113                 /* Skip whitespace. */
114
115                 while (isspace(*in))
116                         in++;
117                 if (*in == 0)
118                         break;
119
120                 /* Found the start of a token. */
121                 
122                 args[num++] = out;
123
124                 /* Read in the token. */
125
126                 for (;;)
127                 {
128                         int c = *in++;
129                         if (isspace(c))
130                                 break;
131                         
132                         if (c == '\"')
133                         {
134                                 /* Found a quoted section. */
135
136                                 for (;;)
137                                 {
138                                         c = *in++;
139                                         if (c == '\"')
140                                                 break;
141                                         else if (c == '\\')
142                                                 c = *in++;
143
144                                         *out++ = c;
145                                         if (c == 0)
146                                                 return num;
147                                 }
148                         }
149                         else if (c == '\\')
150                         {
151                                 c = *in++;
152                                 *out++ = c;
153                         }
154                         else
155                                 *out++ = c;
156
157                         if (c == 0)
158                                 return num;
159                 }
160                 *out++ = '\0';
161         }
162
163         return num;
164 }
165
166 /*****************************************************************************/
167 /*                      MANAGESIEVE Server                                   */
168 /*****************************************************************************/
169
170
171 void sieve_outbuf_append(char *str)
172 {
173         size_t newlen = strlen(str)+1;
174         size_t oldlen = (MGSVE->imap_format_outstring==NULL)? 0 : strlen(MGSVE->imap_format_outstring)+2;
175         char *buf = malloc ( newlen + oldlen + 10 );
176         buf[0]='\0';
177
178         if (oldlen!=0)
179                 sprintf(buf,"%s%s",MGSVE->imap_format_outstring, str);
180         else
181                 memcpy(buf, str, newlen);
182         
183         if (oldlen != 0) free (MGSVE->imap_format_outstring);
184         MGSVE->imap_format_outstring = buf;
185 }
186
187
188 /**
189  * Capability listing. Printed as greeting or on "CAPABILITIES" 
190  * see Section 1.8 ; 2.4
191  */
192 void cmd_mgsve_caps(void)
193
194         cprintf("\"IMPLEMENTATION\" \"CITADEL Sieve " PACKAGE_VERSION "\"\r\n" 
195                 "\"SASL\" \"PLAIN\"\r\n" /*DIGEST-MD5 GSSAPI  SASL sucks.*/
196 #ifdef HAVE_OPENSSL
197 /* if TLS is already there, should we say that again? */
198                 "\"STARTTLS\"\r\n"
199 #endif
200                 "\"SIEVE\" \"%s\"\r\n"
201                 "OK\r\n", msiv_extensions);
202 }
203
204
205 /*
206  * Here's where our managesieve session begins its happy day.
207  */
208 void managesieve_greeting(void) {
209
210         strcpy(CC->cs_clientname, "Managesieve session");
211
212         CC->internal_pgm = 0;
213         CC->cs_flags |= CS_STEALTH;
214         CC->session_specific_data = malloc(sizeof(struct citmgsve));
215         memset(MGSVE, 0, sizeof(struct citmgsve));
216         cmd_mgsve_caps();
217 }
218
219
220 long GetSizeToken(char * token)
221 {
222         char *cursor = token;
223         char *number;
224
225         while (!IsEmptyStr(cursor) && 
226                (*cursor != '{'))
227         {
228                 cursor++;
229         }
230         if (IsEmptyStr(cursor)) 
231                 return -1;
232         number = cursor + 1;
233         while ((*cursor != '\0') && 
234                (*cursor != '}'))
235         {
236                 cursor++;
237         }
238
239         if (cursor[-1] == '+')
240                 cursor--;
241
242         if (IsEmptyStr(cursor)) 
243                 return -1;
244         
245         return atol(number);
246 }
247
248 char *ReadString(long size, char *command)
249 {
250         long ret;
251         if (size < 1) {
252                 cprintf("NO %s: %ld BAD Message length must be at least 1.\r\n",
253                         command, size);
254                 CC->kill_me = KILLME_READSTRING_FAILED;
255                 return NULL;
256         }
257         MGSVE->transmitted_message = malloc(size + 2);
258         if (MGSVE->transmitted_message == NULL) {
259                 cprintf("NO %s Cannot allocate memory.\r\n", command);
260                 CC->kill_me = KILLME_MALLOC_FAILED;
261                 return NULL;
262         }
263         MGSVE->transmitted_length = size;
264         
265         ret = client_read(MGSVE->transmitted_message, size);
266         MGSVE->transmitted_message[size] = '\0';
267         
268         if (ret != 1) {
269                 cprintf("%s NO Read failed.\r\n", command);
270                 return NULL;
271         } 
272         return MGSVE->transmitted_message;
273
274 }
275 /* AUTHENTICATE command; 2.1 */
276 void cmd_mgsve_auth(int num_parms, char **parms, struct sdm_userdata *u)
277 {
278         if ((num_parms == 3) && !strncasecmp(parms[1], "PLAIN", 5))
279                 /* todo, check length*/
280         {
281                 char auth[SIZ];
282                 char *message;
283                 char *username;
284
285                 message = NULL;
286                 memset (auth, 0, SIZ);
287                 if (parms[2][0] == '{')
288                         message = ReadString(GetSizeToken(parms[2]), parms[0]);
289                 
290                 if (message != NULL) {/**< do we have tokenized login? */
291                         CtdlDecodeBase64(auth, MGSVE->transmitted_message, SIZ);
292                 }
293                 else 
294                         CtdlDecodeBase64(auth, parms[2], SIZ);
295                 username = auth;
296                 if ((*username == '\0') && (*(username + 1) != '\0'))
297                         username ++;
298                 
299                 if (login_ok == CtdlLoginExistingUser(NULL, username))
300                 {
301                         char *pass;
302
303                         pass = &(auth[strlen(auth)+1]);
304                         /* for some reason the php script sends us the username twice. y? */
305                         pass = &(pass[strlen(pass)+1]);
306                         
307                         if (pass_ok == CtdlTryPassword(pass, strlen(pass)))
308                         {
309                                 MGSVE->command_state = mgsve_password;
310                                 cprintf("OK\r\n");
311                                 return;
312                         }
313                 }
314         }
315         cprintf("NO \"Authentication Failure.\"\r\n");/* we just support auth plain. */
316         CC->kill_me = KILLME_AUTHFAILED;
317 }
318
319
320 /**
321  * STARTTLS command chapter 2.2 
322  */
323 void cmd_mgsve_starttls(void)
324 { /** answer with OK, and fire off tls session. */
325         cprintf("OK\r\n");
326         CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
327         cmd_mgsve_caps();
328 }
329
330
331
332 /*
333  * LOGOUT command, see chapter 2.3 
334  */
335 void cmd_mgsve_logout(struct sdm_userdata *u)
336 {
337         cprintf("OK\r\n");
338         syslog(LOG_NOTICE, "MgSve bye.");
339         CC->kill_me = KILLME_CLIENT_LOGGED_OUT;
340 }
341
342
343 /*
344  * HAVESPACE command. see chapter 2.5 
345  */
346 void cmd_mgsve_havespace(void)
347 {
348 /* as we don't have quotas in citadel we should always answer with OK; 
349  * pherhaps we should have a max-scriptsize. 
350  */
351         if (MGSVE->command_state != mgsve_password)
352         {
353                 cprintf("NO\r\n");
354                 CC->kill_me = KILLME_QUOTA;
355         }
356         else
357         {
358                 cprintf("OK"); 
359 /* citadel doesn't have quotas. in case of change, please add code here. */
360
361         }
362 }
363
364 /*
365  * PUTSCRIPT command, see chapter 2.6 
366  */
367 void cmd_mgsve_putscript(int num_parms, char **parms, struct sdm_userdata *u)
368 {
369 /* "scriptname" {nnn+} */
370 /* AFTER we have the whole script overwrite existing scripts */
371 /* spellcheck the script before overwrite old ones, and reply with "no" */
372         if (num_parms == 3)
373         {
374                 char *ScriptName;
375                 char *Script;
376                 long slength;
377
378                 if (parms[1][0]=='"')
379                         ScriptName = &parms[1][1];
380                 else
381                         ScriptName = parms[1];
382                 
383                 slength = strlen (ScriptName);
384                 
385                 if (ScriptName[slength] == '"')
386                         ScriptName[slength] = '\0';
387
388                 Script = ReadString(GetSizeToken(parms[2]),parms[0]);
389
390                 if (Script == NULL) return;
391                 
392                 // TODO: do we spellcheck?
393                 msiv_putscript(u, ScriptName, Script);
394                 cprintf("OK\r\n");
395         }
396         else {
397                 cprintf("%s NO Read failed.\r\n", parms[0]);
398                 CC->kill_me = KILLME_READ_FAILED;
399                 return;
400         } 
401
402
403
404 }
405
406
407
408
409 /**
410  * LISTSCRIPT command. see chapter 2.7 
411  */
412 void cmd_mgsve_listscript(int num_parms, char **parms, struct sdm_userdata *u)
413 {
414
415         struct sdm_script *s;
416         long nScripts = 0;
417
418         MGSVE->imap_format_outstring = NULL;
419         for (s=u->first_script; s!=NULL; s=s->next) {
420                 if (s->script_content != NULL) {
421                         cprintf("\"%s\"%s\r\n", 
422                                 s->script_name, 
423                                 (s->script_active)?" ACTIVE":"");
424                         nScripts++;
425                 }
426         }
427         cprintf("OK\r\n");
428 }
429
430
431 /**
432  * \brief SETACTIVE command. see chapter 2.8 
433  */
434 void cmd_mgsve_setactive(int num_parms, char **parms, struct sdm_userdata *u)
435 {
436         if (num_parms == 2)
437         {
438                 if (msiv_setactive(u, parms[1]) == 0) {
439                         cprintf("OK\r\n");
440                 }
441                 else
442                         cprintf("No \"there is no script by that name %s \"\r\n", parms[1]);
443         }
444         else 
445                 cprintf("NO \"unexpected parameters.\"\r\n");
446
447 }
448
449
450 /**
451  * \brief GETSCRIPT command. see chapter 2.9 
452  */
453 void cmd_mgsve_getscript(int num_parms, char **parms, struct sdm_userdata *u)
454 {
455         if (num_parms == 2){
456                 char *script_content;
457                 long  slen;
458
459                 script_content = msiv_getscript(u, parms[1]);
460                 if (script_content != NULL){
461                         char *outbuf;
462
463                         slen = strlen(script_content);
464                         outbuf = malloc (slen + 64);
465                         snprintf(outbuf, slen + 64, "{%ld+}\r\n%s\r\nOK\r\n",slen, script_content);
466                         cprintf("%s", outbuf);
467                 }
468                 else
469                         cprintf("No \"there is no script by that name %s \"\r\n", parms[1]);
470         }
471         else 
472                 cprintf("NO \"unexpected parameters.\"\r\n");
473 }
474
475
476 /**
477  * \brief DELETESCRIPT command. see chapter 2.10 
478  */
479 void cmd_mgsve_deletescript(int num_parms, char **parms, struct sdm_userdata *u)
480 {
481         int i=-1;
482
483         if (num_parms == 2)
484                 i = msiv_deletescript(u, parms[1]);
485         switch (i){             
486         case 0:
487                 cprintf("OK\r\n");
488                 break;
489         case 1:
490                 cprintf("NO \"no script by that name: %s\"\r\n", parms[1]);
491                 break;
492         case 2:
493                 cprintf("NO \"can't delete active Script: %s\"\r\n", parms[1]);
494                 break;
495         default:
496         case -1:
497                 cprintf("NO \"unexpected parameters.\"\r\n");
498                 break;
499         }
500 }
501
502
503 /**
504  * \brief Attempt to perform authenticated managesieve
505  */
506 void mgsve_auth(char *argbuf) {
507         char username_prompt[64];
508         char method[64];
509         char encoded_authstring[1024];
510
511         if (CC->logged_in) {
512                 cprintf("NO \"Already logged in.\"\r\n");
513                 return;
514         }
515
516         extract_token(method, argbuf, 0, ' ', sizeof method);
517
518         if (!strncasecmp(method, "login", 5) ) {
519                 if (strlen(argbuf) >= 7) {
520                 }
521                 else {
522                         CtdlEncodeBase64(username_prompt, "Username:", 9, 0);
523                         cprintf("334 %s\r\n", username_prompt);
524                 }
525                 return;
526         }
527
528         if (!strncasecmp(method, "plain", 5) ) {
529                 if (num_tokens(argbuf, ' ') < 2) {
530                         cprintf("334 \r\n");
531                         return;
532                 }
533                 extract_token(encoded_authstring, argbuf, 1, ' ', sizeof encoded_authstring);
534                 return;
535         }
536
537         if (strncasecmp(method, "login", 5) ) {
538                 cprintf("NO \"Unknown authentication method.\"\r\n");
539                 return;
540         }
541
542 }
543
544
545
546 /*
547  * implements the STARTTLS command (Citadel API version)
548  */
549 void _mgsve_starttls(void)
550 {
551         char ok_response[SIZ];
552         char nosup_response[SIZ];
553         char error_response[SIZ];
554
555         sprintf(ok_response,
556                 "200 2.0.0 Begin TLS negotiation now\r\n");
557         sprintf(nosup_response,
558                 "554 5.7.3 TLS not supported here\r\n");
559         sprintf(error_response,
560                 "554 5.7.3 Internal error\r\n");
561         CtdlModuleStartCryptoMsgs(ok_response, nosup_response, error_response);
562 }
563
564
565 /* 
566  * Main command loop for managesieve sessions.
567  */
568 void managesieve_command_loop(void) {
569         char cmdbuf[SIZ];
570         char *parms[SIZ];
571         int length;
572         int num_parms;
573         struct sdm_userdata u;
574         int changes_made = 0;
575
576         memset(&u, 0, sizeof(struct sdm_userdata));
577
578         time(&CC->lastcmd);
579         memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
580         length = client_getln(cmdbuf, sizeof cmdbuf);
581         if (length >= 1) {
582                 num_parms = old_imap_parameterize(parms, cmdbuf);
583                 if (num_parms == 0) return;
584                 length = strlen(parms[0]);
585         }
586         if (length < 1) {
587                 syslog(LOG_CRIT, "managesieve: client disconnected: ending session.\n");
588                 CC->kill_me = KILLME_CLIENT_DISCONNECTED;
589                 return;
590         }
591         syslog(LOG_INFO, "MANAGESIEVE: %s\n", cmdbuf);
592         if ((length>= 12) && (!strncasecmp(parms[0], "AUTHENTICATE", 12))){
593                 cmd_mgsve_auth(num_parms, parms, &u);
594         }
595
596 #ifdef HAVE_OPENSSL
597         else if ((length>= 8) && (!strncasecmp(parms[0], "STARTTLS", 8))){
598                 cmd_mgsve_starttls();
599         }
600 #endif
601         else if ((length>= 6) && (!strncasecmp(parms[0], "LOGOUT", 6))){
602                 cmd_mgsve_logout(&u);
603         }
604         else if ((length>= 6) && (!strncasecmp(parms[0], "CAPABILITY", 10))){
605                 cmd_mgsve_caps();
606         } 
607         /** these commands need to be authenticated. throw it out if it tries. */
608         else if (CC->logged_in != 0)
609         {
610                 msiv_load(&u);
611                 if ((length>= 9) && (!strncasecmp(parms[0], "HAVESPACE", 9))){
612                         cmd_mgsve_havespace();
613                 }
614                 else if ((length>= 6) && (!strncasecmp(parms[0], "PUTSCRIPT", 9))){
615                         cmd_mgsve_putscript(num_parms, parms, &u);
616                         changes_made = 1;
617                 }
618                 else if ((length>= 6) && (!strncasecmp(parms[0], "LISTSCRIPT", 10))){
619                         cmd_mgsve_listscript(num_parms, parms,&u);
620                 }
621                 else if ((length>= 6) && (!strncasecmp(parms[0], "SETACTIVE", 9))){
622                         cmd_mgsve_setactive(num_parms, parms,&u);
623                         changes_made = 1;
624                 }
625                 else if ((length>= 6) && (!strncasecmp(parms[0], "GETSCRIPT", 9))){
626                         cmd_mgsve_getscript(num_parms, parms, &u);
627                 }
628                 else if ((length>= 6) && (!strncasecmp(parms[0], "DELETESCRIPT", 11))){
629                         cmd_mgsve_deletescript(num_parms, parms, &u);
630                         changes_made = 1;
631                 }
632                 msiv_store(&u, changes_made);
633         }
634         else {
635                 cprintf("No Invalid access or command.\r\n");
636                 syslog(LOG_INFO, "illegal Managesieve command: %s", parms[0]);
637                 CC->kill_me = KILLME_ILLEGAL_MANAGESIEVE_COMMAND;
638         }
639
640
641 }
642
643 /*
644  * This cleanup function blows away the temporary memory and files used by
645  * the server.
646  */
647 void managesieve_cleanup_function(void) {
648
649         /* Don't do this stuff if this is not a managesieve session! */
650         if (CC->h_command_function != managesieve_command_loop) return;
651
652         syslog(LOG_DEBUG, "Performing managesieve cleanup hook\n");
653         free(MGSVE);
654 }
655
656
657
658 const char* CitadelServiceManageSieve = "ManageSieve";
659 CTDL_MODULE_INIT(managesieve)
660 {
661         if (!threading)
662         {
663                 CtdlRegisterServiceHook(config.c_managesieve_port,
664                                         NULL,
665                                         managesieve_greeting,
666                                         managesieve_command_loop,
667                                         NULL, 
668                                         CitadelServiceManageSieve);
669                 CtdlRegisterSessionHook(managesieve_cleanup_function, EVT_STOP);
670         }
671         
672         /* return our module name for the log */
673         return "managesieve";
674 }
675
676