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