Citadel API clean up.
[citadel.git] / citadel / modules / imap / imap_misc.c
1 /*
2  * $Id$
3  *
4  *
5  *
6  * Copyright (c) 2001-2009 by the citadel.org team
7  *
8  *  This program is free software; you can redistribute it and/or modify
9  *  it under the terms of the GNU General Public License as published by
10  *  the Free Software Foundation; either version 3 of the License, or
11  *  (at your option) any later version.
12  *
13  *  This program is distributed in the hope that it will be useful,
14  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *  GNU General Public License for more details.
17  *
18  *  You should have received a copy of the GNU General Public License
19  *  along with this program; if not, write to the Free Software
20  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23
24 #include "sysdep.h"
25 #include <stdlib.h>
26 #include <unistd.h>
27 #include <stdio.h>
28 #include <fcntl.h>
29 #include <signal.h>
30 #include <pwd.h>
31 #include <errno.h>
32 #include <sys/types.h>
33
34 #if TIME_WITH_SYS_TIME
35 # include <sys/time.h>
36 # include <time.h>
37 #else
38 # if HAVE_SYS_TIME_H
39 #  include <sys/time.h>
40 # else
41 #  include <time.h>
42 # endif
43 #endif
44
45 #include <sys/wait.h>
46 #include <ctype.h>
47 #include <string.h>
48 #include <limits.h>
49 #include <libcitadel.h>
50 #include "citadel.h"
51 #include "server.h"
52 #include "sysdep_decls.h"
53 #include "citserver.h"
54 #include "support.h"
55 #include "config.h"
56 #include "user_ops.h"
57 #include "policy.h"
58 #include "database.h"
59 #include "msgbase.h"
60 #include "internet_addressing.h"
61 #include "serv_imap.h"
62 #include "imap_tools.h"
63 #include "imap_fetch.h"
64 #include "imap_misc.h"
65 #include "genstamp.h"
66 #include "ctdl_module.h"
67
68
69
70
71
72 /*
73  * imap_copy() calls imap_do_copy() to do its actual work, once it's
74  * validated and boiled down the request a bit.  (returns 0 on success)
75  */
76 int imap_do_copy(char *destination_folder) {
77         int i;
78         char roomname[ROOMNAMELEN];
79         struct ctdlroom qrbuf;
80         long *selected_msgs = NULL;
81         int num_selected = 0;
82
83         if (IMAP->num_msgs < 1) {
84                 return(0);
85         }
86
87         i = imap_grabroom(roomname, destination_folder, 1);
88         if (i != 0) return(i);
89
90         /*
91          * Copy all the message pointers in one shot.
92          */
93         selected_msgs = malloc(sizeof(long) * IMAP->num_msgs);
94         if (selected_msgs == NULL) return(-1);
95
96         for (i = 0; i < IMAP->num_msgs; ++i) {
97                 if (IMAP->flags[i] & IMAP_SELECTED) {
98                         selected_msgs[num_selected++] = IMAP->msgids[i];
99                 }
100         }
101
102         if (num_selected > 0) {
103                 CtdlSaveMsgPointersInRoom(roomname, selected_msgs, num_selected, 1, NULL);
104         }
105         free(selected_msgs);
106
107         /* Don't bother wasting any more time if there were no messages. */
108         if (num_selected == 0) {
109                 return(0);
110         }
111
112         /* Enumerate lists of messages for which flags are toggled */
113         long *seen_yes = NULL;
114         int num_seen_yes = 0;
115         long *seen_no = NULL;
116         int num_seen_no = 0;
117         long *answ_yes = NULL;
118         int num_answ_yes = 0;
119         long *answ_no = NULL;
120         int num_answ_no = 0;
121
122         seen_yes = malloc(num_selected * sizeof(long));
123         seen_no = malloc(num_selected * sizeof(long));
124         answ_yes = malloc(num_selected * sizeof(long));
125         answ_no = malloc(num_selected * sizeof(long));
126
127         for (i = 0; i < IMAP->num_msgs; ++i) {
128                 if (IMAP->flags[i] & IMAP_SELECTED) {
129                         if (IMAP->flags[i] & IMAP_SEEN) {
130                                 seen_yes[num_seen_yes++] = IMAP->msgids[i];
131                         }
132                         if ((IMAP->flags[i] & IMAP_SEEN) == 0) {
133                                 seen_no[num_seen_no++] = IMAP->msgids[i];
134                         }
135                         if (IMAP->flags[i] & IMAP_ANSWERED) {
136                                 answ_yes[num_answ_yes++] = IMAP->msgids[i];
137                         }
138                         if ((IMAP->flags[i] & IMAP_ANSWERED) == 0) {
139                                 answ_no[num_answ_no++] = IMAP->msgids[i];
140                         }
141                 }
142         }
143
144         /* Set the flags... */
145         i = CtdlGetRoom(&qrbuf, roomname);
146         if (i == 0) {
147                 CtdlSetSeen(seen_yes, num_seen_yes, 1, ctdlsetseen_seen, NULL, &qrbuf);
148                 CtdlSetSeen(seen_no, num_seen_no, 0, ctdlsetseen_seen, NULL, &qrbuf);
149                 CtdlSetSeen(answ_yes, num_answ_yes, 1, ctdlsetseen_answered, NULL, &qrbuf);
150                 CtdlSetSeen(answ_no, num_answ_no, 0, ctdlsetseen_answered, NULL, &qrbuf);
151         }
152
153         free(seen_yes);
154         free(seen_no);
155         free(answ_yes);
156         free(answ_no);
157
158         return(0);
159 }
160
161
162 /*
163  * Output the [COPYUID xxx yyy] response code required by RFC2359
164  * to tell the client the UID's of the messages that were copied (if any).
165  * We are assuming that the IMAP_SELECTED flag is still set on any relevant
166  * messages in our source room.  Since the Citadel system uses UID's that
167  * are both globally unique and persistent across a room-to-room copy, we
168  * can get this done quite easily.
169  */
170 void imap_output_copyuid_response(void) {
171         int i;
172         int num_output = 0;
173   
174         for (i = 0; i < IMAP->num_msgs; ++i) {
175                 if (IMAP->flags[i] & IMAP_SELECTED) {
176                         ++num_output;
177                         if (num_output == 1) {
178                                 cprintf("[COPYUID ");
179                         }
180                         else if (num_output > 1) {
181                                 cprintf(",");
182                         }
183                         cprintf("%ld", IMAP->msgids[i]);
184                 }
185         }
186         if (num_output > 0) {
187                 cprintf("] ");
188         }
189 }
190
191
192 /*
193  * This function is called by the main command loop.
194  */
195 void imap_copy(int num_parms, char *parms[]) {
196         int ret;
197
198         if (num_parms != 4) {
199                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
200                 return;
201         }
202
203         if (imap_is_message_set(parms[2])) {
204                 imap_pick_range(parms[2], 0);
205         }
206         else {
207                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
208                 return;
209         }
210
211         ret = imap_do_copy(parms[3]);
212         if (!ret) {
213                 cprintf("%s OK ", parms[0]);
214                 imap_output_copyuid_response();
215                 cprintf("COPY completed\r\n");
216         }
217         else {
218                 cprintf("%s NO COPY failed (error %d)\r\n", parms[0], ret);
219         }
220 }
221
222 /*
223  * This function is called by the main command loop.
224  */
225 void imap_uidcopy(int num_parms, char *parms[]) {
226
227         if (num_parms != 5) {
228                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
229                 return;
230         }
231
232         if (imap_is_message_set(parms[3])) {
233                 imap_pick_range(parms[3], 1);
234         }
235         else {
236                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
237                 return;
238         }
239
240         if (imap_do_copy(parms[4]) == 0) {
241                 cprintf("%s OK ", parms[0]);
242                 imap_output_copyuid_response();
243                 cprintf("UID COPY completed\r\n");
244         }
245         else {
246                 cprintf("%s NO UID COPY failed\r\n", parms[0]);
247         }
248 }
249
250
251 /*
252  * imap_do_append_flags() is called by imap_append() to set any flags that
253  * the client specified at append time.
254  *
255  * FIXME find a way to do these in bulk so we don't max out our db journal
256  */
257 void imap_do_append_flags(long new_msgnum, char *new_message_flags) {
258         char flags[32];
259         char this_flag[sizeof flags];
260         int i;
261
262         if (new_message_flags == NULL) return;
263         if (IsEmptyStr(new_message_flags)) return;
264
265         safestrncpy(flags, new_message_flags, sizeof flags);
266
267         for (i=0; i<num_tokens(flags, ' '); ++i) {
268                 extract_token(this_flag, flags, i, ' ', sizeof this_flag);
269                 if (this_flag[0] == '\\') strcpy(this_flag, &this_flag[1]);
270                 if (!strcasecmp(this_flag, "Seen")) {
271                         CtdlSetSeen(&new_msgnum, 1, 1, ctdlsetseen_seen,
272                                 NULL, NULL);
273                 }
274                 if (!strcasecmp(this_flag, "Answered")) {
275                         CtdlSetSeen(&new_msgnum, 1, 1, ctdlsetseen_answered,
276                                 NULL, NULL);
277                 }
278         }
279 }
280
281
282 /*
283  * This function is called by the main command loop.
284  */
285 void imap_append(int num_parms, char *parms[]) {
286         long literal_length;
287         long bytes_transferred;
288         long stripped_length = 0;
289         struct CtdlMessage *msg = NULL;
290         long new_msgnum = (-1L);
291         int ret = 0;
292         char roomname[ROOMNAMELEN];
293         char buf[SIZ];
294         char savedroom[ROOMNAMELEN];
295         int msgs, new;
296         int i;
297         char new_message_flags[SIZ];
298         struct citimap *Imap;
299
300         if (num_parms < 4) {
301                 cprintf("%s BAD usage error\r\n", parms[0]);
302                 return;
303         }
304
305         if ( (parms[num_parms-1][0] != '{')
306            || (parms[num_parms-1][strlen(parms[num_parms-1])-1] != '}') )  {
307                 cprintf("%s BAD no message literal supplied\r\n", parms[0]);
308                 return;
309         }
310
311         strcpy(new_message_flags, "");
312         if (num_parms >= 5) {
313                 for (i=3; i<num_parms; ++i) {
314                         strcat(new_message_flags, parms[i]);
315                         strcat(new_message_flags, " ");
316                 }
317                 stripallbut(new_message_flags, '(', ')');
318         }
319
320         /* This is how we'd do this if it were relevant in our data store.
321          * if (num_parms >= 6) {
322          *  new_message_internaldate = parms[4];
323          * }
324          */
325
326         literal_length = atol(&parms[num_parms-1][1]);
327         if (literal_length < 1) {
328                 cprintf("%s BAD Message length must be at least 1.\r\n",
329                         parms[0]);
330                 return;
331         }
332
333         Imap = IMAP;
334         imap_free_transmitted_message();        /* just in case. */
335         Imap->transmitted_message = malloc(literal_length + 1);
336         if (Imap->transmitted_message == NULL) {
337                 cprintf("%s NO Cannot allocate memory.\r\n", parms[0]);
338                 return;
339         }
340         Imap->transmitted_length = literal_length;
341
342         cprintf("+ Transmit message now.\r\n");
343
344         bytes_transferred = 0;
345
346         ret = client_read(Imap->transmitted_message, literal_length);
347         Imap->transmitted_message[literal_length] = 0;
348
349         if (ret != 1) {
350                 cprintf("%s NO Read failed.\r\n", parms[0]);
351                 return;
352         }
353
354         /* Client will transmit a trailing CRLF after the literal (the message
355          * text) is received.  This call to client_getln() absorbs it.
356          */
357         flush_output();
358         client_getln(buf, sizeof buf);
359
360         /* Convert RFC822 newlines (CRLF) to Unix newlines (LF) */
361         CtdlLogPrintf(CTDL_DEBUG, "Converting CRLF to LF\n");
362         stripped_length = 0;
363         for (i=0; i<literal_length; ++i) {
364                 if (strncmp(&Imap->transmitted_message[i], "\r\n", 2)) {
365                         Imap->transmitted_message[stripped_length++] =
366                                 Imap->transmitted_message[i];
367                 }
368         }
369         literal_length = stripped_length;
370         Imap->transmitted_message[literal_length] = 0;  /* reterminate it */
371
372         CtdlLogPrintf(CTDL_DEBUG, "Converting message format\n");
373         msg = convert_internet_message(Imap->transmitted_message);
374         Imap->transmitted_message = NULL;
375         Imap->transmitted_length = 0;
376
377         ret = imap_grabroom(roomname, parms[2], 1);
378         if (ret != 0) {
379                 cprintf("%s NO Invalid mailbox name or access denied\r\n",
380                         parms[0]);
381                 return;
382         }
383
384         /*
385          * CtdlUserGoto() formally takes us to the desired room.  (If another
386          * folder is selected, save its name so we can return there!!!!!)
387          */
388         if (Imap->selected) {
389                 strcpy(savedroom, CC->room.QRname);
390         }
391         CtdlUserGoto(roomname, 0, 0, &msgs, &new);
392
393         /* If the user is locally authenticated, FORCE the From: header to
394          * show up as the real sender.  FIXME do we really want to do this?
395          * Probably should make it site-definable or even room-definable.
396          *
397          * For now, we allow "forgeries" if the room is one of the user's
398          * private mailboxes.
399          */
400         if (CC->logged_in) {
401            if ( ((CC->room.QRflags & QR_MAILBOX) == 0) && (config.c_imap_keep_from == 0)) {
402                 if (msg->cm_fields['A'] != NULL) free(msg->cm_fields['A']);
403                 if (msg->cm_fields['N'] != NULL) free(msg->cm_fields['N']);
404                 if (msg->cm_fields['H'] != NULL) free(msg->cm_fields['H']);
405                 msg->cm_fields['A'] = strdup(CC->user.fullname);
406                 msg->cm_fields['N'] = strdup(config.c_nodename);
407                 msg->cm_fields['H'] = strdup(config.c_humannode);
408             }
409         }
410
411         /* 
412          * Can we post here?
413          */
414         ret = CtdlDoIHavePermissionToPostInThisRoom(buf, sizeof buf, NULL, POST_LOGGED_IN);
415
416         if (ret) {
417                 /* Nope ... print an error message */
418                 cprintf("%s NO %s\r\n", parms[0], buf);
419         }
420
421         else {
422                 /* Yes ... go ahead and post! */
423                 if (msg != NULL) {
424                         new_msgnum = CtdlSubmitMsg(msg, NULL, "", 0);
425                 }
426                 if (new_msgnum >= 0L) {
427                         cprintf("%s OK [APPENDUID %ld %ld] APPEND completed\r\n",
428                                 parms[0], GLOBAL_UIDVALIDITY_VALUE, new_msgnum);
429                 }
430                 else {
431                         cprintf("%s BAD Error %ld saving message to disk.\r\n",
432                                 parms[0], new_msgnum);
433                 }
434         }
435
436         /*
437          * IMAP protocol response to client has already been sent by now.
438          *
439          * If another folder is selected, go back to that room so we can resume
440          * our happy day without violent explosions.
441          */
442         if (Imap->selected) {
443                 CtdlUserGoto(savedroom, 0, 0, &msgs, &new);
444         }
445
446         /* We don't need this buffer anymore */
447         CtdlFreeMessage(msg);
448
449         if (new_message_flags != NULL) {
450                 imap_do_append_flags(new_msgnum, new_message_flags);
451         }
452 }