MailQ: remember & display the room for mailingilst Queue-Entries
[citadel.git] / citadel / modules / network / serv_netmail.c
1 /*
2  * This module handles shared rooms, inter-Citadel mail, and outbound
3  * mailing list processing.
4  *
5  * Copyright (c) 2000-2011 by the citadel.org team
6  *
7  *  This program is open source software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; either version 3 of the License, or
10  *  (at your option) any later version.
11  *
12  *  This program is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *  GNU General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License
18  *  along with this program; if not, write to the Free Software
19  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  *
21  * ** NOTE **   A word on the S_NETCONFIGS semaphore:
22  * This is a fairly high-level type of critical section.  It ensures that no
23  * two threads work on the netconfigs files at the same time.  Since we do
24  * so many things inside these, here are the rules:
25  *  1. begin_critical_section(S_NETCONFIGS) *before* begin_ any others.
26  *  2. Do *not* perform any I/O with the client during these sections.
27  *
28  */
29
30 /*
31  * Duration of time (in seconds) after which pending list subscribe/unsubscribe
32  * requests that have not been confirmed will be deleted.
33  */
34 #define EXP     259200  /* three days */
35
36 #include "sysdep.h"
37 #include <stdlib.h>
38 #include <unistd.h>
39 #include <stdio.h>
40 #include <fcntl.h>
41 #include <ctype.h>
42 #include <signal.h>
43 #include <pwd.h>
44 #include <errno.h>
45 #include <sys/stat.h>
46 #include <sys/types.h>
47 #include <dirent.h>
48 #if TIME_WITH_SYS_TIME
49 # include <sys/time.h>
50 # include <time.h>
51 #else
52 # if HAVE_SYS_TIME_H
53 #  include <sys/time.h>
54 # else
55 #  include <time.h>
56 # endif
57 #endif
58 #ifdef HAVE_SYSCALL_H
59 # include <syscall.h>
60 #else
61 # if HAVE_SYS_SYSCALL_H
62 #  include <sys/syscall.h>
63 # endif
64 #endif
65
66 #include <sys/wait.h>
67 #include <string.h>
68 #include <limits.h>
69 #include <libcitadel.h>
70 #include "citadel.h"
71 #include "server.h"
72 #include "citserver.h"
73 #include "support.h"
74 #include "config.h"
75 #include "user_ops.h"
76 #include "database.h"
77 #include "msgbase.h"
78 #include "internet_addressing.h"
79 #include "serv_network.h"
80 #include "clientsocket.h"
81 #include "file_ops.h"
82 #include "citadel_dirs.h"
83 #include "threads.h"
84
85 #ifndef HAVE_SNPRINTF
86 #include "snprintf.h"
87 #endif
88
89 #include "context.h"
90 #include "netconfig.h"
91 #include "netspool.h"
92 #include "netmail.h"
93 #include "ctdl_module.h"
94
95
96 /*
97  * Deliver digest messages
98  */
99 void network_deliver_digest(SpoolControl *sc) {
100         char buf[SIZ];
101         int i;
102         struct CtdlMessage *msg = NULL;
103         long msglen;
104         char *recps = NULL;
105         size_t recps_len = SIZ;
106         struct recptypes *valid;
107         namelist *nptr;
108         char bounce_to[256];
109
110         if (sc->num_msgs_spooled < 1) {
111                 fclose(sc->digestfp);
112                 sc->digestfp = NULL;
113                 return;
114         }
115
116         msg = malloc(sizeof(struct CtdlMessage));
117         memset(msg, 0, sizeof(struct CtdlMessage));
118         msg->cm_magic = CTDLMESSAGE_MAGIC;
119         msg->cm_format_type = FMT_RFC822;
120         msg->cm_anon_type = MES_NORMAL;
121
122         sprintf(buf, "%ld", time(NULL));
123         msg->cm_fields['T'] = strdup(buf);
124         msg->cm_fields['A'] = strdup(CC->room.QRname);
125         snprintf(buf, sizeof buf, "[%s]", CC->room.QRname);
126         msg->cm_fields['U'] = strdup(buf);
127         sprintf(buf, "room_%s@%s", CC->room.QRname, config.c_fqdn);
128         for (i=0; buf[i]; ++i) {
129                 if (isspace(buf[i])) buf[i]='_';
130                 buf[i] = tolower(buf[i]);
131         }
132         msg->cm_fields['F'] = strdup(buf);
133         msg->cm_fields['R'] = strdup(buf);
134
135         /* Set the 'List-ID' header */
136         msg->cm_fields['L'] = malloc(1024);
137         snprintf(msg->cm_fields['L'], 1024,
138                 "%s <%ld.list-id.%s>",
139                 CC->room.QRname,
140                 CC->room.QRnumber,
141                 config.c_fqdn
142         );
143
144         /*
145          * Go fetch the contents of the digest
146          */
147         fseek(sc->digestfp, 0L, SEEK_END);
148         msglen = ftell(sc->digestfp);
149
150         msg->cm_fields['M'] = malloc(msglen + 1);
151         fseek(sc->digestfp, 0L, SEEK_SET);
152         fread(msg->cm_fields['M'], (size_t)msglen, 1, sc->digestfp);
153         msg->cm_fields['M'][msglen] = '\0';
154
155         fclose(sc->digestfp);
156         sc->digestfp = NULL;
157
158         /* Now generate the delivery instructions */
159
160         /*
161          * Figure out how big a buffer we need to allocate
162          */
163         for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
164                 recps_len = recps_len + strlen(nptr->name) + 2;
165         }
166
167         recps = malloc(recps_len);
168
169         if (recps == NULL) {
170                 syslog(LOG_EMERG,
171                        "Cannot allocate %ld bytes for recps...\n",
172                        (long)recps_len);
173                 abort();
174         }
175
176         strcpy(recps, "");
177
178         /* Each recipient */
179         for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
180                 if (nptr != sc->digestrecps) {
181                         strcat(recps, ",");
182                 }
183                 strcat(recps, nptr->name);
184         }
185
186         /* Where do we want bounces and other noise to be heard?
187          *Surely not the list members! */
188         snprintf(bounce_to, sizeof bounce_to, "room_aide@%s", config.c_fqdn);
189
190         /* Now submit the message */
191         valid = validate_recipients(recps, NULL, 0);
192         free(recps);
193         if (valid != NULL) {
194                 valid->bounce_to = strdup(bounce_to);
195                 valid->envelope_from = strdup(bounce_to);
196                 CtdlSubmitMsg(msg, valid, NULL, 0);
197         }
198         CtdlFreeMessage(msg);
199         free_recipients(valid);
200 }
201
202
203 /*
204  * Deliver list messages to everyone on the list ... efficiently
205  */
206 void network_deliver_list(struct CtdlMessage *msg, SpoolControl *sc, const char *RoomName) {
207         char *recps = NULL;
208         size_t recps_len = SIZ;
209         struct recptypes *valid;
210         namelist *nptr;
211         char bounce_to[256];
212
213         /* Don't do this if there were no recipients! */
214         if (sc->listrecps == NULL) return;
215
216         /* Now generate the delivery instructions */
217
218         /*
219          * Figure out how big a buffer we need to allocate
220          */
221         for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
222                 recps_len = recps_len + strlen(nptr->name) + 2;
223         }
224
225         recps = malloc(recps_len);
226
227         if (recps == NULL) {
228                 syslog(LOG_EMERG,
229                        "Cannot allocate %ld bytes for recps...\n",
230                        (long)recps_len);
231                 abort();
232         }
233
234         strcpy(recps, "");
235
236         /* Each recipient */
237         for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
238                 if (nptr != sc->listrecps) {
239                         strcat(recps, ",");
240                 }
241                 strcat(recps, nptr->name);
242         }
243
244         /* Where do we want bounces and other noise to be heard?
245          *  Surely not the list members! */
246         snprintf(bounce_to, sizeof bounce_to, "room_aide@%s", config.c_fqdn);
247
248         /* Now submit the message */
249         valid = validate_recipients(recps, NULL, 0);
250         free(recps);
251         if (valid != NULL) {
252                 valid->bounce_to = strdup(bounce_to);
253                 valid->envelope_from = strdup(bounce_to);
254                 valid->sending_room = strdup(RoomName);
255                 CtdlSubmitMsg(msg, valid, NULL, 0);
256                 free_recipients(valid);
257         }
258         /* Do not call CtdlFreeMessage(msg) here; the caller will free it. */
259 }
260
261
262 /*
263  * Spools out one message from the list.
264  */
265 void network_spool_msg(long msgnum,
266                        void *userdata)
267 {
268         SpoolControl *sc;
269         int i;
270         char *newpath = NULL;
271         struct CtdlMessage *msg = NULL;
272         namelist *nptr;
273         maplist *mptr;
274         struct ser_ret sermsg;
275         FILE *fp;
276         char filename[PATH_MAX];
277         char buf[SIZ];
278         int bang = 0;
279         int send = 1;
280         int delete_after_send = 0;      /* Set to 1 to delete after spooling */
281         int ok_to_participate = 0;
282         struct recptypes *valid;
283
284         sc = (SpoolControl *)userdata;
285
286         /*
287          * Process mailing list recipients
288          */
289         if (sc->listrecps != NULL) {
290                 /* Fetch the message.  We're going to need to modify it
291                  * in order to insert the [list name] in it, etc.
292                  */
293                 msg = CtdlFetchMessage(msgnum, 1);
294                 if (msg != NULL) {
295                         int rlen;
296                         char *pCh;
297                         StrBuf *Subject, *FlatSubject;
298
299                         if (msg->cm_fields['K'] != NULL)
300                                 free(msg->cm_fields['K']);
301                         if (msg->cm_fields['V'] == NULL){
302                                 /* local message, no enVelope */
303                                 StrBuf *Buf;
304                                 Buf = NewStrBuf();
305                                 StrBufAppendBufPlain(Buf,
306                                                      msg->cm_fields['O']
307                                                      , -1, 0);
308                                 StrBufAppendBufPlain(Buf, HKEY("@"), 0);
309                                 StrBufAppendBufPlain(Buf, config.c_fqdn, -1, 0);
310
311                                 msg->cm_fields['K'] = SmashStrBuf(&Buf);
312                         }
313                         else {
314                                 msg->cm_fields['K'] =
315                                         strdup (msg->cm_fields['V']);
316                         }
317                         /* Set the 'List-ID' header */
318                         if (msg->cm_fields['L'] != NULL) {
319                                 free(msg->cm_fields['L']);
320                         }
321                         msg->cm_fields['L'] = malloc(1024);
322                         snprintf(msg->cm_fields['L'], 1024,
323                                 "%s <%ld.list-id.%s>",
324                                 CC->room.QRname,
325                                 CC->room.QRnumber,
326                                 config.c_fqdn
327                         );
328
329                         /* Prepend "[List name]" to the subject */
330                         if (msg->cm_fields['U'] == NULL) {
331                                 Subject = NewStrBufPlain(HKEY("(no subject)"));
332                         }
333                         else {
334                                 Subject = NewStrBufPlain(
335                                         msg->cm_fields['U'], -1);
336                         }
337                         FlatSubject = NewStrBufPlain(NULL, StrLength(Subject));
338                         StrBuf_RFC822_to_Utf8(FlatSubject, Subject, NULL, NULL);
339
340                         rlen = strlen(CC->room.QRname);
341                         pCh  = strstr(ChrPtr(FlatSubject), CC->room.QRname);
342                         if ((pCh == NULL) ||
343                             (*(pCh + rlen) != ']') ||
344                             (pCh == ChrPtr(FlatSubject)) ||
345                             (*(pCh - 1) != '[')
346                                 )
347                         {
348                                 StrBuf *tmp;
349                                 StrBufPlain(Subject, HKEY("["));
350                                 StrBufAppendBufPlain(Subject,
351                                                      CC->room.QRname,
352                                                      rlen, 0);
353                                 StrBufAppendBufPlain(Subject, HKEY("] "), 0);
354                                 StrBufAppendBuf(Subject, FlatSubject, 0);
355                                  /* so we can free the right one swap them */
356                                 tmp = Subject;
357                                 Subject = FlatSubject;
358                                 FlatSubject = tmp;
359                                 StrBufRFC2047encode(&Subject, FlatSubject);
360                         }
361
362                         if (msg->cm_fields['U'] != NULL)
363                                 free (msg->cm_fields['U']);
364                         msg->cm_fields['U'] = SmashStrBuf(&Subject);
365
366                         FreeStrBuf(&FlatSubject);
367
368                         /* else we won't modify the buffer, since the
369                          * roomname is already here.
370                          */
371
372                         /* if there is no other recipient, Set the recipient
373                          * of the list message to the email address of the
374                          * room itself.
375                          */
376                         if ((msg->cm_fields['R'] == NULL) ||
377                             IsEmptyStr(msg->cm_fields['R']))
378                         {
379                                 if (msg->cm_fields['R'] != NULL)
380                                         free(msg->cm_fields['R']);
381
382                                 msg->cm_fields['R'] = malloc(256);
383                                 snprintf(msg->cm_fields['R'], 256,
384                                          "room_%s@%s", CC->room.QRname,
385                                          config.c_fqdn);
386                                 for (i=0; msg->cm_fields['R'][i]; ++i) {
387                                         if (isspace(msg->cm_fields['R'][i])) {
388                                                 msg->cm_fields['R'][i] = '_';
389                                         }
390                                 }
391                         }
392
393                         /* Handle delivery */
394                         network_deliver_list(msg, sc, CC->room.QRname);
395                         CtdlFreeMessage(msg);
396                 }
397         }
398
399         /*
400          * Process digest recipients
401          */
402         if ((sc->digestrecps != NULL) && (sc->digestfp != NULL)) {
403                 msg = CtdlFetchMessage(msgnum, 1);
404                 if (msg != NULL) {
405                         fprintf(sc->digestfp,
406                                 " -----------------------------------"
407                                 "------------------------------------"
408                                 "-------\n");
409                         fprintf(sc->digestfp, "From: ");
410                         if (msg->cm_fields['A'] != NULL) {
411                                 fprintf(sc->digestfp,
412                                         "%s ",
413                                         msg->cm_fields['A']);
414                         }
415                         if (msg->cm_fields['F'] != NULL) {
416                                 fprintf(sc->digestfp,
417                                         "<%s> ",
418                                         msg->cm_fields['F']);
419                         }
420                         else if (msg->cm_fields['N'] != NULL) {
421                                 fprintf(sc->digestfp,
422                                         "@%s ",
423                                         msg->cm_fields['N']);
424                         }
425                         fprintf(sc->digestfp, "\n");
426                         if (msg->cm_fields['U'] != NULL) {
427                                 fprintf(sc->digestfp,
428                                         "Subject: %s\n",
429                                         msg->cm_fields['U']);
430                         }
431
432                         CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
433
434                         safestrncpy(CC->preferred_formats,
435                                     "text/plain",
436                                     sizeof CC->preferred_formats);
437
438                         CtdlOutputPreLoadedMsg(msg,
439                                                MT_CITADEL,
440                                                HEADERS_NONE,
441                                                0, 0, 0);
442
443                         StrBufTrim(CC->redirect_buffer);
444                         fwrite(HKEY("\n"), 1, sc->digestfp);
445                         fwrite(SKEY(CC->redirect_buffer), 1, sc->digestfp);
446                         fwrite(HKEY("\n"), 1, sc->digestfp);
447
448                         FreeStrBuf(&CC->redirect_buffer);
449
450                         sc->num_msgs_spooled += 1;
451                         CtdlFreeMessage(msg);
452                 }
453         }
454
455         /*
456          * Process client-side list participations for this room
457          */
458         if (sc->participates != NULL) {
459                 msg = CtdlFetchMessage(msgnum, 1);
460                 if (msg != NULL) {
461
462                         /* Only send messages which originated on our own
463                          * Citadel network, otherwise we'll end up sending the
464                          * remote mailing list's messages back to it, which
465                          * is rude...
466                          */
467                         ok_to_participate = 0;
468                         if (msg->cm_fields['N'] != NULL) {
469                                 if (!strcasecmp(msg->cm_fields['N'],
470                                                 config.c_nodename)) {
471                                         ok_to_participate = 1;
472                                 }
473                                 if (is_valid_node(NULL,
474                                                   NULL,
475                                                   msg->cm_fields['N'],
476                                                   sc->working_ignetcfg,
477                                                   sc->the_netmap) == 0)
478                                 {
479                                         ok_to_participate = 1;
480                                 }
481                         }
482                         if (ok_to_participate) {
483                                 if (msg->cm_fields['F'] != NULL) {
484                                         free(msg->cm_fields['F']);
485                                 }
486                                 msg->cm_fields['F'] = malloc(SIZ);
487                                 /* Replace the Internet email address of the
488                                  * actual author with the email address of the
489                                  * room itself, so the remote listserv doesn't
490                                  * reject us.
491                                  * FIXME  I want to be able to pick any address
492                                 */
493                                 snprintf(msg->cm_fields['F'], SIZ,
494                                         "room_%s@%s", CC->room.QRname,
495                                         config.c_fqdn);
496                                 for (i=0; msg->cm_fields['F'][i]; ++i) {
497                                         if (isspace(msg->cm_fields['F'][i])) {
498                                                 msg->cm_fields['F'][i] = '_';
499                                         }
500                                 }
501
502                                 /*
503                                  * Figure out how big a buffer we need to alloc
504                                  */
505                                 for (nptr = sc->participates;
506                                      nptr != NULL;
507                                      nptr = nptr->next)
508                                 {
509                                         if (msg->cm_fields['R'] != NULL) {
510                                                 free(msg->cm_fields['R']);
511                                         }
512                                         msg->cm_fields['R'] =
513                                                 strdup(nptr->name);
514
515                                         valid = validate_recipients(nptr->name,
516                                                                     NULL, 0);
517
518                                         CtdlSubmitMsg(msg, valid, "", 0);
519                                         free_recipients(valid);
520                                 }
521                         }
522                         CtdlFreeMessage(msg);
523                 }
524         }
525
526         /*
527          * Process IGnet push shares
528          */
529         msg = CtdlFetchMessage(msgnum, 1);
530         if (msg != NULL) {
531                 size_t newpath_len;
532
533                 /* Prepend our node name to the Path field whenever
534                  * sending a message to another IGnet node
535                  */
536                 if (msg->cm_fields['P'] == NULL) {
537                         msg->cm_fields['P'] = strdup("username");
538                 }
539                 newpath_len = strlen(msg->cm_fields['P']) +
540                          strlen(config.c_nodename) + 2;
541                 newpath = malloc(newpath_len);
542                 snprintf(newpath, newpath_len, "%s!%s",
543                          config.c_nodename, msg->cm_fields['P']);
544                 free(msg->cm_fields['P']);
545                 msg->cm_fields['P'] = newpath;
546
547                 /*
548                  * Determine if this message is set to be deleted
549                  * after sending out on the network
550                  */
551                 if (msg->cm_fields['S'] != NULL) {
552                         if (!strcasecmp(msg->cm_fields['S'], "CANCEL")) {
553                                 delete_after_send = 1;
554                         }
555                 }
556
557                 /* Now send it to every node */
558                 if (sc->ignet_push_shares != NULL)
559                   for (mptr = sc->ignet_push_shares; mptr != NULL;
560                     mptr = mptr->next) {
561
562                         send = 1;
563
564                         /* Check for valid node name */
565                         if (is_valid_node(NULL,
566                                           NULL,
567                                           mptr->remote_nodename,
568                                           sc->working_ignetcfg,
569                                           sc->the_netmap) != 0)
570                         {
571                                 syslog(LOG_ERR,
572                                        "Invalid node <%s>\n",
573                                        mptr->remote_nodename);
574
575                                 send = 0;
576                         }
577
578                         /* Check for split horizon */
579                         syslog(LOG_DEBUG, "Path is %s\n", msg->cm_fields['P']);
580                         bang = num_tokens(msg->cm_fields['P'], '!');
581                         if (bang > 1) for (i=0; i<(bang-1); ++i) {
582                                 extract_token(buf,
583                                               msg->cm_fields['P'],
584                                               i, '!',
585                                               sizeof buf);
586
587                                 syslog(LOG_DEBUG, "Compare <%s> to <%s>\n",
588                                         buf, mptr->remote_nodename) ;
589                                 if (!strcasecmp(buf, mptr->remote_nodename)) {
590                                         send = 0;
591                                         syslog(LOG_DEBUG, "Not sending to %s\n",
592                                                 mptr->remote_nodename);
593                                 }
594                                 else {
595                                         syslog(LOG_DEBUG,
596                                                "Sending to %s\n",
597                                                mptr->remote_nodename);
598                                 }
599                         }
600
601                         /* Send the message */
602                         if (send == 1)
603                         {
604                                 /*
605                                  * Force the message to appear in the correct
606                                  * room on the far end by setting the C field
607                                  * correctly
608                                  */
609                                 if (msg->cm_fields['C'] != NULL) {
610                                         free(msg->cm_fields['C']);
611                                 }
612                                 if (!IsEmptyStr(mptr->remote_roomname)) {
613                                         msg->cm_fields['C'] =
614                                                 strdup(mptr->remote_roomname);
615                                 }
616                                 else {
617                                         msg->cm_fields['C'] =
618                                                 strdup(CC->room.QRname);
619                                 }
620
621                                 /* serialize it for transmission */
622                                 serialize_message(&sermsg, msg);
623                                 if (sermsg.len > 0) {
624
625                                         /* write it to a spool file */
626                                         snprintf(filename,
627                                                  sizeof(filename),
628                                                  "%s/%s@%lx%x",
629                                                  ctdl_netout_dir,
630                                                  mptr->remote_nodename,
631                                                  time(NULL),
632                                                  rand()
633                                         );
634
635                                         syslog(LOG_DEBUG,
636                                                "Appending to %s\n",
637                                                filename);
638
639                                         fp = fopen(filename, "ab");
640                                         if (fp != NULL) {
641                                                 fwrite(sermsg.ser,
642                                                         sermsg.len, 1, fp);
643                                                 fclose(fp);
644                                         }
645                                         else {
646                                                 syslog(LOG_ERR,
647                                                        "%s: %s\n",
648                                                        filename,
649                                                        strerror(errno));
650                                         }
651
652                                         /* free the serialized version */
653                                         free(sermsg.ser);
654                                 }
655
656                         }
657                 }
658                 CtdlFreeMessage(msg);
659         }
660
661         /* update lastsent */
662         sc->lastsent = msgnum;
663
664         /* Delete this message if delete-after-send is set */
665         if (delete_after_send) {
666                 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "");
667         }
668
669 }