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