1024e0657885d03a657cbcc9f6c675214c9d7d4e
[citadel.git] / webcit / messages.c
1 // Functions which deal with the fetching and displaying of messages.
2 //
3 // Copyright (c) 1996-2022 by the citadel.org team
4 //
5 // This program is open source software.  We call it open source, not
6 // free software, because Richard Stallman is a communist and an asshole.
7 // No one has done more damage to open source software than Stallman (ok,
8 // maybe Nat and Miguel have done more damage, but they were paid by
9 // Microsoft to do so).  Richard Stallman is a far-left ultra-communist
10 // who hates America, hates freedom, and deserves to be canceled.
11 //
12 // The program is licensed under the General Public License, version 3.
13 //
14 // This program is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 // GNU General Public License for more details.
18
19 #include "webcit.h"
20 #include "webserver.h"
21 #include "dav.h"
22 #include "calendar.h"
23
24 HashList *MimeRenderHandler = NULL;
25 HashList *ReadLoopHandler = NULL;
26 int dbg_analyze_msg = 0;
27
28 #define SUBJ_COL_WIDTH_PCT              50      /* Mailbox view column width */
29 #define SENDER_COL_WIDTH_PCT            30      /* Mailbox view column width */
30 #define DATE_PLUS_BUTTONS_WIDTH_PCT     20      /* Mailbox view column width */
31
32 void fixview() {
33         /* workaround for json listview; its not useable directly */
34         if (WC->CurRoom.view == VIEW_JSON_LIST) {
35                 StrBuf *View = NewStrBuf();
36                 StrBufPrintf(View, "%d", VIEW_MAILBOX);
37                 putbstr("view", View);;
38         }
39 }
40
41
42 int load_message(message_summary *Msg, StrBuf *FoundCharset, StrBuf **Error) {
43         StrBuf *Buf;
44         StrBuf *HdrToken;
45         char buf[SIZ];
46         int Done = 0;
47         int state=0;
48         int rc;
49
50         Buf = NewStrBuf();
51         if (Msg->PartNum != NULL) {
52                 serv_printf("MSG4 %ld|%s", Msg->msgnum, ChrPtr(Msg->PartNum));
53         }
54         else {
55                 serv_printf("MSG4 %ld", Msg->msgnum);
56         }
57
58         StrBuf_ServGetln(Buf);
59         if (GetServerStatus(Buf, NULL) != 1) {
60                 *Error = NewStrBuf();
61                 StrBufAppendPrintf(*Error, "<strong>");
62                 StrBufAppendPrintf(*Error, _("ERROR:"));
63                 StrBufAppendPrintf(*Error, "</strong> %s<br>\n", &buf[4]);
64                 FreeStrBuf(&Buf);
65                 return 0;
66         }
67
68         /* begin everythingamundo table */
69         HdrToken = NewStrBuf();
70         while (!Done && StrBuf_ServGetln(Buf)>=0) {
71                 if ( (StrLength(Buf)==3) && 
72                     !strcmp(ChrPtr(Buf), "000")) 
73                 {
74                         Done = 1;
75                         if (state < 2) {
76                                 if (Msg->MsgBody->Data == NULL)
77                                         Msg->MsgBody->Data = NewStrBuf();
78                                 Msg->MsgBody->ContentType = NewStrBufPlain(HKEY("text/html"));
79                                 StrBufAppendPrintf(Msg->MsgBody->Data, "<div><i>");
80                                 StrBufAppendPrintf(Msg->MsgBody->Data, _("Empty message"));
81                                 StrBufAppendPrintf(Msg->MsgBody->Data, "</i><br><br>\n");
82                                 StrBufAppendPrintf(Msg->MsgBody->Data, "</div>\n");
83                         }
84                         break;
85                 }
86                 switch (state) {
87                 case 0:/* Citadel Message Headers */
88                         if (StrLength(Buf) == 0) {
89                                 state ++;
90                                 break;
91                         }
92                         StrBufExtract_token(HdrToken, Buf, 0, '=');
93                         StrBufCutLeft(Buf, StrLength(HdrToken) + 1);
94                         
95                         /* look up one of the examine_* functions to parse the content */
96                         rc =  EvaluateMsgHdr(SKEY(HdrToken), Msg, Buf, FoundCharset);
97                         if (rc == 1) {
98                                 state++;
99                         }
100                         /* TODO: 
101                         else LogError(Target, 
102                                       __FUNCTION__,  
103                                       "don't know how to handle message header[%s]\n", 
104                                       ChrPtr(HdrToken));
105                          */
106                         break;
107                 case 1:/* Message Mime Header */
108                         if (StrLength(Buf) == 0) {
109                                 state++;
110                                 if (Msg->MsgBody->ContentType == NULL)
111                                         /* end of header or no header? */
112                                         Msg->MsgBody->ContentType = NewStrBufPlain(HKEY("text/plain"));
113                                  /* usual end of mime header */
114                         }
115                         else
116                         {
117                                 StrBufExtract_token(HdrToken, Buf, 0, ':');
118                                 if (StrLength(HdrToken) > 0) {
119                                         StrBufCutLeft(Buf, StrLength(HdrToken) + 1);
120                                         /* the examine*'s know how to do with mime headers too... */
121                                         EvaluateMsgHdr(SKEY(HdrToken), Msg, Buf, FoundCharset);
122                                         
123                                         break;
124                                 }
125                         }
126                 case 2: /* Message Body */
127                         
128                         if (Msg->MsgBody->size_known > 0) {
129                                 StrBuf_ServGetBLOBBuffered(Msg->MsgBody->Data, Msg->MsgBody->length);
130                                 state ++;
131                                 /*/ todo: check next line, if not 000, append following lines */
132                         }
133                         else if (1){
134                                 if (StrLength(Msg->MsgBody->Data) > 0)
135                                         StrBufAppendBufPlain(Msg->MsgBody->Data, "\n", 1, 0);
136                                 StrBufAppendBuf(Msg->MsgBody->Data, Buf, 0);
137                         }
138                         break;
139                 case 3:
140                         StrBufAppendBuf(Msg->MsgBody->Data, Buf, 0);
141                         break;
142                 }
143         }
144
145         if (Msg->AllAttach == NULL)
146                 Msg->AllAttach = NewHash(1,NULL);
147         /* now we put the body mimepart we read above into the mimelist */
148         Put(Msg->AllAttach, SKEY(Msg->MsgBody->PartNum), Msg->MsgBody, DestroyMime);
149         
150         FreeStrBuf(&Buf);
151         FreeStrBuf(&HdrToken);
152         return 1;
153 }
154
155
156 /*
157  * Display a message to the user
158  *
159  * msgnum               Message number to display
160  * printable_view       Nonzero to display a printable view
161  * section              Optional for encapsulated message/rfc822 submessage
162  */
163 int read_message(StrBuf *Target, const char *tmpl, long tmpllen, long msgnum, const StrBuf *PartNum, const StrBuf **OutMime, WCTemplputParams *TP) {
164         StrBuf *Buf;
165         StrBuf *FoundCharset;
166         HashPos  *it;
167         void *vMime;
168         message_summary *Msg = NULL;
169         void *vHdr;
170         long len;
171         const char *Key;
172         WCTemplputParams SuperTP;
173         WCTemplputParams SubTP;
174         StrBuf *Error = NULL;
175
176         memset(&SuperTP, 0, sizeof(WCTemplputParams));
177         memset(&SubTP, 0, sizeof(WCTemplputParams));
178
179         Buf = NewStrBuf();
180         FoundCharset = NewStrBuf();
181         Msg = (message_summary *)malloc(sizeof(message_summary));
182         if (!Msg) {
183                 syslog(LOG_DEBUG, "malloc() error");
184                 TRACE;
185         }
186         memset(Msg, 0, sizeof(message_summary));
187         Msg->msgnum = msgnum;
188         Msg->PartNum = PartNum;
189         Msg->MsgBody =  (wc_mime_attachment*) malloc(sizeof(wc_mime_attachment));
190         if (!Msg->MsgBody) {
191                 syslog(LOG_DEBUG, "malloc() error");
192                 TRACE;
193         }
194         memset(Msg->MsgBody, 0, sizeof(wc_mime_attachment));
195         Msg->MsgBody->msgnum = msgnum;
196
197         if (!load_message(Msg, FoundCharset, &Error)) {
198                 StrBufAppendBuf(Target, Error, 0);
199                 FreeStrBuf(&Error);
200         }
201
202         /* Extract just the content-type (omit attributes such as "charset") */
203         StrBufExtract_token(Buf, Msg->MsgBody->ContentType, 0, ';');
204         StrBufTrim(Buf);
205         StrBufLowerCase(Buf);
206
207         StackContext(TP, &SuperTP, Msg, CTX_MAILSUM, 0, NULL);
208         {
209                 /* Locate a renderer capable of converting this MIME part into HTML */
210                 if (GetHash(MimeRenderHandler, SKEY(Buf), &vHdr) &&
211                     (vHdr != NULL)) {
212                         RenderMimeFuncStruct *Render;
213                         
214                         StackContext(&SuperTP, &SubTP, Msg->MsgBody, CTX_MIME_ATACH, 0, NULL);
215                         {
216                                 Render = (RenderMimeFuncStruct*)vHdr;
217                                 Render->f(Target, &SubTP, FoundCharset);
218                         }
219                         UnStackContext(&SubTP);
220                 }
221                 
222                 if (StrLength(Msg->reply_references)> 0) {
223                         /* Trim down excessively long lists of thread references.  We eliminate the
224                          * second one in the list so that the thread root remains intact.
225                          */
226                         int rrtok = num_tokens(ChrPtr(Msg->reply_references), '|');
227                         int rrlen = StrLength(Msg->reply_references);
228                         if ( ((rrtok >= 3) && (rrlen > 900)) || (rrtok > 10) ) {
229                                 StrBufRemove_token(Msg->reply_references, 1, '|');
230                         }
231                 }
232
233                 /* now check if we need to translate some mimeparts, and remove the duplicate */
234                 it = GetNewHashPos(Msg->AllAttach, 0);
235                 while (GetNextHashPos(Msg->AllAttach, it, &len, &Key, &vMime) && 
236                        (vMime != NULL)) {
237                         StackContext(&SuperTP, &SubTP, vMime, CTX_MIME_ATACH, 0, NULL);
238                         {
239                                 evaluate_mime_part(Target, &SubTP);
240                         }
241                         UnStackContext(&SubTP);
242                 }
243                 DeleteHashPos(&it);
244                 *OutMime = DoTemplate(tmpl, tmpllen, Target, &SuperTP);
245         }
246         UnStackContext(&SuperTP);
247
248         DestroyMessageSummary(Msg);
249         FreeStrBuf(&FoundCharset);
250         FreeStrBuf(&Buf);
251         return 1;
252 }
253
254
255 long HttpStatus(long CitadelStatus) {
256         long httpstatus = 502;
257         
258         switch (MAJORCODE(CitadelStatus))
259         {
260         case LISTING_FOLLOWS:
261         case CIT_OK:
262                 httpstatus = 201;
263                 break;
264         case ERROR:
265                 switch (MINORCODE(CitadelStatus))
266                 {
267                 case INTERNAL_ERROR:
268                         httpstatus = 403;
269                         break;
270                         
271                 case TOO_BIG:
272                 case ILLEGAL_VALUE:
273                 case HIGHER_ACCESS_REQUIRED:
274                 case MAX_SESSIONS_EXCEEDED:
275                 case RESOURCE_BUSY:
276                 case RESOURCE_NOT_OPEN:
277                 case NOT_HERE:
278                 case INVALID_FLOOR_OPERATION:
279                 case FILE_NOT_FOUND:
280                 case ROOM_NOT_FOUND:
281                         httpstatus = 409;
282                         break;
283
284                 case MESSAGE_NOT_FOUND:
285                 case ALREADY_EXISTS:
286                         httpstatus = 403;
287                         break;
288
289                 case NO_SUCH_SYSTEM:
290                         httpstatus = 502;
291                         break;
292
293                 default:
294                 case CMD_NOT_SUPPORTED:
295                 case PASSWORD_REQUIRED:
296                 case ALREADY_LOGGED_IN:
297                 case USERNAME_REQUIRED:
298                 case NOT_LOGGED_IN:
299                 case SERVER_SHUTTING_DOWN:
300                 case NO_SUCH_USER:
301                 case ASYNC_GEXP:
302                         httpstatus = 502;
303                         break;
304                 }
305                 break;
306
307         default:
308         case BINARY_FOLLOWS:
309         case SEND_BINARY:
310         case START_CHAT_MODE:
311         case ASYNC_MSG:
312         case MORE_DATA:
313         case SEND_LISTING:
314                 httpstatus = 502; /* aeh... whut? */
315                 break;
316         }
317
318         return httpstatus;
319 }
320
321
322 /*
323  * Unadorned HTML output of an individual message, suitable
324  * for placing in a hidden iframe, for printing, or whatever
325  */
326 void handle_one_message(void) {
327         long CitStatus = ERROR + NOT_HERE;
328         int CopyMessage = 0;
329         const StrBuf *Destination;
330         void *vLine;
331         const StrBuf *Mime;
332         long msgnum = 0L;
333         const StrBuf *Tmpl;
334         StrBuf *CmdBuf = NULL;
335         const char *pMsg;
336
337         pMsg = strchr(ChrPtr(WC->Hdr->HR.ReqLine), '/');
338         if (pMsg == NULL) {
339                 HttpStatus(CitStatus);
340                 return;
341         }
342
343         msgnum = atol(pMsg + 1);
344         StrBufCutAt(WC->Hdr->HR.ReqLine, 0, pMsg);
345         gotoroom(WC->Hdr->HR.ReqLine);
346         switch (WC->Hdr->HR.eReqType)
347         {
348         case eGET:
349         case ePOST:
350                 Tmpl = sbstr("template");
351                 if (StrLength(Tmpl) > 0) 
352                         read_message(WC->WBuf, SKEY(Tmpl), msgnum, NULL, &Mime, NULL);
353                 else 
354                         read_message(WC->WBuf, HKEY("view_message"), msgnum, NULL, &Mime, NULL);
355                 http_transmit_thing(ChrPtr(Mime), 0);
356                 break;
357         case eDELETE:
358                 CmdBuf = NewStrBuf ();
359                 if ((WC->CurRoom.RAFlags & UA_ISTRASH) != 0) {  /* Delete from Trash is a real delete */
360                         serv_printf("DELE %ld", msgnum);        
361                 }
362                 else {                  /* Otherwise move it to Trash */
363                         serv_printf("MOVE %ld|_TRASH_|0", msgnum);
364                 }
365                 StrBuf_ServGetln(CmdBuf);
366                 GetServerStatusMsg(CmdBuf, &CitStatus, 1, 0);
367                 HttpStatus(CitStatus);
368                 break;
369         case eCOPY:
370                 CopyMessage = 1;
371         case eMOVE:
372                 if (GetHash(WC->Hdr->HTTPHeaders, HKEY("DESTINATION"), &vLine) &&
373                     (vLine!=NULL)) {
374                         Destination = (StrBuf*) vLine;
375                         serv_printf("MOVE %ld|%s|%d", msgnum, ChrPtr(Destination), CopyMessage);
376                         StrBuf_ServGetln(CmdBuf);
377                         GetServerStatusMsg(CmdBuf, NULL, 1, 0);
378                         GetServerStatus(CmdBuf, &CitStatus);
379                         HttpStatus(CitStatus);
380                 }
381                 else
382                         HttpStatus(500);
383                 break;
384         default:
385                 break;
386
387         }
388 }
389
390
391 /*
392  * Unadorned HTML output of an individual message, suitable
393  * for placing in a hidden iframe, for printing, or whatever
394  */
395 void embed_message(void) {
396         const StrBuf *Mime;
397         long msgnum = 0L;
398         const StrBuf *Tmpl;
399         StrBuf *CmdBuf = NULL;
400
401         msgnum = StrBufExtract_long(WC->Hdr->HR.ReqLine, 0, '/');
402         if (msgnum <= 0) return;
403
404         switch (WC->Hdr->HR.eReqType)
405         {
406         case eGET:
407         case ePOST:
408                 Tmpl = sbstr("template");
409                 if (StrLength(Tmpl) > 0) 
410                         read_message(WC->WBuf, SKEY(Tmpl), msgnum, NULL, &Mime, NULL);
411                 else 
412                         read_message(WC->WBuf, HKEY("view_message"), msgnum, NULL, &Mime, NULL);
413                 http_transmit_thing(ChrPtr(Mime), 0);
414                 break;
415         case eDELETE:
416                 CmdBuf = NewStrBuf ();
417                 if ((WC->CurRoom.RAFlags & UA_ISTRASH) != 0) {  /* Delete from Trash is a real delete */
418                         serv_printf("DELE %ld", msgnum);        
419                 }
420                 else {                  /* Otherwise move it to Trash */
421                         serv_printf("MOVE %ld|_TRASH_|0", msgnum);
422                 }
423                 StrBuf_ServGetln(CmdBuf);
424                 GetServerStatusMsg(CmdBuf, NULL, 1, 0);
425                 break;
426         default:
427                 break;
428
429         }
430 }
431
432
433 /*
434  * Printable view of a message
435  */
436 void print_message(void) {
437         long msgnum = 0L;
438         const StrBuf *Mime;
439
440         msgnum = StrBufExtract_long(WC->Hdr->HR.ReqLine, 0, '/');
441         output_headers(0, 0, 0, 0, 0, 0);
442
443         hprintf("Content-type: text/html\r\n"
444                 "Server: " PACKAGE_STRING "\r\n"
445                 "Connection: close\r\n");
446
447         begin_burst();
448
449         read_message(WC->WBuf, HKEY("view_message_print"), msgnum, NULL, &Mime, NULL);
450
451         wDumpContent(0);
452 }
453
454
455 /*
456  * Display a message's headers
457  */
458 void display_headers(void) {
459         long msgnum = 0L;
460         char buf[1024];
461
462         msgnum = StrBufExtract_long(WC->Hdr->HR.ReqLine, 0, '/');
463         output_headers(0, 0, 0, 0, 0, 0);
464
465         hprintf("Content-type: text/plain\r\n"
466                 "Server: %s\r\n"
467                 "Connection: close\r\n",
468                 PACKAGE_STRING);
469         begin_burst();
470
471         serv_printf("MSG2 %ld|1", msgnum);
472         serv_getln(buf, sizeof buf);
473         if (buf[0] == '1') {
474                 while (serv_getln(buf, sizeof buf), strcmp(buf, "000")) {
475                         wc_printf("%s\n", buf);
476                 }
477         }
478
479         wDumpContent(0);
480 }
481
482
483 /*
484  * load message pointers from the server for a "read messages" operation
485  *
486  * servcmd:             the citadel command to send to the citserver
487  */
488 int load_msg_ptrs(const char *servcmd,
489                   const char *filter,
490                   StrBuf *FoundCharset,
491                   SharedMessageStatus *Stat, 
492                   void **ViewSpecific,
493                   load_msg_ptrs_detailheaders LH,
494                   StrBuf *FetchMessageList,
495                   eMessageField *MessageFieldList,
496                   long HeaderCount)
497 {
498         message_summary *Msg;
499         StrBuf *Buf, *Buf2;
500         long len;
501         int n;
502         int skipit;
503         const char *Ptr = NULL;
504         int StatMajor;
505
506         Stat->lowest_found = LONG_MAX;
507         Stat->highest_found = LONG_MIN;
508
509         if (WC->summ != NULL) {
510                 DeleteHash(&WC->summ);
511         }
512         WC->summ = NewHash(1, Flathash);
513         
514         Buf = NewStrBuf();
515         serv_puts(servcmd);
516         StrBuf_ServGetln(Buf);
517         StatMajor = GetServerStatus(Buf, NULL);
518         switch (StatMajor) {
519         case 1:
520                 break;
521         case 8:
522                 if (filter != NULL) {
523                         serv_puts(filter);
524                         serv_puts("000");
525                         break;
526                 }
527                 else if (FetchMessageList != NULL) {
528                         serv_putbuf(FetchMessageList);
529                         break;
530                 }
531                 /* fall back to empty filter in case of we were fooled... */
532                 serv_puts("");
533                 serv_puts("000");
534                 break;
535         default:
536                 FreeStrBuf(&Buf);
537                 return (Stat->nummsgs);
538         }
539         Buf2 = NewStrBuf();
540         while (len = StrBuf_ServGetln(Buf), ((len >= 0) && ((len != 3) || strcmp(ChrPtr(Buf), "000")!= 0))) {
541                 if (Stat->nummsgs < Stat->maxload) {
542                         skipit = 0;
543                         Ptr = NULL;
544                         Msg = (message_summary*)malloc(sizeof(message_summary));
545                         if (!Msg) {
546                                 syslog(LOG_DEBUG, "malloc() error");
547                                 TRACE;
548                         }
549                         memset(Msg, 0, sizeof(message_summary));
550
551                         Msg->msgnum = StrBufExtractNext_long(Buf, &Ptr, '|');
552                         Msg->date = StrBufExtractNext_long(Buf, &Ptr, '|');
553                         if (MessageFieldList != NULL) {
554                                 long i;
555                                 for (i = 0; i < HeaderCount; i++) {
556                                         StrBufExtract_NextToken(Buf2, Buf, &Ptr, '|');
557                                         if (StrLength(Buf2) > 0) {
558                                                 EvaluateMsgHdrEnum(MessageFieldList[i], Msg, Buf2, FoundCharset);
559                                         }
560                                 }
561                         }
562                         else {
563                                 if (Stat->nummsgs == 0) {
564                                         if (Msg->msgnum < Stat->lowest_found) {
565                                                 Stat->lowest_found = Msg->msgnum;
566                                         }
567                                         if (Msg->msgnum > Stat->highest_found) {
568                                                 Stat->highest_found = Msg->msgnum;
569                                         }
570                                 }
571
572                                 if ((Msg->msgnum == 0) && (StrLength(Buf) < 32)) {
573                                         free(Msg);
574                                         continue;
575                                 }
576                         }
577                         /* 
578                          * as citserver probably gives us messages in forward date sorting
579                          * nummsgs should be the same order as the message date.
580                          */
581                         if (Msg->date == 0) {
582                                 Msg->date = Stat->nummsgs;
583                                 if (StrLength(Buf) < 32) 
584                                         skipit = 1;
585                         }
586                         if ((!skipit) && (LH != NULL)) {
587                                 if (!LH(Buf, &Ptr, Msg, Buf2, ViewSpecific)){
588                                         free(Msg);
589                                         continue;
590                                 }                                       
591                         }
592                         n = Msg->msgnum;
593                         Put(WC->summ, (const char *)&n, sizeof(n), Msg, DestroyMessageSummary);
594                 }
595                 Stat->nummsgs++;
596         }
597         FreeStrBuf(&Buf2);
598         FreeStrBuf(&Buf);
599         return (Stat->nummsgs);
600 }
601
602
603 /*
604  * sets FlagToSet for each of ScanMe that appears in MatchMSet
605  * ScanMe:       List of BasicMsgStruct to be searched it MatchSet
606  * MatchMSet:    MSet we want to flag
607  * FlagToSet:    Flag to set on each BasicMsgStruct->Flags if in MSet
608  */
609 long SetFlagsFromMSet(HashList *ScanMe, MSet *MatchMSet, int FlagToSet, int Reverse) {
610         const char *HashKey;
611         long HKLen;
612         long count = 0;
613         HashPos *at;
614         void *vMsg;
615         message_summary *Msg;
616
617         at = GetNewHashPos(ScanMe, 0);
618         while (GetNextHashPos(ScanMe, at, &HKLen, &HashKey, &vMsg)) {
619                 /* Are you a new message, or an old message? */
620                 Msg = (message_summary*) vMsg;
621                 if (Reverse && IsInMSetList(MatchMSet, Msg->msgnum)) {
622                         Msg->Flags = Msg->Flags | FlagToSet;
623                         count++;
624                 }
625                 else if (!Reverse && !IsInMSetList(MatchMSet, Msg->msgnum)) {
626                         Msg->Flags = Msg->Flags | FlagToSet;
627                         count++;
628                 }
629         }
630         DeleteHashPos(&at);
631         return count;
632 }
633
634
635 long load_seen_flags(void) {
636         long count = 0;
637         StrBuf *OldMsg;
638         MSet *MatchMSet;
639
640         OldMsg = NewStrBuf();
641         serv_puts("GTSN");
642         StrBuf_ServGetln(OldMsg);
643         if (GetServerStatus(OldMsg, NULL) == 2) {
644                 StrBufCutLeft(OldMsg, 4);
645         }
646         else {
647                 FreeStrBuf(&OldMsg);
648                 return 0;
649         }
650
651         if (ParseMSet(&MatchMSet, OldMsg))
652         {
653                 count = SetFlagsFromMSet(WC->summ, MatchMSet, MSGFLAG_READ, 0);
654         }
655         DeleteMSet(&MatchMSet);
656         FreeStrBuf(&OldMsg);
657         return count;
658 }
659
660 extern readloop_struct rlid[];
661
662 typedef struct _RoomRenderer{
663         int RoomType;
664
665         GetParamsGetServerCall_func GetParamsGetServerCall;
666         
667         PrintViewHeader_func PrintPageHeader;
668         PrintViewHeader_func PrintViewHeader;
669         LoadMsgFromServer_func LoadMsgFromServer;
670         RenderView_or_Tail_func RenderView_or_Tail;
671         View_Cleanup_func ViewCleanup;
672         load_msg_ptrs_detailheaders LHParse;
673         long HeaderCount;
674         StrBuf *FetchMessageList;
675         eMessageField *MessageFieldList;
676 } RoomRenderer;
677
678
679 /*
680  * command loop for reading messages
681  *
682  * Set oper to "readnew" or "readold" or "readfwd" or "headers" or "readgt" or "readlt" or "do_search"
683  */
684 void readloop(long oper, eCustomRoomRenderer ForceRenderer) {
685         RoomRenderer *ViewMsg;
686         void *vViewMsg;
687         void *vMsg;
688         message_summary *Msg;
689         char cmd[256] = "";
690         char filter[256] = "";
691         int i, r;
692         HashPos *at;
693         const char *HashKey;
694         long HKLen;
695         WCTemplputParams SubTP;
696         SharedMessageStatus Stat;
697         void *ViewSpecific = NULL;
698
699         if (havebstr("is_summary") && (1 == (ibstr("is_summary")))) {
700                 WC->CurRoom.view = VIEW_MAILBOX;
701         }
702
703         if (havebstr("view")) {
704                 WC->CurRoom.view = ibstr("view");
705         }
706
707         memset(&Stat, 0, sizeof(SharedMessageStatus));
708         Stat.maxload = 10000;
709         Stat.lowest_found = (-1);
710         Stat.highest_found = (-1);
711         if (ForceRenderer == eUseDefault)
712                 GetHash(ReadLoopHandler, IKEY(WC->CurRoom.view), &vViewMsg);
713         else 
714                 GetHash(ReadLoopHandler, IKEY(ForceRenderer), &vViewMsg);
715         if (vViewMsg == NULL) {
716                 WC->CurRoom.view = VIEW_BBS;
717                 GetHash(ReadLoopHandler, IKEY(WC->CurRoom.view), &vViewMsg);
718         }
719         if (vViewMsg == NULL) {
720                 return;                 /* TODO: print message */
721         }
722
723         ViewMsg = (RoomRenderer*) vViewMsg;
724         if (ViewMsg->PrintPageHeader == NULL)
725                 output_headers(1, 1, 1, 0, 0, 0);
726         else 
727                 ViewMsg->PrintPageHeader(&Stat, ViewSpecific);
728
729         if (ViewMsg->GetParamsGetServerCall != NULL) {
730                 r = ViewMsg->GetParamsGetServerCall(
731                        &Stat,
732                        &ViewSpecific,
733                        oper,
734                        cmd, sizeof(cmd),
735                        filter, sizeof(filter)
736                 );
737         } else {
738                 r = 0;
739         }
740
741         switch(r)
742         {
743         case 400:
744         case 404:
745
746                 return;
747         case 300: /* the callback hook should do the work for us here, since he knows what to do. */
748                 return;
749         case 200:
750         default:
751                 break;
752         }
753         if (!IsEmptyStr(cmd)) {
754                 const char *p = NULL;
755                 StrBuf *FoundCharset = NULL;
756                 if (!IsEmptyStr(filter))
757                         p = filter;
758                 if (ViewMsg->HeaderCount > 0) {
759                         FoundCharset = NewStrBuf();
760                 }
761                 Stat.nummsgs = load_msg_ptrs(cmd, p,
762                                              FoundCharset,
763                                              &Stat,
764                                              &ViewSpecific,
765                                              ViewMsg->LHParse,
766                                              ViewMsg->FetchMessageList,
767                                              ViewMsg->MessageFieldList,
768                                              ViewMsg->HeaderCount);
769                 FreeStrBuf(&FoundCharset);
770         }
771
772         if (Stat.sortit) {
773                 CompareFunc SortIt;
774                 StackContext(NULL, &SubTP, NULL, CTX_MAILSUM, 0, NULL);
775                 {
776                         SortIt =  RetrieveSort(&SubTP,
777                                                NULL, 0,
778                                                HKEY("date"),
779                                                Stat.defaultsortorder);
780                 }
781                 UnStackContext(&SubTP);
782                 if (SortIt != NULL)
783                         SortByPayload(WC->summ, SortIt);
784         }
785         if (Stat.startmsg < 0) {
786                 Stat.startmsg =  0;
787         }
788
789         if (Stat.load_seen) Stat.numNewmsgs = load_seen_flags();
790         
791         /*
792          * Print any inforation above the message list...
793          */
794         if (ViewMsg->PrintViewHeader != NULL)
795                 ViewMsg->PrintViewHeader(&Stat, &ViewSpecific);
796
797         WC->startmsg =  Stat.startmsg;
798         WC->maxmsgs = Stat.maxmsgs;
799         WC->num_displayed = 0;
800
801         /* Put some helpful data in vars for mailsummary_json */
802         {
803                 StrBuf *Foo;
804                 
805                 Foo = NewStrBuf ();
806                 StrBufPrintf(Foo, "%ld", Stat.nummsgs);
807                 PutBstr(HKEY("__READLOOP:TOTALMSGS"), NewStrBufDup(Foo)); /* keep Foo! */
808
809                 StrBufPrintf(Foo, "%ld", Stat.numNewmsgs);
810                 PutBstr(HKEY("__READLOOP:NEWMSGS"), NewStrBufDup(Foo)); /* keep Foo! */
811
812                 StrBufPrintf(Foo, "%ld", Stat.startmsg);
813                 PutBstr(HKEY("__READLOOP:STARTMSG"), Foo); /* store Foo elsewhere, descope it here. */
814         }
815
816         /*
817          * iterate over each message. if we need to load an attachment, do it here. 
818          */
819
820         if ((ViewMsg->LoadMsgFromServer != NULL) && (!IsEmptyStr(cmd))) {
821                 at = GetNewHashPos(WC->summ, 0);
822                 Stat.num_displayed = i = 0;
823                 while ( GetNextHashPos(WC->summ, at, &HKLen, &HashKey, &vMsg)) {
824                         Msg = (message_summary*) vMsg;          
825                         if ((Msg->msgnum >= Stat.startmsg) && (Stat.num_displayed <= Stat.maxmsgs)) {
826                                 ViewMsg->LoadMsgFromServer(&Stat, 
827                                                            &ViewSpecific, 
828                                                            Msg, 
829                                                            (Msg->Flags & MSGFLAG_READ) != 0, 
830                                                            i);
831                         } 
832                         i++;
833                 }
834                 DeleteHashPos(&at);
835         }
836
837         /*
838          * Done iterating the message list. now tasks we want to do after.
839          */
840         if (ViewMsg->RenderView_or_Tail != NULL)
841                 ViewMsg->RenderView_or_Tail(&Stat, &ViewSpecific, oper);
842
843         if (ViewMsg->ViewCleanup != NULL)
844                 ViewMsg->ViewCleanup(&ViewSpecific);
845
846         WC->startmsg = 0;
847         WC->maxmsgs = 0;
848         if (WC->summ != NULL) {
849                 DeleteHash(&WC->summ);
850         }
851 }
852
853
854 /*
855  * Back end for post_message()
856  * ... this is where the actual message gets transmitted to the server.
857  */
858 void post_mime_to_server(void) {
859         char top_boundary[SIZ];
860         char alt_boundary[SIZ];
861         int is_multipart = 0;
862         static int seq = 0;
863         wc_mime_attachment *att;
864         char *encoded;
865         size_t encoded_length;
866         size_t encoded_strlen;
867         char *txtmail = NULL;
868         int include_text_alt = 0;       /* Set to nonzero to include multipart/alternative text/plain */
869
870         sprintf(top_boundary, "Citadel--Multipart--%s--%04x--%04x",
871                 ChrPtr(WC->serv_info->serv_fqdn),
872                 getpid(),
873                 ++seq
874         );
875         sprintf(alt_boundary, "Citadel--Multipart--%s--%04x--%04x",
876                 ChrPtr(WC->serv_info->serv_fqdn),
877                 getpid(),
878                 ++seq
879         );
880
881         /* RFC2045 requires this, and some clients look for it... */
882         serv_puts("MIME-Version: 1.0");
883         serv_puts("X-Mailer: " PACKAGE_STRING);
884
885         /* If there are attachments, we have to do multipart/mixed */
886         syslog(LOG_DEBUG, "This message will have %d attachments", GetCount(WC->attachments));
887         if (GetCount(WC->attachments) > 0) {
888                 is_multipart = 1;
889         }
890
891         /* Only do multipart/alternative for mailboxes.  BBS and Wiki rooms don't need it. */
892         if ((WC->CurRoom.view == VIEW_MAILBOX) || (WC->CurRoom.view == VIEW_JSON_LIST)) {
893                 include_text_alt = 1;
894         }
895
896         if (is_multipart) {
897                 /* Remember, serv_printf() appends an extra newline */
898                 serv_printf("Content-type: multipart/mixed; boundary=\"%s\"\n", top_boundary);
899                 serv_printf("This is a multipart message in MIME format.\n");
900                 serv_printf("--%s", top_boundary);
901         }
902
903         /* Remember, serv_printf() appends an extra newline */
904         if (include_text_alt) {
905                 StrBuf *Buf;
906                 serv_printf("Content-type: multipart/alternative; "
907                         "boundary=\"%s\"\n", alt_boundary);
908                 serv_printf("This is a multipart message in MIME format.\n");
909                 serv_printf("--%s", alt_boundary);
910
911                 serv_puts("Content-type: text/plain; charset=utf-8");
912                 serv_puts("Content-Transfer-Encoding: quoted-printable");
913                 serv_puts("");
914                 txtmail = html_to_ascii(bstr("msgtext"), 0, 80);
915                 Buf = NewStrBufPlain(txtmail, -1);
916                 free(txtmail);
917
918                 text_to_server_qp(Buf);     /* Transmit message in quoted-printable encoding */
919                 FreeStrBuf(&Buf);
920                 serv_printf("\n--%s", alt_boundary);
921         }
922
923         serv_puts("Content-type: text/html; charset=utf-8");
924         serv_puts("Content-Transfer-Encoding: quoted-printable");
925         serv_puts("");
926         serv_puts("<html><body>\r\n");
927         text_to_server_qp(sbstr("msgtext"));    /* Transmit message in quoted-printable encoding */
928         serv_puts("</body></html>\r\n");
929
930         if (include_text_alt) {
931                 serv_printf("--%s--", alt_boundary);
932         }
933         
934         if (is_multipart) {
935                 long len;
936                 const char *Key; 
937                 void *vAtt;
938                 HashPos  *it;
939
940                 /* Add in the attachments */
941                 it = GetNewHashPos(WC->attachments, 0);
942                 while (GetNextHashPos(WC->attachments, it, &len, &Key, &vAtt)) {
943                         att = (wc_mime_attachment *)vAtt;
944                         if (att->length == 0)
945                                 continue;
946
947                         encoded_length = att->length + (att->length / 2);       // make it 150% of the original size for encoding
948                         encoded = malloc(encoded_length);
949                         if (!encoded) {
950                                 syslog(LOG_ERR, "malloc() error");
951                                 break;
952                         }
953                         syslog(LOG_DEBUG, "Attachment: raw len %d", StrLength(att->Data));
954                         encoded_strlen = CtdlEncodeBase64(encoded, ChrPtr(att->Data), StrLength(att->Data), 1);
955                         syslog(LOG_DEBUG, "Attachment: encoded len %d", encoded_strlen);
956
957                         serv_printf("--%s", top_boundary);
958                         serv_printf("Content-type: %s", ChrPtr(att->ContentType));
959                         serv_printf("Content-disposition: attachment; filename=\"%s\"", ChrPtr(att->FileName));
960                         serv_puts("Content-transfer-encoding: base64");
961                         serv_puts("");
962                         serv_write(encoded, encoded_strlen);
963                         serv_puts("");
964                         serv_puts("");
965                         free(encoded);
966                 }
967                 serv_printf("--%s--", top_boundary);
968                 DeleteHashPos(&it);
969         }
970
971         serv_puts("000");
972 }
973
974
975 /*
976  * Post message (or don't post message)
977  *
978  * Note regarding the "dont_post" variable:
979  * A random value (actually, it's just a timestamp) is inserted as a hidden
980  * field called "postseq" when the display_enter page is generated.  This
981  * value is checked when posting, using the static variable dont_post.  If a
982  * user attempts to post twice using the same dont_post value, the message is
983  * discarded.  This prevents the accidental double-saving of the same message
984  * if the user happens to click the browser "back" button.
985  */
986 void post_message(void) {
987         StrBuf *UserName;
988         StrBuf *EmailAddress;
989         StrBuf *EncBuf;
990         char buf[1024];
991         StrBuf *encoded_subject = NULL;
992         static long dont_post = (-1L);
993         int is_anonymous = 0;
994         const StrBuf *display_name = NULL;
995         StrBuf *Buf;
996         
997         if (havebstr("force_room")) {
998                 gotoroom(sbstr("force_room"));
999         }
1000
1001         if (havebstr("display_name")) {
1002                 display_name = sbstr("display_name");
1003                 if (!strcmp(ChrPtr(display_name), "__ANONYMOUS__")) {
1004                         display_name = NULL;
1005                         is_anonymous = 1;
1006                 }
1007         }
1008
1009         if (!strcasecmp(bstr("submit_action"), "cancel")) {
1010                 AppendImportantMessage(_("Cancelled.  Message was not posted."), -1);
1011         } else if (lbstr("postseq") == dont_post) {
1012                 AppendImportantMessage(
1013                         _("Automatically cancelled because you have already "
1014                           "saved this message."), -1);
1015         } else {
1016                 const char CMD[] = "ENT0 1|%s|%d|4|%s|%s||%s|%s|%s|%s|%s";
1017                 StrBuf *Recp = NULL; 
1018                 StrBuf *Cc = NULL;
1019                 StrBuf *Bcc = NULL;
1020                 StrBuf *wikipage = NULL;
1021                 const StrBuf *my_email_addr = NULL;
1022                 StrBuf *CmdBuf = NULL;
1023                 StrBuf *references = NULL;
1024                 int saving_to_drafts = 0;
1025                 long HeaderLen = 0;
1026
1027                 saving_to_drafts = !strcasecmp(bstr("submit_action"), "draft");
1028                 Buf = NewStrBuf();
1029
1030                 if (saving_to_drafts) {
1031                         /* temporarily change to the drafts room */
1032                         serv_puts("GOTO _DRAFTS_");
1033                         StrBuf_ServGetln(Buf);
1034                         if (GetServerStatusMsg(Buf, NULL, 1, 2) != 2) {
1035                                 /* You probably don't even have a dumb Drafts folder */
1036                                 syslog(LOG_DEBUG, "%s:%d: server save to drafts error: %s\n", __FILE__, __LINE__, ChrPtr(Buf) + 4);
1037                                 AppendImportantMessage(_("Saved to Drafts failed: "), -1);
1038                                 display_enter();
1039                                 FreeStrBuf(&Buf);
1040                                 return;
1041                         }
1042                 }
1043
1044                 if (havebstr("references"))
1045                 {
1046                         const StrBuf *ref = sbstr("references");
1047                         references = NewStrBufDup(ref);
1048                         if (*ChrPtr(references) == '|') {       /* remove leading '|' if present */
1049                                 StrBufCutLeft(references, 1);
1050                         }
1051                         StrBufReplaceChars(references, '|', '!');
1052                 }
1053                 if (havebstr("subject")) {
1054                         const StrBuf *Subj;
1055                         /*
1056                          * make enough room for the encoded string; 
1057                          * plus the QP header 
1058                          */
1059                         Subj = sbstr("subject");
1060                         
1061                         StrBufRFC2047encode(&encoded_subject, Subj);
1062                 }
1063                 UserName = NewStrBuf();
1064                 EmailAddress = NewStrBuf();
1065                 EncBuf = NewStrBuf();
1066
1067                 Recp = StrBufSanitizeEmailRecipientVector(sbstr("recp"), UserName, EmailAddress, EncBuf);
1068                 Cc = StrBufSanitizeEmailRecipientVector(sbstr("cc"), UserName, EmailAddress, EncBuf);
1069                 Bcc = StrBufSanitizeEmailRecipientVector(sbstr("bcc"), UserName, EmailAddress, EncBuf);
1070
1071                 FreeStrBuf(&UserName);
1072                 FreeStrBuf(&EmailAddress);
1073                 FreeStrBuf(&EncBuf);
1074
1075                 wikipage = NewStrBufDup(sbstr("page"));
1076                 str_wiki_index(wikipage);
1077                 my_email_addr = sbstr("my_email_addr");
1078                 
1079                 HeaderLen = StrLength(Recp) + 
1080                         StrLength(encoded_subject) +
1081                         StrLength(Cc) +
1082                         StrLength(Bcc) + 
1083                         StrLength(wikipage) +
1084                         StrLength(my_email_addr) + 
1085                         StrLength(references);
1086                 CmdBuf = NewStrBufPlain(NULL, sizeof (CMD) + HeaderLen);
1087                 StrBufPrintf(CmdBuf, 
1088                              CMD,
1089                              saving_to_drafts?"":ChrPtr(Recp),
1090                              is_anonymous,
1091                              ChrPtr(encoded_subject),
1092                              ChrPtr(display_name),
1093                              saving_to_drafts?"":ChrPtr(Cc),
1094                              saving_to_drafts?"":ChrPtr(Bcc),
1095                              ChrPtr(wikipage),
1096                              ChrPtr(my_email_addr),
1097                              ChrPtr(references));
1098                 FreeStrBuf(&references);
1099                 FreeStrBuf(&encoded_subject);
1100                 free(wikipage);
1101
1102                 if ((HeaderLen + StrLength(sbstr("msgtext")) < 10) && 
1103                     (GetCount(WC->attachments) == 0)){
1104                         AppendImportantMessage(_("Refusing to post empty message.\n"), -1);
1105                         FreeStrBuf(&CmdBuf);
1106                                 
1107                 }
1108                 else 
1109                 {
1110                         syslog(LOG_DEBUG, "%s\n", ChrPtr(CmdBuf));
1111                         serv_puts(ChrPtr(CmdBuf));
1112                         FreeStrBuf(&CmdBuf);
1113
1114                         StrBuf_ServGetln(Buf);
1115                         if (GetServerStatus(Buf, NULL) == 4) {
1116                                 if (saving_to_drafts) {
1117                                         if (  (havebstr("recp"))
1118                                               || (havebstr("cc"  ))
1119                                               || (havebstr("bcc" )) ) {
1120                                                 /* save recipient headers or room to post to */
1121                                                 serv_printf("To: %s", ChrPtr(Recp));
1122                                                 serv_printf("Cc: %s", ChrPtr(Cc));
1123                                                 serv_printf("Bcc: %s", ChrPtr(Bcc));
1124                                         } else {
1125                                                 serv_printf("X-Citadel-Room: %s", ChrPtr(WC->CurRoom.name));
1126                                         }
1127                                 }
1128                                 post_mime_to_server();
1129                                 if (saving_to_drafts) {
1130                                         AppendImportantMessage(_("Message has been saved to Drafts.\n"), -1);
1131                                         gotoroom(WC->CurRoom.name);
1132                                         fixview();
1133                                         readloop(readnew, eUseDefault);
1134                                         FreeStrBuf(&Buf);
1135                                         return;
1136                                 } else if (  (havebstr("recp"))
1137                                              || (havebstr("cc"  ))
1138                                              || (havebstr("bcc" ))
1139                                         ) {
1140                                         AppendImportantMessage(_("Message has been sent.\n"), -1);
1141                                 }
1142                                 else {
1143                                         AppendImportantMessage(_("Message has been posted.\n"), -1);
1144                                 }
1145                                 dont_post = lbstr("postseq");
1146                         } else {
1147                                 syslog(LOG_DEBUG, "%s:%d: server post error: %s", __FILE__, __LINE__, ChrPtr(Buf) + 4);
1148                                 AppendImportantMessage(ChrPtr(Buf) + 4, StrLength(Buf) - 4);
1149                                 display_enter();
1150                                 if (saving_to_drafts) gotoroom(WC->CurRoom.name);
1151                                 FreeStrBuf(&Recp);
1152                                 FreeStrBuf(&Buf);
1153                                 FreeStrBuf(&Cc);
1154                                 FreeStrBuf(&Bcc);
1155                                 return;
1156                         }
1157                 }
1158                 FreeStrBuf(&Recp);
1159                 FreeStrBuf(&Buf);
1160                 FreeStrBuf(&Cc);
1161                 FreeStrBuf(&Bcc);
1162         }
1163
1164         DeleteHash(&WC->attachments);
1165
1166         /*
1167          *  We may have been supplied with instructions regarding the location
1168          *  to which we must return after posting.  If found, go there.
1169          */
1170         if (havebstr("return_to")) {
1171                 http_redirect(bstr("return_to"));
1172         }
1173         /*
1174          *  If we were editing a page in a wiki room, go to that page now.
1175          */
1176         else if (havebstr("page")) {
1177                 snprintf(buf, sizeof buf, "wiki?page=%s", bstr("page"));
1178                 http_redirect(buf);
1179         }
1180         /*
1181          *  Otherwise, just go to the "read messages" loop.
1182          */
1183         else {
1184                 fixview();
1185                 readloop(readnew, eUseDefault);
1186         }
1187 }
1188
1189
1190 /*
1191  * Client is uploading an attachment
1192  */
1193 void upload_attachment(void) {
1194         const char *pch;
1195         int n;
1196         const char *newn;
1197         long newnlen;
1198         void *v;
1199         wc_mime_attachment *att;
1200         const StrBuf *Tmpl = sbstr("template");
1201         const StrBuf *MimeType = NULL;
1202         const StrBuf *UID;
1203
1204         begin_burst();
1205         syslog(LOG_DEBUG, "upload_attachment()");
1206         if (!Tmpl) {
1207                 wc_printf("upload_attachment()<br>\n");
1208         }
1209
1210         if (WC->upload_length <= 0) {
1211                 syslog(LOG_DEBUG, "ERROR no attachment was uploaded\n");
1212                 if (Tmpl) {
1213                         putlbstr("UPLOAD_ERROR", 1);
1214                         MimeType = DoTemplate(SKEY(Tmpl), NULL, &NoCtx);
1215                 }
1216                 else {
1217                         wc_printf("ERROR no attachment was uploaded<br>\n");
1218                 }
1219                 http_transmit_thing(ChrPtr(MimeType), 0);
1220
1221                 return;
1222         }
1223
1224         syslog(LOG_DEBUG, "Client has uploaded %d bytes", WC->upload_length);
1225         if (Tmpl) {
1226                 putlbstr("UPLOAD_LENGTH", WC->upload_length);
1227         }
1228         else {
1229                 wc_printf("Client is uploading %d bytes<br>\n", WC->upload_length);
1230         }
1231
1232         att = (wc_mime_attachment*)malloc(sizeof(wc_mime_attachment));
1233         if (!att) {
1234                 syslog(LOG_DEBUG, "malloc() error");
1235                 TRACE;
1236         }
1237         memset(att, 0, sizeof(wc_mime_attachment ));
1238         att->length = WC->upload_length;
1239         att->ContentType = NewStrBufPlain(WC->upload_content_type, -1);
1240         att->FileName = NewStrBufDup(WC->upload_filename);
1241         UID = sbstr("qquuid");
1242         if (UID) {
1243                 att->PartNum = NewStrBufDup(UID);
1244         }
1245
1246         syslog(LOG_DEBUG, "attachment length: %d", att->length);
1247         syslog(LOG_DEBUG, "att. content type: %s", ChrPtr(att->ContentType));
1248         syslog(LOG_DEBUG, "att upload buffer: %s", ((WC->upload == NULL) ? "null" : "not null"));
1249
1250
1251         if (WC->attachments == NULL) {
1252                 WC->attachments = NewHash(1, Flathash);
1253         }
1254
1255         /* And add it to the list. */
1256         n = 0;
1257         if ((GetCount(WC->attachments) > 0) && GetHashAt(WC->attachments, GetCount(WC->attachments) -1, &newnlen, &newn, &v)) {
1258                 n = *((int*) newn) + 1;
1259         }
1260         Put(WC->attachments, IKEY(n), att, DestroyMime);
1261
1262         /*
1263          * Mozilla sends a simple filename, which is what we want,
1264          * but Satan's Browser sends an entire pathname.  Reduce
1265          * the path to just a filename if we need to.
1266          */
1267         pch = strrchr(ChrPtr(att->FileName), '/');
1268         if (pch != NULL) {
1269                 StrBufCutLeft(att->FileName, pch - ChrPtr(att->FileName) + 1);
1270         }
1271         pch = strrchr(ChrPtr(att->FileName), '\\');
1272         if (pch != NULL) {
1273                 StrBufCutLeft(att->FileName, pch - ChrPtr(att->FileName) + 1);
1274         }
1275
1276         /*
1277          * Transfer control of this memory from the upload struct
1278          * to the attachment struct.
1279          */
1280         att->Data = WC->upload;
1281         WC->upload = NULL;
1282         WC->upload_length = 0;
1283         
1284         if (Tmpl) MimeType = DoTemplate(SKEY(Tmpl), NULL, &NoCtx);
1285         http_transmit_thing(ChrPtr(MimeType), 0);
1286 }
1287
1288
1289 /*
1290  * Remove an attachment from the message currently being composed.
1291  *
1292  * Currently we identify the attachment to be removed by its filename.
1293  * There is probably a better way to do this.
1294  */
1295 void remove_attachment(void) {
1296         wc_mime_attachment *att;
1297         void *vAtt;
1298         StrBuf *WhichAttachment;
1299         HashPos *at;
1300         long len;
1301         int found=0;
1302         const char *key;
1303
1304         WhichAttachment = NewStrBufDup(sbstr("which_attachment"));
1305         if (ChrPtr(WhichAttachment)[0] == '/')
1306                 StrBufCutLeft(WhichAttachment, 1);
1307         StrBufUnescape(WhichAttachment, 0);
1308         at = GetNewHashPos(WC->attachments, 0);
1309         do {
1310                 vAtt = NULL;
1311                 GetHashPos(WC->attachments, at, &len, &key, &vAtt);
1312
1313                 att = (wc_mime_attachment*) vAtt;
1314                 if ((att != NULL) &&
1315                     (
1316                             !strcmp(ChrPtr(WhichAttachment), ChrPtr(att->FileName)) ||
1317                     ((att->PartNum != NULL) &&
1318                      !strcmp(ChrPtr(WhichAttachment), ChrPtr(att->PartNum)))
1319                             ))
1320                 {
1321                         DeleteEntryFromHash(WC->attachments, at);
1322                         found=1;
1323                         break;
1324                 }
1325         }
1326         while (NextHashPos(WC->attachments, at));
1327
1328         FreeStrBuf(&WhichAttachment);
1329         wc_printf("remove_attachment(%d) completed\n", found);
1330 }
1331
1332
1333 const char *ReplyToModeStrings [3] = {
1334         "reply",
1335         "replyall",
1336         "forward"
1337 };
1338 typedef enum _eReplyToNodes {
1339         eReply,
1340         eReplyAll,
1341         eForward
1342 }eReplyToNodes;
1343
1344
1345 /*
1346  * display the message entry screen
1347  */
1348 void display_enter(void) {
1349         const char *ReplyingModeStr;
1350         eReplyToNodes ReplyMode = eReply;
1351         StrBuf *Line;
1352         long Result;
1353         int rc;
1354         const StrBuf *display_name = NULL;
1355         int recipient_required = 0;
1356         int subject_required = 0;
1357         int is_anonymous = 0;
1358         int i = 0;
1359         long replying_to;
1360
1361         if (havebstr("force_room")) {
1362                 gotoroom(sbstr("force_room"));
1363         }
1364
1365         display_name = sbstr("display_name");
1366         if (!strcmp(ChrPtr(display_name), "__ANONYMOUS__")) {
1367                 display_name = NULL;
1368                 is_anonymous = 1;
1369         }
1370
1371         /*
1372          * First, do we have permission to enter messages in this room at all?
1373          */
1374         Line = NewStrBuf();
1375         serv_puts("ENT0 0");
1376         StrBuf_ServGetln(Line);
1377         rc = GetServerStatusMsg(Line, &Result, 0, 2);
1378
1379         if (Result == 570) {            /* 570 means that we need a recipient here */
1380                 recipient_required = 1;
1381         }
1382         else if (rc != 2) {             /* Any other error means that we cannot continue */
1383                 rc = GetServerStatusMsg(Line, &Result, 0, 2);
1384                 fixview();
1385                 readloop(readnew, eUseDefault);
1386                 FreeStrBuf(&Line);
1387                 return;
1388         }
1389
1390         /* Is the server strongly recommending that the user enter a message subject? */
1391         if (StrLength(Line) > 4) {
1392                 subject_required = extract_int(ChrPtr(Line) + 4, 1);
1393         }
1394
1395         /*
1396          * Are we perhaps in an address book view?  If so, then an "enter
1397          * message" command really means "add new entry."
1398          */
1399         if (WC->CurRoom.defview == VIEW_ADDRESSBOOK) {
1400                 do_edit_vcard(-1, "", NULL, NULL, "",  ChrPtr(WC->CurRoom.name));
1401                 FreeStrBuf(&Line);
1402                 return;
1403         }
1404
1405         /*
1406          * Are we perhaps in a calendar room?  If so, then an "enter message" command really means "add new calendar item."
1407          */
1408         if (WC->CurRoom.defview == VIEW_CALENDAR) {
1409                 display_edit_event();
1410                 FreeStrBuf(&Line);
1411                 return;
1412         }
1413
1414         /*
1415          * Are we perhaps in a tasks view?  If so, then an "enter
1416          * message" command really means "add new task."
1417          */
1418         if (WC->CurRoom.defview == VIEW_TASKS) {
1419                 display_edit_task();
1420                 FreeStrBuf(&Line);
1421                 return;
1422         }
1423
1424         ReplyingModeStr = bstr("replying_mode");
1425         if (ReplyingModeStr != NULL) {
1426                 for (i = 0; i < 3; i++) {
1427                         if (strcmp(ReplyingModeStr, ReplyToModeStrings[i]) == 0) {
1428                                 ReplyMode = (eReplyToNodes) i;
1429                                 break;
1430                         }
1431                 }
1432         }
1433
1434         /*
1435          * If the "replying_to" variable is set, it refers to a message
1436          * number from which we must extract some header fields...
1437          */
1438         replying_to = lbstr("replying_to");
1439         if (replying_to > 0) {
1440                 long len;
1441                 StrBuf *wefw = NULL;
1442                 StrBuf *msgn = NULL;
1443                 StrBuf *from = NULL;
1444                 StrBuf *rfca = NULL;
1445                 StrBuf *rcpt = NULL;
1446                 StrBuf *cccc = NULL;
1447                 StrBuf *replyto = NULL;
1448                 StrBuf *nvto = NULL;
1449                 int message_originated_locally = 0;
1450                 serv_printf("MSG0 %ld|1", replying_to); 
1451
1452                 StrBuf_ServGetln(Line);
1453                 if (GetServerStatusMsg(Line, NULL, 0, 0) == 1)
1454                         while (len = StrBuf_ServGetln(Line), (len >= 0) && ((len != 3) || strcmp(ChrPtr(Line), "000"))) {
1455                                 eMessageField which;
1456                                 if ((StrLength(Line) > 4) && (ChrPtr(Line)[4] == '=') && GetFieldFromMnemonic(&which, ChrPtr(Line))) switch (which) {
1457                                         case eMsgSubject: {
1458                                                 StrBuf *subj = NewStrBuf();
1459                                                 StrBuf *FlatSubject;
1460
1461                                                 if (ReplyMode == eForward) {
1462                                                         if (strncasecmp(ChrPtr(Line) + 5, "Fw:", 3)) {
1463                                                                 StrBufAppendBufPlain(subj, HKEY("Fw: "), 0);
1464                                                         }
1465                                                 }
1466                                                 else {
1467                                                         if (strncasecmp(ChrPtr(Line) + 5, "Re:", 3)) {
1468                                                                 StrBufAppendBufPlain(subj, HKEY("Re: "), 0);
1469                                                         }
1470                                                 }
1471                                                 StrBufAppendBufPlain(subj, 
1472                                                                      ChrPtr(Line) + 5, 
1473                                                                      StrLength(Line) - 5, 0);
1474                                                 FlatSubject = NewStrBufPlain(NULL, StrLength(subj));
1475                                                 StrBuf_RFC822_to_Utf8(FlatSubject, subj, NULL, NULL);
1476
1477                                                 PutBstr(HKEY("subject"), FlatSubject);
1478                                         }
1479                                                 break;
1480
1481                                         case eIsLocal: {
1482                                                 message_originated_locally = 1;
1483                                                 break;
1484                                         }
1485
1486                                         case eWeferences:
1487                                         {
1488                                                 int rrtok;
1489                                                 int rrlen;
1490
1491                                                 wefw = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1492                                         
1493                                                 /* Trim down excessively long lists of thread references.  We eliminate the
1494                                                  * second one in the list so that the thread root remains intact.
1495                                                  */
1496                                                 rrtok = num_tokens(ChrPtr(wefw), '|');
1497                                                 rrlen = StrLength(wefw);
1498                                                 if ( ((rrtok >= 3) && (rrlen > 900)) || (rrtok > 10) ) {
1499                                                         StrBufRemove_token(wefw, 1, '|');
1500                                                 }
1501                                                 break;
1502                                         }
1503
1504                                         case emessageId:
1505                                                 msgn = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1506                                                 break;
1507
1508                                         case eAuthor: {
1509                                                 StrBuf *FlatFrom;
1510                                                 from = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1511                                                 FlatFrom = NewStrBufPlain(NULL, StrLength(from));
1512                                                 StrBuf_RFC822_to_Utf8(FlatFrom, from, NULL, NULL);
1513                                                 FreeStrBuf(&from);
1514                                                 from = FlatFrom;
1515                                                 for (i=0; i<StrLength(from); ++i) {
1516                                                         if (ChrPtr(from)[i] == ',')
1517                                                                 StrBufPeek(from, NULL, i, ' ');
1518                                                 }
1519                                                 break;
1520                                         }
1521                                         case eRecipient:
1522                                                 rcpt = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1523                                                 break;
1524                                         case eCarbonCopY:
1525                                                 cccc = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1526                                                 break;
1527                                         case eReplyTo:
1528                                                 replyto = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1529                                                 break;
1530                                         case erFc822Addr: {
1531                                                 StrBuf *FlatRFCA;
1532                                                 rfca = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1533                                                 FlatRFCA = NewStrBufPlain(NULL, StrLength(rfca));
1534                                                 StrBuf_RFC822_to_Utf8(FlatRFCA, rfca, NULL, NULL);
1535                                                 FreeStrBuf(&rfca);
1536                                                 rfca = FlatRFCA;
1537                                                 break;
1538                                         }
1539                                         case eenVelopeTo:
1540                                                 nvto = NewStrBufPlain(ChrPtr(Line) + 5, StrLength(Line) - 5);
1541                                                 putbstr("nvto", nvto);
1542                                                 break;
1543                                         case eXclusivID:
1544                                         case eJournal:
1545                                         case eListID:
1546                                         case eMesageText:
1547                                         case eMessagePath:
1548                                         case eSpecialField:
1549                                         case eTimestamp:
1550                                         case eHeaderOnly:
1551                                         case eFormatType:
1552                                         case eMessagePart:
1553                                         case eSubFolder:
1554                                         case eLastHeader:
1555                                                 break;
1556
1557                                         }
1558                         }
1559
1560
1561                 if (StrLength(wefw) + StrLength(msgn) > 0) {
1562                         StrBuf *refs = NewStrBuf();
1563                         if (StrLength(wefw) > 0) {
1564                                 StrBufAppendBuf(refs, wefw, 0);
1565                         }
1566                         if ( (StrLength(wefw) > 0) && 
1567                              (StrLength(msgn) > 0) ) 
1568                         {
1569                                 StrBufAppendBufPlain(refs, HKEY("|"), 0);
1570                         }
1571                         if (StrLength(msgn) > 0) {
1572                                 StrBufAppendBuf(refs, msgn, 0);
1573                         }
1574                         PutBstr(HKEY("references"), refs);
1575                 }
1576
1577                 /*
1578                  * If this is a Reply or a ReplyAll, copy the sender's email into the To: field
1579                  */
1580                 if ((ReplyMode == eReply) || (ReplyMode == eReplyAll)) {
1581                         StrBuf *to_rcpt;
1582
1583                         if ((StrLength(replyto) > 0) && (ReplyMode == eReplyAll)) {
1584                                 to_rcpt = NewStrBuf();
1585                                 StrBufAppendBuf(to_rcpt, replyto, 0);
1586                         }
1587
1588                         else if ( (StrLength(rfca) > 0) && (message_originated_locally == 0) ) {
1589                                 to_rcpt = NewStrBuf();
1590                                 StrBufAppendBuf(to_rcpt, from, 0);
1591                                 StrBufAppendBufPlain(to_rcpt, HKEY(" <"), 0);
1592                                 StrBufAppendBuf(to_rcpt, rfca, 0);
1593                                 StrBufAppendBufPlain(to_rcpt, HKEY(">"), 0);
1594                         }
1595
1596                         else {
1597                                 to_rcpt =  from;
1598                                 from = NULL;
1599                         }
1600                         PutBstr(HKEY("recp"), to_rcpt);
1601                 }
1602
1603                 /*
1604                  * Only if this is a ReplyAll, copy all recipients into the Cc: field
1605                  */
1606                 if (ReplyMode == eReplyAll) {
1607                         StrBuf *cc_rcpt = rcpt;
1608                         rcpt = NULL;
1609                         if ((StrLength(cccc) > 0) && (StrLength(replyto) == 0)) {
1610                                 if (cc_rcpt != NULL)  {
1611                                         StrBufAppendPrintf(cc_rcpt, ", ");
1612                                         StrBufAppendBuf(cc_rcpt, cccc, 0);
1613                                 }
1614                                 else {
1615                                         cc_rcpt = cccc;
1616                                         cccc = NULL;
1617                                 }
1618                         }
1619                         if (cc_rcpt != NULL) {
1620                                 PutBstr(HKEY("cc"), cc_rcpt);
1621                         }
1622                 }
1623
1624                 // We might not need these logs anymore.
1625                 syslog(LOG_DEBUG, "wefw = %s", ChrPtr(wefw));
1626                 syslog(LOG_DEBUG, "msgn = %s", ChrPtr(msgn));
1627                 syslog(LOG_DEBUG, "from = %s", ChrPtr(from));
1628                 syslog(LOG_DEBUG, "rfca = %s", ChrPtr(rfca));
1629                 syslog(LOG_DEBUG, "rcpt = %s", ChrPtr(rcpt));
1630                 syslog(LOG_DEBUG, "cccc = %s", ChrPtr(cccc));
1631                 syslog(LOG_DEBUG, "replyto = %s", ChrPtr(replyto));
1632                 syslog(LOG_DEBUG, "nvto = %s", ChrPtr(nvto));
1633                 syslog(LOG_DEBUG, "local = %d" , message_originated_locally);
1634
1635                 FreeStrBuf(&wefw);
1636                 FreeStrBuf(&msgn);
1637                 FreeStrBuf(&from);
1638                 FreeStrBuf(&rfca);
1639                 FreeStrBuf(&rcpt);
1640                 FreeStrBuf(&cccc);
1641         }
1642         FreeStrBuf(&Line);
1643
1644         /*
1645          * Otherwise proceed normally.
1646          * Do a custom room banner with no navbar...
1647          */
1648         if (recipient_required) {
1649                 const StrBuf *Recp = NULL; 
1650                 const StrBuf *Cc = NULL;
1651                 const StrBuf *Bcc = NULL;
1652                 StrBuf *wikipage = NULL;
1653                 StrBuf *CmdBuf = NULL;
1654                 const char CMD[] = "ENT0 0|%s|%d|0||%s||%s|%s|%s";
1655                 
1656                 Recp = sbstr("recp");
1657                 Cc = sbstr("cc");
1658                 Bcc = sbstr("bcc");
1659                 wikipage = NewStrBufDup(sbstr("page"));
1660                 str_wiki_index(wikipage);
1661                 
1662                 CmdBuf = NewStrBufPlain(NULL, 
1663                                         sizeof (CMD) + 
1664                                         StrLength(Recp) + 
1665                                         StrLength(display_name) +
1666                                         StrLength(Cc) +
1667                                         StrLength(Bcc) + 
1668                                         StrLength(wikipage));
1669
1670                 StrBufPrintf(CmdBuf, 
1671                              CMD,
1672                              ChrPtr(Recp), 
1673                              is_anonymous,
1674                              ChrPtr(display_name),
1675                              ChrPtr(Cc), 
1676                              ChrPtr(Bcc), 
1677                              ChrPtr(wikipage)
1678                 );
1679                 serv_puts(ChrPtr(CmdBuf));
1680                 StrBuf_ServGetln(CmdBuf);
1681                 free(wikipage);
1682
1683                 rc = GetServerStatusMsg(CmdBuf, &Result, 0, 0);
1684
1685                 if (    (Result == 570)         /* invalid or missing recipient(s) */
1686                         || (Result == 550)      /* higher access required to send Internet mail */
1687                 ) {
1688                         /* These errors will have been displayed and are excusable */
1689                 }
1690                 else if (rc != 2) {     /* Any other error means that we cannot continue */
1691                         AppendImportantMessage(ChrPtr(CmdBuf) + 4, StrLength(CmdBuf) - 4);
1692                         FreeStrBuf(&CmdBuf);
1693                         fixview();
1694                         readloop(readnew, eUseDefault);
1695                         return;
1696                 }
1697                 FreeStrBuf(&CmdBuf);
1698         }
1699         if (recipient_required)
1700                 PutBstr(HKEY("__RCPTREQUIRED"), NewStrBufPlain(HKEY("1")));
1701         if (recipient_required || subject_required)
1702                 PutBstr(HKEY("__SUBJREQUIRED"), NewStrBufPlain(HKEY("1")));
1703
1704         begin_burst();
1705         output_headers(1, 0, 0, 0, 1, 0);
1706         DoTemplate(HKEY("edit_message"), NULL, &NoCtx);
1707         end_burst();
1708
1709         return;
1710 }
1711
1712
1713 /*
1714  * delete a message
1715  */
1716 void delete_msg(void) {
1717         long msgid;
1718         StrBuf *Line;
1719         
1720         msgid = lbstr("msgid");
1721         Line = NewStrBuf();
1722         if ((WC->CurRoom.RAFlags & UA_ISTRASH) != 0) {  /* Delete from Trash is a real delete */
1723                 serv_printf("DELE %ld", msgid); 
1724         }
1725         else {                  /* Otherwise move it to Trash */
1726                 serv_printf("MOVE %ld|_TRASH_|0", msgid);
1727         }
1728
1729         StrBuf_ServGetln(Line);
1730         GetServerStatusMsg(Line, NULL, 1, 0);
1731
1732         fixview();
1733
1734         readloop(readnew, eUseDefault);
1735 }
1736
1737
1738 /*
1739  * move a message to another room
1740  */
1741 void move_msg(void) {
1742         long msgid;
1743
1744         msgid = lbstr("msgid");
1745
1746         if (havebstr("move_button")) {
1747                 StrBuf *Line;
1748                 serv_printf("MOVE %ld|%s", msgid, bstr("target_room"));
1749                 Line = NewStrBuf();
1750                 StrBuf_ServGetln(Line);
1751                 GetServerStatusMsg(Line, NULL, 1, 0);
1752                 FreeStrBuf(&Line);
1753         } else {
1754                 AppendImportantMessage(_("The message was not moved."), -1);
1755         }
1756
1757         fixview();
1758         readloop(readnew, eUseDefault);
1759 }
1760
1761
1762 /*
1763  * Generic function to output an arbitrary MIME attachment from
1764  * message being composed
1765  *
1766  * partnum              The MIME part to be output
1767  * filename             Fake filename to give
1768  * force_download       Nonzero to force set the Content-Type: header to "application/octet-stream"
1769  */
1770 void postpart(StrBuf *partnum, StrBuf *filename, int force_download) {
1771         void *vPart;
1772         StrBuf *content_type;
1773         wc_mime_attachment *part;
1774         int i;
1775
1776         i = StrToi(partnum);
1777         if (GetHash(WC->attachments, IKEY(i), &vPart) &&
1778             (vPart != NULL)) {
1779                 part = (wc_mime_attachment*) vPart;
1780                 if (force_download) {
1781                         content_type = NewStrBufPlain(HKEY("application/octet-stream"));
1782                 }
1783                 else {
1784                         content_type = NewStrBufDup(part->ContentType);
1785                 }
1786                 StrBufAppendBuf(WC->WBuf, part->Data, 0);
1787                 http_transmit_thing(ChrPtr(content_type), 0);
1788         } else {
1789                 hprintf("HTTP/1.1 404 %s\n", ChrPtr(partnum));
1790                 output_headers(0, 0, 0, 0, 0, 0);
1791                 hprintf("Content-Type: text/plain\r\n");
1792                 begin_burst();
1793                 wc_printf(_("An error occurred while retrieving this part: %s/%s\n"), 
1794                         ChrPtr(partnum), ChrPtr(filename));
1795                 end_burst();
1796         }
1797         FreeStrBuf(&content_type);
1798 }
1799
1800
1801 /*
1802  * Generic function to output an arbitrary MIME part from an arbitrary
1803  * message number on the server.
1804  *
1805  * msgnum               message number on the citadel server
1806  * partnum              MIME part number to be output
1807  * force_download       Nonzero to force set the Content-Type: header to "application/octet-stream"
1808  */
1809 void view_or_download_mimepart(int force_download) {
1810         long msgnum;
1811         off_t bytes;
1812         StrBuf *Buf;
1813         StrBuf *ContentType;
1814         StrBuf *PartNum;
1815
1816         PartNum = NewStrBuf();
1817
1818         msgnum = StrBufExtract_long(WC->Hdr->HR.ReqLine, 0, '/');
1819         StrBufExtract_token(PartNum, WC->Hdr->HR.ReqLine, 1, '/');
1820
1821         Buf = NewStrBuf();
1822         serv_printf("DLAT %ld|%s", msgnum, ChrPtr(PartNum));    // DLAT will return: 6XX length|-1|filename|cbtype|cbcharset
1823         StrBuf_ServGetln(Buf);
1824         FreeStrBuf(&PartNum);
1825
1826         if (GetServerStatus(Buf, NULL) != 6) {
1827                 FreeStrBuf(&Buf);
1828                 hprintf("HTTP/1.1 500 error\r\n"
1829                         "Pragma: no-cache\r\n"
1830                         "Cache-Control: no-store\r\n"
1831                         "Expires: -1\r\n"
1832                         "Content-Type: text/plain\r\n"
1833                 );
1834                 begin_burst();
1835                 wc_printf(_("An error occurred while retrieving this part: %s\n"), "--");
1836                 return;
1837         }
1838
1839         StrBufCutLeft(Buf, 4);
1840         bytes = StrBufExtract_long(Buf, 0, '|');
1841
1842         if (force_download) {
1843                 ContentType = NewStrBufPlain(HKEY("application/octet-stream"));
1844         }
1845         else {
1846                 ContentType = NewStrBuf();
1847                 StrBufExtract_token(ContentType, Buf, 3, '|');
1848         }
1849
1850         FreeStrBuf(&Buf);
1851         Buf = NewStrBuf();
1852         StrBuf_ServGetBLOBBuffered(Buf, bytes);
1853
1854         WC->WBuf = Buf;
1855         Buf = NULL;
1856         http_transmit_thing(ChrPtr(ContentType), 0);
1857         FreeStrBuf(&ContentType);
1858 }
1859
1860
1861 /*
1862  * Read any MIME part of a message, from the server, into memory.
1863  */
1864 StrBuf *load_mimepart(long msgnum, char *partnum) {
1865         off_t bytes;
1866         StrBuf *Buf;
1867         
1868         Buf = NewStrBuf();
1869         serv_printf("DLAT %ld|%s", msgnum, partnum);
1870         StrBuf_ServGetln(Buf);
1871         if (GetServerStatus(Buf, NULL) == 6) {
1872                 StrBufCutLeft(Buf, 4);
1873                 bytes = StrBufExtract_long(Buf, 0, '|');
1874                 FreeStrBuf(&Buf);
1875                 Buf = NewStrBuf();
1876                 StrBuf_ServGetBLOBBuffered(Buf, bytes);
1877                 return(Buf);
1878         }
1879         else {
1880                 FreeStrBuf(&Buf);
1881                 return(NULL);
1882         }
1883 }
1884
1885
1886 /*
1887  * Read any MIME part of a message, from the server, into memory.
1888  */
1889 void MimeLoadData(wc_mime_attachment *Mime) {
1890         StrBuf *Buf;
1891         const char *Ptr;
1892         off_t bytes;
1893
1894         serv_printf("DLAT %ld|%s", Mime->msgnum, ChrPtr(Mime->PartNum));
1895         Buf = NewStrBuf();
1896         StrBuf_ServGetln(Buf);
1897         if (GetServerStatus(Buf, NULL) == 6) {
1898                 Ptr = &(ChrPtr(Buf)[4]);
1899                 bytes = StrBufExtractNext_long(Buf, &Ptr, '|');
1900                 StrBufSkip_NTokenS(Buf, &Ptr, '|', 3);  /* filename, cbtype, mimetype */
1901                 if (Mime->Charset == NULL) Mime->Charset = NewStrBuf();
1902                 StrBufExtract_NextToken(Mime->Charset, Buf, &Ptr, '|');
1903                 
1904                 if (Mime->Data == NULL) {
1905                         Mime->Data = NewStrBufPlain(NULL, bytes);
1906                 }
1907                 StrBuf_ServGetBLOBBuffered(Mime->Data, bytes);
1908         }
1909         else {
1910                 FlushStrBuf(Mime->Data);
1911         }
1912         FreeStrBuf(&Buf);
1913 }
1914
1915
1916 void view_mimepart(void) {
1917         view_or_download_mimepart(0);
1918 }
1919
1920
1921 void download_mimepart(void) {
1922         view_or_download_mimepart(1);
1923 }
1924
1925
1926 void view_postpart(void) {
1927         StrBuf *filename = NewStrBuf();
1928         StrBuf *partnum = NewStrBuf();
1929
1930         StrBufExtract_token(partnum, WC->Hdr->HR.ReqLine, 0, '/');
1931         StrBufExtract_token(filename, WC->Hdr->HR.ReqLine, 1, '/');
1932
1933         postpart(partnum, filename, 0);
1934
1935         FreeStrBuf(&filename);
1936         FreeStrBuf(&partnum);
1937 }
1938
1939
1940 void download_postpart(void) {
1941         StrBuf *filename = NewStrBuf();
1942         StrBuf *partnum = NewStrBuf();
1943
1944         StrBufExtract_token(partnum, WC->Hdr->HR.ReqLine, 0, '/');
1945         StrBufExtract_token(filename, WC->Hdr->HR.ReqLine, 1, '/');
1946
1947         postpart(partnum, filename, 1);
1948
1949         FreeStrBuf(&filename);
1950         FreeStrBuf(&partnum);
1951 }
1952
1953
1954 void show_num_attachments(void) {
1955         wc_printf("%d", GetCount(WC->attachments));
1956 }
1957
1958
1959 void h_readnew(void) { readloop(readnew, eUseDefault);}
1960 void h_readold(void) { readloop(readold, eUseDefault);}
1961 void h_readfwd(void) { readloop(readfwd, eUseDefault);}
1962 void h_headers(void) { readloop(headers, eUseDefault);}
1963 void h_do_search(void) { readloop(do_search, eUseDefault);}
1964 void h_readgt(void) { readloop(readgt, eUseDefault);}
1965 void h_readlt(void) { readloop(readlt, eUseDefault);}
1966
1967
1968 /* Output message list in JSON format */
1969 void jsonMessageList(void) {
1970         StrBuf *View = NewStrBuf();
1971         const StrBuf *room = sbstr("room");
1972         long oper = (havebstr("query")) ? do_search : readnew;
1973         StrBufPrintf(View, "%d", VIEW_JSON_LIST);
1974         putbstr("view", View);; 
1975         gotoroom(room);
1976         readloop(oper, eUseDefault);
1977 }
1978
1979
1980 void FreeReadLoopHandlerSet(void *v) {
1981         RoomRenderer *Handler = (RoomRenderer *) v;
1982         FreeStrBuf(&Handler->FetchMessageList);
1983         if (Handler->MessageFieldList != NULL) {
1984                 free(Handler->MessageFieldList);
1985         }
1986         free(Handler);
1987 }
1988
1989
1990 void RegisterReadLoopHandlerset(
1991         int RoomType,
1992         GetParamsGetServerCall_func GetParamsGetServerCall,
1993         PrintViewHeader_func PrintPageHeader,
1994         PrintViewHeader_func PrintViewHeader,
1995         load_msg_ptrs_detailheaders LH,
1996         LoadMsgFromServer_func LoadMsgFromServer,
1997         RenderView_or_Tail_func RenderView_or_Tail,
1998         View_Cleanup_func ViewCleanup,
1999         const char **browseListFields
2000         )
2001 {
2002         long count = 0;
2003         long i = 0;
2004         RoomRenderer *Handler;
2005
2006         Handler = (RoomRenderer*) malloc(sizeof(RoomRenderer));
2007
2008         Handler->RoomType = RoomType;
2009         Handler->GetParamsGetServerCall = GetParamsGetServerCall;
2010         Handler->PrintPageHeader = PrintPageHeader;
2011         Handler->PrintViewHeader = PrintViewHeader;
2012         Handler->LoadMsgFromServer = LoadMsgFromServer;
2013         Handler->RenderView_or_Tail = RenderView_or_Tail;
2014         Handler->ViewCleanup = ViewCleanup;
2015         Handler->LHParse = LH;
2016
2017         if (browseListFields != NULL) {
2018                 while (browseListFields[count] != NULL) {
2019                         count ++;
2020                 }
2021                 Handler->HeaderCount = count;
2022                 Handler->MessageFieldList = (eMessageField*) malloc(sizeof(eMessageField) * count);
2023                 Handler->FetchMessageList = NewStrBufPlain(NULL, 5 * count + 4 + 5);
2024                 StrBufPlain(Handler->FetchMessageList, HKEY("time\n"));
2025                 for (i = 0; i < count; i++) {
2026                         if (!GetFieldFromMnemonic(&Handler->MessageFieldList[i], browseListFields[i])) {
2027                                 fprintf(stderr, "Unknown message header: %s\n", browseListFields[i]);
2028                                 exit(1);
2029                         }
2030                         StrBufAppendBufPlain(Handler->FetchMessageList, browseListFields[i], 4, 0);
2031                         StrBufAppendBufPlain(Handler->FetchMessageList, HKEY("\n"), 0);
2032                 }
2033                 StrBufAppendBufPlain(Handler->FetchMessageList, HKEY("000"), 0);
2034         }
2035         else {
2036                 Handler->FetchMessageList = NULL;
2037                 Handler->MessageFieldList = NULL;
2038         }
2039
2040         Put(ReadLoopHandler, IKEY(RoomType), Handler, FreeReadLoopHandlerSet);
2041 }
2042
2043 void 
2044 InitModule_MSG
2045 (void)
2046 {
2047         RegisterPreference("use_sig",
2048                            _("Attach signature to email messages?"), 
2049                            PRF_YESNO, 
2050                            NULL);
2051         RegisterPreference("signature", _("Use this signature:"), PRF_QP_STRING, NULL);
2052         RegisterPreference("default_header_charset",
2053                            _("Default character set for email headers:"), 
2054                            PRF_STRING, 
2055                            NULL);
2056         RegisterPreference("defaultfrom", _("Preferred email address"), PRF_STRING, NULL);
2057         RegisterPreference("defaultname", 
2058                            _("Preferred display name for email messages"), 
2059                            PRF_STRING, 
2060                            NULL);
2061         RegisterPreference("defaulthandle", 
2062                            _("Preferred display name for bulletin board posts"), 
2063                            PRF_STRING, 
2064                            NULL);
2065         RegisterPreference("mailbox",_("Mailbox view mode"), PRF_STRING, NULL);
2066
2067         WebcitAddUrlHandler(HKEY("readnew"), "", 0, h_readnew, ANONYMOUS|NEED_URL);
2068         WebcitAddUrlHandler(HKEY("readold"), "", 0, h_readold, ANONYMOUS|NEED_URL);
2069         WebcitAddUrlHandler(HKEY("readfwd"), "", 0, h_readfwd, ANONYMOUS|NEED_URL);
2070         WebcitAddUrlHandler(HKEY("headers"), "", 0, h_headers, NEED_URL);
2071         WebcitAddUrlHandler(HKEY("readgt"), "", 0, h_readgt, ANONYMOUS|NEED_URL);
2072         WebcitAddUrlHandler(HKEY("readlt"), "", 0, h_readlt, ANONYMOUS|NEED_URL);
2073         WebcitAddUrlHandler(HKEY("do_search"), "", 0, h_do_search, 0);
2074         WebcitAddUrlHandler(HKEY("display_enter"), "", 0, display_enter, 0);
2075         WebcitAddUrlHandler(HKEY("post"), "", 0, post_message, PROHIBIT_STARTPAGE);
2076         WebcitAddUrlHandler(HKEY("move_msg"), "", 0, move_msg, PROHIBIT_STARTPAGE);
2077         WebcitAddUrlHandler(HKEY("delete_msg"), "", 0, delete_msg, PROHIBIT_STARTPAGE);
2078         WebcitAddUrlHandler(HKEY("msg"), "", 0, embed_message, NEED_URL);
2079         WebcitAddUrlHandler(HKEY("message"), "", 0, handle_one_message, NEED_URL|XHTTP_COMMANDS|COOKIEUNNEEDED|FORCE_SESSIONCLOSE);
2080         WebcitAddUrlHandler(HKEY("printmsg"), "", 0, print_message, NEED_URL);
2081         WebcitAddUrlHandler(HKEY("msgheaders"), "", 0, display_headers, NEED_URL);
2082
2083         WebcitAddUrlHandler(HKEY("mimepart"), "", 0, view_mimepart, NEED_URL);
2084         WebcitAddUrlHandler(HKEY("mimepart_download"), "", 0, download_mimepart, NEED_URL);
2085         WebcitAddUrlHandler(HKEY("postpart"), "", 0, view_postpart, NEED_URL|PROHIBIT_STARTPAGE);
2086         WebcitAddUrlHandler(HKEY("postpart_download"), "", 0, download_postpart, NEED_URL|PROHIBIT_STARTPAGE);
2087         WebcitAddUrlHandler(HKEY("upload_attachment"), "", 0, upload_attachment, AJAX);
2088         WebcitAddUrlHandler(HKEY("remove_attachment"), "", 0, remove_attachment, AJAX);
2089         WebcitAddUrlHandler(HKEY("show_num_attachments"), "", 0, show_num_attachments, AJAX);
2090
2091         /* json */
2092         WebcitAddUrlHandler(HKEY("roommsgs"), "", 0, jsonMessageList,0);
2093 }
2094
2095 void
2096 SessionDetachModule_MSG
2097 (wcsession *sess)
2098 {
2099         DeleteHash(&sess->summ);
2100 }