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