9b53968e13cc4c09ef41d5c394ec4a8f3e60a76c
[citadel.git] / citadel / 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 "citadel.h"
42 #include "server.h"
43 #include "sysdep_decls.h"
44 #include "citserver.h"
45 #include "support.h"
46 #include "config.h"
47 #include "control.h"
48 #include "serv_extensions.h"
49 #include "room_ops.h"
50 #include "user_ops.h"
51 #include "policy.h"
52 #include "database.h"
53 #include "msgbase.h"
54 #include "tools.h"
55 #include "internet_addressing.h"
56 #include "imap_tools.h"
57 #include "genstamp.h"
58 #include "domain.h"
59 #include "clientsocket.h"
60 #include "locate_host.h"
61 #include "citadel_dirs.h"
62
63 #ifdef HAVE_OPENSSL
64 #include "serv_crypto.h"
65 #endif
66
67 #ifndef HAVE_SNPRINTF
68 #include "snprintf.h"
69 #endif
70
71 #ifdef HAVE_LIBSIEVE
72
73 #include "serv_sieve.h"
74
75
76 /**
77  * http://tools.ietf.org/html/draft-martin-managesieve-06
78  *
79  * this is the draft this code tries to implement.
80  */
81
82
83 struct citmgsve {               
84         int command_state;             /**< Information about the current session */
85         char *transmitted_message;
86         size_t transmitted_length;
87         char *imap_format_outstring;
88         int imap_outstring_length;
89 };
90
91 enum {  /** Command states for login authentication */
92         mgsve_command,
93         mgsve_tls,
94         mgsve_user,
95         mgsve_password,
96         mgsve_plain
97 };
98
99 #define MGSVE          CC->MGSVE
100
101 /*****************************************************************************/
102 /*                      MANAGESIEVE Server                                   */
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         MGSVE = 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 ((*cursor != '\0') && 
160                (*cursor != '{'))
161         {
162                 cursor++;
163         }
164         if (*cursor == '\0') 
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 (*cursor == '\0') 
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 #ifdef HAVE_OPENSSL
247 /**
248  * STARTTLS command chapter 2.2 
249  */
250 void cmd_mgsve_starttls(void)
251 { /** answer with OK, and fire off tls session. */
252         cprintf("OK\r\n");
253         CtdlStartTLS(NULL, NULL, NULL);
254         cmd_mgsve_caps();
255 }
256 #endif
257
258
259
260 /**
261  *LOGOUT command, see chapter 2.3 
262  */
263 void cmd_mgsve_logout(struct sdm_userdata *u)
264 {
265         cprintf("OK\r\n");
266         lprintf(CTDL_NOTICE, "MgSve bye.");
267         CC->kill_me = 1;
268 }
269
270
271 /**
272  * HAVESPACE command. see chapter 2.5 
273  */
274 void cmd_mgsve_havespace(void)
275 {
276 /* as we don't have quotas in citadel we should always answer with OK; 
277  * pherhaps we should have a max-scriptsize. 
278  */
279         if (MGSVE->command_state != mgsve_password)
280         {
281                 cprintf("NO\r\n");
282                 CC->kill_me = 1;
283         }
284         else
285         {
286                 cprintf("OK"); 
287 /* citadel doesn't have quotas. in case of change, please add code here. */
288
289         }
290 }
291
292 /**
293  * PUTSCRIPT command, see chapter 2.6 
294  */
295 void cmd_mgsve_putscript(int num_parms, char **parms, struct sdm_userdata *u)
296 {
297 /* "scriptname" {nnn+} */
298 /* AFTER we have the whole script overwrite existing scripts */
299 /* spellcheck the script before overwrite old ones, and reply with "no" */
300         if (num_parms == 3)
301         {
302                 char *ScriptName;
303                 char *Script;
304                 long slength;
305
306                 if (parms[1][0]=='"')
307                         ScriptName = &parms[1][1];
308                 else
309                         ScriptName = parms[1];
310                 
311                 slength = strlen (ScriptName);
312                 
313                 if (ScriptName[slength] == '"')
314                         ScriptName[slength] = '\0';
315
316                 Script = ReadString(GetSizeToken(parms[2]),parms[0]);
317
318                 if (Script == NULL) return;
319                 
320                 // TODO: do we spellcheck?
321                 msiv_putscript(u, ScriptName, Script);
322                 cprintf("OK\r\n");
323         }
324         else {
325                 cprintf("%s NO Read failed.\r\n", parms[0]);
326                 CC->kill_me = 1;
327                 return;
328         } 
329
330
331
332 }
333
334
335
336
337 /**
338  * LISTSCRIPT command. see chapter 2.7 
339  */
340 void cmd_mgsve_listscript(int num_parms, char **parms, struct sdm_userdata *u)
341 {
342
343         struct sdm_script *s;
344         long nScripts = 0;
345
346         MGSVE->imap_format_outstring = NULL;
347         for (s=u->first_script; s!=NULL; s=s->next) {
348                 if (s->script_content != NULL) {
349                         cprintf("\"%s\"%s\r\n", 
350                                 s->script_name, 
351                                 (s->script_active)?" ACTIVE":"");
352                         nScripts++;
353                 }
354         }
355         cprintf("OK\r\n");
356 }
357
358
359 /**
360  * \brief SETACTIVE command. see chapter 2.8 
361  */
362 void cmd_mgsve_setactive(int num_parms, char **parms, struct sdm_userdata *u)
363 {
364         if (num_parms == 2)
365         {
366                 if (msiv_setactive(u, parms[1]) == 0) {
367                         cprintf("OK\r\n");
368                 }
369                 else
370                         cprintf("No \"there is no script by that name %s \"\r\n", parms[1]);
371         }
372         else 
373                 cprintf("NO \"unexpected parameters.\"\r\n");
374
375 }
376
377
378 /**
379  * \brief GETSCRIPT command. see chapter 2.9 
380  */
381 void cmd_mgsve_getscript(int num_parms, char **parms, struct sdm_userdata *u)
382 {
383         if (num_parms == 2){
384                 char *script_content;
385                 long  slen;
386
387                 script_content = msiv_getscript(u, parms[1]);
388                 if (script_content != NULL){
389                         char *outbuf;
390
391                         slen = strlen(script_content);
392                         outbuf = malloc (slen + 64);
393                         snprintf(outbuf, slen + 64, "{%ld+}\r\n%s\r\nOK\r\n",slen, script_content);
394                         cprintf(outbuf);
395                 }
396                 else
397                         cprintf("No \"there is no script by that name %s \"\r\n", parms[1]);
398         }
399         else 
400                 cprintf("NO \"unexpected parameters.\"\r\n");
401 }
402
403
404 /**
405  * \brief DELETESCRIPT command. see chapter 2.10 
406  */
407 void cmd_mgsve_deletescript(int num_parms, char **parms, struct sdm_userdata *u)
408 {
409         int i=-1;
410
411         if (num_parms == 2)
412                 i = msiv_deletescript(u, parms[1]);
413         switch (i){             
414         case 0:
415                 cprintf("OK\r\n");
416                 break;
417         case 1:
418                 cprintf("NO \"no script by that name: %s\"\r\n", parms[1]);
419                 break;
420         case 2:
421                 cprintf("NO \"can't delete active Script: %s\"\r\n", parms[1]);
422                 break;
423         default:
424         case -1:
425                 cprintf("NO \"unexpected parameters.\"\r\n");
426                 break;
427         }
428 }
429
430
431 /**
432  * \brief Attempt to perform authenticated managesieve
433  */
434 void mgsve_auth(char *argbuf) {
435         char username_prompt[64];
436         char method[64];
437         char encoded_authstring[1024];
438
439         if (CC->logged_in) {
440                 cprintf("NO \"Already logged in.\"\r\n");
441                 return;
442         }
443
444         extract_token(method, argbuf, 0, ' ', sizeof method);
445
446         if (!strncasecmp(method, "login", 5) ) {
447                 if (strlen(argbuf) >= 7) {
448                 }
449                 else {
450                         CtdlEncodeBase64(username_prompt, "Username:", 9);
451                         cprintf("334 %s\r\n", username_prompt);
452                 }
453                 return;
454         }
455
456         if (!strncasecmp(method, "plain", 5) ) {
457                 if (num_tokens(argbuf, ' ') < 2) {
458                         cprintf("334 \r\n");
459                         return;
460                 }
461                 extract_token(encoded_authstring, argbuf, 1, ' ', sizeof encoded_authstring);
462                 return;
463         }
464
465         if (strncasecmp(method, "login", 5) ) {
466                 cprintf("NO \"Unknown authentication method.\"\r\n");
467                 return;
468         }
469
470 }
471
472
473
474 /*
475  * implements the STARTTLS command (Citadel API version)
476  */
477 #ifdef HAVE_OPENSSL
478 void _mgsve_starttls(void)
479 {
480         char ok_response[SIZ];
481         char nosup_response[SIZ];
482         char error_response[SIZ];
483
484         sprintf(ok_response,
485                 "200 2.0.0 Begin TLS negotiation now\r\n");
486         sprintf(nosup_response,
487                 "554 5.7.3 TLS not supported here\r\n");
488         sprintf(error_response,
489                 "554 5.7.3 Internal error\r\n");
490         CtdlStartTLS(ok_response, nosup_response, error_response);
491 }
492 #endif
493
494
495 /* 
496  * Main command loop for managesieve sessions.
497  */
498 void managesieve_command_loop(void) {
499         char cmdbuf[SIZ];
500         char *parms[SIZ];
501         int length;
502         int num_parms;
503         struct sdm_userdata u;
504         int changes_made = 0;
505
506         memset(&u, 0, sizeof(struct sdm_userdata));
507
508         time(&CC->lastcmd);
509         memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
510         length = client_getln(cmdbuf, sizeof cmdbuf);
511         if (length >= 1) {
512                 num_parms = imap_parameterize(parms, cmdbuf);
513                 if (num_parms == 0) return;
514                 length = strlen(parms[0]);
515         }
516         if (length < 1) {
517                 lprintf(CTDL_CRIT, "Client disconnected: ending session.\n");
518                 CC->kill_me = 1;
519                 return;
520         }
521         lprintf(CTDL_INFO, "MANAGESIEVE: %s\n", cmdbuf);
522         if ((length>= 12) && (!strncasecmp(parms[0], "AUTHENTICATE", 12))){
523                 cmd_mgsve_auth(num_parms, parms, &u);
524         }
525
526 #ifdef HAVE_OPENSSL
527         else if ((length>= 8) && (!strncasecmp(parms[0], "STARTTLS", 8))){
528                 cmd_mgsve_starttls();
529         }
530 #endif
531         else if ((length>= 6) && (!strncasecmp(parms[0], "LOGOUT", 6))){
532                 cmd_mgsve_logout(&u);
533         }
534         else if ((length>= 6) && (!strncasecmp(parms[0], "CAPABILITY", 10))){
535                 cmd_mgsve_caps();
536         } 
537         /** these commands need to be authenticated. throw it out if it tries. */
538         else if (!CtdlAccessCheck(ac_logged_in))
539         {
540                 msiv_load(&u);
541                 if ((length>= 9) && (!strncasecmp(parms[0], "HAVESPACE", 9))){
542                         cmd_mgsve_havespace();
543                 }
544                 else if ((length>= 6) && (!strncasecmp(parms[0], "PUTSCRIPT", 9))){
545                         cmd_mgsve_putscript(num_parms, parms, &u);
546                         changes_made = 1;
547                 }
548                 else if ((length>= 6) && (!strncasecmp(parms[0], "LISTSCRIPT", 10))){
549                         cmd_mgsve_listscript(num_parms, parms,&u);
550                 }
551                 else if ((length>= 6) && (!strncasecmp(parms[0], "SETACTIVE", 9))){
552                         cmd_mgsve_setactive(num_parms, parms,&u);
553                         changes_made = 1;
554                 }
555                 else if ((length>= 6) && (!strncasecmp(parms[0], "GETSCRIPT", 9))){
556                         cmd_mgsve_getscript(num_parms, parms, &u);
557                 }
558                 else if ((length>= 6) && (!strncasecmp(parms[0], "DELETESCRIPT", 11))){
559                         cmd_mgsve_deletescript(num_parms, parms, &u);
560                         changes_made = 1;
561                 }
562                 msiv_store(&u, changes_made);
563         }
564         else {
565                 cprintf("No\r\n");
566                 lprintf(CTDL_INFO, "illegal Managesieve command: %s", parms[0]);
567                 CC->kill_me = 1;
568         }
569
570
571 }
572
573
574
575 char *serv_managesieve_init(void)
576 {
577
578         CtdlRegisterServiceHook(config.c_managesieve_port,      /* MGSVE */
579                                 NULL,
580                                 managesieve_greeting,
581                                 managesieve_command_loop,
582                                 NULL);
583
584         return "$Id$";
585 }
586
587 #else   /* HAVE_LIBSIEVE */
588
589 char *serv_managesieve_init(void)
590 {
591         lprintf(CTDL_INFO, "This server is missing libsieve.  Managesieve protocol is disabled..\n");
592
593         /* return our Subversion id for the Log */
594         return "$Id$";
595 }
596
597 #endif  /* HAVE_LIBSIEVE */