58c649c316d205b5c387808ac2783d32e56650d7
[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         long *selected_msgs = NULL;
67         int num_selected = 0;
68
69         if (IMAP->num_msgs < 1) {
70                 return(0);
71         }
72
73         i = imap_grabroom(roomname, destination_folder, 0);
74         if (i != 0) return(i);
75
76         /*
77          * Copy all the message pointers in one shot.
78          */
79         selected_msgs = malloc(sizeof(long) * IMAP->num_msgs);
80         if (selected_msgs == NULL) return(-1);
81
82         for (i = 0; i < IMAP->num_msgs; ++i) {
83                 if (IMAP->flags[i] & IMAP_SELECTED) {
84                         selected_msgs[num_selected++] = IMAP->msgids[i];
85                 }
86         }
87
88         if (num_selected > 0) {
89                 CtdlCopyMsgsToRoom(selected_msgs, num_selected, roomname);
90         }
91         free(selected_msgs);
92
93         /* Don't bother wasting any more time if there were no messages. */
94         if (num_selected == 0) {
95                 return(0);
96         }
97
98         /* Enumerate lists of messages for which flags are toggled */
99         long *seen_yes = NULL;
100         int num_seen_yes = 0;
101         long *seen_no = NULL;
102         int num_seen_no = 0;
103         long *answ_yes = NULL;
104         int num_answ_yes = 0;
105         long *answ_no = NULL;
106         int num_answ_no = 0;
107
108         seen_yes = malloc(num_selected * sizeof(long));
109         seen_no = malloc(num_selected * sizeof(long));
110         answ_yes = malloc(num_selected * sizeof(long));
111         answ_no = malloc(num_selected * sizeof(long));
112
113         for (i = 0; i < IMAP->num_msgs; ++i) {
114                 if (IMAP->flags[i] & IMAP_SELECTED) {
115                         if (IMAP->flags[i] & IMAP_SEEN) {
116                                 seen_yes[num_seen_yes++] = IMAP->msgids[i];
117                         }
118                         if ((IMAP->flags[i] & IMAP_SEEN) == 0) {
119                                 seen_no[num_seen_no++] = IMAP->msgids[i];
120                         }
121                         if (IMAP->flags[i] & IMAP_ANSWERED) {
122                                 answ_yes[num_answ_yes++] = IMAP->msgids[i];
123                         }
124                         if ((IMAP->flags[i] & IMAP_ANSWERED) == 0) {
125                                 answ_no[num_answ_no++] = IMAP->msgids[i];
126                         }
127                 }
128         }
129
130         /* Set the flags... */
131         i = getroom(&qrbuf, roomname);
132         if (i == 0) {
133                 CtdlSetSeen(seen_yes, num_seen_yes, 1, ctdlsetseen_seen, NULL, &qrbuf);
134                 CtdlSetSeen(seen_no, num_seen_no, 0, ctdlsetseen_seen, NULL, &qrbuf);
135                 CtdlSetSeen(answ_yes, num_answ_yes, 1, ctdlsetseen_answered, NULL, &qrbuf);
136                 CtdlSetSeen(answ_no, num_answ_no, 0, ctdlsetseen_answered, NULL, &qrbuf);
137         }
138
139         free(seen_yes);
140         free(seen_no);
141         free(answ_yes);
142         free(answ_no);
143
144         return(0);
145 }
146
147
148
149 /*
150  * This function is called by the main command loop.
151  */
152 void imap_copy(int num_parms, char *parms[]) {
153         int ret;
154
155         if (num_parms != 4) {
156                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
157                 return;
158         }
159
160         if (imap_is_message_set(parms[2])) {
161                 imap_pick_range(parms[2], 0);
162         }
163         else {
164                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
165                 return;
166         }
167
168         ret = imap_do_copy(parms[3]);
169         if (!ret) {
170                 cprintf("%s OK COPY completed\r\n", parms[0]);
171         }
172         else {
173                 cprintf("%s NO COPY failed (error %d)\r\n", parms[0], ret);
174         }
175 }
176
177 /*
178  * This function is called by the main command loop.
179  */
180 void imap_uidcopy(int num_parms, char *parms[]) {
181
182         if (num_parms != 5) {
183                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
184                 return;
185         }
186
187         if (imap_is_message_set(parms[3])) {
188                 imap_pick_range(parms[3], 1);
189         }
190         else {
191                 cprintf("%s BAD invalid parameters\r\n", parms[0]);
192                 return;
193         }
194
195         if (imap_do_copy(parms[4]) == 0) {
196                 cprintf("%s OK UID COPY completed\r\n", parms[0]);
197         }
198         else {
199                 cprintf("%s NO UID COPY failed\r\n", parms[0]);
200         }
201 }
202
203
204 /*
205  * Poll for instant messages (yeah, we can do this in IMAP ... I think)
206  */
207 void imap_print_instant_messages(void) {
208         struct ExpressMessage *ptr, *holdptr;
209         char *dumpomatic = NULL;
210         char tmp[SIZ];
211         int i;
212         size_t size, size2;
213         struct tm stamp;
214
215         if (CC->FirstExpressMessage == NULL) {
216                 return;
217         }
218         begin_critical_section(S_SESSION_TABLE);
219         ptr = CC->FirstExpressMessage;
220         CC->FirstExpressMessage = NULL;
221         end_critical_section(S_SESSION_TABLE);
222
223         while (ptr != NULL) {
224                 localtime_r(&(ptr->timestamp), &stamp);
225                 size = strlen(ptr->text) + SIZ;
226                 dumpomatic = malloc(size);
227                 strcpy(dumpomatic, "");
228                 if (ptr->flags && EM_BROADCAST)
229                         strcat(dumpomatic, "Broadcast message ");
230                 else if (ptr->flags && EM_CHAT)
231                         strcat(dumpomatic, "Chat request ");
232                 else if (ptr->flags && EM_GO_AWAY)
233                         strcat(dumpomatic, "Please logoff now, as requested ");
234                 else
235                         strcat(dumpomatic, "Message ");
236
237                 /* Timestamp.  Can this be improved? */
238                 if (stamp.tm_hour == 0 || stamp.tm_hour == 12)
239                         sprintf(tmp, "at 12:%02d%cm",
240                                 stamp.tm_min, 
241                                 stamp.tm_hour ? 'p' : 'a');
242                 else if (stamp.tm_hour > 12)            /* pm */
243                         sprintf(tmp, "at %d:%02dpm",
244                                 stamp.tm_hour - 12,
245                                 stamp.tm_min);
246                 else                                    /* am */
247                         sprintf(tmp, "at %d:%02dam",
248                                 stamp.tm_hour, stamp.tm_min);
249                 strcat(dumpomatic, tmp);
250
251                 size2 = strlen(dumpomatic);
252                 snprintf(&dumpomatic[size2], size - size2,
253                         " from %s:\n", ptr->sender);
254                 if (ptr->text != NULL)
255                         strcat(dumpomatic, ptr->text);
256
257                 holdptr = ptr->next;
258                 if (ptr->text != NULL) free(ptr->text);
259                 free(ptr);
260                 ptr = holdptr;
261
262                 for (i=0; i<strlen(dumpomatic); ++i) {
263                         if (!isprint(dumpomatic[i])) dumpomatic[i] = ' ';
264                         if (dumpomatic[i]=='\\') dumpomatic[i]='/';
265                         if (dumpomatic[i]=='\"') dumpomatic[i]='\'';
266                 }
267
268                 cprintf("* OK [ALERT] %s\r\n", dumpomatic);
269                 free(dumpomatic);
270         }
271         cprintf("000\n");
272 }
273
274
275 /*
276  * imap_do_append_flags() is called by imap_append() to set any flags that
277  * the client specified at append time.
278  *
279  * FIXME find a way to do these in bulk so we don't max out our db journal
280  */
281 void imap_do_append_flags(long new_msgnum, char *new_message_flags) {
282         char flags[32];
283         char this_flag[sizeof flags];
284         int i;
285
286         if (new_message_flags == NULL) return;
287         if (strlen(new_message_flags) == 0) return;
288
289         safestrncpy(flags, new_message_flags, sizeof flags);
290
291         for (i=0; i<num_tokens(flags, ' '); ++i) {
292                 extract_token(this_flag, flags, i, ' ', sizeof this_flag);
293                 if (this_flag[0] == '\\') strcpy(this_flag, &this_flag[1]);
294                 if (!strcasecmp(this_flag, "Seen")) {
295                         CtdlSetSeen(&new_msgnum, 1, 1, ctdlsetseen_seen,
296                                 NULL, NULL);
297                 }
298                 if (!strcasecmp(this_flag, "Answered")) {
299                         CtdlSetSeen(&new_msgnum, 1, 1, ctdlsetseen_answered,
300                                 NULL, NULL);
301                 }
302         }
303 }
304
305
306 /*
307  * This function is called by the main command loop.
308  */
309 void imap_append(int num_parms, char *parms[]) {
310         long literal_length;
311         long bytes_transferred;
312         long stripped_length = 0;
313         struct CtdlMessage *msg = NULL;
314         long new_msgnum = (-1L);
315         int ret = 0;
316         char roomname[ROOMNAMELEN];
317         char buf[SIZ];
318         char savedroom[ROOMNAMELEN];
319         int msgs, new;
320         int i;
321         char new_message_flags[SIZ];
322
323         if (num_parms < 4) {
324                 cprintf("%s BAD usage error\r\n", parms[0]);
325                 return;
326         }
327
328         if ( (parms[num_parms-1][0] != '{')
329            || (parms[num_parms-1][strlen(parms[num_parms-1])-1] != '}') )  {
330                 cprintf("%s BAD no message literal supplied\r\n", parms[0]);
331                 return;
332         }
333
334         strcpy(new_message_flags, "");
335         if (num_parms >= 5) {
336                 for (i=3; i<num_parms; ++i) {
337                         strcat(new_message_flags, parms[i]);
338                         strcat(new_message_flags, " ");
339                 }
340                 stripallbut(new_message_flags, '(', ')');
341         }
342
343         /* This is how we'd do this if it were relevant in our data store.
344          * if (num_parms >= 6) {
345          *  new_message_internaldate = parms[4];
346          * }
347          */
348
349         literal_length = atol(&parms[num_parms-1][1]);
350         if (literal_length < 1) {
351                 cprintf("%s BAD Message length must be at least 1.\r\n",
352                         parms[0]);
353                 return;
354         }
355
356         imap_free_transmitted_message();        /* just in case. */
357         IMAP->transmitted_message = malloc(literal_length + 1);
358         if (IMAP->transmitted_message == NULL) {
359                 cprintf("%s NO Cannot allocate memory.\r\n", parms[0]);
360                 return;
361         }
362         IMAP->transmitted_length = literal_length;
363
364         cprintf("+ Transmit message now.\r\n");
365
366         bytes_transferred = 0;
367
368         ret = client_read(IMAP->transmitted_message, literal_length);
369         IMAP->transmitted_message[literal_length] = 0;
370
371         if (ret != 1) {
372                 cprintf("%s NO Read failed.\r\n", parms[0]);
373                 return;
374         }
375
376         /* Client will transmit a trailing CRLF after the literal (the message
377          * text) is received.  This call to client_getln() absorbs it.
378          */
379         flush_output();
380         client_getln(buf, sizeof buf);
381
382         /* Convert RFC822 newlines (CRLF) to Unix newlines (LF) */
383         lprintf(CTDL_DEBUG, "Converting CRLF to LF\n");
384         stripped_length = 0;
385         for (i=0; i<literal_length; ++i) {
386                 if (strncmp(&IMAP->transmitted_message[i], "\r\n", 2)) {
387                         IMAP->transmitted_message[stripped_length++] =
388                                 IMAP->transmitted_message[i];
389                 }
390         }
391         literal_length = stripped_length;
392         IMAP->transmitted_message[literal_length] = 0;  /* reterminate it */
393
394         lprintf(CTDL_DEBUG, "Converting message format\n");
395         msg = convert_internet_message(IMAP->transmitted_message);
396         IMAP->transmitted_message = NULL;
397         IMAP->transmitted_length = 0;
398
399         ret = imap_grabroom(roomname, parms[2], 0);
400         if (ret != 0) {
401                 cprintf("%s NO Invalid mailbox name or access denied\r\n",
402                         parms[0]);
403                 return;
404         }
405
406         /*
407          * usergoto() formally takes us to the desired room.  (If another
408          * folder is selected, save its name so we can return there!!!!!)
409          */
410         if (IMAP->selected) {
411                 strcpy(savedroom, CC->room.QRname);
412         }
413         usergoto(roomname, 0, 0, &msgs, &new);
414
415         /* If the user is locally authenticated, FORCE the From: header to
416          * show up as the real sender.  FIXME do we really want to do this?
417          * Probably should make it site-definable or even room-definable.
418          *
419          * For now, we allow "forgeries" if the room is one of the user's
420          * private mailboxes.
421          */
422         if (CC->logged_in) {
423            if ( (CC->room.QRflags & QR_MAILBOX) == 0) {
424                 if (msg->cm_fields['A'] != NULL) free(msg->cm_fields['A']);
425                 if (msg->cm_fields['N'] != NULL) free(msg->cm_fields['N']);
426                 if (msg->cm_fields['H'] != NULL) free(msg->cm_fields['H']);
427                 msg->cm_fields['A'] = strdup(CC->user.fullname);
428                 msg->cm_fields['N'] = strdup(config.c_nodename);
429                 msg->cm_fields['H'] = strdup(config.c_humannode);
430             }
431         }
432
433         /* 
434          * Can we post here?
435          */
436         ret = CtdlDoIHavePermissionToPostInThisRoom(buf, sizeof buf);
437
438         if (ret) {
439                 /* Nope ... print an error message */
440                 cprintf("%s NO %s\r\n", parms[0], buf);
441         }
442
443         else {
444                 /* Yes ... go ahead and post! */
445                 if (msg != NULL) {
446                         new_msgnum = CtdlSubmitMsg(msg, NULL, "");
447                 }
448                 if (new_msgnum >= 0L) {
449                         cprintf("%s OK APPEND completed\r\n", parms[0]);
450                 }
451                 else {
452                         cprintf("%s BAD Error %ld saving message to disk.\r\n",
453                                 parms[0], new_msgnum);
454                 }
455         }
456
457         /*
458          * IMAP protocol response to client has already been sent by now.
459          *
460          * If another folder is selected, go back to that room so we can resume
461          * our happy day without violent explosions.
462          */
463         if (IMAP->selected) {
464                 usergoto(savedroom, 0, 0, &msgs, &new);
465         }
466
467         /* We don't need this buffer anymore */
468         CtdlFreeMessage(msg);
469
470         if (new_message_flags != NULL) {
471                 imap_do_append_flags(new_msgnum, new_message_flags);
472         }
473 }