Completed the greatly-simplified RSS feed reader
[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         long lens[2];
637         const char *strs[2];
638
639         const StrBuf *secret = NULL;
640         const StrBuf *nexthop = NULL;
641         char err_buf[SIZ] = "";
642
643         /* Authenticate */
644         node = CCC->curr_user;
645         nodelen = extract_token(CCC->curr_user, cmdbuf, 0, '|', sizeof CCC->curr_user);
646         NodeStr = NewStrBufPlain(node, nodelen);
647         /* load the IGnet Configuration to check node validity */
648         working_ignetcfg = CtdlLoadIgNetCfg();
649         v = CtdlIsValidNode(&nexthop, &secret, NodeStr, working_ignetcfg, NULL);
650         if (v != 0) {
651                 snprintf(err_buf, sizeof err_buf,
652                         "An unknown Citadel server called \"%s\" attempted to connect from %s [%s].\n",
653                         node, CCC->cs_host, CCC->cs_addr
654                 );
655                 syslog(LOG_WARNING, "%s", err_buf);
656                 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
657
658                 strs[0] = CCC->cs_addr;
659                 lens[0] = strlen(CCC->cs_addr);
660                 
661                 strs[1] = "SRV_UNKNOWN";
662                 lens[1] = sizeof("SRV_UNKNOWN") - 1;
663
664                 CtdlAideFPMessage(
665                         err_buf,
666                         "IGNet Networking.",
667                         2, strs, (long*) &lens,
668                         CCC->cs_pid, 0,
669                         time(NULL));
670
671                 DeleteHash(&working_ignetcfg);
672                 FreeStrBuf(&NodeStr);
673                 return;
674         }
675
676         extract_token(CCC->user.password, cmdbuf, 1, '|', sizeof CCC->user.password);
677         if (strcasecmp(CCC->user.password, ChrPtr(secret))) {
678                 snprintf(err_buf, sizeof err_buf,
679                         "A Citadel server at %s [%s] failed to authenticate as network node \"%s\".\n",
680                         CCC->cs_host, CCC->cs_addr, node
681                 );
682                 syslog(LOG_WARNING, "%s", err_buf);
683                 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
684
685                 strs[0] = CCC->cs_addr;
686                 lens[0] = strlen(CCC->cs_addr);
687                 
688                 strs[1] = "SRV_PW";
689                 lens[1] = sizeof("SRV_PW") - 1;
690
691                 CtdlAideFPMessage(
692                         err_buf,
693                         "IGNet Networking.",
694                         2, strs,
695                         (long*) &lens,
696                         CCC->cs_pid, 0,
697                         time(NULL));
698
699                 DeleteHash(&working_ignetcfg);
700                 FreeStrBuf(&NodeStr);
701                 return;
702         }
703
704         if (CtdlNetworkTalkingTo(node, nodelen, NTT_CHECK)) {
705                 syslog(LOG_WARNING, "Duplicate session for network node <%s>", node);
706                 cprintf("%d Already talking to %s right now\n", ERROR + RESOURCE_BUSY, node);
707                 DeleteHash(&working_ignetcfg);
708                 FreeStrBuf(&NodeStr);
709                 return;
710         }
711         nodelen = safestrncpy(CCC->net_node, node, sizeof CCC->net_node);
712         CtdlNetworkTalkingTo(CCC->net_node, nodelen, NTT_ADD);
713         syslog(LOG_NOTICE, "Network node <%s> logged in from %s [%s]",
714                 CCC->net_node, CCC->cs_host, CCC->cs_addr
715         );
716         cprintf("%d authenticated as network node '%s'\n", CIT_OK, CCC->net_node);
717         DeleteHash(&working_ignetcfg);
718         FreeStrBuf(&NodeStr);
719 }
720
721
722 /*-----------------------------------------------------------------------------*
723  *                 Network maps: evaluate other nodes                          *
724  *-----------------------------------------------------------------------------*/
725
726 void DeleteNetMap(void *vNetMap)
727 {
728         CtdlNetMap *TheNetMap = (CtdlNetMap*) vNetMap;
729         FreeStrBuf(&TheNetMap->NodeName);
730         FreeStrBuf(&TheNetMap->NextHop);
731         free(TheNetMap);
732 }
733
734 CtdlNetMap *NewNetMap(StrBuf *SerializedNetMap)
735 {
736         const char *Pos = NULL;
737         CtdlNetMap *NM;
738
739         /* we need at least 3 pipes and some other text so its invalid. */
740         if (StrLength(SerializedNetMap) < 6)
741                 return NULL;
742         NM = (CtdlNetMap *) malloc(sizeof(CtdlNetMap));
743
744         NM->NodeName=NewStrBuf();
745         StrBufExtract_NextToken(NM->NodeName, SerializedNetMap, &Pos, '|');
746
747         NM->lastcontact = StrBufExtractNext_long(SerializedNetMap, &Pos, '|');
748
749         NM->NextHop=NewStrBuf();
750         StrBufExtract_NextToken(NM->NextHop, SerializedNetMap, &Pos, '|');
751
752         return NM;
753 }
754
755 HashList* CtdlReadNetworkMap(void)
756 {
757         const char *LinePos;
758         char       *Cfg;
759         StrBuf     *Buf;
760         StrBuf     *LineBuf;
761         HashList   *Hash;
762         CtdlNetMap     *TheNetMap;
763
764         Hash = NewHash(1, NULL);
765         Cfg =  CtdlGetSysConfig(IGNETMAP);
766         if ((Cfg == NULL) || IsEmptyStr(Cfg)) {
767                 if (Cfg != NULL)
768                         free(Cfg);
769                 return Hash;
770         }
771
772         Buf = NewStrBufPlain(Cfg, -1);
773         free(Cfg);
774         LineBuf = NewStrBufPlain(NULL, StrLength(Buf));
775         LinePos = NULL;
776         while (StrBufSipLine(Buf, LineBuf, &LinePos))
777         {
778                 TheNetMap = NewNetMap(LineBuf);
779                 if (TheNetMap != NULL) { /* TODO: is the NodeName Uniq? */
780                         Put(Hash, SKEY(TheNetMap->NodeName), TheNetMap, DeleteNetMap);
781                 }
782         }
783         FreeStrBuf(&Buf);
784         FreeStrBuf(&LineBuf);
785         return Hash;
786 }
787
788 StrBuf *CtdlSerializeNetworkMap(HashList *Map)
789 {
790         void *vMap;
791         const char *key;
792         long len;
793         StrBuf *Ret = NewStrBuf();
794         HashPos *Pos = GetNewHashPos(Map, 0);
795
796         while (GetNextHashPos(Map, Pos, &len, &key, &vMap))
797         {
798                 CtdlNetMap *pMap = (CtdlNetMap*) vMap;
799                 StrBufAppendBuf(Ret, pMap->NodeName, 0);
800                 StrBufAppendBufPlain(Ret, HKEY("|"), 0);
801
802                 StrBufAppendPrintf(Ret, "%ld", pMap->lastcontact, 0);
803                 StrBufAppendBufPlain(Ret, HKEY("|"), 0);
804
805                 StrBufAppendBuf(Ret, pMap->NextHop, 0);
806                 StrBufAppendBufPlain(Ret, HKEY("\n"), 0);
807         }
808         DeleteHashPos(&Pos);
809         return Ret;
810 }
811
812
813 /*
814  * Learn topology from path fields
815  */
816 void NetworkLearnTopology(char *node, char *path, HashList *the_netmap, int *netmap_changed)
817 {
818         CtdlNetMap *pNM = NULL;
819         void *vptr;
820         char nexthop[256];
821         CtdlNetMap *nmptr;
822
823         if (GetHash(the_netmap, node, strlen(node), &vptr) && 
824             (vptr != NULL))/* TODO: is the NodeName Uniq? */
825         {
826                 pNM = (CtdlNetMap*)vptr;
827                 extract_token(nexthop, path, 0, '!', sizeof nexthop);
828                 if (!strcmp(nexthop, ChrPtr(pNM->NextHop))) {
829                         pNM->lastcontact = time(NULL);
830                         (*netmap_changed) ++;
831                         return;
832                 }
833         }
834
835         /* If we got here then it's not in the map, so add it. */
836         nmptr = (CtdlNetMap *) malloc(sizeof (CtdlNetMap));
837         nmptr->NodeName = NewStrBufPlain(node, -1);
838         nmptr->lastcontact = time(NULL);
839         nmptr->NextHop = NewStrBuf ();
840         StrBufExtract_tokenFromStr(nmptr->NextHop, path, strlen(path), 0, '!');
841         /* TODO: is the NodeName Uniq? */
842         Put(the_netmap, SKEY(nmptr->NodeName), nmptr, DeleteNetMap);
843         (*netmap_changed) ++;
844 }
845
846
847 /*
848  * Check the network map and determine whether the supplied node name is
849  * valid.  If it is not a neighbor node, supply the name of a neighbor node
850  * which is the next hop.  If it *is* a neighbor node, we also fill in the
851  * shared secret.
852  */
853 int CtdlIsValidNode(const StrBuf **nexthop,
854                     const StrBuf **secret,
855                     StrBuf *node,
856                     HashList *IgnetCfg,
857                     HashList *the_netmap)
858 {
859         void *vNetMap;
860         void *vNodeConf;
861         CtdlNodeConf *TheNode;
862         CtdlNetMap *TheNetMap;
863
864         if (StrLength(node) == 0) {
865                 return(-1);
866         }
867
868         /*
869          * First try the neighbor nodes
870          */
871         if (GetCount(IgnetCfg) == 0) {
872                 syslog(LOG_INFO, "IgnetCfg is empty!");
873                 if (nexthop != NULL) {
874                         *nexthop = NULL;
875                 }
876                 return(-1);
877         }
878
879         /* try to find a neigbour with the name 'node' */
880         if (GetHash(IgnetCfg, SKEY(node), &vNodeConf) && 
881             (vNodeConf != NULL))
882         {
883                 TheNode = (CtdlNodeConf*)vNodeConf;
884                 if (secret != NULL)
885                         *secret = TheNode->Secret;
886                 return 0;               /* yup, it's a direct neighbor */
887         }
888
889         /*
890          * If we get to this point we have to see if we know the next hop
891          *//* TODO: is the NodeName Uniq? */
892         if ((GetCount(the_netmap) > 0) &&
893             (GetHash(the_netmap, SKEY(node), &vNetMap)))
894         {
895                 TheNetMap = (CtdlNetMap*)vNetMap;
896                 if (nexthop != NULL)
897                         *nexthop = TheNetMap->NextHop;
898                 return(0);
899         }
900
901         /*
902          * If we get to this point, the supplied node name is bogus.
903          */
904         syslog(LOG_ERR, "Invalid node name <%s>", ChrPtr(node));
905         return(-1);
906 }
907
908
909 /*
910  * Convert any legacy configuration files in the "netconfigs" directory
911  */
912 void convert_legacy_netcfg_files(void)
913 {
914         DIR *dh = NULL;
915         struct dirent *dit = NULL;
916         char filename[PATH_MAX];
917         long roomnum;
918         FILE *fp;
919         long len;
920         char *v;
921
922         dh = opendir(ctdl_netcfg_dir);
923         if (!dh) return;
924
925         syslog(LOG_INFO, "Legacy netconfig files exist - converting them!");
926
927         while (dit = readdir(dh), dit != NULL) {                // yes, we use the non-reentrant version; we're not in threaded mode yet
928                 roomnum = atol(dit->d_name);
929                 if (roomnum > 0) {
930                         snprintf(filename, sizeof filename, "%s/%ld", ctdl_netcfg_dir, roomnum);
931                         fp = fopen(filename, "r");
932                         if (fp) {
933                                 fseek(fp, 0L, SEEK_END);
934                                 len = ftell(fp);
935                                 if (len > 0) {
936                                         v = malloc(len);
937                                         if (v) {
938                                                 rewind(fp);
939                                                 if (fread(v, len, 1, fp)) {
940                                                         write_netconfig_to_configdb(roomnum, v);
941                                                         unlink(filename);
942                                                 }
943                                                 free(v);
944                                         }
945                                 }
946                                 else {
947                                         unlink(filename);       // zero length netconfig, just delete it
948                                 }
949                                 fclose(fp);
950                         }
951                 }
952         }
953
954         closedir(dh);
955         rmdir(ctdl_netcfg_dir);
956 }
957
958
959
960 /*
961  * Module entry point
962  */
963 CTDL_MODULE_INIT(netconfig)
964 {
965         if (!threading)
966         {
967                 convert_legacy_netcfg_files();
968                 CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
969                 CtdlRegisterProtoHook(cmd_snet, "SNET", "Set network config");
970                 CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
971         }
972         return "netconfig";
973 }