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