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