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