2 * This module is an managesieve implementation for the Citadel system.
3 * It is compliant with all of the following:
5 * http://tools.ietf.org/html/draft-martin-managesieve-06
6 * as this draft expires with this writing, you might need to search for
9 * Copyright (c) 2007-2012 by the citadel.org team
11 * This program is open source software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License version 3.
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.
34 #include <sys/types.h>
37 #if TIME_WITH_SYS_TIME
38 # include <sys/time.h>
42 # include <sys/time.h>
52 #include <sys/socket.h>
53 #include <netinet/in.h>
54 #include <arpa/inet.h>
55 #include <libcitadel.h>
58 #include "citserver.h"
65 #include "internet_addressing.h"
68 #include "clientsocket.h"
69 #include "locate_host.h"
70 #include "citadel_dirs.h"
77 #include "ctdl_module.h"
78 #include "serv_sieve.h"
82 * http://tools.ietf.org/html/draft-martin-managesieve-06
84 * this is the draft this code tries to implement.
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;
96 enum { /** Command states for login authentication */
104 #define MGSVE ((struct citmgsve *)CC->session_specific_data)
106 int old_imap_parameterize(char** args, char *in)
113 /* Skip whitespace. */
120 /* Found the start of a token. */
124 /* Read in the token. */
134 /* Found a quoted section. */
166 /*****************************************************************************/
167 /* MANAGESIEVE Server */
168 /*****************************************************************************/
171 void sieve_outbuf_append(char *str)
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 );
179 sprintf(buf,"%s%s",MGSVE->imap_format_outstring, str);
181 memcpy(buf, str, newlen);
183 if (oldlen != 0) free (MGSVE->imap_format_outstring);
184 MGSVE->imap_format_outstring = buf;
189 * Capability listing. Printed as greeting or on "CAPABILITIES"
190 * see Section 1.8 ; 2.4
192 void cmd_mgsve_caps(void)
194 cprintf("\"IMPLEMENTATION\" \"CITADEL Sieve " PACKAGE_VERSION "\"\r\n"
195 "\"SASL\" \"PLAIN\"\r\n" /*DIGEST-MD5 GSSAPI SASL sucks.*/
197 /* if TLS is already there, should we say that again? */
200 "\"SIEVE\" \"%s\"\r\n"
201 "OK\r\n", msiv_extensions);
206 * Here's where our managesieve session begins its happy day.
208 void managesieve_greeting(void) {
210 strcpy(CC->cs_clientname, "Managesieve session");
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));
220 long GetSizeToken(char * token)
222 char *cursor = token;
225 while (!IsEmptyStr(cursor) &&
230 if (IsEmptyStr(cursor))
233 while ((*cursor != '\0') &&
239 if (cursor[-1] == '+')
242 if (IsEmptyStr(cursor))
248 char *ReadString(long size, char *command)
252 cprintf("NO %s: %ld BAD Message length must be at least 1.\r\n",
254 CC->kill_me = KILLME_READSTRING_FAILED;
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;
263 MGSVE->transmitted_length = size;
265 ret = client_read(MGSVE->transmitted_message, size);
266 MGSVE->transmitted_message[size] = '\0';
269 cprintf("%s NO Read failed.\r\n", command);
272 return MGSVE->transmitted_message;
275 /* AUTHENTICATE command; 2.1 */
276 void cmd_mgsve_auth(int num_parms, char **parms, struct sdm_userdata *u)
278 if ((num_parms == 3) && !strncasecmp(parms[1], "PLAIN", 5))
279 /* todo, check length*/
286 memset (auth, 0, SIZ);
287 if (parms[2][0] == '{')
288 message = ReadString(GetSizeToken(parms[2]), parms[0]);
290 if (message != NULL) {/**< do we have tokenized login? */
291 CtdlDecodeBase64(auth, MGSVE->transmitted_message, SIZ);
294 CtdlDecodeBase64(auth, parms[2], SIZ);
296 if ((*username == '\0') && (*(username + 1) != '\0'))
299 if (login_ok == CtdlLoginExistingUser(NULL, username))
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]);
307 if (pass_ok == CtdlTryPassword(pass, strlen(pass)))
309 MGSVE->command_state = mgsve_password;
315 cprintf("NO \"Authentication Failure.\"\r\n");/* we just support auth plain. */
316 CC->kill_me = KILLME_AUTHFAILED;
321 * STARTTLS command chapter 2.2
323 void cmd_mgsve_starttls(void)
324 { /** answer with OK, and fire off tls session. */
326 CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
333 * LOGOUT command, see chapter 2.3
335 void cmd_mgsve_logout(struct sdm_userdata *u)
338 syslog(LOG_NOTICE, "MgSve bye.");
339 CC->kill_me = KILLME_CLIENT_LOGGED_OUT;
344 * HAVESPACE command. see chapter 2.5
346 void cmd_mgsve_havespace(void)
348 /* as we don't have quotas in citadel we should always answer with OK;
349 * pherhaps we should have a max-scriptsize.
351 if (MGSVE->command_state != mgsve_password)
354 CC->kill_me = KILLME_QUOTA;
359 /* citadel doesn't have quotas. in case of change, please add code here. */
365 * PUTSCRIPT command, see chapter 2.6
367 void cmd_mgsve_putscript(int num_parms, char **parms, struct sdm_userdata *u)
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" */
378 if (parms[1][0]=='"')
379 ScriptName = &parms[1][1];
381 ScriptName = parms[1];
383 slength = strlen (ScriptName);
385 if (ScriptName[slength] == '"')
386 ScriptName[slength] = '\0';
388 Script = ReadString(GetSizeToken(parms[2]),parms[0]);
390 if (Script == NULL) return;
392 // TODO: do we spellcheck?
393 msiv_putscript(u, ScriptName, Script);
397 cprintf("%s NO Read failed.\r\n", parms[0]);
398 CC->kill_me = KILLME_READ_FAILED;
410 * LISTSCRIPT command. see chapter 2.7
412 void cmd_mgsve_listscript(int num_parms, char **parms, struct sdm_userdata *u)
415 struct sdm_script *s;
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",
423 (s->script_active)?" ACTIVE":"");
432 * \brief SETACTIVE command. see chapter 2.8
434 void cmd_mgsve_setactive(int num_parms, char **parms, struct sdm_userdata *u)
438 if (msiv_setactive(u, parms[1]) == 0) {
442 cprintf("No \"there is no script by that name %s \"\r\n", parms[1]);
445 cprintf("NO \"unexpected parameters.\"\r\n");
451 * \brief GETSCRIPT command. see chapter 2.9
453 void cmd_mgsve_getscript(int num_parms, char **parms, struct sdm_userdata *u)
456 char *script_content;
459 script_content = msiv_getscript(u, parms[1]);
460 if (script_content != NULL){
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);
469 cprintf("No \"there is no script by that name %s \"\r\n", parms[1]);
472 cprintf("NO \"unexpected parameters.\"\r\n");
477 * \brief DELETESCRIPT command. see chapter 2.10
479 void cmd_mgsve_deletescript(int num_parms, char **parms, struct sdm_userdata *u)
484 i = msiv_deletescript(u, parms[1]);
490 cprintf("NO \"no script by that name: %s\"\r\n", parms[1]);
493 cprintf("NO \"can't delete active Script: %s\"\r\n", parms[1]);
497 cprintf("NO \"unexpected parameters.\"\r\n");
504 * \brief Attempt to perform authenticated managesieve
506 void mgsve_auth(char *argbuf) {
507 char username_prompt[64];
509 char encoded_authstring[1024];
512 cprintf("NO \"Already logged in.\"\r\n");
516 extract_token(method, argbuf, 0, ' ', sizeof method);
518 if (!strncasecmp(method, "login", 5) ) {
519 if (strlen(argbuf) >= 7) {
522 CtdlEncodeBase64(username_prompt, "Username:", 9, 0);
523 cprintf("334 %s\r\n", username_prompt);
528 if (!strncasecmp(method, "plain", 5) ) {
529 if (num_tokens(argbuf, ' ') < 2) {
533 extract_token(encoded_authstring, argbuf, 1, ' ', sizeof encoded_authstring);
537 if (strncasecmp(method, "login", 5) ) {
538 cprintf("NO \"Unknown authentication method.\"\r\n");
547 * implements the STARTTLS command (Citadel API version)
549 void _mgsve_starttls(void)
551 char ok_response[SIZ];
552 char nosup_response[SIZ];
553 char error_response[SIZ];
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);
566 * Main command loop for managesieve sessions.
568 void managesieve_command_loop(void) {
573 struct sdm_userdata u;
574 int changes_made = 0;
576 memset(&u, 0, sizeof(struct sdm_userdata));
579 memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
580 length = client_getln(cmdbuf, sizeof cmdbuf);
582 num_parms = old_imap_parameterize(parms, cmdbuf);
583 if (num_parms == 0) return;
584 length = strlen(parms[0]);
587 syslog(LOG_CRIT, "managesieve: client disconnected: ending session.\n");
588 CC->kill_me = KILLME_CLIENT_DISCONNECTED;
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);
597 else if ((length>= 8) && (!strncasecmp(parms[0], "STARTTLS", 8))){
598 cmd_mgsve_starttls();
601 else if ((length>= 6) && (!strncasecmp(parms[0], "LOGOUT", 6))){
602 cmd_mgsve_logout(&u);
604 else if ((length>= 6) && (!strncasecmp(parms[0], "CAPABILITY", 10))){
607 /** these commands need to be authenticated. throw it out if it tries. */
608 else if (CC->logged_in != 0)
611 if ((length>= 9) && (!strncasecmp(parms[0], "HAVESPACE", 9))){
612 cmd_mgsve_havespace();
614 else if ((length>= 6) && (!strncasecmp(parms[0], "PUTSCRIPT", 9))){
615 cmd_mgsve_putscript(num_parms, parms, &u);
618 else if ((length>= 6) && (!strncasecmp(parms[0], "LISTSCRIPT", 10))){
619 cmd_mgsve_listscript(num_parms, parms,&u);
621 else if ((length>= 6) && (!strncasecmp(parms[0], "SETACTIVE", 9))){
622 cmd_mgsve_setactive(num_parms, parms,&u);
625 else if ((length>= 6) && (!strncasecmp(parms[0], "GETSCRIPT", 9))){
626 cmd_mgsve_getscript(num_parms, parms, &u);
628 else if ((length>= 6) && (!strncasecmp(parms[0], "DELETESCRIPT", 11))){
629 cmd_mgsve_deletescript(num_parms, parms, &u);
632 msiv_store(&u, changes_made);
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;
644 * This cleanup function blows away the temporary memory and files used by
647 void managesieve_cleanup_function(void) {
649 /* Don't do this stuff if this is not a managesieve session! */
650 if (CC->h_command_function != managesieve_command_loop) return;
652 syslog(LOG_DEBUG, "Performing managesieve cleanup hook\n");
658 const char* CitadelServiceManageSieve = "ManageSieve";
659 CTDL_MODULE_INIT(managesieve)
663 CtdlRegisterServiceHook(config.c_managesieve_port,
665 managesieve_greeting,
666 managesieve_command_loop,
668 CitadelServiceManageSieve);
669 CtdlRegisterSessionHook(managesieve_cleanup_function, EVT_STOP);
672 /* return our module name for the log */
673 return "managesieve";