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