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