* fixed tbirds managesieve login troubles.
[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 " PACKAGE_VERSION "\"\r\n" 
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 = 0;
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;
218                 char *username;
219                 char *password;
220
221                 message = NULL;
222                 memset (auth, 0, SIZ);
223                 if (parms[2][0] == '{')
224                         message = ReadString(GetSizeToken(parms[2]), parms[0]);
225                 
226                 if (message != NULL) {/**< do we have tokenized login? */
227                         retval = CtdlDecodeBase64(auth, MGSVE->transmitted_message, SIZ);
228                 }
229                 else 
230                         retval = CtdlDecodeBase64(auth, parms[2], SIZ);
231                 username = auth;
232                 if ((*username == '\0') && (*(username + 1) != '\0'))
233                         username ++;
234                 
235                 if (login_ok == CtdlLoginExistingUser(NULL, username))
236                 {
237                         char *pass;
238                         pass = &(auth[strlen(auth)+1]);
239                         /* for some reason the php script sends us the username twice. y? */
240                         pass = &(pass[strlen(pass)+1]);
241                         
242                         if (pass_ok == CtdlTryPassword(pass))
243                         {
244                                 MGSVE->command_state = mgsve_password;
245                                 cprintf("OK\r\n");
246                                 return;
247                         }
248                 }
249         }
250         cprintf("NO \"Authentication Failure.\"\r\n");/* we just support auth plain. */
251         CC->kill_me = 1;
252 }
253
254
255 /**
256  * STARTTLS command chapter 2.2 
257  */
258 void cmd_mgsve_starttls(void)
259 { /** answer with OK, and fire off tls session. */
260         cprintf("OK\r\n");
261         CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
262         cmd_mgsve_caps();
263 }
264
265
266
267 /**
268  *LOGOUT command, see chapter 2.3 
269  */
270 void cmd_mgsve_logout(struct sdm_userdata *u)
271 {
272         cprintf("OK\r\n");
273         lprintf(CTDL_NOTICE, "MgSve bye.");
274         CC->kill_me = 1;
275 }
276
277
278 /**
279  * HAVESPACE command. see chapter 2.5 
280  */
281 void cmd_mgsve_havespace(void)
282 {
283 /* as we don't have quotas in citadel we should always answer with OK; 
284  * pherhaps we should have a max-scriptsize. 
285  */
286         if (MGSVE->command_state != mgsve_password)
287         {
288                 cprintf("NO\r\n");
289                 CC->kill_me = 1;
290         }
291         else
292         {
293                 cprintf("OK"); 
294 /* citadel doesn't have quotas. in case of change, please add code here. */
295
296         }
297 }
298
299 /**
300  * PUTSCRIPT command, see chapter 2.6 
301  */
302 void cmd_mgsve_putscript(int num_parms, char **parms, struct sdm_userdata *u)
303 {
304 /* "scriptname" {nnn+} */
305 /* AFTER we have the whole script overwrite existing scripts */
306 /* spellcheck the script before overwrite old ones, and reply with "no" */
307         if (num_parms == 3)
308         {
309                 char *ScriptName;
310                 char *Script;
311                 long slength;
312
313                 if (parms[1][0]=='"')
314                         ScriptName = &parms[1][1];
315                 else
316                         ScriptName = parms[1];
317                 
318                 slength = strlen (ScriptName);
319                 
320                 if (ScriptName[slength] == '"')
321                         ScriptName[slength] = '\0';
322
323                 Script = ReadString(GetSizeToken(parms[2]),parms[0]);
324
325                 if (Script == NULL) return;
326                 
327                 // TODO: do we spellcheck?
328                 msiv_putscript(u, ScriptName, Script);
329                 cprintf("OK\r\n");
330         }
331         else {
332                 cprintf("%s NO Read failed.\r\n", parms[0]);
333                 CC->kill_me = 1;
334                 return;
335         } 
336
337
338
339 }
340
341
342
343
344 /**
345  * LISTSCRIPT command. see chapter 2.7 
346  */
347 void cmd_mgsve_listscript(int num_parms, char **parms, struct sdm_userdata *u)
348 {
349
350         struct sdm_script *s;
351         long nScripts = 0;
352
353         MGSVE->imap_format_outstring = NULL;
354         for (s=u->first_script; s!=NULL; s=s->next) {
355                 if (s->script_content != NULL) {
356                         cprintf("\"%s\"%s\r\n", 
357                                 s->script_name, 
358                                 (s->script_active)?" ACTIVE":"");
359                         nScripts++;
360                 }
361         }
362         cprintf("OK\r\n");
363 }
364
365
366 /**
367  * \brief SETACTIVE command. see chapter 2.8 
368  */
369 void cmd_mgsve_setactive(int num_parms, char **parms, struct sdm_userdata *u)
370 {
371         if (num_parms == 2)
372         {
373                 if (msiv_setactive(u, parms[1]) == 0) {
374                         cprintf("OK\r\n");
375                 }
376                 else
377                         cprintf("No \"there is no script by that name %s \"\r\n", parms[1]);
378         }
379         else 
380                 cprintf("NO \"unexpected parameters.\"\r\n");
381
382 }
383
384
385 /**
386  * \brief GETSCRIPT command. see chapter 2.9 
387  */
388 void cmd_mgsve_getscript(int num_parms, char **parms, struct sdm_userdata *u)
389 {
390         if (num_parms == 2){
391                 char *script_content;
392                 long  slen;
393
394                 script_content = msiv_getscript(u, parms[1]);
395                 if (script_content != NULL){
396                         char *outbuf;
397
398                         slen = strlen(script_content);
399                         outbuf = malloc (slen + 64);
400                         snprintf(outbuf, slen + 64, "{%ld+}\r\n%s\r\nOK\r\n",slen, script_content);
401                         cprintf(outbuf);
402                 }
403                 else
404                         cprintf("No \"there is no script by that name %s \"\r\n", parms[1]);
405         }
406         else 
407                 cprintf("NO \"unexpected parameters.\"\r\n");
408 }
409
410
411 /**
412  * \brief DELETESCRIPT command. see chapter 2.10 
413  */
414 void cmd_mgsve_deletescript(int num_parms, char **parms, struct sdm_userdata *u)
415 {
416         int i=-1;
417
418         if (num_parms == 2)
419                 i = msiv_deletescript(u, parms[1]);
420         switch (i){             
421         case 0:
422                 cprintf("OK\r\n");
423                 break;
424         case 1:
425                 cprintf("NO \"no script by that name: %s\"\r\n", parms[1]);
426                 break;
427         case 2:
428                 cprintf("NO \"can't delete active Script: %s\"\r\n", parms[1]);
429                 break;
430         default:
431         case -1:
432                 cprintf("NO \"unexpected parameters.\"\r\n");
433                 break;
434         }
435 }
436
437
438 /**
439  * \brief Attempt to perform authenticated managesieve
440  */
441 void mgsve_auth(char *argbuf) {
442         char username_prompt[64];
443         char method[64];
444         char encoded_authstring[1024];
445
446         if (CC->logged_in) {
447                 cprintf("NO \"Already logged in.\"\r\n");
448                 return;
449         }
450
451         extract_token(method, argbuf, 0, ' ', sizeof method);
452
453         if (!strncasecmp(method, "login", 5) ) {
454                 if (strlen(argbuf) >= 7) {
455                 }
456                 else {
457                         CtdlEncodeBase64(username_prompt, "Username:", 9, 0);
458                         cprintf("334 %s\r\n", username_prompt);
459                 }
460                 return;
461         }
462
463         if (!strncasecmp(method, "plain", 5) ) {
464                 if (num_tokens(argbuf, ' ') < 2) {
465                         cprintf("334 \r\n");
466                         return;
467                 }
468                 extract_token(encoded_authstring, argbuf, 1, ' ', sizeof encoded_authstring);
469                 return;
470         }
471
472         if (strncasecmp(method, "login", 5) ) {
473                 cprintf("NO \"Unknown authentication method.\"\r\n");
474                 return;
475         }
476
477 }
478
479
480
481 /*
482  * implements the STARTTLS command (Citadel API version)
483  */
484 void _mgsve_starttls(void)
485 {
486         char ok_response[SIZ];
487         char nosup_response[SIZ];
488         char error_response[SIZ];
489
490         sprintf(ok_response,
491                 "200 2.0.0 Begin TLS negotiation now\r\n");
492         sprintf(nosup_response,
493                 "554 5.7.3 TLS not supported here\r\n");
494         sprintf(error_response,
495                 "554 5.7.3 Internal error\r\n");
496         CtdlModuleStartCryptoMsgs(ok_response, nosup_response, error_response);
497 }
498
499
500 /* 
501  * Main command loop for managesieve sessions.
502  */
503 void managesieve_command_loop(void) {
504         char cmdbuf[SIZ];
505         char *parms[SIZ];
506         int length;
507         int num_parms;
508         struct sdm_userdata u;
509         int changes_made = 0;
510
511         memset(&u, 0, sizeof(struct sdm_userdata));
512
513         time(&CC->lastcmd);
514         memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
515         length = client_getln(cmdbuf, sizeof cmdbuf);
516         if (length >= 1) {
517                 num_parms = imap_parameterize(parms, cmdbuf);
518                 if (num_parms == 0) return;
519                 length = strlen(parms[0]);
520         }
521         if (length < 1) {
522                 lprintf(CTDL_CRIT, "Client disconnected: ending session.\n");
523                 CC->kill_me = 1;
524                 return;
525         }
526         lprintf(CTDL_INFO, "MANAGESIEVE: %s\n", cmdbuf);
527         if ((length>= 12) && (!strncasecmp(parms[0], "AUTHENTICATE", 12))){
528                 cmd_mgsve_auth(num_parms, parms, &u);
529         }
530
531 #ifdef HAVE_OPENSSL
532         else if ((length>= 8) && (!strncasecmp(parms[0], "STARTTLS", 8))){
533                 cmd_mgsve_starttls();
534         }
535 #endif
536         else if ((length>= 6) && (!strncasecmp(parms[0], "LOGOUT", 6))){
537                 cmd_mgsve_logout(&u);
538         }
539         else if ((length>= 6) && (!strncasecmp(parms[0], "CAPABILITY", 10))){
540                 cmd_mgsve_caps();
541         } 
542         /** these commands need to be authenticated. throw it out if it tries. */
543         else if (CC->logged_in != 0)
544         {
545                 msiv_load(&u);
546                 if ((length>= 9) && (!strncasecmp(parms[0], "HAVESPACE", 9))){
547                         cmd_mgsve_havespace();
548                 }
549                 else if ((length>= 6) && (!strncasecmp(parms[0], "PUTSCRIPT", 9))){
550                         cmd_mgsve_putscript(num_parms, parms, &u);
551                         changes_made = 1;
552                 }
553                 else if ((length>= 6) && (!strncasecmp(parms[0], "LISTSCRIPT", 10))){
554                         cmd_mgsve_listscript(num_parms, parms,&u);
555                 }
556                 else if ((length>= 6) && (!strncasecmp(parms[0], "SETACTIVE", 9))){
557                         cmd_mgsve_setactive(num_parms, parms,&u);
558                         changes_made = 1;
559                 }
560                 else if ((length>= 6) && (!strncasecmp(parms[0], "GETSCRIPT", 9))){
561                         cmd_mgsve_getscript(num_parms, parms, &u);
562                 }
563                 else if ((length>= 6) && (!strncasecmp(parms[0], "DELETESCRIPT", 11))){
564                         cmd_mgsve_deletescript(num_parms, parms, &u);
565                         changes_made = 1;
566                 }
567                 msiv_store(&u, changes_made);
568         }
569         else {
570                 cprintf("No Invalid access or command.\r\n");
571                 lprintf(CTDL_INFO, "illegal Managesieve command: %s", parms[0]);
572                 CC->kill_me = 1;
573         }
574
575
576 }
577
578 /*
579  * This cleanup function blows away the temporary memory and files used by
580  * the server.
581  */
582 void managesieve_cleanup_function(void) {
583
584         /* Don't do this stuff if this is not a managesieve session! */
585         if (CC->h_command_function != managesieve_command_loop) return;
586
587         lprintf(CTDL_DEBUG, "Performing managesieve cleanup hook\n");
588         free(MGSVE);
589 }
590
591
592
593 #endif  /* HAVE_LIBSIEVE */
594 const char* CitadelServiceManageSieve = "ManageSieve";
595 CTDL_MODULE_INIT(managesieve)
596 {
597         if (!threading)
598         {
599 #ifdef HAVE_LIBSIEVE
600                 CtdlRegisterServiceHook(config.c_managesieve_port,
601                                         NULL,
602                                         managesieve_greeting,
603                                         managesieve_command_loop,
604                                         NULL, 
605                                         CitadelServiceManageSieve);
606                 CtdlRegisterSessionHook(managesieve_cleanup_function, EVT_STOP);
607
608 #else   /* HAVE_LIBSIEVE */
609
610                 lprintf(CTDL_INFO, "This server is missing libsieve.  Managesieve protocol is disabled..\n");
611
612 #endif  /* HAVE_LIBSIEVE */
613         }
614         
615         /* return our Subversion id for the Log */
616         return "$Id$";
617 }
618
619