]> code.citadel.org Git - citadel.git/blob - citadel/serv_managesieve.c
cleaned up some comments etc.
[citadel.git] / citadel / serv_managesieve.c
1 /**
2  * $Id: $
3  *
4  * This module is an Manage Sieve 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
68
69 #ifndef HAVE_SNPRINTF
70 #include "snprintf.h"
71 #endif
72
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 helo_node[SIZ];
85         struct ctdluser vrfy_buffer;
86         int vrfy_count;
87         char vrfy_match[SIZ];
88         char from[SIZ];
89         char recipients[SIZ];
90         int number_of_recipients;
91         int delivery_mode;
92         int message_originated_locally;
93         char *transmitted_message;      /* for APPEND command... */
94         size_t transmitted_length;
95 };
96
97 enum {  /** Command states for login authentication */
98         mgsve_command,
99         mgsve_tls,
100         mgsve_user,
101         mgsve_password,
102         mgsve_plain
103 };
104
105
106 #define MGSVE          CC->MGSVE
107
108 /*****************************************************************************/
109 /*                      MANAGESIEVE Server                                   */
110 /*****************************************************************************/
111
112
113 void goto_sieverules_room(void)
114 {// TODO: check if we're authenticated.
115         struct ctdlroom QRscratch;
116         int c;
117         char augmented_roomname[ROOMNAMELEN];
118         int transiently = 0;
119
120         MailboxName(augmented_roomname, sizeof augmented_roomname,
121                     &CC->user, SIEVERULES);
122         c = getroom(&QRscratch, augmented_roomname);
123         if (c != 0)/* something went wrong. hit it! */
124         {
125                 cprintf("BYE\r\n");
126                 CC->kill_me = 1;
127                 return;
128         }
129         /* move to the sieve room. */
130         memcpy(&CC->room, &QRscratch,
131                sizeof(struct ctdlroom));
132         usergoto(NULL, 1, transiently, NULL, NULL);
133 }
134
135 /**
136  * Capability listing. Printed as greeting or on "CAPABILITIES" 
137  * see Section 1.8 ; 2.4
138  */
139 void cmd_mgsve_caps(void)
140
141         cprintf("\"IMPLEMENTATION\" \"CITADEL Sieve v6.84\"\r\n" /* TODO: put citversion here. */
142                 "\"SASL\" \"PLAIN\"\r\n" /*DIGEST-MD5 GSSAPI  SASL sucks.*/
143 #ifdef HAVE_OPENSSL
144 /* if TLS is already there, should we say that again? */
145                 "\"STARTTLS\"\r\n"
146 #endif
147                 "\"SIEVE\" \"FILEINTO VACATION\"\r\n" /* TODO: print sieve extensions here. */
148                 "OK\r\n");
149 }
150
151
152 /*
153  * Here's where our managesieve session begins its happy day.
154  */
155 void managesieve_greeting(void) {
156
157         strcpy(CC->cs_clientname, "Managesieve session");
158
159         CC->internal_pgm = 1;
160         CC->cs_flags |= CS_STEALTH;
161         MGSVE = malloc(sizeof(struct citmgsve));
162         memset(MGSVE, 0, sizeof(struct citmgsve));
163         cmd_mgsve_caps();
164 }
165
166 /* AUTHENTICATE command; 2.1 */
167 void cmd_mgsve_auth(int num_parms, char **parms)
168 {
169 /* TODO: compare "digest-md5" or "gssapi" and answer with "NO" */
170         if ((num_parms == 3) && !strncasecmp(parms[1], "PLAIN", 5))
171                 /* todo, check length*/
172         {
173                 char auth[SIZ];
174                 int retval;
175                 
176                 /* todo: how to do plain auth? */
177                 
178                 if (parms[2][0] == '{') 
179                 {
180                         long literal_length;
181                         long ret;
182                         
183                         literal_length = atol(&parms[2][1]);
184                         if (literal_length < 1) {
185                                 cprintf("NO %s BAD Message length must be at least 1.\n",
186                                         parms[0]);
187                                 CC->kill_me = 1;
188                                 return;
189                         }
190                         MGSVE->transmitted_message = malloc(literal_length + 2);
191                         if (MGSVE->transmitted_message == NULL) {
192                                 cprintf("NO %s Cannot allocate memory.\r\n", parms[0]);
193                                 CC->kill_me = 1;
194                                 return;
195                         }
196                         MGSVE->transmitted_length = literal_length;
197                         
198                         ret = client_read(MGSVE->transmitted_message, literal_length);
199                         MGSVE->transmitted_message[literal_length] = 0;
200                         
201                         if (ret != 1) {
202                                 cprintf("%s NO Read failed.\r\n", parms[0]);
203                                 return;
204                         } 
205                         
206                         retval = CtdlDecodeBase64(auth, MGSVE->transmitted_message, SIZ);
207                         
208                 }
209                 else 
210                         retval = CtdlDecodeBase64(auth, parms[2], SIZ);
211                 if (login_ok == CtdlLoginExistingUser(auth))
212                 {
213                         char *pass;
214                         pass = &(auth[strlen(auth)+1]);
215                         /* for some reason the php script sends us the username twice. y? */
216                         pass = &(pass[strlen(pass)+1]);
217                         
218                         if (pass_ok == CtdlTryPassword(pass))
219                         {
220                                 MGSVE->command_state = mgsve_password;
221                                 cprintf("OK\n");
222                                 return;
223                         }
224                 }
225         }
226         
227         cprintf("NO\n");/* we just support auth plain. */
228         CC->kill_me = 1;
229         
230 }
231
232
233 #ifdef HAVE_OPENSSL
234 /* STARTTLS command chapter 2.2 */
235 void cmd_mgsve_starttls(void)
236 { /* answer with OK, and fire off tls session. */
237         cprintf("OK\n");
238         CtdlStartTLS(NULL, NULL, NULL);
239         cmd_mgsve_caps();
240 }
241 #endif
242
243
244
245 /* LOGOUT command, see chapter 2.3 */
246 void cmd_mgsve_logout(void)
247 {/* send "OK" and terminate the connection. */
248         cprintf("OK\r\n");
249         lprintf(CTDL_NOTICE, "MgSve bye.");
250         CC->kill_me = 1;
251 }
252
253
254 /* HAVESPACE command. see chapter 2.5 */
255 void cmd_mgsve_havespace(void)
256 {
257 /* TODO answer NO in any case if auth is missing. */
258 /* as we don't have quotas in citadel we should always answer with OK; 
259  * pherhaps we should have a max-scriptsize. 
260  */
261         if (MGSVE->command_state != mgsve_password)
262         {
263                 cprintf("NO\n");
264                 CC->kill_me = 1;
265         }
266         else
267         {
268                 cprintf("OK"); 
269 /* citadel doesn't have quotas. in case of change, please add code here. */
270
271         }
272 }
273
274 /* PUTSCRIPT command, see chapter 2.6 */
275 void cmd_mgsve_putscript(void)
276 {
277 /* "scriptname" {nnn+} */
278 /* TODO: answer with "NO" instant, if we're unauthorized. */
279 /* AFTER we have the whole script overwrite existing scripts */
280 /* spellcheck the script before overwrite old ones, and reply with "no" */
281
282 }
283
284
285 /** forward declaration for function in msgbase.c */
286 void headers_listing(long msgnum, void *userdata);
287
288
289 /* LISTSCRIPT command. see chapter 2.7 */
290 void cmd_mgsve_listscript(void)
291 {
292         goto_sieverules_room();/* TODO: do we need a template? */
293         CtdlForEachMessage(MSGS_ALL, 0, NULL, NULL, NULL,
294                            headers_listing, NULL);
295
296         
297 /* TODO: check auth, if not, answer with "no" */
298 /* do something like the sieve room indexlisting, one per row, in quotes. ACTIVE behind the active one.*/ 
299
300 ///     ra = getroom(sieveroom, SIEVERULES);
301 ///     /* Only list rooms to which the user has access!! */
302 ///     CtdlRoomAccess(SIEVERULES, &CC->user, &ra, NULL);
303 ///     if ((ra & UA_KNOWN)
304 ///         || ((ra & UA_GOTOALLOWED) && (ra & UA_ZAPPED))) {
305 ///             imap_mailboxname(buf, sizeof buf, qrbuf);
306 ///             if (imap_mailbox_matches_pattern(pattern, buf)) {
307 ///                     cprintf("* LIST () \"/\" ");
308 ///                     imap_strout(buf);
309 ///                     cprintf("\r\n");
310 ///             }
311 ///     }
312 ///
313         cprintf("OK\r\n");
314 }
315
316
317 /* SETACTIVE command. see chapter 2.8 */
318 void cmd_mgsve_setactive(void)
319 {
320 /* TODO: check auth, if not, answer with "no" */
321 /* search our room for subjects with that scriptname, 
322  * if the scriptname is empty, use the default flag.
323  * if the script is not there answer "No "there is no script by that name "
324  */
325
326
327
328 }
329
330
331 /* GETSCRIPT command. see chapter 2.9 */
332 void cmd_mgsve_getscript(void)
333 {
334 /* TODO: check auth, if not, answer with "no" */
335 /* check first param, this is the name. look up that in the folder.
336  * answer with the size {nnn+}and spill it out, one blank line and OK
337  */
338
339 }
340
341
342 /* DELETESCRIPT command. see chapter 2.10 */
343 void cmd_mgsve_deletescript(void)
344 {
345 /* TODO: check auth, if not, answer with "no" */
346
347
348 }
349
350
351
352 /*
353  *
354 void smtp_get_user(char *argbuf) {
355         char buf[SIZ];
356         char username[SIZ];
357
358         CtdlDecodeBase64(username, argbuf, SIZ);
359         / * lprintf(CTDL_DEBUG, "Trying <%s>\n", username); * /
360         if (CtdlLoginExistingUser(username) == login_ok) {
361                 CtdlEncodeBase64(buf, "Password:", 9);
362                 cprintf("334 %s\r\n", buf);
363                 SMTP->command_state = smtp_password;
364         }
365         else {
366                 cprintf("500 5.7.0 No such user.\r\n");
367                 SMTP->command_state = smtp_command;
368         }
369 }
370  */
371
372
373 /*
374  *
375 void smtp_get_pass(char *argbuf) {
376         char password[SIZ];
377
378         CtdlDecodeBase64(password, argbuf, SIZ);
379         / * lprintf(CTDL_DEBUG, "Trying <%s>\n", password); * /
380         if (CtdlTryPassword(password) == pass_ok) {
381                 smtp_auth_greeting();
382         }
383         else {
384                 cprintf("535 5.7.0 Authentication failed.\r\n");
385         }
386         SMTP->command_state = smtp_command;
387 }
388  */
389
390
391 /*
392  * Back end for PLAIN auth method (either inline or multistate)
393  */
394 void mgsve_try_plain(char *encoded_authstring) {
395         char decoded_authstring[1024];
396         char ident[256];
397         char user[256];
398         char pass[256];
399
400         CtdlDecodeBase64(decoded_authstring,
401                         encoded_authstring,
402                         strlen(encoded_authstring) );
403         safestrncpy(ident, decoded_authstring, sizeof ident);
404         safestrncpy(user, &decoded_authstring[strlen(ident) + 1], sizeof user);
405         safestrncpy(pass, &decoded_authstring[strlen(ident) + strlen(user) + 2], sizeof pass);
406
407 //      SMTP->command_state = smtp_command;
408 /*
409         if (CtdlLoginExistingUser(user) == login_ok) {
410                 if (CtdlTryPassword(pass) == pass_ok) {
411                         smtp_auth_greeting();
412                         return;
413                 }
414         }
415 */
416         cprintf("504 5.7.4 Authentication failed.\r\n");
417 }
418
419
420 /*
421  * Attempt to perform authenticated SMTP
422  */
423 void mgsve_auth(char *argbuf) {
424         char username_prompt[64];
425         char method[64];
426         char encoded_authstring[1024];
427
428         if (CC->logged_in) {
429                 cprintf("504 5.7.4 Already logged in.\r\n");
430                 return;
431         }
432
433         extract_token(method, argbuf, 0, ' ', sizeof method);
434
435         if (!strncasecmp(method, "login", 5) ) {
436                 if (strlen(argbuf) >= 7) {
437 //                      smtp_get_user(&argbuf[6]);
438                 }
439                 else {
440                         CtdlEncodeBase64(username_prompt, "Username:", 9);
441                         cprintf("334 %s\r\n", username_prompt);
442 //                      SMTP->command_state = smtp_user;
443                 }
444                 return;
445         }
446
447         if (!strncasecmp(method, "plain", 5) ) {
448                 if (num_tokens(argbuf, ' ') < 2) {
449                         cprintf("334 \r\n");
450 //                      SMTP->command_state = smtp_plain;
451                         return;
452                 }
453
454                 extract_token(encoded_authstring, argbuf, 1, ' ', sizeof encoded_authstring);
455
456 ///             smtp_try_plain(encoded_authstring);
457                 return;
458         }
459
460         if (strncasecmp(method, "login", 5) ) {
461                 cprintf("504 5.7.4 Unknown authentication method.\r\n");
462                 return;
463         }
464
465 }
466
467
468
469 /*
470  * implements the STARTTLS command (Citadel API version)
471  */
472 #ifdef HAVE_OPENSSL
473 void _smtp_starttls(void)
474 {
475         char ok_response[SIZ];
476         char nosup_response[SIZ];
477         char error_response[SIZ];
478
479         sprintf(ok_response,
480                 "200 2.0.0 Begin TLS negotiation now\r\n");
481         sprintf(nosup_response,
482                 "554 5.7.3 TLS not supported here\r\n");
483         sprintf(error_response,
484                 "554 5.7.3 Internal error\r\n");
485         CtdlStartTLS(ok_response, nosup_response, error_response);
486 ///     smtp_rset(0);
487 }
488 #endif
489
490
491 void mgsve_create_room(void)
492 {
493
494         /* Create the tasks list room if it doesn't already exist */
495         create_room(SIEVERULES, 4, "", 0, 1, 0, VIEW_SIEVE);
496 }
497
498 /* 
499  * Main command loop for manage Sieve sessions.
500  */
501 void managesieve_command_loop(void) {
502         char cmdbuf[SIZ];
503         char *parms[SIZ];
504         int length;
505         int num_parms;
506
507         time(&CC->lastcmd);
508         memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
509         length = client_getln(cmdbuf, sizeof cmdbuf);
510         if (length >= 1) {
511                 num_parms = imap_parameterize(parms, cmdbuf);
512                 ///             length = client_getln(parms[0], sizeof parms[0]);
513                 length = strlen(parms[0]);
514         }
515         if (length < 1) {
516                 lprintf(CTDL_CRIT, "Client disconnected: ending session.\n");
517                 CC->kill_me = 1;
518                 return;
519         }
520         lprintf(CTDL_INFO, "MANAGESIEVE: %s\n", cmdbuf);
521 //// we have different lengths  while (strlen(cmdbuf) < 5) strcat(cmdbuf, " ");
522         if ((length>= 12) && (!strncasecmp(parms[0], "AUTHENTICATE", 12))){
523                 cmd_mgsve_auth(num_parms, parms);
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();
533         }
534         else if ((length>= 6) && (!strncasecmp(parms[0], "CAPABILITY", 10))){
535                 cmd_mgsve_caps();
536         } /* these commands need to be authenticated. throw it out if it tries. */
537         else if (MGSVE->command_state == mgsve_password)
538         {
539                 if ((length>= 9) && (!strncasecmp(parms[0], "HAVESPACE", 9))){
540                         cmd_mgsve_havespace();
541                 }
542                 else if ((length>= 6) && (!strncasecmp(parms[0], "PUTSCRIPT", 9))){
543                         cmd_mgsve_putscript();
544                 }
545                 else if ((length>= 6) && (!strncasecmp(parms[0], "LISTSCRIPT", 10))){
546                         cmd_mgsve_listscript();
547                 }
548                 else if ((length>= 6) && (!strncasecmp(parms[0], "SETACTIVE", 9))){
549                         cmd_mgsve_setactive();
550                 }
551                 else if ((length>= 6) && (!strncasecmp(parms[0], "GETSCRIPT", 9))){
552                         cmd_mgsve_getscript();
553                 }
554                 else if ((length>= 6) && (!strncasecmp(parms[0], "DELETESCRIPT", 11))){
555                         cmd_mgsve_deletescript();
556                 }
557         }
558         else {
559                 cprintf("No\r\n");
560                 CC->kill_me = 1;
561         }
562
563
564 }
565
566
567
568
569
570
571
572
573 char *serv_managesieve_init(void)
574 {
575
576         CtdlRegisterServiceHook(config.c_managesieve_port,      /* MGSVE */
577                                 NULL,
578                                 managesieve_greeting,
579                                 managesieve_command_loop,
580                                 NULL);
581
582         CtdlRegisterSessionHook(mgsve_create_room, EVT_LOGIN);
583         return "$Id: serv_managesieve.c 4570 2006-08-27 02:07:18Z dothebart $";
584 }