Networker reordering; remove / change dependencies
[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 "ctdl_module.h"
93
94
95 /*
96  * Deliver digest messages
97  */
98 void network_deliver_digest(SpoolControl *sc) {
99         char buf[SIZ];
100         int i;
101         struct CtdlMessage *msg = NULL;
102         long msglen;
103         char *recps = NULL;
104         size_t recps_len = SIZ;
105         struct recptypes *valid;
106         namelist *nptr;
107         char bounce_to[256];
108
109         if (sc->num_msgs_spooled < 1) {
110                 fclose(sc->digestfp);
111                 sc->digestfp = NULL;
112                 return;
113         }
114
115         msg = malloc(sizeof(struct CtdlMessage));
116         memset(msg, 0, sizeof(struct CtdlMessage));
117         msg->cm_magic = CTDLMESSAGE_MAGIC;
118         msg->cm_format_type = FMT_RFC822;
119         msg->cm_anon_type = MES_NORMAL;
120
121         sprintf(buf, "%ld", time(NULL));
122         msg->cm_fields['T'] = strdup(buf);
123         msg->cm_fields['A'] = strdup(CC->room.QRname);
124         snprintf(buf, sizeof buf, "[%s]", CC->room.QRname);
125         msg->cm_fields['U'] = strdup(buf);
126         sprintf(buf, "room_%s@%s", CC->room.QRname, config.c_fqdn);
127         for (i=0; buf[i]; ++i) {
128                 if (isspace(buf[i])) buf[i]='_';
129                 buf[i] = tolower(buf[i]);
130         }
131         msg->cm_fields['F'] = strdup(buf);
132         msg->cm_fields['R'] = strdup(buf);
133
134         /* Set the 'List-ID' header */
135         msg->cm_fields['L'] = malloc(1024);
136         snprintf(msg->cm_fields['L'], 1024,
137                 "%s <%ld.list-id.%s>",
138                 CC->room.QRname,
139                 CC->room.QRnumber,
140                 config.c_fqdn
141         );
142
143         /*
144          * Go fetch the contents of the digest
145          */
146         fseek(sc->digestfp, 0L, SEEK_END);
147         msglen = ftell(sc->digestfp);
148
149         msg->cm_fields['M'] = malloc(msglen + 1);
150         fseek(sc->digestfp, 0L, SEEK_SET);
151         fread(msg->cm_fields['M'], (size_t)msglen, 1, sc->digestfp);
152         msg->cm_fields['M'][msglen] = '\0';
153
154         fclose(sc->digestfp);
155         sc->digestfp = NULL;
156
157         /* Now generate the delivery instructions */
158
159         /* 
160          * Figure out how big a buffer we need to allocate
161          */
162         for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
163                 recps_len = recps_len + strlen(nptr->name) + 2;
164         }
165         
166         recps = malloc(recps_len);
167
168         if (recps == NULL) {
169                 syslog(LOG_EMERG, "Cannot allocate %ld bytes for recps...\n", (long)recps_len);
170                 abort();
171         }
172
173         strcpy(recps, "");
174
175         /* Each recipient */
176         for (nptr = sc->digestrecps; nptr != NULL; nptr = nptr->next) {
177                 if (nptr != sc->digestrecps) {
178                         strcat(recps, ",");
179                 }
180                 strcat(recps, nptr->name);
181         }
182
183         /* Where do we want bounces and other noise to be heard?  Surely not the list members! */
184         snprintf(bounce_to, sizeof bounce_to, "room_aide@%s", config.c_fqdn);
185
186         /* Now submit the message */
187         valid = validate_recipients(recps, NULL, 0);
188         free(recps);
189         if (valid != NULL) {
190                 valid->bounce_to = strdup(bounce_to);
191                 valid->envelope_from = strdup(bounce_to);
192                 CtdlSubmitMsg(msg, valid, NULL, 0);
193         }
194         CtdlFreeMessage(msg);
195         free_recipients(valid);
196 }
197
198
199 /*
200  * Deliver list messages to everyone on the list ... efficiently
201  */
202 void network_deliver_list(struct CtdlMessage *msg, SpoolControl *sc) {
203         char *recps = NULL;
204         size_t recps_len = SIZ;
205         struct recptypes *valid;
206         namelist *nptr;
207         char bounce_to[256];
208
209         /* Don't do this if there were no recipients! */
210         if (sc->listrecps == NULL) return;
211
212         /* Now generate the delivery instructions */
213
214         /* 
215          * Figure out how big a buffer we need to allocate
216          */
217         for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
218                 recps_len = recps_len + strlen(nptr->name) + 2;
219         }
220         
221         recps = malloc(recps_len);
222
223         if (recps == NULL) {
224                 syslog(LOG_EMERG, "Cannot allocate %ld bytes for recps...\n", (long)recps_len);
225                 abort();
226         }
227
228         strcpy(recps, "");
229
230         /* Each recipient */
231         for (nptr = sc->listrecps; nptr != NULL; nptr = nptr->next) {
232                 if (nptr != sc->listrecps) {
233                         strcat(recps, ",");
234                 }
235                 strcat(recps, nptr->name);
236         }
237
238         /* Where do we want bounces and other noise to be heard?  Surely not the list members! */
239         snprintf(bounce_to, sizeof bounce_to, "room_aide@%s", config.c_fqdn);
240
241         /* Now submit the message */
242         valid = validate_recipients(recps, NULL, 0);
243         free(recps);
244         if (valid != NULL) {
245                 valid->bounce_to = strdup(bounce_to);
246                 valid->envelope_from = strdup(bounce_to);
247                 CtdlSubmitMsg(msg, valid, NULL, 0);
248                 free_recipients(valid);
249         }
250         /* Do not call CtdlFreeMessage(msg) here; the caller will free it. */
251 }
252
253
254
255
256 /*
257  * Spools out one message from the list.
258  */
259 void network_spool_msg(long msgnum, void *userdata) {
260         SpoolControl *sc;
261         int i;
262         char *newpath = NULL;
263         struct CtdlMessage *msg = NULL;
264         namelist *nptr;
265         maplist *mptr;
266         struct ser_ret sermsg;
267         FILE *fp;
268         char filename[PATH_MAX];
269         char buf[SIZ];
270         int bang = 0;
271         int send = 1;
272         int delete_after_send = 0;      /* Set to 1 to delete after spooling */
273         int ok_to_participate = 0;
274         struct recptypes *valid;
275
276         sc = (SpoolControl *)userdata;
277
278         /*
279          * Process mailing list recipients
280          */
281         if (sc->listrecps != NULL) {
282                 /* Fetch the message.  We're going to need to modify it
283                  * in order to insert the [list name] in it, etc.
284                  */
285                 msg = CtdlFetchMessage(msgnum, 1);
286                 if (msg != NULL) {
287                         int rlen;
288                         char *pCh;
289                         StrBuf *Subject, *FlatSubject;
290
291                         if (msg->cm_fields['V'] == NULL){
292                                 /* local message, no enVelope */
293                                 StrBuf *Buf;
294                                 Buf = NewStrBuf();
295                                 StrBufAppendBufPlain(Buf, msg->cm_fields['O'], -1, 0);
296                                 StrBufAppendBufPlain(Buf, HKEY("@"), 0);
297                                 StrBufAppendBufPlain(Buf, config.c_fqdn, -1, 0);
298                                 
299                                 msg->cm_fields['K'] = SmashStrBuf(&Buf);
300                         }
301                         else {
302                                 msg->cm_fields['K'] = strdup (msg->cm_fields['V']);
303                         }
304                         /* Set the 'List-ID' header */
305                         if (msg->cm_fields['L'] != NULL) {
306                                 free(msg->cm_fields['L']);
307                         }
308                         msg->cm_fields['L'] = malloc(1024);
309                         snprintf(msg->cm_fields['L'], 1024,
310                                 "%s <%ld.list-id.%s>",
311                                 CC->room.QRname,
312                                 CC->room.QRnumber,
313                                 config.c_fqdn
314                         );
315
316                         /* Prepend "[List name]" to the subject */
317                         if (msg->cm_fields['U'] == NULL) {
318                                 Subject = NewStrBufPlain(HKEY("(no subject)"));
319                         }
320                         else {
321                                 Subject = NewStrBufPlain(msg->cm_fields['U'], -1);
322                         }
323                         FlatSubject = NewStrBufPlain(NULL, StrLength(Subject));
324                         StrBuf_RFC822_to_Utf8(FlatSubject, Subject, NULL, NULL);
325
326                         rlen = strlen(CC->room.QRname);
327                         pCh  = strstr(ChrPtr(FlatSubject), CC->room.QRname);
328                         if ((pCh == NULL) ||
329                             (*(pCh + rlen) != ']') ||
330                             (pCh == ChrPtr(FlatSubject)) ||
331                             (*(pCh - 1) != '[')
332                                 )
333                         {
334                                 StrBuf *tmp;
335                                 StrBufPlain(Subject, HKEY("["));
336                                 StrBufAppendBufPlain(Subject, CC->room.QRname, rlen, 0);
337                                 StrBufAppendBufPlain(Subject, HKEY("] "), 0);
338                                 StrBufAppendBuf(Subject, FlatSubject, 0);
339                                 tmp = Subject;  Subject = FlatSubject;  FlatSubject = tmp; /* so we can free the right one... */
340                                 StrBufRFC2047encode(&Subject, FlatSubject);
341                         }
342                         
343                         if (msg->cm_fields['U'] != NULL)
344                                 free (msg->cm_fields['U']);
345                         msg->cm_fields['U'] = SmashStrBuf(&Subject);
346
347                         FreeStrBuf(&FlatSubject);
348
349                         /* else we won't modify the buffer, since the roomname is already here. */
350
351                         /* Set the recipient of the list message to the
352                          * email address of the room itself.
353                          * FIXME ... I want to be able to pick any address
354                          */
355                         if (msg->cm_fields['R'] != NULL) {
356                                 free(msg->cm_fields['R']);
357                         }
358                         msg->cm_fields['R'] = malloc(256);
359                         snprintf(msg->cm_fields['R'], 256,
360                                 "room_%s@%s", CC->room.QRname,
361                                 config.c_fqdn);
362                         for (i=0; msg->cm_fields['R'][i]; ++i) {
363                                 if (isspace(msg->cm_fields['R'][i])) {
364                                         msg->cm_fields['R'][i] = '_';
365                                 }
366                         }
367
368                         /* Handle delivery */
369                         network_deliver_list(msg, sc);
370                         CtdlFreeMessage(msg);
371                 }
372         }
373
374         /*
375          * Process digest recipients
376          */
377         if ((sc->digestrecps != NULL) && (sc->digestfp != NULL)) {
378                 msg = CtdlFetchMessage(msgnum, 1);
379                 if (msg != NULL) {
380                         fprintf(sc->digestfp,   " -----------------------------------"
381                                                 "------------------------------------"
382                                                 "-------\n");
383                         fprintf(sc->digestfp, "From: ");
384                         if (msg->cm_fields['A'] != NULL) {
385                                 fprintf(sc->digestfp, "%s ", msg->cm_fields['A']);
386                         }
387                         if (msg->cm_fields['F'] != NULL) {
388                                 fprintf(sc->digestfp, "<%s> ", msg->cm_fields['F']);
389                         }
390                         else if (msg->cm_fields['N'] != NULL) {
391                                 fprintf(sc->digestfp, "@%s ", msg->cm_fields['N']);
392                         }
393                         fprintf(sc->digestfp, "\n");
394                         if (msg->cm_fields['U'] != NULL) {
395                                 fprintf(sc->digestfp, "Subject: %s\n", msg->cm_fields['U']);
396                         }
397
398                         CC->redirect_buffer = NewStrBufPlain(NULL, SIZ);
399                         
400                         safestrncpy(CC->preferred_formats, "text/plain", sizeof CC->preferred_formats);
401                         CtdlOutputPreLoadedMsg(msg, MT_CITADEL, HEADERS_NONE, 0, 0, 0);
402
403                         StrBufTrim(CC->redirect_buffer);
404                         fwrite(HKEY("\n"), 1, sc->digestfp);
405                         fwrite(SKEY(CC->redirect_buffer), 1, sc->digestfp);
406                         fwrite(HKEY("\n"), 1, sc->digestfp);
407
408                         FreeStrBuf(&CC->redirect_buffer);
409
410                         sc->num_msgs_spooled += 1;
411                         free(msg);
412                 }
413         }
414
415         /*
416          * Process client-side list participations for this room
417          */
418         if (sc->participates != NULL) {
419                 msg = CtdlFetchMessage(msgnum, 1);
420                 if (msg != NULL) {
421
422                         /* Only send messages which originated on our own Citadel
423                          * network, otherwise we'll end up sending the remote
424                          * mailing list's messages back to it, which is rude...
425                          */
426                         ok_to_participate = 0;
427                         if (msg->cm_fields['N'] != NULL) {
428                                 if (!strcasecmp(msg->cm_fields['N'], config.c_nodename)) {
429                                         ok_to_participate = 1;
430                                 }
431                                 if (is_valid_node(NULL, NULL, msg->cm_fields['N']) == 0) {
432                                         ok_to_participate = 1;
433                                 }
434                         }
435                         if (ok_to_participate) {
436                                 if (msg->cm_fields['F'] != NULL) {
437                                         free(msg->cm_fields['F']);
438                                 }
439                                 msg->cm_fields['F'] = malloc(SIZ);
440                                 /* Replace the Internet email address of the actual
441                                 * author with the email address of the room itself,
442                                 * so the remote listserv doesn't reject us.
443                                 * FIXME ... I want to be able to pick any address
444                                 */
445                                 snprintf(msg->cm_fields['F'], SIZ,
446                                         "room_%s@%s", CC->room.QRname,
447                                         config.c_fqdn);
448                                 for (i=0; msg->cm_fields['F'][i]; ++i) {
449                                         if (isspace(msg->cm_fields['F'][i])) {
450                                                 msg->cm_fields['F'][i] = '_';
451                                         }
452                                 }
453
454                                 /* 
455                                  * Figure out how big a buffer we need to allocate
456                                  */
457                                 for (nptr = sc->participates; nptr != NULL; nptr = nptr->next) {
458
459                                         if (msg->cm_fields['R'] == NULL) {
460                                                 free(msg->cm_fields['R']);
461                                         }
462                                         msg->cm_fields['R'] = strdup(nptr->name);
463         
464                                         valid = validate_recipients(nptr->name, NULL, 0);
465                                         CtdlSubmitMsg(msg, valid, "", 0);
466                                         free_recipients(valid);
467                                 }
468                         
469                         }
470                         CtdlFreeMessage(msg);
471                 }
472         }
473         
474         /*
475          * Process IGnet push shares
476          */
477         msg = CtdlFetchMessage(msgnum, 1);
478         if (msg != NULL) {
479                 size_t newpath_len;
480
481                 /* Prepend our node name to the Path field whenever
482                  * sending a message to another IGnet node
483                  */
484                 if (msg->cm_fields['P'] == NULL) {
485                         msg->cm_fields['P'] = strdup("username");
486                 }
487                 newpath_len = strlen(msg->cm_fields['P']) +
488                          strlen(config.c_nodename) + 2;
489                 newpath = malloc(newpath_len);
490                 snprintf(newpath, newpath_len, "%s!%s",
491                          config.c_nodename, msg->cm_fields['P']);
492                 free(msg->cm_fields['P']);
493                 msg->cm_fields['P'] = newpath;
494
495                 /*
496                  * Determine if this message is set to be deleted
497                  * after sending out on the network
498                  */
499                 if (msg->cm_fields['S'] != NULL) {
500                         if (!strcasecmp(msg->cm_fields['S'], "CANCEL")) {
501                                 delete_after_send = 1;
502                         }
503                 }
504
505                 /* Now send it to every node */
506                 if (sc->ignet_push_shares != NULL)
507                   for (mptr = sc->ignet_push_shares; mptr != NULL;
508                     mptr = mptr->next) {
509
510                         send = 1;
511
512                         /* Check for valid node name */
513                         if (is_valid_node(NULL, NULL, mptr->remote_nodename) != 0) {
514                                 syslog(LOG_ERR, "Invalid node <%s>\n", mptr->remote_nodename);
515                                 send = 0;
516                         }
517
518                         /* Check for split horizon */
519                         syslog(LOG_DEBUG, "Path is %s\n", msg->cm_fields['P']);
520                         bang = num_tokens(msg->cm_fields['P'], '!');
521                         if (bang > 1) for (i=0; i<(bang-1); ++i) {
522                                 extract_token(buf, msg->cm_fields['P'], i, '!', sizeof buf);
523                                 syslog(LOG_DEBUG, "Compare <%s> to <%s>\n",
524                                         buf, mptr->remote_nodename) ;
525                                 if (!strcasecmp(buf, mptr->remote_nodename)) {
526                                         send = 0;
527                                         syslog(LOG_DEBUG, "Not sending to %s\n",
528                                                 mptr->remote_nodename);
529                                 }
530                                 else {
531                                         syslog(LOG_DEBUG, "Sending to %s\n", mptr->remote_nodename);
532                                 }
533                         }
534
535                         /* Send the message */
536                         if (send == 1) {
537
538                                 /*
539                                  * Force the message to appear in the correct room
540                                  * on the far end by setting the C field correctly
541                                  */
542                                 if (msg->cm_fields['C'] != NULL) {
543                                         free(msg->cm_fields['C']);
544                                 }
545                                 if (!IsEmptyStr(mptr->remote_roomname)) {
546                                         msg->cm_fields['C'] = strdup(mptr->remote_roomname);
547                                 }
548                                 else {
549                                         msg->cm_fields['C'] = strdup(CC->room.QRname);
550                                 }
551
552                                 /* serialize it for transmission */
553                                 serialize_message(&sermsg, msg);
554                                 if (sermsg.len > 0) {
555
556                                         /* write it to a spool file */
557                                         snprintf(filename, sizeof filename,"%s/%s@%lx%x",
558                                                 ctdl_netout_dir,
559                                                 mptr->remote_nodename,
560                                                 time(NULL),
561                                                 rand()
562                                         );
563                                         syslog(LOG_DEBUG, "Appending to %s\n", filename);
564                                         fp = fopen(filename, "ab");
565                                         if (fp != NULL) {
566                                                 fwrite(sermsg.ser,
567                                                         sermsg.len, 1, fp);
568                                                 fclose(fp);
569                                         }
570                                         else {
571                                                 syslog(LOG_ERR, "%s: %s\n", filename, strerror(errno));
572                                         }
573         
574                                         /* free the serialized version */
575                                         free(sermsg.ser);
576                                 }
577
578                         }
579                 }
580                 CtdlFreeMessage(msg);
581         }
582
583         /* update lastsent */
584         sc->lastsent = msgnum;
585
586         /* Delete this message if delete-after-send is set */
587         if (delete_after_send) {
588                 CtdlDeleteMessages(CC->room.QRname, &msgnum, 1, "");
589         }
590
591 }