6137bd3d48d99202e0d3ca0f779ea2f80d7e21e3
[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-2012 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
20 #ifdef HAVE_SYSCALL_H
21 # include <syscall.h>
22 #else 
23 # if HAVE_SYS_SYSCALL_H
24 #  include <sys/syscall.h>
25 # endif
26 #endif
27
28 #include <libcitadel.h>
29
30 #include "include/ctdl_module.h"
31 HashList *CfgTypeHash = NULL;
32
33 /*-----------------------------------------------------------------------------*
34  *                       Per room network configs                              *
35  *-----------------------------------------------------------------------------*/
36 void RegisterRoomCfgType(const char* Name, long len, RoomNetCfg eCfg, CfgLineParser p, int uniq, CfgLineSerializer s, CfgLineDeAllocator d)
37 {
38         CfgLineType *pCfg;
39
40         pCfg = (CfgLineType*) malloc(sizeof(CfgLineType));
41         pCfg->Parser = p;
42         pCfg->Serializer = s;
43         pCfg->C = eCfg;
44         pCfg->Str.Key = Name;
45         pCfg->Str.len = len;
46         pCfg->IsSingleLine = uniq;
47
48         if (CfgTypeHash == NULL)
49                 CfgTypeHash = NewHash(1, NULL);
50         Put(CfgTypeHash, Name, len, pCfg, NULL);
51 }
52
53
54 const CfgLineType *GetCfgTypeByStr(const char *Key, long len)
55 {
56         void *pv;
57         
58         if (GetHash(CfgTypeHash, Key, len, &pv) && (pv != NULL))
59         {
60                 return (const CfgLineType *) pv;
61         }
62         else
63         {
64                 return NULL;
65         }
66 }
67
68 const CfgLineType *GetCfgTypeByEnum(RoomNetCfg eCfg, HashPos *It)
69 {
70         const char *Key;
71         long len;
72         void *pv;
73         CfgLineType *pCfg;
74
75         RewindHashPos(CfgTypeHash, It, 1);
76         while (GetNextHashPos(CfgTypeHash, It, &len, &Key, &pv) && (pv != NULL))
77         {
78                 pCfg = (CfgLineType*) pv;
79                 if (pCfg->C == eCfg)
80                         return pCfg;
81         }
82         return NULL;
83 }
84 void ParseGeneric(const CfgLineType *ThisOne, StrBuf *Line, const char *LinePos, OneRoomNetCfg *OneRNCFG)
85 {
86         RoomNetCfgLine *nptr;
87
88         nptr = (RoomNetCfgLine *)
89                 malloc(sizeof(RoomNetCfgLine));
90         nptr->next = OneRNCFG->NetConfigs[ThisOne->C];
91         nptr->Value = NewStrBufPlain(LinePos, StrLength(Line) - ( LinePos - ChrPtr(Line)) );
92         OneRNCFG->NetConfigs[ThisOne->C] = nptr;
93 }
94
95 void SerializeGeneric(const CfgLineType *ThisOne, StrBuf *OutputBuffer, OneRoomNetCfg *OneRNCFG, RoomNetCfgLine *data)
96 {
97         StrBufAppendBufPlain(OutputBuffer, CKEY(ThisOne->Str), 0);
98         StrBufAppendBuf(OutputBuffer, data->Value, 0);
99         StrBufAppendBufPlain(OutputBuffer, HKEY("\n"), 0);
100 }
101
102 void DeleteGenericCfgLine(const CfgLineType *ThisOne, RoomNetCfgLine **data)
103 {
104         FreeStrBuf(&(*data)->Value);
105         free(*data);
106         *data = NULL;
107 }
108 int read_spoolcontrol_file(OneRoomNetCfg **pOneRNCFG, char *filename)
109 {
110         int fd;
111         const char *ErrStr = NULL;
112         const char *Pos;
113         const CfgLineType *pCfg;
114         StrBuf *Line;
115         StrBuf *InStr;
116         OneRoomNetCfg *OneRNCFG;
117
118         fd = open(filename, O_NONBLOCK|O_RDONLY);
119         if (fd == -1) {
120                 *pOneRNCFG = NULL;
121                 return 0;
122         }
123         OneRNCFG = malloc(sizeof(OneRoomNetCfg));
124         memset(OneRNCFG, 0, sizeof(OneRoomNetCfg));
125         *pOneRNCFG = OneRNCFG;
126
127         while (StrBufTCP_read_line(Line, &fd, 0, &ErrStr) >= 0) {
128                 if (StrLength(Line) == 0)
129                         continue;
130                 Pos = NULL;
131                 InStr = NewStrBufPlain(NULL, StrLength(Line));
132                 StrBufExtract_NextToken(InStr, Line, &Pos, '|');
133
134                 pCfg = GetCfgTypeByStr(SKEY(InStr));
135                 if (pCfg != NULL)
136                 {
137                         pCfg->Parser(pCfg, Line, Pos, OneRNCFG);
138                 }
139                 else
140                 {
141                         if (OneRNCFG->misc == NULL)
142                         {
143                                 OneRNCFG->misc = NewStrBufDup(Line);
144                         }
145                         else
146                         {
147                                 if(StrLength(OneRNCFG->misc) > 0)
148                                         StrBufAppendBufPlain(OneRNCFG->misc, HKEY("\n"), 0);
149                                 StrBufAppendBuf(OneRNCFG->misc, Line, 0);
150                         }
151                 }
152         }
153         if (fd > 0)
154                 close(fd);
155         FreeStrBuf(&InStr);
156         FreeStrBuf(&Line);
157         return 1;
158 }
159
160 int save_spoolcontrol_file(OneRoomNetCfg *OneRNCFG, char *filename)
161 {
162         RoomNetCfg eCfg;
163         StrBuf *Cfg;
164         char tempfilename[PATH_MAX];
165         int TmpFD;
166         long len;
167         time_t unixtime;
168         struct timeval tv;
169         long reltid; /* if we don't have SYS_gettid, use "random" value */
170         StrBuf *OutBuffer;
171         int rc;
172         HashPos *CfgIt;
173
174         len = strlen(filename);
175         memcpy(tempfilename, filename, len + 1);
176
177 #if defined(HAVE_SYONERNCFGALL_H) && defined (SYS_gettid)
178         reltid = syOneRNCFGall(SYS_gettid);
179 #endif
180         gettimeofday(&tv, NULL);
181         /* Promote to time_t; types differ on some OSes (like darwin) */
182         unixtime = tv.tv_sec;
183
184         sprintf(tempfilename + len, ".%ld-%ld", reltid, unixtime);
185         errno = 0;
186         TmpFD = open(tempfilename, O_CREAT|O_EXCL|O_RDWR, S_IRUSR|S_IWUSR);
187         Cfg = NewStrBuf();
188         if ((TmpFD < 0) || (errno != 0)) {
189                 syslog(LOG_CRIT, "ERROR: cannot open %s: %s\n",
190                         filename, strerror(errno));
191                 unlink(tempfilename);
192                 return 0;
193         }
194         else {
195                 CfgIt = GetNewHashPos(CfgTypeHash, 1);
196                 fchown(TmpFD, config.c_ctdluid, 0);
197                 for (eCfg = subpending; eCfg < maxRoomNetCfg; eCfg ++)
198                 {
199                         const CfgLineType *pCfg;
200                         pCfg = GetCfgTypeByEnum(eCfg, CfgIt);
201                         if (pCfg->IsSingleLine)
202                         {
203                                 pCfg->Serializer(pCfg, OutBuffer, OneRNCFG, NULL);
204                         }
205                         else
206                         {
207                                 RoomNetCfgLine *pName = OneRNCFG->NetConfigs[pCfg->C];
208                                 while (pName != NULL)
209                                 {
210                                         pCfg->Serializer(pCfg, OutBuffer, OneRNCFG, pName);
211                                         pName = pName->next;
212                                 }
213                                 
214                                 
215                         }
216
217                 }
218                 DeleteHashPos(&CfgIt);
219
220
221                 if (OneRNCFG->misc != NULL) {
222                         StrBufAppendBuf(OutBuffer, OneRNCFG->misc, 0);
223                 }
224
225                 rc = write(TmpFD, ChrPtr(OutBuffer), StrLength(OutBuffer));
226                 if ((rc >=0 ) && (rc == StrLength(Cfg))) 
227                 {
228                         close(TmpFD);
229                         rename(tempfilename, filename);
230                         rc = 1;
231                 }
232                 else {
233                         syslog(LOG_EMERG, 
234                                       "unable to write %s; [%s]; not enough space on the disk?\n", 
235                                       tempfilename, 
236                                       strerror(errno));
237                         close(TmpFD);
238                         unlink(tempfilename);
239                         rc = 0;
240                 }
241                 FreeStrBuf(&OutBuffer);
242                 
243         }
244         return rc;
245 }
246
247
248
249 void free_spoolcontrol_struct(OneRoomNetCfg **pOneRNCFG)
250 {
251         RoomNetCfg eCfg;
252         HashPos *CfgIt;
253         OneRoomNetCfg *OneRNCFG;
254
255         OneRNCFG = *pOneRNCFG;
256         CfgIt = GetNewHashPos(CfgTypeHash, 1);
257         for (eCfg = subpending; eCfg < maxRoomNetCfg; eCfg ++)
258         {
259                 const CfgLineType *pCfg;
260                 RoomNetCfgLine *pNext, *pName;
261                 
262                 pCfg = GetCfgTypeByEnum(eCfg, CfgIt);
263                 pName= OneRNCFG->NetConfigs[pCfg->C];
264                 while (pName != NULL)
265                 {
266                         pNext = pName->next;
267                         pCfg->DeAllocator(pCfg, &pName);
268                         pName = pNext;
269                 }
270         }
271         DeleteHashPos(&CfgIt);
272
273         FreeStrBuf(&OneRNCFG->Sender);
274         FreeStrBuf(&OneRNCFG->RoomInfo);
275         FreeStrBuf(&OneRNCFG->misc);
276         free(OneRNCFG);
277         *pOneRNCFG=NULL;
278 }
279
280
281 /*-----------------------------------------------------------------------------*
282  *              Per room network configs : exchange with client                *
283  *-----------------------------------------------------------------------------*/
284 void cmd_gnet(char *argbuf)
285 {
286         char filename[PATH_MAX];
287         char buf[SIZ];
288         FILE *fp;
289
290
291         if (!IsEmptyStr(argbuf))
292         {
293                 if (CtdlAccessCheck(ac_aide)) return;
294                 if (strcmp(argbuf, FILE_MAILALIAS))
295                 {
296                         cprintf("%d No such file or directory\n",
297                                 ERROR + INTERNAL_ERROR);
298                         return;
299                 }
300                 safestrncpy(filename, file_mail_aliases, sizeof(filename));
301                 cprintf("%d Settings for <%s>\n",
302                         LISTING_FOLLOWS,
303                         filename);
304         }
305         else
306         {
307                 if ( (CC->room.QRflags & QR_MAILBOX) && (CC->user.usernum == atol(CC->room.QRname)) ) {
308                         /* users can edit the netconfigs for their own mailbox rooms */
309                 }
310                 else if (CtdlAccessCheck(ac_room_aide)) return;
311                 
312                 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
313                 cprintf("%d Network settings for room #%ld <%s>\n",
314                         LISTING_FOLLOWS,
315                         CC->room.QRnumber, CC->room.QRname);
316         }
317
318         fp = fopen(filename, "r");
319         if (fp != NULL) {
320                 while (fgets(buf, sizeof buf, fp) != NULL) {
321                         buf[strlen(buf)-1] = 0;
322                         cprintf("%s\n", buf);
323                 }
324                 fclose(fp);
325         }
326
327         cprintf("000\n");
328 }
329
330 #define nForceAliases 5
331 const ConstStr ForceAliases[nForceAliases] = {
332         {HKEY("bbs,")},
333         {HKEY("root,")},
334         {HKEY("Auto,")},
335         {HKEY("postmaster,")},
336         {HKEY("abuse,")}
337 };
338
339 void cmd_snet(char *argbuf) {
340         char tempfilename[PATH_MAX];
341         char filename[PATH_MAX];
342         int TmpFD;
343         StrBuf *Line;
344         struct stat StatBuf;
345         long len;
346         int rc;
347         int IsMailAlias = 0;
348         int MailAliasesFound[nForceAliases];
349
350         unbuffer_output();
351
352         if (!IsEmptyStr(argbuf))
353         {
354                 if (CtdlAccessCheck(ac_aide)) return;
355                 if (strcmp(argbuf, FILE_MAILALIAS))
356                 {
357                         cprintf("%d No such file or directory\n",
358                                 ERROR + INTERNAL_ERROR);
359                         return;
360                 }
361                 len = safestrncpy(filename, file_mail_aliases, sizeof(filename));
362                 memset(MailAliasesFound, 0, sizeof(MailAliasesFound));
363                 memcpy(tempfilename, filename, len + 1);
364                 IsMailAlias = 1;
365         }
366         else
367         {
368                 if ( (CC->room.QRflags & QR_MAILBOX) && (CC->user.usernum == atol(CC->room.QRname)) ) {
369                         /* users can edit the netconfigs for their own mailbox rooms */
370                 }
371                 else if (CtdlAccessCheck(ac_room_aide)) return;
372                 
373                 len = assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
374                 memcpy(tempfilename, filename, len + 1);
375         }
376         memset(&StatBuf, 0, sizeof(struct stat));
377         if ((stat(filename, &StatBuf)  == -1) || (StatBuf.st_size == 0))
378                 StatBuf.st_size = 80; /* Not there or empty? guess 80 chars line. */
379
380         sprintf(tempfilename + len, ".%d", CC->cs_pid);
381         errno = 0;
382         TmpFD = open(tempfilename, O_CREAT|O_EXCL|O_RDWR, S_IRUSR|S_IWUSR);
383
384         if ((TmpFD > 0) && (errno == 0))
385         {
386                 char *tmp = malloc(StatBuf.st_size * 2);
387                 memset(tmp, ' ', StatBuf.st_size * 2);
388                 rc = write(TmpFD, tmp, StatBuf.st_size * 2);
389                 free(tmp);
390                 if ((rc <= 0) || (rc != StatBuf.st_size * 2))
391                 {
392                         close(TmpFD);
393                         cprintf("%d Unable to allocate the space required for %s: %s\n",
394                                 ERROR + INTERNAL_ERROR,
395                                 tempfilename,
396                                 strerror(errno));
397                         unlink(tempfilename);
398                         return;
399                 }       
400                 lseek(TmpFD, SEEK_SET, 0);
401         }
402         else {
403                 cprintf("%d Unable to allocate the space required for %s: %s\n",
404                         ERROR + INTERNAL_ERROR,
405                         tempfilename,
406                         strerror(errno));
407                 unlink(tempfilename);
408                 return;
409         }
410         Line = NewStrBuf();
411
412         cprintf("%d %s\n", SEND_LISTING, tempfilename);
413
414         len = 0;
415         while (rc = CtdlClientGetLine(Line), 
416                (rc >= 0))
417         {
418                 if ((rc == 3) && (strcmp(ChrPtr(Line), "000") == 0))
419                         break;
420                 if (IsMailAlias)
421                 {
422                         int i;
423
424                         for (i = 0; i < nForceAliases; i++)
425                         {
426                                 if ((!MailAliasesFound[i]) && 
427                                     (strncmp(ForceAliases[i].Key, 
428                                              ChrPtr(Line),
429                                              ForceAliases[i].len) == 0)
430                                         )
431                                     {
432                                             MailAliasesFound[i] = 1;
433                                             break;
434                                     }
435                         }
436                 }
437
438                 StrBufAppendBufPlain(Line, HKEY("\n"), 0);
439                 write(TmpFD, ChrPtr(Line), StrLength(Line));
440                 len += StrLength(Line);
441         }
442         FreeStrBuf(&Line);
443         ftruncate(TmpFD, len);
444         close(TmpFD);
445
446         if (IsMailAlias)
447         {
448                 int i, state;
449                 /*
450                  * Sanity check whether all aliases required by the RFCs were set
451                  * else bail out.
452                  */
453                 state = 1;
454                 for (i = 0; i < nForceAliases; i++)
455                 {
456                         if (!MailAliasesFound[i]) 
457                                 state = 0;
458                 }
459                 if (state == 0)
460                 {
461                         cprintf("%d won't do this - you're missing an RFC required alias.\n",
462                                 ERROR + INTERNAL_ERROR);
463                         unlink(tempfilename);
464                         return;
465                 }
466         }
467
468         /* Now copy the temp file to its permanent location.
469          * (We copy instead of link because they may be on different filesystems)
470          */
471         begin_critical_section(S_NETCONFIGS);
472         rename(tempfilename, filename);
473         end_critical_section(S_NETCONFIGS);
474 }
475
476
477 /*-----------------------------------------------------------------------------*
478  *                       Per node network configs                              *
479  *-----------------------------------------------------------------------------*/
480 void DeleteCtdlNodeConf(void *vNode)
481 {
482         CtdlNodeConf *Node = (CtdlNodeConf*) vNode;
483         FreeStrBuf(&Node->NodeName);
484         FreeStrBuf(&Node->Secret);
485         FreeStrBuf(&Node->Host);
486         FreeStrBuf(&Node->Port);
487         free(Node);
488 }
489
490 CtdlNodeConf *NewNode(StrBuf *SerializedNode)
491 {
492         const char *Pos = NULL;
493         CtdlNodeConf *Node;
494
495         /* we need at least 4 pipes and some other text so its invalid. */
496         if (StrLength(SerializedNode) < 8)
497                 return NULL;
498         Node = (CtdlNodeConf *) malloc(sizeof(CtdlNodeConf));
499
500         Node->DeleteMe = 0;
501
502         Node->NodeName=NewStrBuf();
503         StrBufExtract_NextToken(Node->NodeName, SerializedNode, &Pos, '|');
504
505         Node->Secret=NewStrBuf();
506         StrBufExtract_NextToken(Node->Secret, SerializedNode, &Pos, '|');
507
508         Node->Host=NewStrBuf();
509         StrBufExtract_NextToken(Node->Host, SerializedNode, &Pos, '|');
510
511         Node->Port=NewStrBuf();
512         StrBufExtract_NextToken(Node->Port, SerializedNode, &Pos, '|');
513         return Node;
514 }
515
516
517 /*
518  * Load or refresh the Citadel network (IGnet) configuration for this node.
519  */
520 HashList* CtdlLoadIgNetCfg(void)
521 {
522         const char *LinePos;
523         char       *Cfg;
524         StrBuf     *Buf;
525         StrBuf     *LineBuf;
526         HashList   *Hash;
527         CtdlNodeConf   *Node;
528
529         Cfg =  CtdlGetSysConfig(IGNETCFG);
530         if ((Cfg == NULL) || IsEmptyStr(Cfg)) {
531                 if (Cfg != NULL)
532                         free(Cfg);
533                 return NULL;
534         }
535
536         Hash = NewHash(1, NULL);
537         Buf = NewStrBufPlain(Cfg, -1);
538         free(Cfg);
539         LineBuf = NewStrBufPlain(NULL, StrLength(Buf));
540         LinePos = NULL;
541         do
542         {
543                 StrBufSipLine(LineBuf, Buf, &LinePos);
544                 if (StrLength(LineBuf) != 0) {
545                         Node = NewNode(LineBuf);
546                         if (Node != NULL) {
547                                 Put(Hash, SKEY(Node->NodeName), Node, DeleteCtdlNodeConf);
548                         }
549                 }
550         } while (LinePos != StrBufNOTNULL);
551         FreeStrBuf(&Buf);
552         FreeStrBuf(&LineBuf);
553         return Hash;
554 }
555
556
557 int is_recipient(OneRoomNetCfg *RNCfg, const char *Name)
558 {
559         const RoomNetCfg RecipientCfgs[] = {
560                 listrecp,
561                 digestrecp,
562                 participate,
563                 maxRoomNetCfg
564         };
565         int i;
566         RoomNetCfgLine *nptr;
567         size_t len;
568         
569         len = strlen(Name);
570         i = 0;
571         while (RecipientCfgs[i] != maxRoomNetCfg)
572         {
573                 nptr = RNCfg->NetConfigs[RecipientCfgs[i]];
574                 
575                 while (nptr != NULL)
576                 {
577                         if ((StrLength(nptr->Value) == len) && 
578                             (!strcmp(Name, ChrPtr(nptr->Value))))
579                         {
580                                 return 1;
581                         }
582                         nptr = nptr->next;
583                 }
584         }
585         return 0;
586 }
587
588
589
590 int CtdlNetconfigCheckRoomaccess(
591         char *errmsgbuf, 
592         size_t n,
593         const char* RemoteIdentifier)
594 {
595         OneRoomNetCfg *RNCfg;
596         char filename[SIZ];
597         int found;
598
599         if (RemoteIdentifier == NULL)
600         {
601                 snprintf(errmsgbuf, n, "Need sender to permit access.");
602                 return (ERROR + USERNAME_REQUIRED);
603         }
604
605         assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
606         begin_critical_section(S_NETCONFIGS);
607         if (!read_spoolcontrol_file(&RNCfg, filename))
608         {
609                 end_critical_section(S_NETCONFIGS);
610                 snprintf(errmsgbuf, n,
611                          "This mailing list only accepts posts from subscribers.");
612                 return (ERROR + NO_SUCH_USER);
613         }
614         end_critical_section(S_NETCONFIGS);
615         found = is_recipient (RNCfg, RemoteIdentifier);
616         free_spoolcontrol_struct(&RNCfg);
617         if (found) {
618                 return (0);
619         }
620         else {
621                 snprintf(errmsgbuf, n,
622                          "This mailing list only accepts posts from subscribers.");
623                 return (ERROR + NO_SUCH_USER);
624         }
625 }
626
627
628
629 /*
630  * cmd_netp() - authenticate to the server as another Citadel node polling
631  *            for network traffic
632  */
633 void cmd_netp(char *cmdbuf)
634 {
635         struct CitContext *CCC = CC;
636         HashList *working_ignetcfg;
637         char *node;
638         StrBuf *NodeStr;
639         long nodelen;
640         int v;
641         long lens[2];
642         const char *strs[2];
643
644         const StrBuf *secret = NULL;
645         const StrBuf *nexthop = NULL;
646         char err_buf[SIZ] = "";
647
648         /* Authenticate */
649         node = CCC->curr_user;
650         nodelen = extract_token(CCC->curr_user, cmdbuf, 0, '|', sizeof CCC->curr_user);
651         NodeStr = NewStrBufPlain(node, nodelen);
652         /* load the IGnet Configuration to check node validity */
653         working_ignetcfg = CtdlLoadIgNetCfg();
654         v = CtdlIsValidNode(&nexthop, &secret, NodeStr, working_ignetcfg, NULL);
655         if (v != 0) {
656                 snprintf(err_buf, sizeof err_buf,
657                         "An unknown Citadel server called \"%s\" attempted to connect from %s [%s].\n",
658                         node, CCC->cs_host, CCC->cs_addr
659                 );
660                 syslog(LOG_WARNING, "%s", err_buf);
661                 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
662
663                 strs[0] = CCC->cs_addr;
664                 lens[0] = strlen(CCC->cs_addr);
665                 
666                 strs[1] = "SRV_UNKNOWN";
667                 lens[1] = sizeof("SRV_UNKNOWN" - 1);
668
669                 CtdlAideFPMessage(
670                         err_buf,
671                         "IGNet Networking.",
672                         2, strs, (long*) &lens);
673
674                 DeleteHash(&working_ignetcfg);
675                 FreeStrBuf(&NodeStr);
676                 return;
677         }
678
679         extract_token(CCC->user.password, cmdbuf, 1, '|', sizeof CCC->user.password);
680         if (strcasecmp(CCC->user.password, ChrPtr(secret))) {
681                 snprintf(err_buf, sizeof err_buf,
682                         "A Citadel server at %s [%s] failed to authenticate as network node \"%s\".\n",
683                         CCC->cs_host, CCC->cs_addr, node
684                 );
685                 syslog(LOG_WARNING, "%s", err_buf);
686                 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
687
688                 strs[0] = CCC->cs_addr;
689                 lens[0] = strlen(CCC->cs_addr);
690                 
691                 strs[1] = "SRV_PW";
692                 lens[1] = sizeof("SRV_PW" - 1);
693
694                 CtdlAideFPMessage(
695                         err_buf,
696                         "IGNet Networking.",
697                         2, strs, (long*) &lens);
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]\n",
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         Cfg =  CtdlGetSysConfig(IGNETMAP);
765         if ((Cfg == NULL) || IsEmptyStr(Cfg)) {
766                 if (Cfg != NULL)
767                         free(Cfg);
768                 return NULL;
769         }
770
771         Hash = NewHash(1, NULL);
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!\n");
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>\n", ChrPtr(node));
905         return(-1);
906 }
907
908
909 /*
910  * Module entry point
911  */
912 CTDL_MODULE_INIT(netconfig)
913 {
914         if (!threading)
915         {
916
917                 CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
918                 CtdlRegisterProtoHook(cmd_snet, "SNET", "Set network config");
919                 CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
920         }
921         return "netconfig";
922 }