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