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