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