* PEXP and GEXP no longer trip the idle time display
[citadel.git] / citadel / msgbase.c
1 /* $Id$ */
2 #include "sysdep.h"
3 #include <stdlib.h>
4 #include <unistd.h>
5 #include <stdio.h>
6 #include <fcntl.h>
7 #include <time.h>
8 #include <ctype.h>
9 #include <string.h>
10 #include <syslog.h>
11 #ifdef HAVE_PTHREAD_H
12 #include <pthread.h>
13 #endif
14 #include <limits.h>
15 #include "citadel.h"
16 #include "server.h"
17 #include <errno.h>
18 #include <sys/stat.h>
19 #include "database.h"
20 #include "msgbase.h"
21 #include "support.h"
22 #include "sysdep_decls.h"
23 #include "citserver.h"
24 #include "room_ops.h"
25 #include "user_ops.h"
26 #include "file_ops.h"
27 #include "control.h"
28 #include "dynloader.h"
29 #include "tools.h"
30 #include "mime_parser.h"
31
32 #define MSGS_ALL        0
33 #define MSGS_OLD        1
34 #define MSGS_NEW        2
35 #define MSGS_FIRST      3
36 #define MSGS_LAST       4
37 #define MSGS_GT         5
38
39 #define desired_section ((char *)CtdlGetUserData(SYM_DESIRED_SECTION))
40
41 extern struct config config;
42
43
44 /*
45  * This function is self explanatory.
46  * (What can I say, I'm in a weird mood today...)
47  */
48 void remove_any_whitespace_to_the_left_or_right_of_at_symbol(char *name)
49 {
50         int i;
51
52         for (i = 0; i < strlen(name); ++i)
53                 if (name[i] == '@') {
54                         if (i > 0)
55                                 if (isspace(name[i - 1])) {
56                                         strcpy(&name[i - 1], &name[i]);
57                                         i = 0;
58                                 }
59                         while (isspace(name[i + 1])) {
60                                 strcpy(&name[i + 1], &name[i + 2]);
61                         }
62                 }
63 }
64
65
66 /*
67  * Aliasing for network mail.
68  * (Error messages have been commented out, because this is a server.)
69  */
70 int alias(char *name)
71 {                               /* process alias and routing info for mail */
72         FILE *fp;
73         int a, b;
74         char aaa[300], bbb[300];
75
76         lprintf(9, "alias() called for <%s>\n", name);
77
78         remove_any_whitespace_to_the_left_or_right_of_at_symbol(name);
79
80         fp = fopen("network/mail.aliases", "r");
81         if (fp == NULL)
82                 fp = fopen("/dev/null", "r");
83         if (fp == NULL)
84                 return (MES_ERROR);
85         strcpy(aaa, "");
86         strcpy(bbb, "");
87         while (fgets(aaa, sizeof aaa, fp) != NULL) {
88                 while (isspace(name[0]))
89                         strcpy(name, &name[1]);
90                 aaa[strlen(aaa) - 1] = 0;
91                 strcpy(bbb, "");
92                 for (a = 0; a < strlen(aaa); ++a) {
93                         if (aaa[a] == ',') {
94                                 strcpy(bbb, &aaa[a + 1]);
95                                 aaa[a] = 0;
96                         }
97                 }
98                 if (!strcasecmp(name, aaa))
99                         strcpy(name, bbb);
100         }
101         fclose(fp);
102         lprintf(7, "Mail is being forwarded to %s\n", name);
103
104         /* determine local or remote type, see citadel.h */
105         for (a = 0; a < strlen(name); ++a)
106                 if (name[a] == '!')
107                         return (MES_INTERNET);
108         for (a = 0; a < strlen(name); ++a)
109                 if (name[a] == '@')
110                         for (b = a; b < strlen(name); ++b)
111                                 if (name[b] == '.')
112                                         return (MES_INTERNET);
113         b = 0;
114         for (a = 0; a < strlen(name); ++a)
115                 if (name[a] == '@')
116                         ++b;
117         if (b > 1) {
118                 lprintf(7, "Too many @'s in address\n");
119                 return (MES_ERROR);
120         }
121         if (b == 1) {
122                 for (a = 0; a < strlen(name); ++a)
123                         if (name[a] == '@')
124                                 strcpy(bbb, &name[a + 1]);
125                 while (bbb[0] == 32)
126                         strcpy(bbb, &bbb[1]);
127                 fp = fopen("network/mail.sysinfo", "r");
128                 if (fp == NULL)
129                         return (MES_ERROR);
130               GETSN:do {
131                         a = getstring(fp, aaa);
132                 } while ((a >= 0) && (strcasecmp(aaa, bbb)));
133                 a = getstring(fp, aaa);
134                 if (!strncmp(aaa, "use ", 4)) {
135                         strcpy(bbb, &aaa[4]);
136                         fseek(fp, 0L, 0);
137                         goto GETSN;
138                 }
139                 fclose(fp);
140                 if (!strncmp(aaa, "uum", 3)) {
141                         strcpy(bbb, name);
142                         for (a = 0; a < strlen(bbb); ++a) {
143                                 if (bbb[a] == '@')
144                                         bbb[a] = 0;
145                                 if (bbb[a] == ' ')
146                                         bbb[a] = '_';
147                         }
148                         while (bbb[strlen(bbb) - 1] == '_')
149                                 bbb[strlen(bbb) - 1] = 0;
150                         sprintf(name, &aaa[4], bbb);
151                         return (MES_INTERNET);
152                 }
153                 if (!strncmp(aaa, "bin", 3)) {
154                         strcpy(aaa, name);
155                         strcpy(bbb, name);
156                         while (aaa[strlen(aaa) - 1] != '@')
157                                 aaa[strlen(aaa) - 1] = 0;
158                         aaa[strlen(aaa) - 1] = 0;
159                         while (aaa[strlen(aaa) - 1] == ' ')
160                                 aaa[strlen(aaa) - 1] = 0;
161                         while (bbb[0] != '@')
162                                 strcpy(bbb, &bbb[1]);
163                         strcpy(bbb, &bbb[1]);
164                         while (bbb[0] == ' ')
165                                 strcpy(bbb, &bbb[1]);
166                         sprintf(name, "%s @%s", aaa, bbb);
167                         return (MES_BINARY);
168                 }
169                 return (MES_ERROR);
170         }
171         return (MES_LOCAL);
172 }
173
174
175 void get_mm(void)
176 {
177         FILE *fp;
178
179         fp = fopen("citadel.control", "r");
180         fread((char *) &CitControl, sizeof(struct CitControl), 1, fp);
181         fclose(fp);
182 }
183
184 /*
185  * cmd_msgs()  -  get list of message #'s in this room
186  */
187 void cmd_msgs(char *cmdbuf)
188 {
189         int a = 0;
190         int mode = 0;
191         char which[256];
192         int cm_howmany = 0;
193         long cm_gt = 0L;
194         struct visit vbuf;
195
196         extract(which, cmdbuf, 0);
197
198         mode = MSGS_ALL;
199         strcat(which, "   ");
200         if (!strncasecmp(which, "OLD", 3))
201                 mode = MSGS_OLD;
202         if (!strncasecmp(which, "NEW", 3))
203                 mode = MSGS_NEW;
204         if (!strncasecmp(which, "FIRST", 5)) {
205                 mode = MSGS_FIRST;
206                 cm_howmany = extract_int(cmdbuf, 1);
207         }
208         if (!strncasecmp(which, "LAST", 4)) {
209                 mode = MSGS_LAST;
210                 cm_howmany = extract_int(cmdbuf, 1);
211         }
212         if (!strncasecmp(which, "GT", 2)) {
213                 mode = MSGS_GT;
214                 cm_gt = extract_long(cmdbuf, 1);
215         }
216         if ((!(CC->logged_in)) && (!(CC->internal_pgm))) {
217                 cprintf("%d not logged in\n", ERROR + NOT_LOGGED_IN);
218                 return;
219         }
220         get_mm();
221         get_msglist(&CC->quickroom);
222         getuser(&CC->usersupp, CC->curr_user);
223         CtdlGetRelationship(&vbuf, &CC->usersupp, &CC->quickroom);
224
225         cprintf("%d Message list...\n", LISTING_FOLLOWS);
226         if (CC->num_msgs != 0) {
227                 for (a = 0; a < (CC->num_msgs); ++a)
228                         if ((MessageFromList(a) >= 0)
229                             && (
230
231                                        (mode == MSGS_ALL)
232                                        || ((mode == MSGS_OLD) && (MessageFromList(a) <= vbuf.v_lastseen))
233                                        || ((mode == MSGS_NEW) && (MessageFromList(a) > vbuf.v_lastseen))
234                                        || ((mode == MSGS_NEW) && (MessageFromList(a) >= vbuf.v_lastseen)
235                                     && (CC->usersupp.flags & US_LASTOLD))
236                                        || ((mode == MSGS_LAST) && (a >= (CC->num_msgs - cm_howmany)))
237                             || ((mode == MSGS_FIRST) && (a < cm_howmany))
238                                        || ((mode == MSGS_GT) && (MessageFromList(a) > cm_gt))
239                             )
240                             ) {
241                                 cprintf("%ld\n", MessageFromList(a));
242                         }
243         }
244         cprintf("000\n");
245 }
246
247
248
249 /* 
250  * help_subst()  -  support routine for help file viewer
251  */
252 void help_subst(char *strbuf, char *source, char *dest)
253 {
254         char workbuf[256];
255         int p;
256
257         while (p = pattern2(strbuf, source), (p >= 0)) {
258                 strcpy(workbuf, &strbuf[p + strlen(source)]);
259                 strcpy(&strbuf[p], dest);
260                 strcat(strbuf, workbuf);
261         }
262 }
263
264
265 void do_help_subst(char *buffer)
266 {
267         char buf2[16];
268
269         help_subst(buffer, "^nodename", config.c_nodename);
270         help_subst(buffer, "^humannode", config.c_humannode);
271         help_subst(buffer, "^fqdn", config.c_fqdn);
272         help_subst(buffer, "^username", CC->usersupp.fullname);
273         sprintf(buf2, "%ld", CC->usersupp.usernum);
274         help_subst(buffer, "^usernum", buf2);
275         help_subst(buffer, "^sysadm", config.c_sysadm);
276         help_subst(buffer, "^variantname", CITADEL);
277         sprintf(buf2, "%d", config.c_maxsessions);
278         help_subst(buffer, "^maxsessions", buf2);
279 }
280
281
282
283 /*
284  * memfmout()  -  Citadel text formatter and paginator.
285  *             Although the original purpose of this routine was to format
286  *             text to the reader's screen width, all we're really using it
287  *             for here is to format text out to 80 columns before sending it
288  *             to the client.  The client software may reformat it again.
289  */
290 void memfmout(int width, char *mptr, char subst)
291                         /* screen width to use */
292                         /* where are we going to get our text from? */
293                         /* nonzero if we should use hypertext mode */
294 {
295         int a, b, c;
296         int real = 0;
297         int old = 0;
298         CIT_UBYTE ch;
299         char aaa[140];
300         char buffer[256];
301
302         strcpy(aaa, "");
303         old = 255;
304         strcpy(buffer, "");
305         c = 1;                  /* c is the current pos */
306
307 FMTA:   if (subst) {
308                 while (ch = *mptr, ((ch != 0) && (strlen(buffer) < 126))) {
309                         ch = *mptr++;
310                         buffer[strlen(buffer) + 1] = 0;
311                         buffer[strlen(buffer)] = ch;
312                 }
313
314                 if (buffer[0] == '^')
315                         do_help_subst(buffer);
316
317                 buffer[strlen(buffer) + 1] = 0;
318                 a = buffer[0];
319                 strcpy(buffer, &buffer[1]);
320         } else
321                 ch = *mptr++;
322
323         old = real;
324         real = ch;
325         if (ch <= 0)
326                 goto FMTEND;
327
328         if (((ch == 13) || (ch == 10)) && (old != 13) && (old != 10))
329                 ch = 32;
330         if (((old == 13) || (old == 10)) && (isspace(real))) {
331                 cprintf("\n");
332                 c = 1;
333         }
334         if (ch > 126)
335                 goto FMTA;
336
337         if (ch > 32) {
338                 if (((strlen(aaa) + c) > (width - 5)) && (strlen(aaa) > (width - 5))) {
339                         cprintf("\n%s", aaa);
340                         c = strlen(aaa);
341                         aaa[0] = 0;
342                 }
343                 b = strlen(aaa);
344                 aaa[b] = ch;
345                 aaa[b + 1] = 0;
346         }
347         if (ch == 32) {
348                 if ((strlen(aaa) + c) > (width - 5)) {
349                         cprintf("\n");
350                         c = 1;
351                 }
352                 cprintf("%s ", aaa);
353                 ++c;
354                 c = c + strlen(aaa);
355                 strcpy(aaa, "");
356                 goto FMTA;
357         }
358         if ((ch == 13) || (ch == 10)) {
359                 cprintf("%s\n", aaa);
360                 c = 1;
361                 strcpy(aaa, "");
362                 goto FMTA;
363         }
364         goto FMTA;
365
366 FMTEND: cprintf("%s\n", aaa);
367 }
368
369
370
371 /*
372  * Callback function for mime parser that simply lists the part
373  */
374 void list_this_part(char *name, char *filename, char *partnum, char *disp,
375                     void *content, char *cbtype, size_t length)
376 {
377
378         cprintf("part=%s|%s|%s|%s|%s|%d\n",
379                 name, filename, partnum, disp, cbtype, length);
380 }
381
382
383 /*
384  * Callback function for mime parser that wants to display text
385  */
386 void fixed_output(char *name, char *filename, char *partnum, char *disp,
387                   void *content, char *cbtype, size_t length)
388 {
389
390         if (!strcasecmp(cbtype, "text/plain")) {
391                 client_write(content, length);
392         } else {
393                 cprintf("Part %s: %s (%s) (%d bytes)\n",
394                         partnum, filename, cbtype, length);
395         }
396 }
397
398
399 /*
400  * Callback function for mime parser that opens a section for downloading
401  */
402 void mime_download(char *name, char *filename, char *partnum, char *disp,
403                    void *content, char *cbtype, size_t length)
404 {
405
406         /* Silently go away if there's already a download open... */
407         if (CC->download_fp != NULL)
408                 return;
409
410         /* ...or if this is not the desired section */
411         if (strcasecmp(desired_section, partnum))
412                 return;
413
414         CC->download_fp = tmpfile();
415         if (CC->download_fp == NULL)
416                 return;
417
418         fwrite(content, length, 1, CC->download_fp);
419         fflush(CC->download_fp);
420         rewind(CC->download_fp);
421
422         OpenCmdResult(filename, cbtype);
423 }
424
425
426
427 /*
428  * Get a message off disk.  (return value is the message's timestamp)
429  * 
430  */
431 time_t output_message(char *msgid, int mode, int headers_only)
432 {
433         long msg_num;
434         int a;
435         CIT_UBYTE ch, rch;
436         CIT_UBYTE format_type, anon_flag;
437         char buf[1024];
438         long msg_len;
439         int msg_ok = 0;
440
441         struct cdbdata *dmsgtext;
442         char *mptr;
443
444         /* buffers needed for RFC822 translation */
445         char suser[256];
446         char luser[256];
447         char snode[256];
448         char lnode[256];
449         char mid[256];
450         time_t xtime = 0L;
451         /*                                       */
452
453         msg_num = atol(msgid);
454
455
456         if ((!(CC->logged_in)) && (!(CC->internal_pgm)) && (mode != MT_DATE)) {
457                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
458                 return (xtime);
459         }
460         /* We used to need to check in the current room's message list
461          * to determine where the message's disk position.  We no longer need
462          * to do this, but we do it anyway as a security measure, in order to
463          * prevent rogue clients from reading messages not in the current room.
464          */
465
466         msg_ok = 0;
467         if (CC->num_msgs > 0) {
468                 for (a = 0; a < CC->num_msgs; ++a) {
469                         if (MessageFromList(a) == msg_num) {
470                                 msg_ok = 1;
471                         }
472                 }
473         }
474         if (!msg_ok) {
475                 if (mode != MT_DATE)
476                         cprintf("%d Message %ld is not in this room.\n",
477                                 ERROR, msg_num);
478                 return (xtime);
479         }
480         dmsgtext = cdb_fetch(CDB_MSGMAIN, &msg_num, sizeof(long));
481
482         if (dmsgtext == NULL) {
483                 if (mode != MT_DATE)
484                         cprintf("%d Can't find message %ld\n",
485                                 ERROR + INTERNAL_ERROR);
486                 return (xtime);
487         }
488         msg_len = (long) dmsgtext->len;
489         mptr = dmsgtext->ptr;
490
491         /* this loop spews out the whole message if we're doing raw format */
492         if (mode == MT_RAW) {
493                 cprintf("%d %ld\n", BINARY_FOLLOWS, msg_len);
494                 client_write(dmsgtext->ptr, (int) msg_len);
495                 cdb_free(dmsgtext);
496                 return (xtime);
497         }
498         /* Otherwise, we'll start parsing it field by field... */
499         ch = *mptr++;
500         if (ch != 255) {
501                 cprintf("%d Illegal message format on disk\n",
502                         ERROR + INTERNAL_ERROR);
503                 cdb_free(dmsgtext);
504                 return (xtime);
505         }
506         anon_flag = *mptr++;
507         format_type = *mptr++;
508
509         /* Are we downloading a MIME component? */
510         if (mode == MT_DOWNLOAD) {
511                 if (format_type != 4) {
512                         cprintf("%d This is not a MIME message.\n",
513                                 ERROR);
514                 } else if (CC->download_fp != NULL) {
515                         cprintf("%d You already have a download open.\n",
516                                 ERROR);
517                 } else {
518                         /* Skip to the message body */
519                         while (ch = *mptr++, (ch != 'M' && ch != 0)) {
520                                 buf[0] = 0;
521                                 do {
522                                         buf[strlen(buf) + 1] = 0;
523                                         rch = *mptr++;
524                                         buf[strlen(buf)] = rch;
525                                 } while (rch > 0);
526                         }
527                         /* Now parse it */
528                         mime_parser(mptr, NULL, *mime_download);
529                         /* If there's no file open by this time, the requested
530                          * section wasn't found, so print an error
531                          */
532                         if (CC->download_fp == NULL) {
533                                 cprintf("%d Section %s not found.\n",
534                                         ERROR + FILE_NOT_FOUND,
535                                         desired_section);
536                         }
537                 }
538                 cdb_free(dmsgtext);
539                 return (xtime);
540         }
541         /* Are we just looking for the message date? */
542         if (mode == MT_DATE)
543                 while (ch = *mptr++, (ch != 'M' && ch != 0)) {
544                         buf[0] = 0;
545                         do {
546                                 buf[strlen(buf) + 1] = 0;
547                                 rch = *mptr++;
548                                 buf[strlen(buf)] = rch;
549                         } while (rch > 0);
550
551                         if (ch == 'T') {
552                                 xtime = atol(buf);
553                                 cdb_free(dmsgtext);
554                                 return (xtime);
555                         }
556                 }
557         /* now for the user-mode message reading loops */
558         cprintf("%d Message %ld:\n", LISTING_FOLLOWS, msg_num);
559
560         if (mode == MT_CITADEL)
561                 cprintf("type=%d\n", format_type);
562
563         if ((anon_flag == MES_ANON) && (mode == MT_CITADEL)) {
564                 cprintf("nhdr=yes\n");
565         }
566         /* begin header processing loop for Citadel message format */
567
568         if ((mode == MT_CITADEL) || (mode == MT_MIME))
569                 while (ch = *mptr++, (ch != 'M' && ch != 0)) {
570                         buf[0] = 0;
571                         do {
572                                 buf[strlen(buf) + 1] = 0;
573                                 rch = *mptr++;
574                                 buf[strlen(buf)] = rch;
575                         } while (rch > 0);
576
577                         if (ch == 'A') {
578                                 PerformUserHooks(buf, (-1L), EVT_OUTPUTMSG);
579                                 if (anon_flag == MES_ANON)
580                                         cprintf("from=****");
581                                 else if (anon_flag == MES_AN2)
582                                         cprintf("from=anonymous");
583                                 else
584                                         cprintf("from=%s", buf);
585                                 if ((is_room_aide()) && ((anon_flag == MES_ANON)
586                                               || (anon_flag == MES_AN2)))
587                                         cprintf(" [%s]", buf);
588                                 cprintf("\n");
589                         } else if (ch == 'P')
590                                 cprintf("path=%s\n", buf);
591                         else if (ch == 'U')
592                                 cprintf("subj=%s\n", buf);
593                         else if (ch == 'I')
594                                 cprintf("msgn=%s\n", buf);
595                         else if (ch == 'H')
596                                 cprintf("hnod=%s\n", buf);
597                         else if (ch == 'O')
598                                 cprintf("room=%s\n", buf);
599                         else if (ch == 'N')
600                                 cprintf("node=%s\n", buf);
601                         else if (ch == 'R')
602                                 cprintf("rcpt=%s\n", buf);
603                         else if (ch == 'T')
604                                 cprintf("time=%s\n", buf);
605                         /* else cprintf("fld%c=%s\n",ch,buf); */
606                 }
607         /* begin header processing loop for RFC822 transfer format */
608
609         strcpy(suser, "");
610         strcpy(luser, "");
611         strcpy(snode, NODENAME);
612         strcpy(lnode, HUMANNODE);
613         if (mode == MT_RFC822)
614                 while (ch = *mptr++, (ch != 'M' && ch != 0)) {
615                         buf[0] = 0;
616                         do {
617                                 buf[strlen(buf) + 1] = 0;
618                                 rch = *mptr++;
619                                 buf[strlen(buf)] = rch;
620                         } while (rch > 0);
621
622                         if (ch == 'A')
623                                 strcpy(luser, buf);
624                         else if (ch == 'P') {
625                                 cprintf("Path: %s\n", buf);
626                                 for (a = 0; a < strlen(buf); ++a) {
627                                         if (buf[a] == '!') {
628                                                 strcpy(buf, &buf[a + 1]);
629                                                 a = 0;
630                                         }
631                                 }
632                                 strcpy(suser, buf);
633                         } else if (ch == 'U')
634                                 cprintf("Subject: %s\n", buf);
635                         else if (ch == 'I')
636                                 strcpy(mid, buf);
637                         else if (ch == 'H')
638                                 strcpy(lnode, buf);
639                         else if (ch == 'O')
640                                 cprintf("X-Citadel-Room: %s\n", buf);
641                         else if (ch == 'N')
642                                 strcpy(snode, buf);
643                         else if (ch == 'R')
644                                 cprintf("To: %s\n", buf);
645                         else if (ch == 'T') {
646                                 xtime = atol(buf);
647                                 cprintf("Date: %s", asctime(localtime(&xtime)));
648                         }
649                 }
650         if (mode == MT_RFC822) {
651                 if (!strcasecmp(snode, NODENAME)) {
652                         strcpy(snode, FQDN);
653                 }
654                 cprintf("Message-ID: <%s@%s>\n", mid, snode);
655                 PerformUserHooks(luser, (-1L), EVT_OUTPUTMSG);
656                 cprintf("From: %s@%s (%s)\n",
657                         suser, snode, luser);
658                 cprintf("Organization: %s\n", lnode);
659         }
660         /* end header processing loop ... at this point, we're in the text */
661
662         if (ch == 0) {
663                 cprintf("text\n*** ?Message truncated\n000\n");
664                 cdb_free(dmsgtext);
665                 return (xtime);
666         }
667         /* do some sort of MIME output */
668         if (format_type == 4) {
669                 if ((mode == MT_CITADEL) || (mode == MT_MIME)) {
670                         mime_parser(mptr, NULL, *list_this_part);
671                 }
672                 if (mode == MT_MIME) {  /* If MT_MIME then it's parts only */
673                         cprintf("000\n");
674                         cdb_free(dmsgtext);
675                         return (xtime);
676                 }
677         }
678         if (headers_only) {
679                 /* give 'em a length */
680                 msg_len = 0L;
681                 while (ch = *mptr++, ch > 0) {
682                         ++msg_len;
683                 }
684                 cprintf("mlen=%ld\n", msg_len);
685                 cprintf("000\n");
686                 cdb_free(dmsgtext);
687                 return (xtime);
688         }
689         /* signify start of msg text */
690         if (mode == MT_CITADEL)
691                 cprintf("text\n");
692         if ((mode == MT_RFC822) && (format_type != 4))
693                 cprintf("\n");
694
695         /* If the format type on disk is 1 (fixed-format), then we want
696          * everything to be output completely literally ... regardless of
697          * what message transfer format is in use.
698          */
699         if (format_type == 1) {
700                 strcpy(buf, "");
701                 while (ch = *mptr++, ch > 0) {
702                         if (ch == 13)
703                                 ch = 10;
704                         if ((ch == 10) || (strlen(buf) > 250)) {
705                                 cprintf("%s\n", buf);
706                                 strcpy(buf, "");
707                         } else {
708                                 buf[strlen(buf) + 1] = 0;
709                                 buf[strlen(buf)] = ch;
710                         }
711                 }
712                 if (strlen(buf) > 0)
713                         cprintf("%s\n", buf);
714         }
715         /* If the message on disk is format 0 (Citadel vari-format), we
716          * output using the formatter at 80 columns.  This is the final output
717          * form if the transfer format is RFC822, but if the transfer format
718          * is Citadel proprietary, it'll still work, because the indentation
719          * for new paragraphs is correct and the client will reformat the
720          * message to the reader's screen width.
721          */
722         if (format_type == 0) {
723                 memfmout(80, mptr, 0);
724         }
725         /* If the message on disk is format 4 (MIME), we've gotta hand it
726          * off to the MIME parser.  The client has already been told that
727          * this message is format 1 (fixed format), so the callback function
728          * we use will display those parts as-is.
729          */
730         if (format_type == 4) {
731                 mime_parser(mptr, NULL, *fixed_output);
732         }
733         /* now we're done */
734         cprintf("000\n");
735         cdb_free(dmsgtext);
736         return (xtime);
737 }
738
739
740 /*
741  * display a message (mode 0 - Citadel proprietary)
742  */
743 void cmd_msg0(char *cmdbuf)
744 {
745         char msgid[256];
746         int headers_only = 0;
747
748         extract(msgid, cmdbuf, 0);
749         headers_only = extract_int(cmdbuf, 1);
750
751         output_message(msgid, MT_CITADEL, headers_only);
752         return;
753 }
754
755
756 /*
757  * display a message (mode 2 - RFC822)
758  */
759 void cmd_msg2(char *cmdbuf)
760 {
761         char msgid[256];
762         int headers_only = 0;
763
764         extract(msgid, cmdbuf, 0);
765         headers_only = extract_int(cmdbuf, 1);
766
767         output_message(msgid, MT_RFC822, headers_only);
768 }
769
770 /* 
771  * display a message (mode 3 - IGnet raw format - internal programs only)
772  */
773 void cmd_msg3(char *cmdbuf)
774 {
775         char msgid[256];
776         int headers_only = 0;
777
778         if (CC->internal_pgm == 0) {
779                 cprintf("%d This command is for internal programs only.\n",
780                         ERROR);
781                 return;
782         }
783         extract(msgid, cmdbuf, 0);
784         headers_only = extract_int(cmdbuf, 1);
785
786         output_message(msgid, MT_RAW, headers_only);
787 }
788
789 /* 
790  * display a message (mode 4 - MIME) (FIX ... still evolving, not complete)
791  */
792 void cmd_msg4(char *cmdbuf)
793 {
794         char msgid[256];
795
796         extract(msgid, cmdbuf, 0);
797
798         output_message(msgid, MT_MIME, 0);
799 }
800
801
802
803 /*
804  * Open a component of a MIME message as a download file 
805  */
806 void cmd_opna(char *cmdbuf)
807 {
808         char msgid[256];
809
810         CtdlAllocUserData(SYM_DESIRED_SECTION, 64);
811
812         extract(msgid, cmdbuf, 0);
813         extract(desired_section, cmdbuf, 1);
814
815         output_message(msgid, MT_DOWNLOAD, 0);
816 }
817
818
819
820 /*
821  * Message base operation to send a message to the master file
822  * (returns new message number)
823  */
824 long send_message(char *message_in_memory,      /* pointer to buffer */
825                   size_t message_length,        /* length of buffer */
826                   int generate_id)
827 {                               /* 1 to generate an I field */
828
829         long newmsgid;
830         char *actual_message;
831         size_t actual_length;
832         long retval;
833         char msgidbuf[32];
834
835         /* Get a new message number */
836         newmsgid = get_new_message_number();
837
838         if (generate_id) {
839                 sprintf(msgidbuf, "I%ld", newmsgid);
840                 actual_length = message_length + strlen(msgidbuf) + 1;
841                 actual_message = mallok(actual_length);
842                 memcpy(actual_message, message_in_memory, 3);
843                 memcpy(&actual_message[3], msgidbuf, (strlen(msgidbuf) + 1));
844                 memcpy(&actual_message[strlen(msgidbuf) + 4],
845                        &message_in_memory[3], message_length - 3);
846         } else {
847                 actual_message = message_in_memory;
848                 actual_length = message_length;
849         }
850
851         /* Write our little bundle of joy into the message base */
852         begin_critical_section(S_MSGMAIN);
853         if (cdb_store(CDB_MSGMAIN, &newmsgid, sizeof(long),
854                       actual_message, actual_length) < 0) {
855                 lprintf(2, "Can't store message\n");
856                 retval = 0L;
857         } else {
858                 retval = newmsgid;
859         }
860         end_critical_section(S_MSGMAIN);
861
862         if (generate_id) {
863                 phree(actual_message);
864         }
865         /* Finally, return the pointers */
866         return (retval);
867 }
868
869
870
871 /*
872  * this is a simple file copy routine.
873  */
874 void copy_file(char *from, char *to)
875 {
876         FILE *ffp, *tfp;
877         int a;
878
879         ffp = fopen(from, "r");
880         if (ffp == NULL)
881                 return;
882         tfp = fopen(to, "w");
883         if (tfp == NULL) {
884                 fclose(ffp);
885                 return;
886         }
887         while (a = getc(ffp), a >= 0) {
888                 putc(a, tfp);
889         }
890         fclose(ffp);
891         fclose(tfp);
892         return;
893 }
894
895
896
897 /*
898  * message base operation to save a message and install its pointers
899  */
900 void save_message(char *mtmp,   /* file containing proper message */
901                   char *rec,    /* Recipient (if mail) */
902                   char *force,  /* if non-zero length, force a room */
903                   int mailtype, /* local or remote type, see citadel.h */
904                   int generate_id)
905 {                               /* set to 1 to generate an 'I' field */
906         char aaa[100];
907         char hold_rm[ROOMNAMELEN];
908         char actual_rm[ROOMNAMELEN];
909         char force_room[ROOMNAMELEN];
910         char recipient[256];
911         long newmsgid;
912         char *message_in_memory;
913         struct stat statbuf;
914         size_t templen;
915         FILE *fp;
916         struct usersupp userbuf;
917         int a;
918         static int seqnum = 0;
919         int successful_local_recipients = 0;
920         struct quickroom qtemp;
921
922         lprintf(9, "save_message(%s,%s,%s,%d,%d)\n",
923                 mtmp, rec, force, mailtype, generate_id);
924
925         strcpy(force_room, force);
926
927         /* Strip non-printable characters out of the recipient name */
928         strcpy(recipient, rec);
929         for (a = 0; a < strlen(recipient); ++a)
930                 if (!isprint(recipient[a]))
931                         strcpy(&recipient[a], &recipient[a + 1]);
932
933         /* Measure the message */
934         stat(mtmp, &statbuf);
935         templen = statbuf.st_size;
936
937         /* Now read it into memory */
938         message_in_memory = (char *) mallok(templen);
939         if (message_in_memory == NULL) {
940                 lprintf(2, "Can't allocate memory to save message!\n");
941                 return;
942         }
943         fp = fopen(mtmp, "rb");
944         fread(message_in_memory, templen, 1, fp);
945         fclose(fp);
946
947         newmsgid = send_message(message_in_memory, templen, generate_id);
948         phree(message_in_memory);
949         if (newmsgid <= 0L)
950                 return;
951
952         strcpy(actual_rm, CC->quickroom.QRname);
953         strcpy(hold_rm, "");
954
955         /* If this is being done by the networker delivering a private
956          * message, we want to BYPASS saving the sender's copy (because there
957          * is no local sender; it would otherwise go to the Trashcan), and
958          * consequently set successful_local_recipients to (-1) so it gets
959          * set to 0 later on (a sleazy hack to make the reference count 1
960          * instead of 2)
961          */
962         if (CC->internal_pgm) {
963                 --successful_local_recipients;
964         } else {
965
966                 /* If the user is a twit, move to the twit room for posting */
967                 if (TWITDETECT)
968                         if (CC->usersupp.axlevel == 2) {
969                                 strcpy(hold_rm, actual_rm);
970                                 strcpy(actual_rm, config.c_twitroom);
971                         }
972                 /* ...or if this message is destined for Aide> then go there. */
973                 lprintf(9, "actual room forcing loop\n");
974                 if (strlen(force_room) > 0) {
975                         strcpy(hold_rm, actual_rm);
976                         strcpy(actual_rm, force_room);
977                 }
978                 /* This call to usergoto() changes rooms if necessary.  It also
979                 * causes the latest message list to be read into memory.
980                 */
981                 usergoto(actual_rm, 0);
982         
983                 /* read in the quickroom record, obtaining a lock... */
984                 lgetroom(&CC->quickroom, actual_rm);
985         
986                 /* Fix an obscure bug */
987                 if (!strcasecmp(CC->quickroom.QRname, AIDEROOM)) {
988                         CC->quickroom.QRflags =
989                                 CC->quickroom.QRflags & ~QR_MAILBOX;
990                 }
991
992                 /* Add the message pointer to the room */
993                 CC->quickroom.QRhighest =
994                         AddMessageToRoom(&CC->quickroom, newmsgid);
995         
996                 /* update quickroom */
997                 lputroom(&CC->quickroom);
998         }
999
1000         /* Network mail - send a copy to the network program. */
1001         if ((strlen(recipient) > 0) && (mailtype != MES_LOCAL)) {
1002                 sprintf(aaa, "./network/spoolin/netmail.%04lx.%04x.%04x",
1003                         (long) getpid(), CC->cs_pid, ++seqnum);
1004                 copy_file(mtmp, aaa);
1005                 system("exec nohup ./netproc -i >/dev/null 2>&1 &");
1006         }
1007         /* Bump this user's messages posted counter. */
1008         lgetuser(&CC->usersupp, CC->curr_user);
1009         CC->usersupp.posted = CC->usersupp.posted + 1;
1010         lputuser(&CC->usersupp);
1011
1012         /* If this is private, local mail, make a copy in the
1013          * recipient's mailbox and bump the reference count.
1014          */
1015         if ((strlen(recipient) > 0) && (mailtype == MES_LOCAL)) {
1016                 if (getuser(&userbuf, recipient) == 0) {
1017                         MailboxName(actual_rm, &userbuf, MAILROOM);
1018                         lprintf(9, "Targeting mailbox: <%s>\n", actual_rm);
1019                         if (lgetroom(&qtemp, actual_rm) == 0) {
1020                                 qtemp.QRhighest =
1021                                         AddMessageToRoom(&qtemp, newmsgid);
1022                                 lputroom(&qtemp);
1023                                 ++successful_local_recipients;
1024                         }
1025                 }
1026         }
1027         /* If we've posted in a room other than the current room, then we
1028          * have to now go back to the current room...
1029          */
1030         if (strlen(hold_rm) > 0) {
1031                 usergoto(hold_rm, 0);
1032         }
1033         unlink(mtmp);           /* delete the temporary file */
1034
1035         /* If the message was delivered to more than one location locally,
1036          * we have to bump the reference count accordingly.
1037          */
1038         if (successful_local_recipients != 0) {
1039                 AdjRefCount(newmsgid, successful_local_recipients);
1040         }
1041 }
1042
1043
1044 /*
1045  * Generate an administrative message and post it in the Aide> room.
1046  */
1047 void aide_message(char *text)
1048 {
1049         FILE *fp;
1050
1051         fp = fopen(CC->temp, "wb");
1052         fprintf(fp, "%c%c%c", 255, MES_NORMAL, 0);
1053         fprintf(fp, "Psysop%c", 0);
1054         fprintf(fp, "T%ld%c", (long) time(NULL), 0);
1055         fprintf(fp, "ACitadel%c", 0);
1056         fprintf(fp, "OAide%c", 0);
1057         fprintf(fp, "N%s%c", NODENAME, 0);
1058         fprintf(fp, "M%s\n%c", text, 0);
1059         fclose(fp);
1060         save_message(CC->temp, "", AIDEROOM, MES_LOCAL, 1);
1061         syslog(LOG_NOTICE, text);
1062 }
1063
1064
1065
1066 /*
1067  * Build a binary message to be saved on disk.
1068  */
1069 void make_message(
1070                          char *filename,        /* temporary file name */
1071                          struct usersupp *author,       /* author's usersupp structure */
1072                          char *recipient,       /* NULL if it's not mail */
1073                          char *room,    /* room where it's going */
1074                          int type,      /* see MES_ types in header file */
1075                          int net_type,  /* see MES_ types in header file */
1076                          int format_type,       /* local or remote (see citadel.h) */
1077                          char *fake_name)
1078 {                               /* who we're masquerading as */
1079
1080         FILE *fp;
1081         int a;
1082         time_t now;
1083         char dest_node[32];
1084         char buf[256];
1085
1086         /* Don't confuse the poor folks if it's not routed mail. */
1087         strcpy(dest_node, "");
1088
1089
1090         /* If net_type is MES_BINARY, split out the destination node. */
1091         if (net_type == MES_BINARY) {
1092                 strcpy(dest_node, NODENAME);
1093                 for (a = 0; a < strlen(recipient); ++a) {
1094                         if (recipient[a] == '@') {
1095                                 recipient[a] = 0;
1096                                 strcpy(dest_node, &recipient[a + 1]);
1097                         }
1098                 }
1099         }
1100         /* if net_type is MES_INTERNET, set the dest node to 'internet' */
1101         if (net_type == MES_INTERNET) {
1102                 strcpy(dest_node, "internet");
1103         }
1104         while (isspace(recipient[strlen(recipient) - 1]))
1105                 recipient[strlen(recipient) - 1] = 0;
1106
1107         time(&now);
1108         fp = fopen(filename, "w");
1109         putc(255, fp);
1110         putc(type, fp);         /* Normal or anonymous, see MES_ flags */
1111         putc(format_type, fp);  /* Formatted or unformatted */
1112         fprintf(fp, "Pcit%ld%c", author->usernum, 0);   /* path */
1113         fprintf(fp, "T%ld%c", (long) now, 0);   /* date/time */
1114         if (fake_name[0])
1115                 fprintf(fp, "A%s%c", fake_name, 0);
1116         else
1117                 fprintf(fp, "A%s%c", author->fullname, 0);      /* author */
1118
1119         if (CC->quickroom.QRflags & QR_MAILBOX) {       /* room */
1120                 fprintf(fp, "O%s%c", &CC->quickroom.QRname[11], 0);
1121         } else {
1122                 fprintf(fp, "O%s%c", CC->quickroom.QRname, 0);
1123         }
1124
1125         fprintf(fp, "N%s%c", NODENAME, 0);      /* nodename */
1126         fprintf(fp, "H%s%c", HUMANNODE, 0);     /* human nodename */
1127
1128         if (recipient[0] != 0)
1129                 fprintf(fp, "R%s%c", recipient, 0);
1130         if (dest_node[0] != 0)
1131                 fprintf(fp, "D%s%c", dest_node, 0);
1132
1133         putc('M', fp);
1134
1135         while (client_gets(buf), strcmp(buf, "000")) {
1136                 fprintf(fp, "%s\n", buf);
1137         }
1138         putc(0, fp);
1139         fclose(fp);
1140 }
1141
1142
1143
1144
1145
1146 /*
1147  * message entry  -  mode 0 (normal) <bc>
1148  */
1149 void cmd_ent0(char *entargs)
1150 {
1151         int post = 0;
1152         char recipient[256];
1153         int anon_flag = 0;
1154         int format_type = 0;
1155         char newusername[256];  /* <bc> */
1156
1157         int a, b;
1158         int e = 0;
1159         int mtsflag = 0;
1160         struct usersupp tempUS;
1161         char buf[256];
1162
1163         post = extract_int(entargs, 0);
1164         extract(recipient, entargs, 1);
1165         anon_flag = extract_int(entargs, 2);
1166         format_type = extract_int(entargs, 3);
1167
1168         /* first check to make sure the request is valid. */
1169
1170         if (!(CC->logged_in)) {
1171                 cprintf("%d Not logged in.\n", ERROR + NOT_LOGGED_IN);
1172                 return;
1173         }
1174         if ((CC->usersupp.axlevel < 2) && ((CC->quickroom.QRflags & QR_MAILBOX) == 0)) {
1175                 cprintf("%d Need to be validated to enter ",
1176                         ERROR + HIGHER_ACCESS_REQUIRED);
1177                 cprintf("(except in %s> to sysop)\n", MAILROOM);
1178                 return;
1179         }
1180         if ((CC->usersupp.axlevel < 4) && (CC->quickroom.QRflags & QR_NETWORK)) {
1181                 cprintf("%d Need net privileges to enter here.\n",
1182                         ERROR + HIGHER_ACCESS_REQUIRED);
1183                 return;
1184         }
1185         if ((CC->usersupp.axlevel < 6) && (CC->quickroom.QRflags & QR_READONLY)) {
1186                 cprintf("%d Sorry, this is a read-only room.\n",
1187                         ERROR + HIGHER_ACCESS_REQUIRED);
1188                 return;
1189         }
1190         mtsflag = 0;
1191
1192
1193         if (post == 2) {        /* <bc> */
1194                 if (CC->usersupp.axlevel < 6) {
1195                         cprintf("%d You don't have permission to do an aide post.\n",
1196                                 ERROR + HIGHER_ACCESS_REQUIRED);
1197                         return;
1198                 }
1199                 extract(newusername, entargs, 4);
1200                 memset(CC->fake_postname, 0, 32);
1201                 strcpy(CC->fake_postname, newusername);
1202                 cprintf("%d Ok\n", OK);
1203                 return;
1204         }
1205         CC->cs_flags |= CS_POSTING;
1206
1207         buf[0] = 0;
1208         if (CC->quickroom.QRflags & QR_MAILBOX) {
1209                 if (CC->usersupp.axlevel >= 2) {
1210                         strcpy(buf, recipient);
1211                 } else
1212                         strcpy(buf, "sysop");
1213                 lprintf(9, "calling alias()\n");
1214                 e = alias(buf); /* alias and mail type */
1215                 lprintf(9, "alias() returned %d\n", e);
1216                 if ((buf[0] == 0) || (e == MES_ERROR)) {
1217                         cprintf("%d Unknown address - cannot send message.\n",
1218                                 ERROR + NO_SUCH_USER);
1219                         return;
1220                 }
1221                 if ((e != MES_LOCAL) && (CC->usersupp.axlevel < 4)) {
1222                         cprintf("%d Net privileges required for network mail.\n",
1223                                 ERROR + HIGHER_ACCESS_REQUIRED);
1224                         return;
1225                 }
1226                 if ((RESTRICT_INTERNET == 1) && (e == MES_INTERNET)
1227                     && ((CC->usersupp.flags & US_INTERNET) == 0)
1228                     && (!CC->internal_pgm)) {
1229                         cprintf("%d You don't have access to Internet mail.\n",
1230                                 ERROR + HIGHER_ACCESS_REQUIRED);
1231                         return;
1232                 }
1233                 if (!strcasecmp(buf, "sysop")) {
1234                         mtsflag = 1;
1235                         goto SKFALL;
1236                 }
1237                 if (e != MES_LOCAL)
1238                         goto SKFALL;    /* don't search local file  */
1239                 if (!strcasecmp(buf, CC->usersupp.fullname)) {
1240                         cprintf("%d Can't send mail to yourself!\n",
1241                                 ERROR + NO_SUCH_USER);
1242                         return;
1243                 }
1244                 /* Check to make sure the user exists; also get the correct
1245                    * upper/lower casing of the name. 
1246                  */
1247                 a = getuser(&tempUS, buf);
1248                 if (a != 0) {
1249                         cprintf("%d No such user.\n", ERROR + NO_SUCH_USER);
1250                         return;
1251                 }
1252                 strcpy(buf, tempUS.fullname);
1253         }
1254       SKFALL:b = MES_NORMAL;
1255         if (CC->quickroom.QRflags & QR_ANONONLY)
1256                 b = MES_ANON;
1257         if (CC->quickroom.QRflags & QR_ANONOPT) {
1258                 if (anon_flag == 1)
1259                         b = MES_AN2;
1260         }
1261         if ((CC->quickroom.QRflags & QR_MAILBOX) == 0)
1262                 buf[0] = 0;
1263
1264         /* If we're only checking the validity of the request, return
1265          * success without creating the message.
1266          */
1267         if (post == 0) {
1268                 cprintf("%d %s\n", OK, buf);
1269                 return;
1270         }
1271         cprintf("%d send message\n", SEND_LISTING);
1272         if (CC->fake_postname[0])
1273                 make_message(CC->temp, &CC->usersupp, buf, CC->quickroom.QRname, b, e, format_type, CC->fake_postname);
1274         else if (CC->fake_username[0])
1275                 make_message(CC->temp, &CC->usersupp, buf, CC->quickroom.QRname, b, e, format_type, CC->fake_username);
1276         else
1277                 make_message(CC->temp, &CC->usersupp, buf, CC->quickroom.QRname, b, e, format_type, "");
1278         save_message(CC->temp, buf, (mtsflag ? AIDEROOM : ""), e, 1);
1279         CC->fake_postname[0] = '\0';
1280         return;
1281 }
1282
1283
1284
1285 /* 
1286  * message entry - mode 3 (raw)
1287  */
1288 void cmd_ent3(char *entargs)
1289 {
1290         char recp[256];
1291         char buf[256];
1292         int a;
1293         int e = 0;
1294         struct usersupp tempUS;
1295         long msglen;
1296         long bloklen;
1297         FILE *fp;
1298
1299         if (CC->internal_pgm == 0) {
1300                 cprintf("%d This command is for internal programs only.\n",
1301                         ERROR);
1302                 return;
1303         }
1304         /* See if there's a recipient, but make sure it's a real one */
1305         extract(recp, entargs, 1);
1306         for (a = 0; a < strlen(recp); ++a)
1307                 if (!isprint(recp[a]))
1308                         strcpy(&recp[a], &recp[a + 1]);
1309         while (isspace(recp[0]))
1310                 strcpy(recp, &recp[1]);
1311         while (isspace(recp[strlen(recp) - 1]))
1312                 recp[strlen(recp) - 1] = 0;
1313
1314         /* If we're in Mail, check the recipient */
1315         if (strlen(recp) > 0) {
1316                 e = alias(recp);        /* alias and mail type */
1317                 if ((recp[0] == 0) || (e == MES_ERROR)) {
1318                         cprintf("%d Unknown address - cannot send message.\n",
1319                                 ERROR + NO_SUCH_USER);
1320                         return;
1321                 }
1322                 if (e == MES_LOCAL) {
1323                         a = getuser(&tempUS, recp);
1324                         if (a != 0) {
1325                                 cprintf("%d No such user.\n",
1326                                         ERROR + NO_SUCH_USER);
1327                                 return;
1328                         }
1329                 }
1330         }
1331         /* At this point, message has been approved. */
1332         if (extract_int(entargs, 0) == 0) {
1333                 cprintf("%d OK to send\n", OK);
1334                 return;
1335         }
1336         /* open a temp file to hold the message */
1337         fp = fopen(CC->temp, "wb");
1338         if (fp == NULL) {
1339                 cprintf("%d Cannot open %s: %s\n",
1340                         ERROR + INTERNAL_ERROR,
1341                         CC->temp, strerror(errno));
1342                 return;
1343         }
1344         msglen = extract_long(entargs, 2);
1345         cprintf("%d %ld\n", SEND_BINARY, msglen);
1346         while (msglen > 0L) {
1347                 bloklen = ((msglen >= 255L) ? 255 : msglen);
1348                 client_read(buf, (int) bloklen);
1349                 fwrite(buf, (int) bloklen, 1, fp);
1350                 msglen = msglen - bloklen;
1351         }
1352         fclose(fp);
1353
1354         save_message(CC->temp, recp, "", e, 0);
1355 }
1356
1357
1358 /*
1359  * Delete message from current room
1360  */
1361 void cmd_dele(char *delstr)
1362 {
1363         long delnum;
1364         int a, ok;
1365
1366         getuser(&CC->usersupp, CC->curr_user);
1367         if ((CC->usersupp.axlevel < 6)
1368             && (CC->usersupp.usernum != CC->quickroom.QRroomaide)
1369             && ((CC->quickroom.QRflags & QR_MAILBOX) == 0)) {
1370                 cprintf("%d Higher access required.\n",
1371                         ERROR + HIGHER_ACCESS_REQUIRED);
1372                 return;
1373         }
1374         delnum = extract_long(delstr, 0);
1375
1376         /* get room records, obtaining a lock... */
1377         lgetroom(&CC->quickroom, CC->quickroom.QRname);
1378         get_msglist(&CC->quickroom);
1379
1380         ok = 0;
1381         if (CC->num_msgs > 0)
1382                 for (a = 0; a < (CC->num_msgs); ++a) {
1383                         if (MessageFromList(a) == delnum) {
1384                                 SetMessageInList(a, 0L);
1385                                 ok = 1;
1386                         }
1387                 }
1388         CC->num_msgs = sort_msglist(CC->msglist, CC->num_msgs);
1389         CC->quickroom.QRhighest = MessageFromList(CC->num_msgs - 1);
1390
1391         put_msglist(&CC->quickroom);
1392         lputroom(&CC->quickroom);
1393         if (ok == 1) {
1394                 AdjRefCount(delnum, -1);
1395                 cprintf("%d Message deleted.\n", OK);
1396         } else
1397                 cprintf("%d No message %ld.\n", ERROR, delnum);
1398 }
1399
1400
1401 /*
1402  * move a message to another room
1403  */
1404 void cmd_move(char *args)
1405 {
1406         long num;
1407         char targ[32];
1408         int a;
1409         struct quickroom qtemp;
1410         int foundit;
1411
1412         num = extract_long(args, 0);
1413         extract(targ, args, 1);
1414
1415         getuser(&CC->usersupp, CC->curr_user);
1416         if ((CC->usersupp.axlevel < 6)
1417             && (CC->usersupp.usernum != CC->quickroom.QRroomaide)) {
1418                 cprintf("%d Higher access required.\n",
1419                         ERROR + HIGHER_ACCESS_REQUIRED);
1420                 return;
1421         }
1422         if (getroom(&qtemp, targ) != 0) {
1423                 cprintf("%d '%s' does not exist.\n", ERROR, targ);
1424                 return;
1425         }
1426         /* yank the message out of the current room... */
1427         lgetroom(&CC->quickroom, CC->quickroom.QRname);
1428         get_msglist(&CC->quickroom);
1429
1430         foundit = 0;
1431         for (a = 0; a < (CC->num_msgs); ++a) {
1432                 if (MessageFromList(a) == num) {
1433                         foundit = 1;
1434                         SetMessageInList(a, 0L);
1435                 }
1436         }
1437         if (foundit) {
1438                 CC->num_msgs = sort_msglist(CC->msglist, CC->num_msgs);
1439                 put_msglist(&CC->quickroom);
1440                 CC->quickroom.QRhighest = MessageFromList((CC->num_msgs) - 1);
1441         }
1442         lputroom(&CC->quickroom);
1443         if (!foundit) {
1444                 cprintf("%d msg %ld does not exist.\n", ERROR, num);
1445                 return;
1446         }
1447         /* put the message into the target room */
1448         lgetroom(&qtemp, targ);
1449         qtemp.QRhighest = AddMessageToRoom(&qtemp, num);
1450         lputroom(&qtemp);
1451
1452         cprintf("%d Message moved.\n", OK);
1453 }
1454
1455
1456
1457 /*
1458  * GetSuppMsgInfo()  -  Get the supplementary record for a message
1459  */
1460 void GetSuppMsgInfo(struct SuppMsgInfo *smibuf, long msgnum)
1461 {
1462
1463         struct cdbdata *cdbsmi;
1464         long TheIndex;
1465
1466         memset(smibuf, 0, sizeof(struct SuppMsgInfo));
1467         smibuf->smi_msgnum = msgnum;
1468         smibuf->smi_refcount = 1;       /* Default reference count is 1 */
1469
1470         /* Use the negative of the message number for its supp record index */
1471         TheIndex = (0L - msgnum);
1472
1473         cdbsmi = cdb_fetch(CDB_MSGMAIN, &TheIndex, sizeof(long));
1474         if (cdbsmi == NULL) {
1475                 return;         /* record not found; go with defaults */
1476         }
1477         memcpy(smibuf, cdbsmi->ptr,
1478                ((cdbsmi->len > sizeof(struct SuppMsgInfo)) ?
1479                 sizeof(struct SuppMsgInfo) : cdbsmi->len));
1480         cdb_free(cdbsmi);
1481         return;
1482 }
1483
1484
1485 /*
1486  * PutSuppMsgInfo()  -  (re)write supplementary record for a message
1487  */
1488 void PutSuppMsgInfo(struct SuppMsgInfo *smibuf)
1489 {
1490         long TheIndex;
1491
1492         /* Use the negative of the message number for its supp record index */
1493         TheIndex = (0L - smibuf->smi_msgnum);
1494
1495         cdb_store(CDB_MSGMAIN,
1496                   &TheIndex, sizeof(long),
1497                   smibuf, sizeof(struct SuppMsgInfo));
1498
1499 }
1500
1501
1502
1503 /*
1504  * AdjRefCount  -  change the reference count for a message;
1505  *                 delete the message if it reaches zero
1506  */
1507 void AdjRefCount(long msgnum, int incr)
1508 {
1509
1510         struct SuppMsgInfo smi;
1511         long delnum;
1512
1513         lprintf(9, "Adjust msg <%ld> ref count by <%d>\n",
1514                 msgnum, incr);
1515
1516         /* This is a *tight* critical section; please keep it that way, as
1517          * it may get called while nested in other critical sections.  
1518          * Complicating this any further will surely cause deadlock!
1519          */
1520         begin_critical_section(S_SUPPMSGMAIN);
1521         GetSuppMsgInfo(&smi, msgnum);
1522         smi.smi_refcount += incr;
1523         PutSuppMsgInfo(&smi);
1524         end_critical_section(S_SUPPMSGMAIN);
1525
1526         lprintf(9, "Ref count for message <%ld> after write is <%d>\n",
1527                 msgnum, smi.smi_refcount);
1528
1529         /* If the reference count is now zero, delete the message
1530          * (and its supplementary record as well).
1531          */
1532         if (smi.smi_refcount == 0) {
1533                 lprintf(9, "Deleting message <%ld>\n", msgnum);
1534                 delnum = msgnum;
1535                 cdb_delete(CDB_MSGMAIN, &delnum, sizeof(long));
1536                 delnum = (0L - msgnum);
1537                 cdb_delete(CDB_MSGMAIN, &delnum, sizeof(long));
1538         }
1539 }