Networker reordering; remove / change dependencies
[citadel.git] / citadel / modules / network / serv_netconfig.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  * We build a map of network nodes during processing.
97  */
98 NetMap *the_netmap = NULL;
99 int netmap_changed = 0;
100 char *working_ignetcfg = NULL;
101
102 /*
103  * Load or refresh the Citadel network (IGnet) configuration for this node.
104  */
105 void load_working_ignetcfg(void) {
106         char *cfg;
107         char *oldcfg;
108
109         cfg = CtdlGetSysConfig(IGNETCFG);
110         if (cfg == NULL) {
111                 cfg = strdup("");
112         }
113
114         oldcfg = working_ignetcfg;
115         working_ignetcfg = cfg;
116         if (oldcfg != NULL) {
117                 free(oldcfg);
118         }
119 }
120
121 /* 
122  * Read the network map from its configuration file into memory.
123  */
124 void read_network_map(void) {
125         char *serialized_map = NULL;
126         int i;
127         char buf[SIZ];
128         NetMap *nmptr;
129
130         serialized_map = CtdlGetSysConfig(IGNETMAP);
131         if (serialized_map == NULL) return;     /* if null, no entries */
132
133         /* Use the string tokenizer to grab one line at a time */
134         for (i=0; i<num_tokens(serialized_map, '\n'); ++i) {
135                 extract_token(buf, serialized_map, i, '\n', sizeof buf);
136                 nmptr = (NetMap *) malloc(sizeof(NetMap));
137                 extract_token(nmptr->nodename, buf, 0, '|', sizeof nmptr->nodename);
138                 nmptr->lastcontact = extract_long(buf, 1);
139                 extract_token(nmptr->nexthop, buf, 2, '|', sizeof nmptr->nexthop);
140                 nmptr->next = the_netmap;
141                 the_netmap = nmptr;
142         }
143
144         free(serialized_map);
145         netmap_changed = 0;
146 }
147
148
149 /*
150  * Write the network map from memory back to the configuration file.
151  */
152 void write_network_map(void) {
153         char *serialized_map = NULL;
154         NetMap *nmptr;
155
156
157         if (netmap_changed) {
158                 serialized_map = strdup("");
159         
160                 if (the_netmap != NULL) {
161                         for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
162                                 serialized_map = realloc(serialized_map,
163                                                         (strlen(serialized_map)+SIZ) );
164                                 if (!IsEmptyStr(nmptr->nodename)) {
165                                         snprintf(&serialized_map[strlen(serialized_map)],
166                                                 SIZ,
167                                                 "%s|%ld|%s\n",
168                                                 nmptr->nodename,
169                                                 (long)nmptr->lastcontact,
170                                                 nmptr->nexthop);
171                                 }
172                         }
173                 }
174
175                 CtdlPutSysConfig(IGNETMAP, serialized_map);
176                 free(serialized_map);
177         }
178
179         /* Now free the list */
180         while (the_netmap != NULL) {
181                 nmptr = the_netmap->next;
182                 free(the_netmap);
183                 the_netmap = nmptr;
184         }
185         netmap_changed = 0;
186 }
187
188
189 /* 
190  * Check the network map and determine whether the supplied node name is
191  * valid.  If it is not a neighbor node, supply the name of a neighbor node
192  * which is the next hop.  If it *is* a neighbor node, we also fill in the
193  * shared secret.
194  */
195 int is_valid_node(char *nexthop, char *secret, char *node) {
196         int i;
197         char linebuf[SIZ];
198         char buf[SIZ];
199         int retval;
200         NetMap *nmptr;
201
202         if (node == NULL) {
203                 return(-1);
204         }
205
206         /*
207          * First try the neighbor nodes
208          */
209         if (working_ignetcfg == NULL) {
210                 syslog(LOG_ERR, "working_ignetcfg is NULL!\n");
211                 if (nexthop != NULL) {
212                         strcpy(nexthop, "");
213                 }
214                 return(-1);
215         }
216
217         retval = (-1);
218         if (nexthop != NULL) {
219                 strcpy(nexthop, "");
220         }
221
222         /* Use the string tokenizer to grab one line at a time */
223         for (i=0; i<num_tokens(working_ignetcfg, '\n'); ++i) {
224                 extract_token(linebuf, working_ignetcfg, i, '\n', sizeof linebuf);
225                 extract_token(buf, linebuf, 0, '|', sizeof buf);
226                 if (!strcasecmp(buf, node)) {
227                         if (nexthop != NULL) {
228                                 strcpy(nexthop, "");
229                         }
230                         if (secret != NULL) {
231                                 extract_token(secret, linebuf, 1, '|', 256);
232                         }
233                         retval = 0;
234                 }
235         }
236
237         if (retval == 0) {
238                 return(retval);         /* yup, it's a direct neighbor */
239         }
240
241         /*      
242          * If we get to this point we have to see if we know the next hop
243          */
244         if (the_netmap != NULL) {
245                 for (nmptr = the_netmap; nmptr != NULL; nmptr = nmptr->next) {
246                         if (!strcasecmp(nmptr->nodename, node)) {
247                                 if (nexthop != NULL) {
248                                         strcpy(nexthop, nmptr->nexthop);
249                                 }
250                                 return(0);
251                         }
252                 }
253         }
254
255         /*
256          * If we get to this point, the supplied node name is bogus.
257          */
258         syslog(LOG_ERR, "Invalid node name <%s>\n", node);
259         return(-1);
260 }
261
262
263
264 void cmd_gnet(char *argbuf) {
265         char filename[PATH_MAX];
266         char buf[SIZ];
267         FILE *fp;
268
269         if ( (CC->room.QRflags & QR_MAILBOX) && (CC->user.usernum == atol(CC->room.QRname)) ) {
270                 /* users can edit the netconfigs for their own mailbox rooms */
271         }
272         else if (CtdlAccessCheck(ac_room_aide)) return;
273
274         assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
275         cprintf("%d Network settings for room #%ld <%s>\n",
276                 LISTING_FOLLOWS,
277                 CC->room.QRnumber, CC->room.QRname);
278
279         fp = fopen(filename, "r");
280         if (fp != NULL) {
281                 while (fgets(buf, sizeof buf, fp) != NULL) {
282                         buf[strlen(buf)-1] = 0;
283                         cprintf("%s\n", buf);
284                 }
285                 fclose(fp);
286         }
287
288         cprintf("000\n");
289 }
290
291
292 void cmd_snet(char *argbuf) {
293         char tempfilename[PATH_MAX];
294         char filename[PATH_MAX];
295         int TmpFD;
296         StrBuf *Line;
297         struct stat StatBuf;
298         long len;
299         int rc;
300
301         unbuffer_output();
302
303         if ( (CC->room.QRflags & QR_MAILBOX) && (CC->user.usernum == atol(CC->room.QRname)) ) {
304                 /* users can edit the netconfigs for their own mailbox rooms */
305         }
306         else if (CtdlAccessCheck(ac_room_aide)) return;
307
308         len = assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
309         memcpy(tempfilename, filename, len + 1);
310
311         memset(&StatBuf, 0, sizeof(struct stat));
312         if ((stat(filename, &StatBuf)  == -1) || (StatBuf.st_size == 0))
313                 StatBuf.st_size = 80; /* Not there or empty? guess 80 chars line. */
314
315         sprintf(tempfilename + len, ".%d", CC->cs_pid);
316         errno = 0;
317         TmpFD = open(tempfilename, O_CREAT|O_EXCL|O_RDWR, S_IRUSR|S_IWUSR);
318
319         if ((TmpFD > 0) && (errno == 0))
320         {
321                 char *tmp = malloc(StatBuf.st_size * 2);
322                 memset(tmp, ' ', StatBuf.st_size * 2);
323                 rc = write(TmpFD, tmp, StatBuf.st_size * 2);
324                 free(tmp);
325                 if ((rc <= 0) || (rc != StatBuf.st_size * 2))
326                 {
327                         close(TmpFD);
328                         cprintf("%d Unable to allocate the space required for %s: %s\n",
329                                 ERROR + INTERNAL_ERROR,
330                                 tempfilename,
331                                 strerror(errno));
332                         unlink(tempfilename);
333                         return;
334                 }       
335                 lseek(TmpFD, SEEK_SET, 0);
336         }
337         else {
338                 cprintf("%d Unable to allocate the space required for %s: %s\n",
339                         ERROR + INTERNAL_ERROR,
340                         tempfilename,
341                         strerror(errno));
342                 unlink(tempfilename);
343                 return;
344         }
345         Line = NewStrBuf();
346
347         cprintf("%d %s\n", SEND_LISTING, tempfilename);
348
349         len = 0;
350         while (rc = CtdlClientGetLine(Line), 
351                (rc >= 0))
352         {
353                 if ((rc == 3) && (strcmp(ChrPtr(Line), "000") == 0))
354                         break;
355                 StrBufAppendBufPlain(Line, HKEY("\n"), 0);
356                 write(TmpFD, ChrPtr(Line), StrLength(Line));
357                 len += StrLength(Line);
358         }
359         FreeStrBuf(&Line);
360         ftruncate(TmpFD, len);
361         close(TmpFD);
362
363         /* Now copy the temp file to its permanent location.
364          * (We copy instead of link because they may be on different filesystems)
365          */
366         begin_critical_section(S_NETCONFIGS);
367         rename(tempfilename, filename);
368         end_critical_section(S_NETCONFIGS);
369 }
370
371 /*
372  * cmd_netp() - authenticate to the server as another Citadel node polling
373  *            for network traffic
374  */
375 void cmd_netp(char *cmdbuf)
376 {
377         char node[256];
378         char pass[256];
379         int v;
380
381         char secret[256];
382         char nexthop[256];
383         char err_buf[SIZ];
384
385         /* Authenticate */
386         extract_token(node, cmdbuf, 0, '|', sizeof node);
387         extract_token(pass, cmdbuf, 1, '|', sizeof pass);
388
389         /* load the IGnet Configuration to check node validity */
390         load_working_ignetcfg();
391         v = is_valid_node(nexthop, secret, node);
392
393         if (v != 0) {
394                 snprintf(err_buf, sizeof err_buf,
395                         "An unknown Citadel server called \"%s\" attempted to connect from %s [%s].\n",
396                         node, CC->cs_host, CC->cs_addr
397                 );
398                 syslog(LOG_WARNING, "%s", err_buf);
399                 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
400                 CtdlAideMessage(err_buf, "IGNet Networking.");
401                 return;
402         }
403
404         if (strcasecmp(pass, secret)) {
405                 snprintf(err_buf, sizeof err_buf,
406                         "A Citadel server at %s [%s] failed to authenticate as network node \"%s\".\n",
407                         CC->cs_host, CC->cs_addr, node
408                 );
409                 syslog(LOG_WARNING, "%s", err_buf);
410                 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
411                 CtdlAideMessage(err_buf, "IGNet Networking.");
412                 return;
413         }
414
415         if (network_talking_to(node, NTT_CHECK)) {
416                 syslog(LOG_WARNING, "Duplicate session for network node <%s>", node);
417                 cprintf("%d Already talking to %s right now\n", ERROR + RESOURCE_BUSY, node);
418                 return;
419         }
420
421         safestrncpy(CC->net_node, node, sizeof CC->net_node);
422         network_talking_to(node, NTT_ADD);
423         syslog(LOG_NOTICE, "Network node <%s> logged in from %s [%s]\n",
424                 CC->net_node, CC->cs_host, CC->cs_addr
425         );
426         cprintf("%d authenticated as network node '%s'\n", CIT_OK, CC->net_node);
427 }
428
429 int netconfig_check_roomaccess(
430         char *errmsgbuf, 
431         size_t n,
432         const char* RemoteIdentifier)
433 {
434         SpoolControl *sc;
435         char filename[SIZ];
436         int found;
437
438         if (RemoteIdentifier == NULL)
439         {
440                 snprintf(errmsgbuf, n, "Need sender to permit access.");
441                 return (ERROR + USERNAME_REQUIRED);
442         }
443
444         assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
445         begin_critical_section(S_NETCONFIGS);
446         if (!read_spoolcontrol_file(&sc, filename))
447         {
448                 end_critical_section(S_NETCONFIGS);
449                 snprintf(errmsgbuf, n,
450                          "This mailing list only accepts posts from subscribers.");
451                 return (ERROR + NO_SUCH_USER);
452         }
453         end_critical_section(S_NETCONFIGS);
454         found = is_recipient (sc, RemoteIdentifier);
455         free_spoolcontrol_struct(&sc);
456         if (found) {
457                 return (0);
458         }
459         else {
460                 snprintf(errmsgbuf, n,
461                          "This mailing list only accepts posts from subscribers.");
462                 return (ERROR + NO_SUCH_USER);
463         }
464 }
465 /*
466  * Module entry point
467  */
468 CTDL_MODULE_INIT(netconfig)
469 {
470         if (!threading)
471         {
472                 CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
473                 CtdlRegisterProtoHook(cmd_snet, "SNET", "Set network config");
474                 CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
475         }
476         return "netconfig";
477 }