239796981111497f49a17efc57b359b698a6585e
[citadel.git] / citadel / netconfig.c
1 /*
2  * This module handles shared rooms, inter-Citadel mail, and outbound
3  * mailing list processing.
4  *
5  * Copyright (c) 2000-2016 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, version 3.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  */
16
17 #include "sysdep.h"
18 #include <stdio.h>
19 #include <sys/types.h>
20 #include <dirent.h>
21
22 #ifdef HAVE_SYSCALL_H
23 # include <syscall.h>
24 #else 
25 # if HAVE_SYS_SYSCALL_H
26 #  include <sys/syscall.h>
27 # endif
28 #endif
29 #include <dirent.h>
30 #include <assert.h>
31
32 #include <libcitadel.h>
33
34 #include "include/ctdl_module.h"
35 #include "serv_extensions.h"
36 #include "config.h"
37
38 void vFreeRoomNetworkStruct(void *vOneRoomNetCfg);
39 void FreeRoomNetworkStructContent(OneRoomNetCfg *OneRNCfg);
40
41 HashList *CfgTypeHash = NULL;
42
43 /*-----------------------------------------------------------------------------*
44  *                       Per room network configs                              *
45  *-----------------------------------------------------------------------------*/
46
47
48 void RegisterRoomCfgType(const char* Name, long len, RoomNetCfg eCfg, CfgLineParser p, int uniq,  int nSegments, CfgLineSerializer s, CfgLineDeAllocator d)
49 {
50         CfgLineType *pCfg;
51
52         pCfg = (CfgLineType*) malloc(sizeof(CfgLineType));
53         pCfg->Parser = p;
54         pCfg->Serializer = s;
55         pCfg->DeAllocator = d;
56         pCfg->C = eCfg;
57         pCfg->Str.Key = Name;
58         pCfg->Str.len = len;
59         pCfg->IsSingleLine = uniq;
60         pCfg->nSegments = nSegments;
61         if (CfgTypeHash == NULL) {
62                 CfgTypeHash = NewHash(1, NULL);
63         }
64         Put(CfgTypeHash, Name, len, pCfg, NULL);
65 }
66
67
68 const CfgLineType *GetCfgTypeByStr(const char *Key, long len)
69 {
70         void *pv;
71         
72         if (GetHash(CfgTypeHash, Key, len, &pv) && (pv != NULL))
73         {
74                 return (const CfgLineType *) pv;
75         }
76         else
77         {
78                 return NULL;
79         }
80 }
81
82 const CfgLineType *GetCfgTypeByEnum(RoomNetCfg eCfg, HashPos *It)
83 {
84         const char *Key;
85         long len;
86         void *pv;
87         CfgLineType *pCfg;
88
89         RewindHashPos(CfgTypeHash, It, 1);
90         while (GetNextHashPos(CfgTypeHash, It, &len, &Key, &pv) && (pv != NULL))
91         {
92                 pCfg = (CfgLineType*) pv;
93                 if (pCfg->C == eCfg)
94                         return pCfg;
95         }
96         return NULL;
97 }
98
99 void ParseGeneric(const CfgLineType *ThisOne, StrBuf *Line, const char *LinePos, OneRoomNetCfg *OneRNCfg)
100 {
101         RoomNetCfgLine *nptr;
102         int i;
103
104         nptr = (RoomNetCfgLine *)
105                 malloc(sizeof(RoomNetCfgLine));
106         nptr->next = OneRNCfg->NetConfigs[ThisOne->C];
107         nptr->Value = malloc(sizeof(StrBuf*) * ThisOne->nSegments);
108         nptr->nValues = 0;
109         memset(nptr->Value, 0, sizeof(StrBuf*) * ThisOne->nSegments);
110         if (ThisOne->nSegments == 1)
111         {
112                 nptr->Value[0] = NewStrBufPlain(LinePos, StrLength(Line) - ( LinePos - ChrPtr(Line)) );
113                 nptr->nValues = 1;
114         }
115         else for (i = 0; i < ThisOne->nSegments; i++)
116         {
117                 nptr->nValues++;
118                 nptr->Value[i] = NewStrBufPlain(NULL, StrLength(Line) - ( LinePos - ChrPtr(Line)) );
119                 StrBufExtract_NextToken(nptr->Value[i], Line, &LinePos, '|');
120         }
121
122         OneRNCfg->NetConfigs[ThisOne->C] = nptr;
123 }
124
125 void SerializeGeneric(const CfgLineType *ThisOne, StrBuf *OutputBuffer, OneRoomNetCfg *OneRNCfg, RoomNetCfgLine *data)
126 {
127         int i;
128
129         StrBufAppendBufPlain(OutputBuffer, CKEY(ThisOne->Str), 0);
130         StrBufAppendBufPlain(OutputBuffer, HKEY("|"), 0);
131         for (i = 0; i < ThisOne->nSegments; i++)
132         {
133                 StrBufAppendBuf(OutputBuffer, data->Value[i], 0);
134                 if (i + 1 < ThisOne->nSegments)
135                         StrBufAppendBufPlain(OutputBuffer, HKEY("|"), 0);
136         }
137         StrBufAppendBufPlain(OutputBuffer, HKEY("\n"), 0);
138 }
139
140 void DeleteGenericCfgLine(const CfgLineType *ThisOne, RoomNetCfgLine **data)
141 {
142         int i;
143
144         if (*data == NULL)
145                 return;
146
147         for (i = 0; i < (*data)->nValues; i++)
148         {
149                 FreeStrBuf(&(*data)->Value[i]);
150         }
151         free ((*data)->Value);
152         free(*data);
153         *data = NULL;
154 }
155
156 RoomNetCfgLine *DuplicateOneGenericCfgLine(const RoomNetCfgLine *data)
157 {
158         int i;
159         RoomNetCfgLine *NewData;
160
161         NewData = (RoomNetCfgLine*)malloc(sizeof(RoomNetCfgLine));
162         memset(NewData, 0, sizeof(RoomNetCfgLine));
163         NewData->Value = (StrBuf **)malloc(sizeof(StrBuf*) * data->nValues);
164         memset(NewData->Value, 0, sizeof(StrBuf*) * data->nValues);
165
166         for (i = 0; i < data->nValues; i++)
167         {
168                 NewData->Value[i] = NewStrBufDup(data->Value[i]);
169         }
170         NewData->nValues = data->nValues;
171         return NewData;
172 }
173
174
175 /*
176  * Create a config key for a room's netconfig entry
177  */
178 void netcfg_keyname(char *keybuf, long roomnum)
179 {
180         if (!keybuf) return;
181         sprintf(keybuf, "c_netconfig_%010ld", roomnum);
182 }
183
184
185
186 /*
187  * Given a room number and a textual netconfig, convert to base64 and write to the configdb
188  */
189 void write_netconfig_to_configdb(long roomnum, const char *raw_netconfig)
190 {
191         char keyname[25];
192         char *enc;
193         int enc_len;
194         int len;
195
196         len = strlen(raw_netconfig);
197         netcfg_keyname(keyname, roomnum);
198         enc = malloc(len * 2);
199
200         if (enc) {
201                 enc_len = CtdlEncodeBase64(enc, raw_netconfig, len, 0);
202                 if ((enc_len > 1) && (enc[enc_len-2] == 13)) enc[enc_len-2] = 0;
203                 if ((enc_len > 0) && (enc[enc_len-1] == 10)) enc[enc_len-1] = 0;
204                 enc[enc_len] = 0;
205                 syslog(LOG_DEBUG, "Writing key '%s' (length=%d)", keyname, enc_len);
206                 CtdlSetConfigStr(keyname, enc);
207                 free(enc);
208         }
209 }
210
211
212
213 /*
214  * Given a room number, attempt to load the netconfig configdb entry for that room.
215  * If it returns NULL, there is no netconfig.
216  * Otherwise the caller owns the returned memory and is responsible for freeing it.
217  */
218 char *LoadRoomNetConfigFile(long roomnum)
219 {
220         char keyname[25];
221         char *encoded_netconfig = NULL;
222         char *decoded_netconfig = NULL;
223
224         netcfg_keyname(keyname, roomnum);
225         encoded_netconfig = CtdlGetConfigStr(keyname);
226         if (!encoded_netconfig) return NULL;
227
228         decoded_netconfig = malloc(strlen(encoded_netconfig));  // yeah, way bigger than it needs to be, but safe
229         CtdlDecodeBase64(decoded_netconfig, encoded_netconfig, strlen(encoded_netconfig));
230         return decoded_netconfig;
231 }
232
233
234 /*
235  * Deserialize a netconfig , allocate and return structured data
236  */
237 OneRoomNetCfg *ParseRoomNetConfigFile(char *serialized_data)
238 {
239         const char *Pos = NULL;
240         const CfgLineType *pCfg = NULL;
241         StrBuf *Line = NULL;
242         StrBuf *InStr = NULL;
243         StrBuf *Cfg = NULL;
244         OneRoomNetCfg *OneRNCfg = NULL;
245         int num_lines = 0;
246         int i = 0;
247
248         OneRNCfg = malloc(sizeof(OneRoomNetCfg));
249         memset(OneRNCfg, 0, sizeof(OneRoomNetCfg));
250
251         Line = NewStrBuf();
252         InStr = NewStrBuf();
253         Cfg = NewStrBufPlain(serialized_data, -1);
254         num_lines = num_tokens(ChrPtr(Cfg), '\n');
255
256         for (i=0; i<num_lines; ++i) {
257                 StrBufExtract_token(Line, Cfg, i, '\n');
258                 if (StrLength(Line) > 0) {
259                         Pos = NULL;
260                         StrBufExtract_NextToken(InStr, Line, &Pos, '|');
261         
262                         pCfg = GetCfgTypeByStr(SKEY(InStr));
263                         if (pCfg != NULL)
264                         {
265                                 pCfg->Parser(pCfg, Line, Pos, OneRNCfg);
266                         }
267                         else
268                         {
269                                 if (OneRNCfg->misc == NULL)
270                                 {
271                                         OneRNCfg->misc = NewStrBufDup(Line);
272                                 }
273                                 else
274                                 {
275                                         if (StrLength(OneRNCfg->misc) > 0) {
276                                                 StrBufAppendBufPlain(OneRNCfg->misc, HKEY("\n"), 0);
277                                         }
278                                         StrBufAppendBuf(OneRNCfg->misc, Line, 0);
279                                 }
280                         }
281                 }
282         }
283         FreeStrBuf(&InStr);
284         FreeStrBuf(&Line);
285         FreeStrBuf(&Cfg);
286         return OneRNCfg;
287 }
288
289
290 void SaveRoomNetConfigFile(OneRoomNetCfg *OneRNCfg, long roomnum)
291 {
292         RoomNetCfg eCfg;
293         StrBuf *Cfg = NULL;
294         StrBuf *OutBuffer = NULL;
295         HashPos *CfgIt;
296
297         Cfg = NewStrBuf();
298         OutBuffer = NewStrBuf();
299         CfgIt = GetNewHashPos(CfgTypeHash, 1);
300         for (eCfg = subpending; eCfg < maxRoomNetCfg; eCfg ++)
301         {
302                 const CfgLineType *pCfg;
303                 pCfg = GetCfgTypeByEnum(eCfg, CfgIt);
304                 if (pCfg)
305                 {
306                         if (pCfg->IsSingleLine)
307                         {
308                                 pCfg->Serializer(pCfg, OutBuffer, OneRNCfg, NULL);
309                         }
310                         else
311                         {
312                                 RoomNetCfgLine *pName = OneRNCfg->NetConfigs[pCfg->C];
313                                 while (pName != NULL)
314                                 {
315                                         pCfg->Serializer(pCfg, OutBuffer, OneRNCfg, pName);
316                                         pName = pName->next;
317                                 }
318                         }
319                 }
320
321         }
322         DeleteHashPos(&CfgIt);
323
324         if (OneRNCfg->misc != NULL) {
325                 StrBufAppendBuf(OutBuffer, OneRNCfg->misc, 0);
326         }
327
328         write_netconfig_to_configdb(roomnum, ChrPtr(OutBuffer));
329
330         FreeStrBuf(&OutBuffer);
331         FreeStrBuf(&Cfg);
332 }
333
334
335
336 void AddRoomCfgLine(OneRoomNetCfg *OneRNCfg, struct ctdlroom *qrbuf, RoomNetCfg LineType, RoomNetCfgLine *Line)
337 {
338         RoomNetCfgLine **pLine;
339
340         if (OneRNCfg == NULL)
341         {
342                 OneRNCfg = (OneRoomNetCfg*) malloc(sizeof(OneRoomNetCfg));
343                 memset(OneRNCfg, 0, sizeof(OneRoomNetCfg));
344         }
345         pLine = &OneRNCfg->NetConfigs[LineType];
346
347         while(*pLine != NULL) pLine = &((*pLine)->next);
348         *pLine = Line;
349 }
350
351
352 void FreeRoomNetworkStructContent(OneRoomNetCfg *OneRNCfg)
353 {
354         RoomNetCfg eCfg;
355         HashPos *CfgIt;
356
357         CfgIt = GetNewHashPos(CfgTypeHash, 1);
358         for (eCfg = subpending; eCfg < maxRoomNetCfg; eCfg ++)
359         {
360                 const CfgLineType *pCfg;
361                 RoomNetCfgLine *pNext, *pName;
362                 
363                 pCfg = GetCfgTypeByEnum(eCfg, CfgIt);
364                 pName= OneRNCfg->NetConfigs[eCfg];
365                 while (pName != NULL)
366                 {
367                         pNext = pName->next;
368                         if (pCfg != NULL)
369                         {
370                                 pCfg->DeAllocator(pCfg, &pName);
371                         }
372                         else
373                         {
374                                 DeleteGenericCfgLine(NULL, &pName);
375                         }
376                         pName = pNext;
377                 }
378         }
379         DeleteHashPos(&CfgIt);
380
381         FreeStrBuf(&OneRNCfg->Sender);
382         FreeStrBuf(&OneRNCfg->RoomInfo);
383         FreeStrBuf(&OneRNCfg->misc);
384         memset(OneRNCfg, 0, sizeof(OneRoomNetCfg));
385 }
386
387
388 void vFreeRoomNetworkStruct(void *vOneRoomNetCfg)
389 {
390         OneRoomNetCfg *OneRNCfg;
391         OneRNCfg = (OneRoomNetCfg*)vOneRoomNetCfg;
392         FreeRoomNetworkStructContent(OneRNCfg);
393         free(OneRNCfg);
394 }
395
396
397 void FreeRoomNetworkStruct(OneRoomNetCfg **pOneRNCfg)
398 {
399         vFreeRoomNetworkStruct(*pOneRNCfg);
400         *pOneRNCfg=NULL;
401 }
402
403
404 /*
405  * Fetch the netconfig entry for a room, parse it, and return the data.
406  * Caller owns the returned memory and MUST free it using FreeRoomNetworkStruct()
407  */
408 OneRoomNetCfg *CtdlGetNetCfgForRoom(long roomnum)
409 {
410         OneRoomNetCfg *OneRNCfg = NULL;
411         char *serialized_config = NULL;
412
413         serialized_config = LoadRoomNetConfigFile(roomnum);
414         if (!serialized_config) return NULL;
415
416         OneRNCfg = ParseRoomNetConfigFile(serialized_config);
417         free(serialized_config);
418         return OneRNCfg;
419 }
420
421
422 /*-----------------------------------------------------------------------------*
423  *              Per room network configs : exchange with client                *
424  *-----------------------------------------------------------------------------*/
425
426 void cmd_gnet(char *argbuf)
427 {
428         if ( (CC->room.QRflags & QR_MAILBOX) && (CC->user.usernum == atol(CC->room.QRname)) ) {
429                 /* users can edit the netconfigs for their own mailbox rooms */
430         }
431         else if (CtdlAccessCheck(ac_room_aide)) return;
432         
433         cprintf("%d Network settings for room #%ld <%s>\n", LISTING_FOLLOWS, CC->room.QRnumber, CC->room.QRname);
434
435         char *c = LoadRoomNetConfigFile(CC->room.QRnumber);
436         if (c) {
437                 cprintf("%s\n", c);
438                 free(c);
439         }
440         cprintf("000\n");
441 }
442
443
444 void cmd_snet(char *argbuf)
445 {
446         struct CitContext *CCC = CC;
447         StrBuf *Line = NULL;
448         StrBuf *TheConfig = NULL;
449         int rc;
450
451         unbuffer_output();
452         Line = NewStrBuf();
453         TheConfig = NewStrBuf();
454         cprintf("%d send new netconfig now\n", SEND_LISTING);
455
456         while (rc = CtdlClientGetLine(Line), (rc >= 0))
457         {
458                 if ((rc == 3) && (strcmp(ChrPtr(Line), "000") == 0))
459                         break;
460
461                 StrBufAppendBuf(TheConfig, Line, 0);
462                 StrBufAppendBufPlain(TheConfig, HKEY("\n"), 0);
463         }
464         FreeStrBuf(&Line);
465
466         write_netconfig_to_configdb(CCC->room.QRnumber, ChrPtr(TheConfig));
467         FreeStrBuf(&TheConfig);
468 }
469
470
471 /*-----------------------------------------------------------------------------*
472  *                       Per node network configs                              *
473  *-----------------------------------------------------------------------------*/
474 void DeleteCtdlNodeConf(void *vNode)
475 {
476         CtdlNodeConf *Node = (CtdlNodeConf*) vNode;
477         FreeStrBuf(&Node->NodeName);
478         FreeStrBuf(&Node->Secret);
479         FreeStrBuf(&Node->Host);
480         FreeStrBuf(&Node->Port);
481         free(Node);
482 }
483
484 CtdlNodeConf *NewNode(StrBuf *SerializedNode)
485 {
486         const char *Pos = NULL;
487         CtdlNodeConf *Node;
488
489         /* we need at least 4 pipes and some other text so its invalid. */
490         if (StrLength(SerializedNode) < 8)
491                 return NULL;
492         Node = (CtdlNodeConf *) malloc(sizeof(CtdlNodeConf));
493
494         Node->DeleteMe = 0;
495
496         Node->NodeName=NewStrBuf();
497         StrBufExtract_NextToken(Node->NodeName, SerializedNode, &Pos, '|');
498
499         Node->Secret=NewStrBuf();
500         StrBufExtract_NextToken(Node->Secret, SerializedNode, &Pos, '|');
501
502         Node->Host=NewStrBuf();
503         StrBufExtract_NextToken(Node->Host, SerializedNode, &Pos, '|');
504
505         Node->Port=NewStrBuf();
506         StrBufExtract_NextToken(Node->Port, SerializedNode, &Pos, '|');
507         return Node;
508 }
509
510
511 /*
512  * Load or refresh the Citadel network (IGnet) configuration for this node.
513  */
514 HashList* CtdlLoadIgNetCfg(void)
515 {
516         const char *LinePos;
517         char       *Cfg;
518         StrBuf     *Buf;
519         StrBuf     *LineBuf;
520         HashList   *Hash;
521         CtdlNodeConf   *Node;
522
523         Cfg =  CtdlGetSysConfig(IGNETCFG);
524         if ((Cfg == NULL) || IsEmptyStr(Cfg)) {
525                 if (Cfg != NULL)
526                         free(Cfg);
527                 return NULL;
528         }
529
530         Hash = NewHash(1, NULL);
531         Buf = NewStrBufPlain(Cfg, -1);
532         free(Cfg);
533         LineBuf = NewStrBufPlain(NULL, StrLength(Buf));
534         LinePos = NULL;
535         do
536         {
537                 StrBufSipLine(LineBuf, Buf, &LinePos);
538                 if (StrLength(LineBuf) != 0) {
539                         Node = NewNode(LineBuf);
540                         if (Node != NULL) {
541                                 Put(Hash, SKEY(Node->NodeName), Node, DeleteCtdlNodeConf);
542                         }
543                 }
544         } while (LinePos != StrBufNOTNULL);
545         FreeStrBuf(&Buf);
546         FreeStrBuf(&LineBuf);
547         return Hash;
548 }
549
550
551 int is_recipient(OneRoomNetCfg *RNCfg, const char *Name)
552 {
553         const RoomNetCfg RecipientCfgs[] = {
554                 listrecp,
555                 digestrecp,
556                 participate,
557                 maxRoomNetCfg
558         };
559         int i;
560         RoomNetCfgLine *nptr;
561         size_t len;
562         
563         len = strlen(Name);
564         i = 0;
565         while (RecipientCfgs[i] != maxRoomNetCfg)
566         {
567                 nptr = RNCfg->NetConfigs[RecipientCfgs[i]];
568                 
569                 while (nptr != NULL)
570                 {
571                         if ((StrLength(nptr->Value[0]) == len) && 
572                             (!strcmp(Name, ChrPtr(nptr->Value[0]))))
573                         {
574                                 return 1;
575                         }
576                         nptr = nptr->next;
577                 }
578                 i++;
579         }
580         return 0;
581 }
582
583
584
585 int CtdlNetconfigCheckRoomaccess(
586         char *errmsgbuf, 
587         size_t n,
588         const char* RemoteIdentifier)
589 {
590         OneRoomNetCfg *RNCfg;
591         int found;
592
593         if (RemoteIdentifier == NULL)
594         {
595                 snprintf(errmsgbuf, n, "Need sender to permit access.");
596                 return (ERROR + USERNAME_REQUIRED);
597         }
598
599         begin_critical_section(S_NETCONFIGS);
600         RNCfg = CtdlGetNetCfgForRoom (CC->room.QRnumber);
601         if (RNCfg == NULL)
602         {
603                 end_critical_section(S_NETCONFIGS);
604                 snprintf(errmsgbuf, n,
605                          "This mailing list only accepts posts from subscribers.");
606                 return (ERROR + NO_SUCH_USER);
607         }
608         found = is_recipient (RNCfg, RemoteIdentifier);
609         FreeRoomNetworkStruct(&RNCfg);
610         end_critical_section(S_NETCONFIGS);
611
612         if (found) {
613                 return (0);
614         }
615         else {
616                 snprintf(errmsgbuf, n,
617                          "This mailing list only accepts posts from subscribers.");
618                 return (ERROR + NO_SUCH_USER);
619         }
620 }
621
622
623
624 /*
625  * cmd_netp() - authenticate to the server as another Citadel node polling
626  *            for network traffic
627  */
628 void cmd_netp(char *cmdbuf)
629 {
630         struct CitContext *CCC = CC;
631         HashList *working_ignetcfg;
632         char *node;
633         StrBuf *NodeStr;
634         long nodelen;
635         int v;
636
637         const StrBuf *secret = NULL;
638         const StrBuf *nexthop = NULL;
639         char err_buf[SIZ] = "";
640
641         /* Authenticate */
642         node = CCC->curr_user;
643         nodelen = extract_token(CCC->curr_user, cmdbuf, 0, '|', sizeof CCC->curr_user);
644         NodeStr = NewStrBufPlain(node, nodelen);
645         /* load the IGnet Configuration to check node validity */
646         working_ignetcfg = CtdlLoadIgNetCfg();
647         v = CtdlIsValidNode(&nexthop, &secret, NodeStr, working_ignetcfg, NULL);
648         if (v != 0) {
649                 snprintf(err_buf, sizeof err_buf,
650                         "An unknown Citadel server called \"%s\" attempted to connect from %s [%s].\n",
651                         node, CCC->cs_host, CCC->cs_addr
652                 );
653                 syslog(LOG_WARNING, "%s", err_buf);
654                 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
655                 CtdlAideMessage(err_buf, "IGNet Networking");
656                 DeleteHash(&working_ignetcfg);
657                 FreeStrBuf(&NodeStr);
658                 return;
659         }
660
661         extract_token(CCC->user.password, cmdbuf, 1, '|', sizeof CCC->user.password);
662         if (strcasecmp(CCC->user.password, ChrPtr(secret))) {
663                 snprintf(err_buf, sizeof err_buf,
664                         "A Citadel server at %s [%s] failed to authenticate as network node \"%s\".\n",
665                         CCC->cs_host, CCC->cs_addr, node
666                 );
667                 syslog(LOG_WARNING, "%s", err_buf);
668                 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
669
670                 CtdlAideMessage(err_buf, "IGNet Networking");
671                 DeleteHash(&working_ignetcfg);
672                 FreeStrBuf(&NodeStr);
673                 return;
674         }
675
676         if (CtdlNetworkTalkingTo(node, nodelen, NTT_CHECK)) {
677                 syslog(LOG_WARNING, "Duplicate session for network node <%s>", node);
678                 cprintf("%d Already talking to %s right now\n", ERROR + RESOURCE_BUSY, node);
679                 DeleteHash(&working_ignetcfg);
680                 FreeStrBuf(&NodeStr);
681                 return;
682         }
683         nodelen = safestrncpy(CCC->net_node, node, sizeof CCC->net_node);
684         CtdlNetworkTalkingTo(CCC->net_node, nodelen, NTT_ADD);
685         syslog(LOG_NOTICE, "Network node <%s> logged in from %s [%s]",
686                 CCC->net_node, CCC->cs_host, CCC->cs_addr
687         );
688         cprintf("%d authenticated as network node '%s'\n", CIT_OK, CCC->net_node);
689         DeleteHash(&working_ignetcfg);
690         FreeStrBuf(&NodeStr);
691 }
692
693
694 /*-----------------------------------------------------------------------------*
695  *                 Network maps: evaluate other nodes                          *
696  *-----------------------------------------------------------------------------*/
697
698 void DeleteNetMap(void *vNetMap)
699 {
700         CtdlNetMap *TheNetMap = (CtdlNetMap*) vNetMap;
701         FreeStrBuf(&TheNetMap->NodeName);
702         FreeStrBuf(&TheNetMap->NextHop);
703         free(TheNetMap);
704 }
705
706 CtdlNetMap *NewNetMap(StrBuf *SerializedNetMap)
707 {
708         const char *Pos = NULL;
709         CtdlNetMap *NM;
710
711         /* we need at least 3 pipes and some other text so its invalid. */
712         if (StrLength(SerializedNetMap) < 6)
713                 return NULL;
714         NM = (CtdlNetMap *) malloc(sizeof(CtdlNetMap));
715
716         NM->NodeName=NewStrBuf();
717         StrBufExtract_NextToken(NM->NodeName, SerializedNetMap, &Pos, '|');
718
719         NM->lastcontact = StrBufExtractNext_long(SerializedNetMap, &Pos, '|');
720
721         NM->NextHop=NewStrBuf();
722         StrBufExtract_NextToken(NM->NextHop, SerializedNetMap, &Pos, '|');
723
724         return NM;
725 }
726
727 HashList* CtdlReadNetworkMap(void)
728 {
729         const char *LinePos;
730         char       *Cfg;
731         StrBuf     *Buf;
732         StrBuf     *LineBuf;
733         HashList   *Hash;
734         CtdlNetMap     *TheNetMap;
735
736         Hash = NewHash(1, NULL);
737         Cfg =  CtdlGetSysConfig(IGNETMAP);
738         if ((Cfg == NULL) || IsEmptyStr(Cfg)) {
739                 if (Cfg != NULL)
740                         free(Cfg);
741                 return Hash;
742         }
743
744         Buf = NewStrBufPlain(Cfg, -1);
745         free(Cfg);
746         LineBuf = NewStrBufPlain(NULL, StrLength(Buf));
747         LinePos = NULL;
748         while (StrBufSipLine(Buf, LineBuf, &LinePos))
749         {
750                 TheNetMap = NewNetMap(LineBuf);
751                 if (TheNetMap != NULL) { /* TODO: is the NodeName Uniq? */
752                         Put(Hash, SKEY(TheNetMap->NodeName), TheNetMap, DeleteNetMap);
753                 }
754         }
755         FreeStrBuf(&Buf);
756         FreeStrBuf(&LineBuf);
757         return Hash;
758 }
759
760 StrBuf *CtdlSerializeNetworkMap(HashList *Map)
761 {
762         void *vMap;
763         const char *key;
764         long len;
765         StrBuf *Ret = NewStrBuf();
766         HashPos *Pos = GetNewHashPos(Map, 0);
767
768         while (GetNextHashPos(Map, Pos, &len, &key, &vMap))
769         {
770                 CtdlNetMap *pMap = (CtdlNetMap*) vMap;
771                 StrBufAppendBuf(Ret, pMap->NodeName, 0);
772                 StrBufAppendBufPlain(Ret, HKEY("|"), 0);
773
774                 StrBufAppendPrintf(Ret, "%ld", pMap->lastcontact, 0);
775                 StrBufAppendBufPlain(Ret, HKEY("|"), 0);
776
777                 StrBufAppendBuf(Ret, pMap->NextHop, 0);
778                 StrBufAppendBufPlain(Ret, HKEY("\n"), 0);
779         }
780         DeleteHashPos(&Pos);
781         return Ret;
782 }
783
784
785 /*
786  * Learn topology from path fields
787  */
788 void NetworkLearnTopology(char *node, char *path, HashList *the_netmap, int *netmap_changed)
789 {
790         CtdlNetMap *pNM = NULL;
791         void *vptr;
792         char nexthop[256];
793         CtdlNetMap *nmptr;
794
795         if (GetHash(the_netmap, node, strlen(node), &vptr) && 
796             (vptr != NULL))/* TODO: is the NodeName Uniq? */
797         {
798                 pNM = (CtdlNetMap*)vptr;
799                 extract_token(nexthop, path, 0, '!', sizeof nexthop);
800                 if (!strcmp(nexthop, ChrPtr(pNM->NextHop))) {
801                         pNM->lastcontact = time(NULL);
802                         (*netmap_changed) ++;
803                         return;
804                 }
805         }
806
807         /* If we got here then it's not in the map, so add it. */
808         nmptr = (CtdlNetMap *) malloc(sizeof (CtdlNetMap));
809         nmptr->NodeName = NewStrBufPlain(node, -1);
810         nmptr->lastcontact = time(NULL);
811         nmptr->NextHop = NewStrBuf ();
812         StrBufExtract_tokenFromStr(nmptr->NextHop, path, strlen(path), 0, '!');
813         /* TODO: is the NodeName Uniq? */
814         Put(the_netmap, SKEY(nmptr->NodeName), nmptr, DeleteNetMap);
815         (*netmap_changed) ++;
816 }
817
818
819 /*
820  * Check the network map and determine whether the supplied node name is
821  * valid.  If it is not a neighbor node, supply the name of a neighbor node
822  * which is the next hop.  If it *is* a neighbor node, we also fill in the
823  * shared secret.
824  */
825 int CtdlIsValidNode(const StrBuf **nexthop,
826                     const StrBuf **secret,
827                     StrBuf *node,
828                     HashList *IgnetCfg,
829                     HashList *the_netmap)
830 {
831         void *vNetMap;
832         void *vNodeConf;
833         CtdlNodeConf *TheNode;
834         CtdlNetMap *TheNetMap;
835
836         if (StrLength(node) == 0) {
837                 return(-1);
838         }
839
840         /*
841          * First try the neighbor nodes
842          */
843         if (GetCount(IgnetCfg) == 0) {
844                 syslog(LOG_INFO, "IgnetCfg is empty!");
845                 if (nexthop != NULL) {
846                         *nexthop = NULL;
847                 }
848                 return(-1);
849         }
850
851         /* try to find a neigbour with the name 'node' */
852         if (GetHash(IgnetCfg, SKEY(node), &vNodeConf) && 
853             (vNodeConf != NULL))
854         {
855                 TheNode = (CtdlNodeConf*)vNodeConf;
856                 if (secret != NULL)
857                         *secret = TheNode->Secret;
858                 return 0;               /* yup, it's a direct neighbor */
859         }
860
861         /*
862          * If we get to this point we have to see if we know the next hop
863          *//* TODO: is the NodeName Uniq? */
864         if ((GetCount(the_netmap) > 0) &&
865             (GetHash(the_netmap, SKEY(node), &vNetMap)))
866         {
867                 TheNetMap = (CtdlNetMap*)vNetMap;
868                 if (nexthop != NULL)
869                         *nexthop = TheNetMap->NextHop;
870                 return(0);
871         }
872
873         /*
874          * If we get to this point, the supplied node name is bogus.
875          */
876         syslog(LOG_ERR, "Invalid node name <%s>", ChrPtr(node));
877         return(-1);
878 }
879
880
881 /*
882  * Convert any legacy configuration files in the "netconfigs" directory
883  */
884 void convert_legacy_netcfg_files(void)
885 {
886         DIR *dh = NULL;
887         struct dirent *dit = NULL;
888         char filename[PATH_MAX];
889         long roomnum;
890         FILE *fp;
891         long len;
892         char *v;
893
894         dh = opendir(ctdl_netcfg_dir);
895         if (!dh) return;
896
897         syslog(LOG_INFO, "Legacy netconfig files exist - converting them!");
898
899         while (dit = readdir(dh), dit != NULL) {                // yes, we use the non-reentrant version; we're not in threaded mode yet
900                 roomnum = atol(dit->d_name);
901                 if (roomnum > 0) {
902                         snprintf(filename, sizeof filename, "%s/%ld", ctdl_netcfg_dir, roomnum);
903                         fp = fopen(filename, "r");
904                         if (fp) {
905                                 fseek(fp, 0L, SEEK_END);
906                                 len = ftell(fp);
907                                 if (len > 0) {
908                                         v = malloc(len);
909                                         if (v) {
910                                                 rewind(fp);
911                                                 if (fread(v, len, 1, fp)) {
912                                                         write_netconfig_to_configdb(roomnum, v);
913                                                         unlink(filename);
914                                                 }
915                                                 free(v);
916                                         }
917                                 }
918                                 else {
919                                         unlink(filename);       // zero length netconfig, just delete it
920                                 }
921                                 fclose(fp);
922                         }
923                 }
924         }
925
926         closedir(dh);
927         rmdir(ctdl_netcfg_dir);
928 }
929
930
931
932 /*
933  * Module entry point
934  */
935 CTDL_MODULE_INIT(netconfig)
936 {
937         if (!threading)
938         {
939                 convert_legacy_netcfg_files();
940                 CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
941                 CtdlRegisterProtoHook(cmd_snet, "SNET", "Set network config");
942                 CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
943         }
944         return "netconfig";
945 }