b250e6d729869520eaca4804f46e86de3c3950cf
[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-2012 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 void DeleteNodeConf(void *vNode)
97 {
98         NodeConf *Node = (NodeConf*) vNode;
99         FreeStrBuf(&Node->NodeName);
100         FreeStrBuf(&Node->Secret);
101         FreeStrBuf(&Node->Host);
102         FreeStrBuf(&Node->Port);
103         free(Node);
104 }
105
106 NodeConf *NewNode(StrBuf *SerializedNode)
107 {
108         const char *Pos = NULL;
109         NodeConf *Node;
110
111         /* we need at least 4 pipes and some other text so its invalid. */
112         if (StrLength(SerializedNode) < 8)
113                 return NULL;
114         Node = (NodeConf *) malloc(sizeof(NodeConf));
115
116         Node->DeleteMe = 0;
117
118         Node->NodeName=NewStrBuf();
119         StrBufExtract_NextToken(Node->NodeName, SerializedNode, &Pos, '|');
120
121         Node->Secret=NewStrBuf();
122         StrBufExtract_NextToken(Node->Secret, SerializedNode, &Pos, '|');
123
124         Node->Host=NewStrBuf();
125         StrBufExtract_NextToken(Node->Host, SerializedNode, &Pos, '|');
126
127         Node->Port=NewStrBuf();
128         StrBufExtract_NextToken(Node->Port, SerializedNode, &Pos, '|');
129         return Node;
130 }
131
132
133 /*
134  * Load or refresh the Citadel network (IGnet) configuration for this node.
135  */
136 HashList* load_ignetcfg(void)
137 {
138         const char *LinePos;
139         char       *Cfg;
140         StrBuf     *Buf;
141         StrBuf     *LineBuf;
142         HashList   *Hash;
143         NodeConf   *Node;
144
145         Cfg =  CtdlGetSysConfig(IGNETCFG);
146         if ((Cfg == NULL) || IsEmptyStr(Cfg)) {
147                 if (Cfg != NULL)
148                         free(Cfg);
149                 return NULL;
150         }
151
152         Hash = NewHash(1, NULL);
153         Buf = NewStrBufPlain(Cfg, -1);
154         free(Cfg);
155         LineBuf = NewStrBufPlain(NULL, StrLength(Buf));
156         LinePos = NULL;
157         do
158         {
159                 StrBufSipLine(LineBuf, Buf, &LinePos);
160                 if (StrLength(LineBuf) != 0) {
161                         Node = NewNode(LineBuf);
162                         if (Node != NULL) {
163                                 Put(Hash, SKEY(Node->NodeName), Node, DeleteNodeConf);
164                         }
165                 }
166         } while (LinePos != StrBufNOTNULL);
167         FreeStrBuf(&Buf);
168         FreeStrBuf(&LineBuf);
169         return Hash;
170 }
171
172 void DeleteNetMap(void *vNetMap)
173 {
174         NetMap *TheNetMap = (NetMap*) vNetMap;
175         FreeStrBuf(&TheNetMap->NodeName);
176         FreeStrBuf(&TheNetMap->NextHop);
177         free(TheNetMap);
178 }
179
180 NetMap *NewNetMap(StrBuf *SerializedNetMap)
181 {
182         const char *Pos = NULL;
183         NetMap *NM;
184
185         /* we need at least 3 pipes and some other text so its invalid. */
186         if (StrLength(SerializedNetMap) < 6)
187                 return NULL;
188         NM = (NetMap *) malloc(sizeof(NetMap));
189
190         NM->NodeName=NewStrBuf();
191         StrBufExtract_NextToken(NM->NodeName, SerializedNetMap, &Pos, '|');
192
193         NM->lastcontact = StrBufExtractNext_long(SerializedNetMap, &Pos, '|');
194
195         NM->NextHop=NewStrBuf();
196         StrBufExtract_NextToken(NM->NextHop, SerializedNetMap, &Pos, '|');
197
198         return NM;
199 }
200
201 HashList* read_network_map(void)
202 {
203         const char *LinePos;
204         char       *Cfg;
205         StrBuf     *Buf;
206         StrBuf     *LineBuf;
207         HashList   *Hash;
208         NetMap     *TheNetMap;
209
210         Cfg =  CtdlGetSysConfig(IGNETMAP);
211         if ((Cfg == NULL) || IsEmptyStr(Cfg)) {
212                 if (Cfg != NULL)
213                         free(Cfg);
214                 return NULL;
215         }
216
217         Hash = NewHash(1, NULL);
218         Buf = NewStrBufPlain(Cfg, -1);
219         free(Cfg);
220         LineBuf = NewStrBufPlain(NULL, StrLength(Buf));
221         LinePos = NULL;
222         while (StrBufSipLine(Buf, LineBuf, &LinePos))
223         {
224                 TheNetMap = NewNetMap(LineBuf);
225                 if (TheNetMap != NULL) { /* TODO: is the NodeName Uniq? */
226                         Put(Hash, SKEY(TheNetMap->NodeName), TheNetMap, DeleteNetMap);
227                 }
228         }
229         FreeStrBuf(&Buf);
230         FreeStrBuf(&LineBuf);
231         return Hash;
232 }
233
234 StrBuf *SerializeNetworkMap(HashList *Map)
235 {
236         void *vMap;
237         const char *key;
238         long len;
239         StrBuf *Ret = NewStrBuf();
240         HashPos *Pos = GetNewHashPos(Map, 0);
241
242         while (GetNextHashPos(Map, Pos, &len, &key, &vMap))
243         {
244                 NetMap *pMap = (NetMap*) vMap;
245                 StrBufAppendBuf(Ret, pMap->NodeName, 0);
246                 StrBufAppendBufPlain(Ret, HKEY("|"), 0);
247
248                 StrBufAppendPrintf(Ret, "%ld", pMap->lastcontact, 0);
249                 StrBufAppendBufPlain(Ret, HKEY("|"), 0);
250
251                 StrBufAppendBuf(Ret, pMap->NextHop, 0);
252                 StrBufAppendBufPlain(Ret, HKEY("\n"), 0);
253         }
254         DeleteHashPos(&Pos);
255         return Ret;
256 }
257
258
259 /*
260  * Learn topology from path fields
261  */
262 void network_learn_topology(char *node, char *path, HashList *the_netmap, int *netmap_changed)
263 {
264         NetMap *pNM = NULL;
265         void *vptr;
266         char nexthop[256];
267         NetMap *nmptr;
268
269         if (GetHash(the_netmap, node, strlen(node), &vptr) && 
270             (vptr != NULL))/* TODO: is the NodeName Uniq? */
271         {
272                 pNM = (NetMap*)vptr;
273                 extract_token(nexthop, path, 0, '!', sizeof nexthop);
274                 if (!strcmp(nexthop, ChrPtr(pNM->NextHop))) {
275                         pNM->lastcontact = time(NULL);
276                         (*netmap_changed) ++;
277                         return;
278                 }
279         }
280
281         /* If we got here then it's not in the map, so add it. */
282         nmptr = (NetMap *) malloc(sizeof (NetMap));
283         nmptr->NodeName = NewStrBufPlain(node, -1);
284         nmptr->lastcontact = time(NULL);
285         nmptr->NextHop = NewStrBuf ();
286         StrBufExtract_tokenFromStr(nmptr->NextHop, path, strlen(path), 0, '!');
287         /* TODO: is the NodeName Uniq? */
288         Put(the_netmap, SKEY(nmptr->NodeName), nmptr, DeleteNetMap);
289         (*netmap_changed) ++;
290 }
291
292
293 /*
294  * Check the network map and determine whether the supplied node name is
295  * valid.  If it is not a neighbor node, supply the name of a neighbor node
296  * which is the next hop.  If it *is* a neighbor node, we also fill in the
297  * shared secret.
298  */
299 int is_valid_node(const StrBuf **nexthop,
300                   const StrBuf **secret,
301                   StrBuf *node,
302                   HashList *IgnetCfg,
303                   HashList *the_netmap)
304 {
305         void *vNetMap;
306         void *vNodeConf;
307         NodeConf *TheNode;
308         NetMap *TheNetMap;
309
310         if (StrLength(node) == 0) {
311                 return(-1);
312         }
313
314         /*
315          * First try the neighbor nodes
316          */
317         if (GetCount(IgnetCfg) == 0) {
318                 syslog(LOG_INFO, "IgnetCfg is empty!\n");
319                 if (nexthop != NULL) {
320                         *nexthop = NULL;
321                 }
322                 return(-1);
323         }
324
325         /* try to find a neigbour with the name 'node' */
326         if (GetHash(IgnetCfg, SKEY(node), &vNodeConf) && 
327             (vNodeConf != NULL))
328         {
329                 TheNode = (NodeConf*)vNodeConf;
330                 if (secret != NULL)
331                         *secret = TheNode->Secret;
332                 return 0;               /* yup, it's a direct neighbor */
333         }
334
335         /*
336          * If we get to this point we have to see if we know the next hop
337          *//* TODO: is the NodeName Uniq? */
338         if ((GetCount(the_netmap) > 0) &&
339             (GetHash(the_netmap, SKEY(node), &vNetMap)))
340         {
341                 TheNetMap = (NetMap*)vNetMap;
342                 if (nexthop != NULL)
343                         *nexthop = TheNetMap->NextHop;
344                 return(0);
345         }
346
347         /*
348          * If we get to this point, the supplied node name is bogus.
349          */
350         syslog(LOG_ERR, "Invalid node name <%s>\n", ChrPtr(node));
351         return(-1);
352 }
353
354
355 void cmd_gnet(char *argbuf)
356 {
357         char filename[PATH_MAX];
358         char buf[SIZ];
359         FILE *fp;
360
361         if ( (CC->room.QRflags & QR_MAILBOX) && (CC->user.usernum == atol(CC->room.QRname)) ) {
362                 /* users can edit the netconfigs for their own mailbox rooms */
363         }
364         else if (CtdlAccessCheck(ac_room_aide)) return;
365
366         assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
367         cprintf("%d Network settings for room #%ld <%s>\n",
368                 LISTING_FOLLOWS,
369                 CC->room.QRnumber, CC->room.QRname);
370
371         fp = fopen(filename, "r");
372         if (fp != NULL) {
373                 while (fgets(buf, sizeof buf, fp) != NULL) {
374                         buf[strlen(buf)-1] = 0;
375                         cprintf("%s\n", buf);
376                 }
377                 fclose(fp);
378         }
379
380         cprintf("000\n");
381 }
382
383
384 void cmd_snet(char *argbuf) {
385         char tempfilename[PATH_MAX];
386         char filename[PATH_MAX];
387         int TmpFD;
388         StrBuf *Line;
389         struct stat StatBuf;
390         long len;
391         int rc;
392
393         unbuffer_output();
394
395         if ( (CC->room.QRflags & QR_MAILBOX) && (CC->user.usernum == atol(CC->room.QRname)) ) {
396                 /* users can edit the netconfigs for their own mailbox rooms */
397         }
398         else if (CtdlAccessCheck(ac_room_aide)) return;
399
400         len = assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
401         memcpy(tempfilename, filename, len + 1);
402
403         memset(&StatBuf, 0, sizeof(struct stat));
404         if ((stat(filename, &StatBuf)  == -1) || (StatBuf.st_size == 0))
405                 StatBuf.st_size = 80; /* Not there or empty? guess 80 chars line. */
406
407         sprintf(tempfilename + len, ".%d", CC->cs_pid);
408         errno = 0;
409         TmpFD = open(tempfilename, O_CREAT|O_EXCL|O_RDWR, S_IRUSR|S_IWUSR);
410
411         if ((TmpFD > 0) && (errno == 0))
412         {
413                 char *tmp = malloc(StatBuf.st_size * 2);
414                 memset(tmp, ' ', StatBuf.st_size * 2);
415                 rc = write(TmpFD, tmp, StatBuf.st_size * 2);
416                 free(tmp);
417                 if ((rc <= 0) || (rc != StatBuf.st_size * 2))
418                 {
419                         close(TmpFD);
420                         cprintf("%d Unable to allocate the space required for %s: %s\n",
421                                 ERROR + INTERNAL_ERROR,
422                                 tempfilename,
423                                 strerror(errno));
424                         unlink(tempfilename);
425                         return;
426                 }       
427                 lseek(TmpFD, SEEK_SET, 0);
428         }
429         else {
430                 cprintf("%d Unable to allocate the space required for %s: %s\n",
431                         ERROR + INTERNAL_ERROR,
432                         tempfilename,
433                         strerror(errno));
434                 unlink(tempfilename);
435                 return;
436         }
437         Line = NewStrBuf();
438
439         cprintf("%d %s\n", SEND_LISTING, tempfilename);
440
441         len = 0;
442         while (rc = CtdlClientGetLine(Line), 
443                (rc >= 0))
444         {
445                 if ((rc == 3) && (strcmp(ChrPtr(Line), "000") == 0))
446                         break;
447                 StrBufAppendBufPlain(Line, HKEY("\n"), 0);
448                 write(TmpFD, ChrPtr(Line), StrLength(Line));
449                 len += StrLength(Line);
450         }
451         FreeStrBuf(&Line);
452         ftruncate(TmpFD, len);
453         close(TmpFD);
454
455         /* Now copy the temp file to its permanent location.
456          * (We copy instead of link because they may be on different filesystems)
457          */
458         begin_critical_section(S_NETCONFIGS);
459         rename(tempfilename, filename);
460         end_critical_section(S_NETCONFIGS);
461 }
462
463 /*
464  * cmd_netp() - authenticate to the server as another Citadel node polling
465  *            for network traffic
466  */
467 void cmd_netp(char *cmdbuf)
468 {
469         struct CitContext *CCC = CC;
470         HashList *working_ignetcfg;
471         char *node;
472         StrBuf *NodeStr;
473         long nodelen;
474         int v;
475         long lens[2];
476         const char *strs[2];
477
478         const StrBuf *secret = NULL;
479         const StrBuf *nexthop = NULL;
480         char err_buf[SIZ] = "";
481
482         /* Authenticate */
483         node = CCC->curr_user;
484         nodelen = extract_token(CCC->curr_user, cmdbuf, 0, '|', sizeof CCC->curr_user);
485         NodeStr = NewStrBufPlain(node, nodelen);
486         /* load the IGnet Configuration to check node validity */
487         working_ignetcfg = load_ignetcfg();
488         v = is_valid_node(&nexthop, &secret, NodeStr, working_ignetcfg, NULL);
489         if (v != 0) {
490                 snprintf(err_buf, sizeof err_buf,
491                         "An unknown Citadel server called \"%s\" attempted to connect from %s [%s].\n",
492                         node, CCC->cs_host, CCC->cs_addr
493                 );
494                 syslog(LOG_WARNING, "%s", err_buf);
495                 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
496
497                 strs[0] = CCC->cs_addr;
498                 lens[0] = strlen(CCC->cs_addr);
499                 
500                 strs[1] = "SRV_UNKNOWN";
501                 lens[1] = sizeof("SRV_UNKNOWN" - 1);
502
503                 CtdlAideFPMessage(
504                         err_buf,
505                         "IGNet Networking.",
506                         2, strs, (long*) &lens);
507
508                 DeleteHash(&working_ignetcfg);
509                 FreeStrBuf(&NodeStr);
510                 return;
511         }
512
513         extract_token(CCC->user.password, cmdbuf, 1, '|', sizeof CCC->user.password);
514         if (strcasecmp(CCC->user.password, ChrPtr(secret))) {
515                 snprintf(err_buf, sizeof err_buf,
516                         "A Citadel server at %s [%s] failed to authenticate as network node \"%s\".\n",
517                         CCC->cs_host, CCC->cs_addr, node
518                 );
519                 syslog(LOG_WARNING, "%s", err_buf);
520                 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
521
522                 strs[0] = CCC->cs_addr;
523                 lens[0] = strlen(CCC->cs_addr);
524                 
525                 strs[1] = "SRV_PW";
526                 lens[1] = sizeof("SRV_PW" - 1);
527
528                 CtdlAideFPMessage(
529                         err_buf,
530                         "IGNet Networking.",
531                         2, strs, (long*) &lens);
532
533                 DeleteHash(&working_ignetcfg);
534                 FreeStrBuf(&NodeStr);
535                 return;
536         }
537
538         if (network_talking_to(node, nodelen, NTT_CHECK)) {
539                 syslog(LOG_WARNING, "Duplicate session for network node <%s>", node);
540                 cprintf("%d Already talking to %s right now\n", ERROR + RESOURCE_BUSY, node);
541                 DeleteHash(&working_ignetcfg);
542                 FreeStrBuf(&NodeStr);
543                 return;
544         }
545         nodelen = safestrncpy(CCC->net_node, node, sizeof CCC->net_node);
546         network_talking_to(CCC->net_node, nodelen, NTT_ADD);
547         syslog(LOG_NOTICE, "Network node <%s> logged in from %s [%s]\n",
548                 CCC->net_node, CCC->cs_host, CCC->cs_addr
549         );
550         cprintf("%d authenticated as network node '%s'\n", CIT_OK, CCC->net_node);
551         DeleteHash(&working_ignetcfg);
552         FreeStrBuf(&NodeStr);
553 }
554
555 int netconfig_check_roomaccess(
556         char *errmsgbuf, 
557         size_t n,
558         const char* RemoteIdentifier)
559 {
560         SpoolControl *sc;
561         char filename[SIZ];
562         int found;
563
564         if (RemoteIdentifier == NULL)
565         {
566                 snprintf(errmsgbuf, n, "Need sender to permit access.");
567                 return (ERROR + USERNAME_REQUIRED);
568         }
569
570         assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
571         begin_critical_section(S_NETCONFIGS);
572         if (!read_spoolcontrol_file(&sc, filename))
573         {
574                 end_critical_section(S_NETCONFIGS);
575                 snprintf(errmsgbuf, n,
576                          "This mailing list only accepts posts from subscribers.");
577                 return (ERROR + NO_SUCH_USER);
578         }
579         end_critical_section(S_NETCONFIGS);
580         found = is_recipient (sc, RemoteIdentifier);
581         free_spoolcontrol_struct(&sc);
582         if (found) {
583                 return (0);
584         }
585         else {
586                 snprintf(errmsgbuf, n,
587                          "This mailing list only accepts posts from subscribers.");
588                 return (ERROR + NO_SUCH_USER);
589         }
590 }
591 /*
592  * Module entry point
593  */
594 CTDL_MODULE_INIT(netconfig)
595 {
596         if (!threading)
597         {
598                 CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
599                 CtdlRegisterProtoHook(cmd_snet, "SNET", "Set network config");
600                 CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
601         }
602         return "netconfig";
603 }