* Replication checks and EUID indexing are now only enabled for rooms whose
[citadel.git] / citadel / imap_misc.c
1 /*
2  * $Id$
3  *
4  *
5  */
6
7
8 #include "sysdep.h"
9 #include <stdlib.h>
10 #include <unistd.h>
11 #include <stdio.h>
12 #include <fcntl.h>
13 #include <signal.h>
14 #include <pwd.h>
15 #include <errno.h>
16 #include <sys/types.h>
17
18 #if TIME_WITH_SYS_TIME
19 # include <sys/time.h>
20 # include <time.h>
21 #else
22 # if HAVE_SYS_TIME_H
23 #  include <sys/time.h>
24 # else
25 #  include <time.h>
26 # endif
27 #endif
28
29 #include <sys/wait.h>
30 #include <ctype.h>
31 #include <string.h>
32 #include <limits.h>
33 #include "citadel.h"
34 #include "server.h"
35 #include "sysdep_decls.h"
36 #include "citserver.h"
37 #include "support.h"
38 #include "config.h"
39 #include "serv_extensions.h"
40 #include "room_ops.h"
41 #include "user_ops.h"
42 #include "policy.h"
43 #include "database.h"
44 #include "msgbase.h"
45 #include "tools.h"
46 #include "internet_addressing.h"
47 #include "serv_imap.h"
48 #include "imap_tools.h"
49 #include "imap_fetch.h"
50 #include "imap_misc.h"
51 #include "genstamp.h"
52
53
54
55
56
57
58 /*
59  * imap_copy() calls imap_do_copy() to do its actual work, once it's
60  * validated and boiled down the request a bit.  (returns 0 on success)
61  */
62 int imap_do_copy(char *destination_folder) {
63         int i;
64         char roomname[ROOMNAMELEN];
65         struct ctdlroom qrbuf;
66         struct timeval tv1, tv2, tv3;
67
68         if (IMAP->num_msgs < 1) {
69                 return(0);
70         }
71
72         i = imap_grabroom(roomname, destination_folder, 0);
73         if (i != 0) return(i);
74
75         /*
76          * Optimization note ... ajc 2005oct09
77          * 
78          * As we can see below, we're going to end up making lots of
79          * repeated calls to CtdlCopyMsgToRoom() if the user selects
80          * multiple messages and then does a copy or move operation.
81          *
82          * The plan (documented in this comment so I don't forget what I was
83          * going to do) is to refactor CtdlCopyMsgToRoom() so that it accepts
84          * a list of message ID's instead of a single one.  Then we can alter
85          * the code which appears below, to copy all the message pointers in
86          * one shot.
87          * 
88          * But the REAL resource waster is further down, where we call
89          * the CtdlSetSeen() API for each message moved.  That's a HUGE
90          * performance drag.  Fix that too.
91          *
92          */
93         gettimeofday(&tv1, NULL);
94         for (i = 0; i < IMAP->num_msgs; ++i) {
95                 if (IMAP->flags[i] & IMAP_SELECTED) {
96                         CtdlCopyMsgToRoom(IMAP->msgids[i], roomname);
97                 }
98         }
99
100         /* Set the flags... */
101         gettimeofday(&tv2, NULL);
102         i = getroom(&qrbuf, roomname);
103         if (i != 0) return(i);
104
105         for (i = 0; i < IMAP->num_msgs; ++i) {
106                 if (IMAP->flags[i] & IMAP_SELECTED) {
107                         CtdlSetSeen(&IMAP->msgids[i], 1,
108                                 ((IMAP->flags[i] & IMAP_SEEN) ? 1 : 0),
109                                 ctdlsetseen_seen,
110                                 NULL, &qrbuf
111                         );
112                         CtdlSetSeen(&IMAP->msgids[i], 1,
113                                 ((IMAP->flags[i] & IMAP_ANSWERED) ? 1 : 0),
114                                 ctdlsetseen_answered,
115                                 NULL, &qrbuf
116                         );
117                 }
118         }
119
120         gettimeofday(&tv3, NULL);
121         lprintf(CTDL_DEBUG, "Copying the pointers took %ld microseconds\n",
122                 (tv2.tv_usec + (tv2.tv_sec * 1000))
123                 - (tv1.tv_usec + (tv1.tv_sec * 1000))
124         );
125         lprintf(CTDL_DEBUG, "Setting the flags took %ld microseconds\n",
126                 (tv3.tv_usec + (tv3.tv_sec * 1000))
127                 - (tv2.tv_usec + (tv2.tv_sec * 1000))
128         );
129         return(0);
130 }
131
132
133
134 /*
135  * This function is called by the main command loop.
136  */
137 void imap_copy(int num_parms, char *parms[]) {
138         int ret;
139
140         if (num_parms != 4) {
141                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
142                 return;
143         }
144
145         if (imap_is_message_set(parms[2])) {
146                 imap_pick_range(parms[2], 0);
147         }
148         else {
149                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
150                 return;
151         }
152
153         ret = imap_do_copy(parms[3]);
154         if (!ret) {
155                 cprintf("%s OK COPY completed\r\n", parms[0]);
156         }
157         else {
158                 cprintf("%s NO COPY failed (error %d)\r\n", parms[0], ret);
159         }
160 }
161
162 /*
163  * This function is called by the main command loop.
164  */
165 void imap_uidcopy(int num_parms, char *parms[]) {
166
167         if (num_parms != 5) {
168                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
169                 return;
170         }
171
172         if (imap_is_message_set(parms[3])) {
173                 imap_pick_range(parms[3], 1);
174         }
175         else {
176                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
177                 return;
178         }
179
180         if (imap_do_copy(parms[4]) == 0) {
181                 cprintf("%s OK UID COPY completed\r\n", parms[0]);
182         }
183         else {
184                 cprintf("%s NO UID COPY failed\r\n", parms[0]);
185         }
186 }
187
188
189 /*
190  * Poll for instant messages (yeah, we can do this in IMAP ... I think)
191  */
192 void imap_print_instant_messages(void) {
193         struct ExpressMessage *ptr, *holdptr;
194         char *dumpomatic = NULL;
195         char tmp[SIZ];
196         int i;
197         size_t size, size2;
198         struct tm stamp;
199
200         if (CC->FirstExpressMessage == NULL) {
201                 return;
202         }
203         begin_critical_section(S_SESSION_TABLE);
204         ptr = CC->FirstExpressMessage;
205         CC->FirstExpressMessage = NULL;
206         end_critical_section(S_SESSION_TABLE);
207
208         while (ptr != NULL) {
209                 localtime_r(&(ptr->timestamp), &stamp);
210                 size = strlen(ptr->text) + SIZ;
211                 dumpomatic = malloc(size);
212                 strcpy(dumpomatic, "");
213                 if (ptr->flags && EM_BROADCAST)
214                         strcat(dumpomatic, "Broadcast message ");
215                 else if (ptr->flags && EM_CHAT)
216                         strcat(dumpomatic, "Chat request ");
217                 else if (ptr->flags && EM_GO_AWAY)
218                         strcat(dumpomatic, "Please logoff now, as requested ");
219                 else
220                         strcat(dumpomatic, "Message ");
221
222                 /* Timestamp.  Can this be improved? */
223                 if (stamp.tm_hour == 0 || stamp.tm_hour == 12)
224                         sprintf(tmp, "at 12:%02d%cm",
225                                 stamp.tm_min, 
226                                 stamp.tm_hour ? 'p' : 'a');
227                 else if (stamp.tm_hour > 12)            /* pm */
228                         sprintf(tmp, "at %d:%02dpm",
229                                 stamp.tm_hour - 12,
230                                 stamp.tm_min);
231                 else                                    /* am */
232                         sprintf(tmp, "at %d:%02dam",
233                                 stamp.tm_hour, stamp.tm_min);
234                 strcat(dumpomatic, tmp);
235
236                 size2 = strlen(dumpomatic);
237                 snprintf(&dumpomatic[size2], size - size2,
238                         " from %s:\n", ptr->sender);
239                 if (ptr->text != NULL)
240                         strcat(dumpomatic, ptr->text);
241
242                 holdptr = ptr->next;
243                 if (ptr->text != NULL) free(ptr->text);
244                 free(ptr);
245                 ptr = holdptr;
246
247                 for (i=0; i<strlen(dumpomatic); ++i) {
248                         if (!isprint(dumpomatic[i])) dumpomatic[i] = ' ';
249                         if (dumpomatic[i]=='\\') dumpomatic[i]='/';
250                         if (dumpomatic[i]=='\"') dumpomatic[i]='\'';
251                 }
252
253                 cprintf("* OK [ALERT] %s\r\n", dumpomatic);
254                 free(dumpomatic);
255         }
256         cprintf("000\n");
257 }
258
259
260 /*
261  * imap_do_append_flags() is called by imap_append() to set any flags that
262  * the client specified at append time.
263  *
264  * FIXME find a way to do these in bulk so we don't max out our db journal
265  */
266 void imap_do_append_flags(long new_msgnum, char *new_message_flags) {
267         char flags[32];
268         char this_flag[sizeof flags];
269         int i;
270
271         if (new_message_flags == NULL) return;
272         if (strlen(new_message_flags) == 0) return;
273
274         safestrncpy(flags, new_message_flags, sizeof flags);
275
276         for (i=0; i<num_tokens(flags, ' '); ++i) {
277                 extract_token(this_flag, flags, i, ' ', sizeof this_flag);
278                 if (this_flag[0] == '\\') strcpy(this_flag, &this_flag[1]);
279                 if (!strcasecmp(this_flag, "Seen")) {
280                         CtdlSetSeen(&new_msgnum, 1, 1, ctdlsetseen_seen,
281                                 NULL, NULL);
282                 }
283                 if (!strcasecmp(this_flag, "Answered")) {
284                         CtdlSetSeen(&new_msgnum, 1, 1, ctdlsetseen_answered,
285                                 NULL, NULL);
286                 }
287         }
288 }
289
290
291 /*
292  * This function is called by the main command loop.
293  */
294 void imap_append(int num_parms, char *parms[]) {
295         long literal_length;
296         long bytes_transferred;
297         long stripped_length = 0;
298         struct CtdlMessage *msg;
299         long new_msgnum = (-1L);
300         int ret = 0;
301         char roomname[ROOMNAMELEN];
302         char buf[SIZ];
303         char savedroom[ROOMNAMELEN];
304         int msgs, new;
305         int i;
306         char new_message_flags[SIZ];
307
308         if (num_parms < 4) {
309                 cprintf("%s BAD usage error\r\n", parms[0]);
310                 return;
311         }
312
313         if ( (parms[num_parms-1][0] != '{')
314            || (parms[num_parms-1][strlen(parms[num_parms-1])-1] != '}') )  {
315                 cprintf("%s BAD no message literal supplied\r\n", parms[0]);
316                 return;
317         }
318
319         strcpy(new_message_flags, "");
320         if (num_parms >= 5) {
321                 for (i=3; i<num_parms; ++i) {
322                         strcat(new_message_flags, parms[i]);
323                         strcat(new_message_flags, " ");
324                 }
325                 stripallbut(new_message_flags, '(', ')');
326         }
327
328         /* This is how we'd do this if it were relevant in our data store.
329          * if (num_parms >= 6) {
330          *  new_message_internaldate = parms[4];
331          * }
332          */
333
334         literal_length = atol(&parms[num_parms-1][1]);
335         if (literal_length < 1) {
336                 cprintf("%s BAD Message length must be at least 1.\r\n",
337                         parms[0]);
338                 return;
339         }
340
341         imap_free_transmitted_message();        /* just in case. */
342         IMAP->transmitted_message = malloc(literal_length + 1);
343         if (IMAP->transmitted_message == NULL) {
344                 cprintf("%s NO Cannot allocate memory.\r\n", parms[0]);
345                 return;
346         }
347         IMAP->transmitted_length = literal_length;
348
349         cprintf("+ Transmit message now.\r\n");
350
351         bytes_transferred = 0;
352
353         ret = client_read(IMAP->transmitted_message, literal_length);
354         IMAP->transmitted_message[literal_length] = 0;
355
356         if (ret != 1) {
357                 cprintf("%s NO Read failed.\r\n", parms[0]);
358                 return;
359         }
360
361         /* Client will transmit a trailing CRLF after the literal (the message
362          * text) is received.  This call to client_getln() absorbs it.
363          */
364         flush_output();
365         client_getln(buf, sizeof buf);
366
367         /* Convert RFC822 newlines (CRLF) to Unix newlines (LF) */
368         lprintf(CTDL_DEBUG, "Converting CRLF to LF\n");
369         stripped_length = 0;
370         for (i=0; i<literal_length; ++i) {
371                 if (strncmp(&IMAP->transmitted_message[i], "\r\n", 2)) {
372                         IMAP->transmitted_message[stripped_length++] =
373                                 IMAP->transmitted_message[i];
374                 }
375         }
376         literal_length = stripped_length;
377         IMAP->transmitted_message[literal_length] = 0;  /* reterminate it */
378
379         lprintf(CTDL_DEBUG, "Converting message format\n");
380         msg = convert_internet_message(IMAP->transmitted_message);
381         IMAP->transmitted_message = NULL;
382         IMAP->transmitted_length = 0;
383
384         ret = imap_grabroom(roomname, parms[2], 0);
385         if (ret != 0) {
386                 cprintf("%s NO Invalid mailbox name or access denied\r\n",
387                         parms[0]);
388                 return;
389         }
390
391         /*
392          * usergoto() formally takes us to the desired room.  (If another
393          * folder is selected, save its name so we can return there!!!!!)
394          */
395         if (IMAP->selected) {
396                 strcpy(savedroom, CC->room.QRname);
397         }
398         usergoto(roomname, 0, 0, &msgs, &new);
399
400         /* If the user is locally authenticated, FORCE the From: header to
401          * show up as the real sender.  FIXME do we really want to do this?
402          * Probably should make it site-definable or even room-definable.
403          *
404          * For now, we allow "forgeries" if the room is one of the user's
405          * private mailboxes.
406          */
407         if (CC->logged_in) {
408            if ( (CC->room.QRflags & QR_MAILBOX) == 0) {
409                 if (msg->cm_fields['A'] != NULL) free(msg->cm_fields['A']);
410                 if (msg->cm_fields['N'] != NULL) free(msg->cm_fields['N']);
411                 if (msg->cm_fields['H'] != NULL) free(msg->cm_fields['H']);
412                 msg->cm_fields['A'] = strdup(CC->user.fullname);
413                 msg->cm_fields['N'] = strdup(config.c_nodename);
414                 msg->cm_fields['H'] = strdup(config.c_humannode);
415             }
416         }
417
418         /* 
419          * Can we post here?
420          */
421         ret = CtdlDoIHavePermissionToPostInThisRoom(buf, sizeof buf);
422
423         if (ret) {
424                 /* Nope ... print an error message */
425                 cprintf("%s NO %s\r\n", parms[0], buf);
426         }
427
428         else {
429                 /* Yes ... go ahead and post! */
430                 if (msg != NULL) {
431                         new_msgnum = CtdlSubmitMsg(msg, NULL, "");
432                 }
433                 if (new_msgnum >= 0L) {
434                         cprintf("%s OK APPEND completed\r\n", parms[0]);
435                 }
436                 else {
437                         cprintf("%s BAD Error %ld saving message to disk.\r\n",
438                                 parms[0], new_msgnum);
439                 }
440         }
441
442         /*
443          * IMAP protocol response to client has already been sent by now.
444          *
445          * If another folder is selected, go back to that room so we can resume
446          * our happy day without violent explosions.
447          */
448         if (IMAP->selected) {
449                 usergoto(savedroom, 0, 0, &msgs, &new);
450         }
451
452         /* We don't need this buffer anymore */
453         CtdlFreeMessage(msg);
454
455         if (new_message_flags != NULL) {
456                 imap_do_append_flags(new_msgnum, new_message_flags);
457         }
458 }