52adbbddff79cdb60730b3893a4c740a42399562
[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 #include <dirent.h>
28
29 #include <libcitadel.h>
30
31 #include "include/ctdl_module.h"
32
33
34 void vFreeRoomNetworkStruct(void *vOneRoomNetCfg);
35
36 HashList *CfgTypeHash = NULL;
37 HashList *RoomConfigs = NULL;
38 /*-----------------------------------------------------------------------------*
39  *                       Per room network configs                              *
40  *-----------------------------------------------------------------------------*/
41 void RegisterRoomCfgType(const char* Name, long len, RoomNetCfg eCfg, CfgLineParser p, int uniq,  int nSegments, CfgLineSerializer s, CfgLineDeAllocator d)
42 {
43         CfgLineType *pCfg;
44
45         pCfg = (CfgLineType*) malloc(sizeof(CfgLineType));
46         pCfg->Parser = p;
47         pCfg->Serializer = s;
48         pCfg->DeAllocator = d;
49         pCfg->C = eCfg;
50         pCfg->Str.Key = Name;
51         pCfg->Str.len = len;
52         pCfg->IsSingleLine = uniq;
53         pCfg->nSegments = nSegments;
54         if (CfgTypeHash == NULL)
55                 CfgTypeHash = NewHash(1, NULL);
56         Put(CfgTypeHash, Name, len, pCfg, NULL);
57 }
58
59
60 const CfgLineType *GetCfgTypeByStr(const char *Key, long len)
61 {
62         void *pv;
63         
64         if (GetHash(CfgTypeHash, Key, len, &pv) && (pv != NULL))
65         {
66                 return (const CfgLineType *) pv;
67         }
68         else
69         {
70                 return NULL;
71         }
72 }
73
74 const CfgLineType *GetCfgTypeByEnum(RoomNetCfg eCfg, HashPos *It)
75 {
76         const char *Key;
77         long len;
78         void *pv;
79         CfgLineType *pCfg;
80
81         RewindHashPos(CfgTypeHash, It, 1);
82         while (GetNextHashPos(CfgTypeHash, It, &len, &Key, &pv) && (pv != NULL))
83         {
84                 pCfg = (CfgLineType*) pv;
85                 if (pCfg->C == eCfg)
86                         return pCfg;
87         }
88         return NULL;
89 }
90 void ParseGeneric(const CfgLineType *ThisOne, StrBuf *Line, const char *LinePos, OneRoomNetCfg *OneRNCfg)
91 {
92         RoomNetCfgLine *nptr;
93         int i;
94
95         nptr = (RoomNetCfgLine *)
96                 malloc(sizeof(RoomNetCfgLine));
97         nptr->next = OneRNCfg->NetConfigs[ThisOne->C];
98         nptr->Value = malloc(sizeof(StrBuf*) * ThisOne->nSegments);
99         nptr->nValues = 0;
100         memset(nptr->Value, 0, sizeof(StrBuf*) * ThisOne->nSegments);
101         if (ThisOne->nSegments == 1)
102         {
103                 nptr->Value[0] = NewStrBufPlain(LinePos, StrLength(Line) - ( LinePos - ChrPtr(Line)) );
104                 nptr->nValues = 1;
105         }
106         else for (i = 0; i < ThisOne->nSegments; i++)
107         {
108                 nptr->nValues++;
109                 nptr->Value[i] = NewStrBufPlain(NULL, StrLength(Line) - ( LinePos - ChrPtr(Line)) );
110                 StrBufExtract_NextToken(nptr->Value[i], Line, &LinePos, '|');
111         }
112
113         OneRNCfg->NetConfigs[ThisOne->C] = nptr;
114 }
115
116 void SerializeGeneric(const CfgLineType *ThisOne, StrBuf *OutputBuffer, OneRoomNetCfg *OneRNCfg, RoomNetCfgLine *data)
117 {
118         int i;
119
120         StrBufAppendBufPlain(OutputBuffer, CKEY(ThisOne->Str), 0);
121         StrBufAppendBufPlain(OutputBuffer, HKEY("|"), 0);
122         for (i = 0; i < ThisOne->nSegments; i++)
123         {
124                 StrBufAppendBuf(OutputBuffer, data->Value[i], 0);
125                 if (i + 1 < ThisOne->nSegments)
126                         StrBufAppendBufPlain(OutputBuffer, HKEY("|"), 0);
127         }
128         StrBufAppendBufPlain(OutputBuffer, HKEY("\n"), 0);
129 }
130
131 void DeleteGenericCfgLine(const CfgLineType *ThisOne, RoomNetCfgLine **data)
132 {
133         int i;
134
135         if (*data == NULL)
136                 return;
137
138         for (i = 0; i < (*data)->nValues; i++)
139         {
140                 FreeStrBuf(&(*data)->Value[i]);
141         }
142         free ((*data)->Value);
143         free(*data);
144         *data = NULL;
145 }
146 RoomNetCfgLine *DuplicateOneGenericCfgLine(const RoomNetCfgLine *data)
147 {
148         RoomNetCfgLine *NewData;
149
150         NewData = (RoomNetCfgLine*)malloc(sizeof(RoomNetCfgLine));
151         int i;
152         NewData->Value = (StrBuf **)malloc(sizeof(StrBuf*) * data->nValues);
153
154         for (i = 0; i < data->nValues; i++)
155         {
156                 NewData->Value[i] = NewStrBufDup(data->Value[i]);
157         }
158         return NewData;
159 }
160 int ReadRoomNetConfigFile(OneRoomNetCfg **pOneRNCfg, char *filename)
161 {
162         int fd;
163         const char *ErrStr = NULL;
164         const char *Pos;
165         const CfgLineType *pCfg;
166         StrBuf *Line;
167         StrBuf *InStr;
168         OneRoomNetCfg *OneRNCfg;
169
170         fd = open(filename, O_NONBLOCK|O_RDONLY);
171         if (fd == -1) {
172                 *pOneRNCfg = NULL;
173                 return 0;
174         }
175         if (*pOneRNCfg != NULL)
176                 OneRNCfg = *pOneRNCfg;
177         else
178                 OneRNCfg = malloc(sizeof(OneRoomNetCfg));
179         memset(OneRNCfg, 0, sizeof(OneRoomNetCfg));
180         *pOneRNCfg = OneRNCfg;
181         Line = NewStrBuf();
182         InStr = NewStrBuf();
183
184         while (StrBufTCP_read_line(Line, &fd, 0, &ErrStr) >= 0) {
185                 if (StrLength(Line) == 0)
186                         continue;
187                 Pos = NULL;
188                 StrBufExtract_NextToken(InStr, Line, &Pos, '|');
189
190                 pCfg = GetCfgTypeByStr(SKEY(InStr));
191                 if (pCfg != NULL)
192                 {
193                         pCfg->Parser(pCfg, Line, Pos, OneRNCfg);
194                 }
195                 else
196                 {
197                         if (OneRNCfg->misc == NULL)
198                         {
199                                 OneRNCfg->misc = NewStrBufDup(Line);
200                         }
201                         else
202                         {
203                                 if(StrLength(OneRNCfg->misc) > 0)
204                                         StrBufAppendBufPlain(OneRNCfg->misc, HKEY("\n"), 0);
205                                 StrBufAppendBuf(OneRNCfg->misc, Line, 0);
206                         }
207                 }
208         }
209         if (fd > 0)
210                 close(fd);
211         FreeStrBuf(&InStr);
212         FreeStrBuf(&Line);
213         return 1;
214 }
215
216 int SaveRoomNetConfigFile(OneRoomNetCfg *OneRNCfg, char *filename)
217 {
218         RoomNetCfg eCfg;
219         StrBuf *Cfg = NULL;
220         StrBuf *OutBuffer = NULL;
221         char tempfilename[PATH_MAX];
222         int TmpFD;
223         long len;
224         time_t unixtime;
225         struct timeval tv;
226         long reltid; /* if we don't have SYS_gettid, use "random" value */
227         int rc;
228         HashPos *CfgIt;
229
230         len = strlen(filename);
231         memcpy(tempfilename, filename, len + 1);
232
233 #if defined(HAVE_SYSCALL_H) && defined (SYS_gettid)
234         reltid = syscall(SYS_gettid);
235 #endif
236         gettimeofday(&tv, NULL);
237         /* Promote to time_t; types differ on some OSes (like darwin) */
238         unixtime = tv.tv_sec;
239
240         sprintf(tempfilename + len, ".%ld-%ld", reltid, unixtime);
241         errno = 0;
242         TmpFD = open(tempfilename, O_CREAT|O_EXCL|O_RDWR, S_IRUSR|S_IWUSR);
243         Cfg = NewStrBuf();
244         if ((TmpFD < 0) || (errno != 0)) {
245                 syslog(LOG_CRIT, "ERROR: cannot open %s: %s\n",
246                         filename, strerror(errno));
247                 unlink(tempfilename);
248                 FreeStrBuf(&Cfg);
249                 return 0;
250         }
251         else {
252                 OutBuffer = NewStrBuf();
253                 CfgIt = GetNewHashPos(CfgTypeHash, 1);
254                 fchown(TmpFD, config.c_ctdluid, 0);
255                 for (eCfg = subpending; eCfg < maxRoomNetCfg; eCfg ++)
256                 {
257                         const CfgLineType *pCfg;
258                         pCfg = GetCfgTypeByEnum(eCfg, CfgIt);
259                         if (pCfg->IsSingleLine)
260                         {
261                                 pCfg->Serializer(pCfg, OutBuffer, OneRNCfg, NULL);
262                         }
263                         else
264                         {
265                                 RoomNetCfgLine *pName = OneRNCfg->NetConfigs[pCfg->C];
266                                 while (pName != NULL)
267                                 {
268                                         pCfg->Serializer(pCfg, OutBuffer, OneRNCfg, pName);
269                                         pName = pName->next;
270                                 }
271                                 
272                                 
273                         }
274
275                 }
276                 DeleteHashPos(&CfgIt);
277
278
279                 if (OneRNCfg->misc != NULL) {
280                         StrBufAppendBuf(OutBuffer, OneRNCfg->misc, 0);
281                 }
282
283                 rc = write(TmpFD, ChrPtr(OutBuffer), StrLength(OutBuffer));
284                 if ((rc >=0 ) && (rc == StrLength(OutBuffer))) 
285                 {
286                         close(TmpFD);
287                         rename(tempfilename, filename);
288                         rc = 1;
289                 }
290                 else {
291                         syslog(LOG_EMERG, 
292                                       "unable to write %s; [%s]; not enough space on the disk?\n", 
293                                       tempfilename, 
294                                       strerror(errno));
295                         close(TmpFD);
296                         unlink(tempfilename);
297                         rc = 0;
298                 }
299                 FreeStrBuf(&OutBuffer);
300                 
301         }
302         FreeStrBuf(&Cfg);
303         return rc;
304 }
305
306 void SaveModifiedRooms(struct ctdlroom *qrbuf, void *data, OneRoomNetCfg *OneRNCfg)
307 {
308         char filename[PATH_MAX];
309
310         if (OneRNCfg->changed)
311         {
312                 assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
313                 SaveRoomNetConfigFile(OneRNCfg, filename);
314                 OneRNCfg->changed = 0;
315         }
316 }
317 void SaveChangedConfigs(void)
318 {
319         CtdlForEachNetCfgRoom(SaveModifiedRooms,
320                               NULL, 
321                               maxRoomNetCfg);
322 }
323
324
325 void AddRoomCfgLine(OneRoomNetCfg *OneRNCfg, struct ctdlroom *qrbuf, RoomNetCfg LineType, RoomNetCfgLine *Line)
326 {
327         int new = 0;
328         RoomNetCfgLine **pLine;
329         char filename[PATH_MAX];
330
331         if (OneRNCfg == NULL)
332         {
333                 new = 1;
334                 OneRNCfg = (OneRoomNetCfg*) malloc(sizeof(OneRoomNetCfg));
335                 memset(OneRNCfg, 0, sizeof(OneRoomNetCfg));
336         }
337         pLine = &OneRNCfg->NetConfigs[LineType];
338
339         while(*pLine != NULL) pLine = &((*pLine)->next);
340         *pLine = Line;
341
342         assoc_file_name(filename, sizeof filename, qrbuf, ctdl_netcfg_dir);
343         SaveRoomNetConfigFile(OneRNCfg, filename);
344         OneRNCfg->changed = 0;
345         if (new)
346         {
347                 Put(RoomConfigs, LKEY(qrbuf->QRnumber), OneRNCfg, vFreeRoomNetworkStruct);
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 }
384 void vFreeRoomNetworkStruct(void *vOneRoomNetCfg)
385 {
386         OneRoomNetCfg *OneRNCfg;
387         OneRNCfg = (OneRoomNetCfg*)vOneRoomNetCfg;
388         FreeRoomNetworkStructContent(OneRNCfg);
389         free(OneRNCfg);
390 }
391 void FreeRoomNetworkStruct(OneRoomNetCfg **pOneRNCfg)
392 {
393         vFreeRoomNetworkStruct(*pOneRNCfg);
394         *pOneRNCfg=NULL;
395 }
396
397 OneRoomNetCfg* CtdlGetNetCfgForRoom(long QRNumber)
398 {
399         void *pv;
400         GetHash(RoomConfigs, LKEY(QRNumber), &pv);
401         return (OneRoomNetCfg*)pv;
402 }
403
404
405 void LoadAllNetConfigs(void)
406 {
407         DIR *filedir = NULL;
408         struct dirent *d;
409         struct dirent *filedir_entry;
410         int d_type = 0;
411         int d_namelen;
412         long RoomNumber;
413         OneRoomNetCfg *OneRNCfg;
414         int IsNumOnly;
415         const char *pch;
416         char path[PATH_MAX];
417
418         RoomConfigs = NewHash(1, NULL);
419         filedir = opendir (ctdl_netcfg_dir);
420         if (filedir == NULL) {
421                 return ; /// todo: panic!
422         }
423
424         d = (struct dirent *)malloc(offsetof(struct dirent, d_name) + PATH_MAX + 1);
425         if (d == NULL) {
426                 closedir(filedir);
427                 return ;
428         }
429
430         while ((readdir_r(filedir, d, &filedir_entry) == 0) &&
431                (filedir_entry != NULL))
432         {
433 #ifdef _DIRENT_HAVE_D_NAMLEN
434                 d_namelen = filedir_entry->d_namelen;
435 #else
436                 d_namelen = strlen(filedir_entry->d_name);
437 #endif
438
439 #ifdef _DIRENT_HAVE_D_TYPE
440                 d_type = filedir_entry->d_type;
441 #else
442
443 #ifndef DT_UNKNOWN
444 #define DT_UNKNOWN     0
445 #define DT_DIR         4
446 #define DT_REG         8
447 #define DT_LNK         10
448
449 #define IFTODT(mode)   (((mode) & 0170000) >> 12)
450 #define DTTOIF(dirtype)        ((dirtype) << 12)
451 #endif
452                 d_type = DT_UNKNOWN;
453 #endif
454                 if ((d_namelen > 1) && filedir_entry->d_name[d_namelen - 1] == '~')
455                         continue; /* Ignore backup files... */
456
457                 if ((d_namelen == 1) && 
458                     (filedir_entry->d_name[0] == '.'))
459                         continue;
460
461                 if ((d_namelen == 2) && 
462                     (filedir_entry->d_name[0] == '.') &&
463                     (filedir_entry->d_name[1] == '.'))
464                         continue;
465
466                 snprintf(path, PATH_MAX, "%s/%s", 
467                          ctdl_netcfg_dir, filedir_entry->d_name);
468
469                 if (d_type == DT_UNKNOWN) {
470                         struct stat s;
471                         if (lstat(path, &s) == 0) {
472                                 d_type = IFTODT(s.st_mode);
473                         }
474                 }
475
476                 switch (d_type)
477                 {
478                 case DT_DIR:
479                         break;
480                 case DT_LNK: /* TODO: check whether its a file or a directory */
481                 case DT_REG:
482                         IsNumOnly = 1;
483                         pch = filedir_entry->d_name;
484                         while (*pch != '\0')
485                         {
486                                 if (!isdigit(*pch))
487                                 {
488                                         IsNumOnly = 0;
489                                 }
490                                 pch ++;
491                         }
492                         if (IsNumOnly)
493                         {
494                                 OneRNCfg = NULL;
495                                 RoomNumber = atol(filedir_entry->d_name);
496                                 ReadRoomNetConfigFile(&OneRNCfg, path);
497
498                                 if (OneRNCfg != NULL)
499                                         Put(RoomConfigs, LKEY(RoomNumber), OneRNCfg, vFreeRoomNetworkStruct);
500                                 /* syslog(9, "[%s | %s]\n", ChrPtr(OneWebName), ChrPtr(FileName)); */
501                         }
502                         break;
503                 default:
504                         break;
505                 }
506
507
508         }
509         free(d);
510         closedir(filedir);
511 }
512
513
514 /*-----------------------------------------------------------------------------*
515  *              Per room network configs : exchange with client                *
516  *-----------------------------------------------------------------------------*/
517 void cmd_gnet(char *argbuf)
518 {
519         char filename[PATH_MAX];
520         char buf[SIZ];
521         FILE *fp;
522
523
524         if (!IsEmptyStr(argbuf))
525         {
526                 if (CtdlAccessCheck(ac_aide)) return;
527                 if (strcmp(argbuf, FILE_MAILALIAS))
528                 {
529                         cprintf("%d No such file or directory\n",
530                                 ERROR + INTERNAL_ERROR);
531                         return;
532                 }
533                 safestrncpy(filename, file_mail_aliases, sizeof(filename));
534                 cprintf("%d Settings for <%s>\n",
535                         LISTING_FOLLOWS,
536                         filename);
537         }
538         else
539         {
540                 if ( (CC->room.QRflags & QR_MAILBOX) && (CC->user.usernum == atol(CC->room.QRname)) ) {
541                         /* users can edit the netconfigs for their own mailbox rooms */
542                 }
543                 else if (CtdlAccessCheck(ac_room_aide)) return;
544                 
545                 assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
546                 cprintf("%d Network settings for room #%ld <%s>\n",
547                         LISTING_FOLLOWS,
548                         CC->room.QRnumber, CC->room.QRname);
549         }
550
551         fp = fopen(filename, "r");
552         if (fp != NULL) {
553                 while (fgets(buf, sizeof buf, fp) != NULL) {
554                         buf[strlen(buf)-1] = 0;
555                         cprintf("%s\n", buf);
556                 }
557                 fclose(fp);
558         }
559
560         cprintf("000\n");
561 }
562
563 #define nForceAliases 5
564 const ConstStr ForceAliases[nForceAliases] = {
565         {HKEY("bbs,")},
566         {HKEY("root,")},
567         {HKEY("Auto,")},
568         {HKEY("postmaster,")},
569         {HKEY("abuse,")}
570 };
571
572 void cmd_snet(char *argbuf)
573 {
574         struct CitContext *CCC = CC;
575         char tempfilename[PATH_MAX];
576         char filename[PATH_MAX];
577         int TmpFD;
578         StrBuf *Line;
579         struct stat StatBuf;
580         long len;
581         int rc;
582         int IsMailAlias = 0;
583         int MailAliasesFound[nForceAliases];
584
585         unbuffer_output();
586
587         if (!IsEmptyStr(argbuf))
588         {
589                 if (CtdlAccessCheck(ac_aide)) return;
590                 if (strcmp(argbuf, FILE_MAILALIAS))
591                 {
592                         cprintf("%d No such file or directory\n",
593                                 ERROR + INTERNAL_ERROR);
594                         return;
595                 }
596                 len = safestrncpy(filename, file_mail_aliases, sizeof(filename));
597                 memset(MailAliasesFound, 0, sizeof(MailAliasesFound));
598                 memcpy(tempfilename, filename, len + 1);
599                 IsMailAlias = 1;
600         }
601         else
602         {
603                 if ( (CCC->room.QRflags & QR_MAILBOX) && (CCC->user.usernum == atol(CCC->room.QRname)) ) {
604                         /* users can edit the netconfigs for their own mailbox rooms */
605                 }
606                 else if (CtdlAccessCheck(ac_room_aide)) return;
607                 
608                 len = assoc_file_name(filename, sizeof filename, &CCC->room, ctdl_netcfg_dir);
609                 memcpy(tempfilename, filename, len + 1);
610         }
611         memset(&StatBuf, 0, sizeof(struct stat));
612         if ((stat(filename, &StatBuf)  == -1) || (StatBuf.st_size == 0))
613                 StatBuf.st_size = 80; /* Not there or empty? guess 80 chars line. */
614
615         sprintf(tempfilename + len, ".%d", CCC->cs_pid);
616         errno = 0;
617         TmpFD = open(tempfilename, O_CREAT|O_EXCL|O_RDWR, S_IRUSR|S_IWUSR);
618
619         if ((TmpFD > 0) && (errno == 0))
620         {
621                 char *tmp = malloc(StatBuf.st_size * 2);
622                 memset(tmp, ' ', StatBuf.st_size * 2);
623                 rc = write(TmpFD, tmp, StatBuf.st_size * 2);
624                 free(tmp);
625                 if ((rc <= 0) || (rc != StatBuf.st_size * 2))
626                 {
627                         close(TmpFD);
628                         cprintf("%d Unable to allocate the space required for %s: %s\n",
629                                 ERROR + INTERNAL_ERROR,
630                                 tempfilename,
631                                 strerror(errno));
632                         unlink(tempfilename);
633                         return;
634                 }       
635                 lseek(TmpFD, SEEK_SET, 0);
636         }
637         else {
638                 cprintf("%d Unable to allocate the space required for %s: %s\n",
639                         ERROR + INTERNAL_ERROR,
640                         tempfilename,
641                         strerror(errno));
642                 unlink(tempfilename);
643                 return;
644         }
645         Line = NewStrBuf();
646
647         cprintf("%d %s\n", SEND_LISTING, tempfilename);
648
649         len = 0;
650         while (rc = CtdlClientGetLine(Line), 
651                (rc >= 0))
652         {
653                 if ((rc == 3) && (strcmp(ChrPtr(Line), "000") == 0))
654                         break;
655                 if (IsMailAlias)
656                 {
657                         int i;
658
659                         for (i = 0; i < nForceAliases; i++)
660                         {
661                                 if ((!MailAliasesFound[i]) && 
662                                     (strncmp(ForceAliases[i].Key, 
663                                              ChrPtr(Line),
664                                              ForceAliases[i].len) == 0)
665                                         )
666                                     {
667                                             MailAliasesFound[i] = 1;
668                                             break;
669                                     }
670                         }
671                 }
672
673                 StrBufAppendBufPlain(Line, HKEY("\n"), 0);
674                 write(TmpFD, ChrPtr(Line), StrLength(Line));
675                 len += StrLength(Line);
676         }
677         FreeStrBuf(&Line);
678         ftruncate(TmpFD, len);
679         close(TmpFD);
680
681         if (IsMailAlias)
682         {
683                 int i, state;
684                 /*
685                  * Sanity check whether all aliases required by the RFCs were set
686                  * else bail out.
687                  */
688                 state = 1;
689                 for (i = 0; i < nForceAliases; i++)
690                 {
691                         if (!MailAliasesFound[i]) 
692                                 state = 0;
693                 }
694                 if (state == 0)
695                 {
696                         cprintf("%d won't do this - you're missing an RFC required alias.\n",
697                                 ERROR + INTERNAL_ERROR);
698                         unlink(tempfilename);
699                         return;
700                 }
701         }
702
703         /* Now copy the temp file to its permanent location.
704          * (We copy instead of link because they may be on different filesystems)
705          */
706         begin_critical_section(S_NETCONFIGS);
707         rename(tempfilename, filename);
708         if (!IsMailAlias)
709         {
710                 OneRoomNetCfg *RNCfg;
711                 RNCfg = CtdlGetNetCfgForRoom(CCC->room.QRnumber);
712                 if (RNCfg != NULL)
713                 {
714                         FreeRoomNetworkStructContent(RNCfg);
715                         ReadRoomNetConfigFile(&RNCfg, filename);
716                 }
717                 else
718                 {
719                         ReadRoomNetConfigFile(&RNCfg, filename);
720                         Put(RoomConfigs, LKEY(CCC->room.QRnumber), RNCfg, vFreeRoomNetworkStruct);
721                 }
722         }
723         end_critical_section(S_NETCONFIGS);
724 }
725
726
727 /*-----------------------------------------------------------------------------*
728  *                       Per node network configs                              *
729  *-----------------------------------------------------------------------------*/
730 void DeleteCtdlNodeConf(void *vNode)
731 {
732         CtdlNodeConf *Node = (CtdlNodeConf*) vNode;
733         FreeStrBuf(&Node->NodeName);
734         FreeStrBuf(&Node->Secret);
735         FreeStrBuf(&Node->Host);
736         FreeStrBuf(&Node->Port);
737         free(Node);
738 }
739
740 CtdlNodeConf *NewNode(StrBuf *SerializedNode)
741 {
742         const char *Pos = NULL;
743         CtdlNodeConf *Node;
744
745         /* we need at least 4 pipes and some other text so its invalid. */
746         if (StrLength(SerializedNode) < 8)
747                 return NULL;
748         Node = (CtdlNodeConf *) malloc(sizeof(CtdlNodeConf));
749
750         Node->DeleteMe = 0;
751
752         Node->NodeName=NewStrBuf();
753         StrBufExtract_NextToken(Node->NodeName, SerializedNode, &Pos, '|');
754
755         Node->Secret=NewStrBuf();
756         StrBufExtract_NextToken(Node->Secret, SerializedNode, &Pos, '|');
757
758         Node->Host=NewStrBuf();
759         StrBufExtract_NextToken(Node->Host, SerializedNode, &Pos, '|');
760
761         Node->Port=NewStrBuf();
762         StrBufExtract_NextToken(Node->Port, SerializedNode, &Pos, '|');
763         return Node;
764 }
765
766
767 /*
768  * Load or refresh the Citadel network (IGnet) configuration for this node.
769  */
770 HashList* CtdlLoadIgNetCfg(void)
771 {
772         const char *LinePos;
773         char       *Cfg;
774         StrBuf     *Buf;
775         StrBuf     *LineBuf;
776         HashList   *Hash;
777         CtdlNodeConf   *Node;
778
779         Cfg =  CtdlGetSysConfig(IGNETCFG);
780         if ((Cfg == NULL) || IsEmptyStr(Cfg)) {
781                 if (Cfg != NULL)
782                         free(Cfg);
783                 return NULL;
784         }
785
786         Hash = NewHash(1, NULL);
787         Buf = NewStrBufPlain(Cfg, -1);
788         free(Cfg);
789         LineBuf = NewStrBufPlain(NULL, StrLength(Buf));
790         LinePos = NULL;
791         do
792         {
793                 StrBufSipLine(LineBuf, Buf, &LinePos);
794                 if (StrLength(LineBuf) != 0) {
795                         Node = NewNode(LineBuf);
796                         if (Node != NULL) {
797                                 Put(Hash, SKEY(Node->NodeName), Node, DeleteCtdlNodeConf);
798                         }
799                 }
800         } while (LinePos != StrBufNOTNULL);
801         FreeStrBuf(&Buf);
802         FreeStrBuf(&LineBuf);
803         return Hash;
804 }
805
806
807 int is_recipient(OneRoomNetCfg *RNCfg, const char *Name)
808 {
809         const RoomNetCfg RecipientCfgs[] = {
810                 listrecp,
811                 digestrecp,
812                 participate,
813                 maxRoomNetCfg
814         };
815         int i;
816         RoomNetCfgLine *nptr;
817         size_t len;
818         
819         len = strlen(Name);
820         i = 0;
821         while (RecipientCfgs[i] != maxRoomNetCfg)
822         {
823                 nptr = RNCfg->NetConfigs[RecipientCfgs[i]];
824                 
825                 while (nptr != NULL)
826                 {
827                         if ((StrLength(nptr->Value[0]) == len) && 
828                             (!strcmp(Name, ChrPtr(nptr->Value[0]))))
829                         {
830                                 return 1;
831                         }
832                         nptr = nptr->next;
833                 }
834         }
835         return 0;
836 }
837
838
839
840 int CtdlNetconfigCheckRoomaccess(
841         char *errmsgbuf, 
842         size_t n,
843         const char* RemoteIdentifier)
844 {
845         OneRoomNetCfg *RNCfg;
846         char filename[SIZ];
847         int found;
848
849         if (RemoteIdentifier == NULL)
850         {
851                 snprintf(errmsgbuf, n, "Need sender to permit access.");
852                 return (ERROR + USERNAME_REQUIRED);
853         }
854
855         assoc_file_name(filename, sizeof filename, &CC->room, ctdl_netcfg_dir);
856         begin_critical_section(S_NETCONFIGS);
857         if (!ReadRoomNetConfigFile(&RNCfg, filename))
858         {
859                 end_critical_section(S_NETCONFIGS);
860                 snprintf(errmsgbuf, n,
861                          "This mailing list only accepts posts from subscribers.");
862                 return (ERROR + NO_SUCH_USER);
863         }
864         end_critical_section(S_NETCONFIGS);
865         found = is_recipient (RNCfg, RemoteIdentifier);
866         vFreeRoomNetworkStruct(&RNCfg);
867         if (found) {
868                 return (0);
869         }
870         else {
871                 snprintf(errmsgbuf, n,
872                          "This mailing list only accepts posts from subscribers.");
873                 return (ERROR + NO_SUCH_USER);
874         }
875 }
876
877
878
879 /*
880  * cmd_netp() - authenticate to the server as another Citadel node polling
881  *            for network traffic
882  */
883 void cmd_netp(char *cmdbuf)
884 {
885         struct CitContext *CCC = CC;
886         HashList *working_ignetcfg;
887         char *node;
888         StrBuf *NodeStr;
889         long nodelen;
890         int v;
891         long lens[2];
892         const char *strs[2];
893
894         const StrBuf *secret = NULL;
895         const StrBuf *nexthop = NULL;
896         char err_buf[SIZ] = "";
897
898         /* Authenticate */
899         node = CCC->curr_user;
900         nodelen = extract_token(CCC->curr_user, cmdbuf, 0, '|', sizeof CCC->curr_user);
901         NodeStr = NewStrBufPlain(node, nodelen);
902         /* load the IGnet Configuration to check node validity */
903         working_ignetcfg = CtdlLoadIgNetCfg();
904         v = CtdlIsValidNode(&nexthop, &secret, NodeStr, working_ignetcfg, NULL);
905         if (v != 0) {
906                 snprintf(err_buf, sizeof err_buf,
907                         "An unknown Citadel server called \"%s\" attempted to connect from %s [%s].\n",
908                         node, CCC->cs_host, CCC->cs_addr
909                 );
910                 syslog(LOG_WARNING, "%s", err_buf);
911                 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
912
913                 strs[0] = CCC->cs_addr;
914                 lens[0] = strlen(CCC->cs_addr);
915                 
916                 strs[1] = "SRV_UNKNOWN";
917                 lens[1] = sizeof("SRV_UNKNOWN" - 1);
918
919                 CtdlAideFPMessage(
920                         err_buf,
921                         "IGNet Networking.",
922                         2, strs, (long*) &lens);
923
924                 DeleteHash(&working_ignetcfg);
925                 FreeStrBuf(&NodeStr);
926                 return;
927         }
928
929         extract_token(CCC->user.password, cmdbuf, 1, '|', sizeof CCC->user.password);
930         if (strcasecmp(CCC->user.password, ChrPtr(secret))) {
931                 snprintf(err_buf, sizeof err_buf,
932                         "A Citadel server at %s [%s] failed to authenticate as network node \"%s\".\n",
933                         CCC->cs_host, CCC->cs_addr, node
934                 );
935                 syslog(LOG_WARNING, "%s", err_buf);
936                 cprintf("%d authentication failed\n", ERROR + PASSWORD_REQUIRED);
937
938                 strs[0] = CCC->cs_addr;
939                 lens[0] = strlen(CCC->cs_addr);
940                 
941                 strs[1] = "SRV_PW";
942                 lens[1] = sizeof("SRV_PW" - 1);
943
944                 CtdlAideFPMessage(
945                         err_buf,
946                         "IGNet Networking.",
947                         2, strs, (long*) &lens);
948
949                 DeleteHash(&working_ignetcfg);
950                 FreeStrBuf(&NodeStr);
951                 return;
952         }
953
954         if (CtdlNetworkTalkingTo(node, nodelen, NTT_CHECK)) {
955                 syslog(LOG_WARNING, "Duplicate session for network node <%s>", node);
956                 cprintf("%d Already talking to %s right now\n", ERROR + RESOURCE_BUSY, node);
957                 DeleteHash(&working_ignetcfg);
958                 FreeStrBuf(&NodeStr);
959                 return;
960         }
961         nodelen = safestrncpy(CCC->net_node, node, sizeof CCC->net_node);
962         CtdlNetworkTalkingTo(CCC->net_node, nodelen, NTT_ADD);
963         syslog(LOG_NOTICE, "Network node <%s> logged in from %s [%s]\n",
964                 CCC->net_node, CCC->cs_host, CCC->cs_addr
965         );
966         cprintf("%d authenticated as network node '%s'\n", CIT_OK, CCC->net_node);
967         DeleteHash(&working_ignetcfg);
968         FreeStrBuf(&NodeStr);
969 }
970
971
972 /*-----------------------------------------------------------------------------*
973  *                 Network maps: evaluate other nodes                          *
974  *-----------------------------------------------------------------------------*/
975
976 void DeleteNetMap(void *vNetMap)
977 {
978         CtdlNetMap *TheNetMap = (CtdlNetMap*) vNetMap;
979         FreeStrBuf(&TheNetMap->NodeName);
980         FreeStrBuf(&TheNetMap->NextHop);
981         free(TheNetMap);
982 }
983
984 CtdlNetMap *NewNetMap(StrBuf *SerializedNetMap)
985 {
986         const char *Pos = NULL;
987         CtdlNetMap *NM;
988
989         /* we need at least 3 pipes and some other text so its invalid. */
990         if (StrLength(SerializedNetMap) < 6)
991                 return NULL;
992         NM = (CtdlNetMap *) malloc(sizeof(CtdlNetMap));
993
994         NM->NodeName=NewStrBuf();
995         StrBufExtract_NextToken(NM->NodeName, SerializedNetMap, &Pos, '|');
996
997         NM->lastcontact = StrBufExtractNext_long(SerializedNetMap, &Pos, '|');
998
999         NM->NextHop=NewStrBuf();
1000         StrBufExtract_NextToken(NM->NextHop, SerializedNetMap, &Pos, '|');
1001
1002         return NM;
1003 }
1004
1005 HashList* CtdlReadNetworkMap(void)
1006 {
1007         const char *LinePos;
1008         char       *Cfg;
1009         StrBuf     *Buf;
1010         StrBuf     *LineBuf;
1011         HashList   *Hash;
1012         CtdlNetMap     *TheNetMap;
1013
1014         Hash = NewHash(1, NULL);
1015         Cfg =  CtdlGetSysConfig(IGNETMAP);
1016         if ((Cfg == NULL) || IsEmptyStr(Cfg)) {
1017                 if (Cfg != NULL)
1018                         free(Cfg);
1019                 return Hash;
1020         }
1021
1022         Buf = NewStrBufPlain(Cfg, -1);
1023         free(Cfg);
1024         LineBuf = NewStrBufPlain(NULL, StrLength(Buf));
1025         LinePos = NULL;
1026         while (StrBufSipLine(Buf, LineBuf, &LinePos))
1027         {
1028                 TheNetMap = NewNetMap(LineBuf);
1029                 if (TheNetMap != NULL) { /* TODO: is the NodeName Uniq? */
1030                         Put(Hash, SKEY(TheNetMap->NodeName), TheNetMap, DeleteNetMap);
1031                 }
1032         }
1033         FreeStrBuf(&Buf);
1034         FreeStrBuf(&LineBuf);
1035         return Hash;
1036 }
1037
1038 StrBuf *CtdlSerializeNetworkMap(HashList *Map)
1039 {
1040         void *vMap;
1041         const char *key;
1042         long len;
1043         StrBuf *Ret = NewStrBuf();
1044         HashPos *Pos = GetNewHashPos(Map, 0);
1045
1046         while (GetNextHashPos(Map, Pos, &len, &key, &vMap))
1047         {
1048                 CtdlNetMap *pMap = (CtdlNetMap*) vMap;
1049                 StrBufAppendBuf(Ret, pMap->NodeName, 0);
1050                 StrBufAppendBufPlain(Ret, HKEY("|"), 0);
1051
1052                 StrBufAppendPrintf(Ret, "%ld", pMap->lastcontact, 0);
1053                 StrBufAppendBufPlain(Ret, HKEY("|"), 0);
1054
1055                 StrBufAppendBuf(Ret, pMap->NextHop, 0);
1056                 StrBufAppendBufPlain(Ret, HKEY("\n"), 0);
1057         }
1058         DeleteHashPos(&Pos);
1059         return Ret;
1060 }
1061
1062
1063 /*
1064  * Learn topology from path fields
1065  */
1066 void NetworkLearnTopology(char *node, char *path, HashList *the_netmap, int *netmap_changed)
1067 {
1068         CtdlNetMap *pNM = NULL;
1069         void *vptr;
1070         char nexthop[256];
1071         CtdlNetMap *nmptr;
1072
1073         if (GetHash(the_netmap, node, strlen(node), &vptr) && 
1074             (vptr != NULL))/* TODO: is the NodeName Uniq? */
1075         {
1076                 pNM = (CtdlNetMap*)vptr;
1077                 extract_token(nexthop, path, 0, '!', sizeof nexthop);
1078                 if (!strcmp(nexthop, ChrPtr(pNM->NextHop))) {
1079                         pNM->lastcontact = time(NULL);
1080                         (*netmap_changed) ++;
1081                         return;
1082                 }
1083         }
1084
1085         /* If we got here then it's not in the map, so add it. */
1086         nmptr = (CtdlNetMap *) malloc(sizeof (CtdlNetMap));
1087         nmptr->NodeName = NewStrBufPlain(node, -1);
1088         nmptr->lastcontact = time(NULL);
1089         nmptr->NextHop = NewStrBuf ();
1090         StrBufExtract_tokenFromStr(nmptr->NextHop, path, strlen(path), 0, '!');
1091         /* TODO: is the NodeName Uniq? */
1092         Put(the_netmap, SKEY(nmptr->NodeName), nmptr, DeleteNetMap);
1093         (*netmap_changed) ++;
1094 }
1095
1096
1097 /*
1098  * Check the network map and determine whether the supplied node name is
1099  * valid.  If it is not a neighbor node, supply the name of a neighbor node
1100  * which is the next hop.  If it *is* a neighbor node, we also fill in the
1101  * shared secret.
1102  */
1103 int CtdlIsValidNode(const StrBuf **nexthop,
1104                     const StrBuf **secret,
1105                     StrBuf *node,
1106                     HashList *IgnetCfg,
1107                     HashList *the_netmap)
1108 {
1109         void *vNetMap;
1110         void *vNodeConf;
1111         CtdlNodeConf *TheNode;
1112         CtdlNetMap *TheNetMap;
1113
1114         if (StrLength(node) == 0) {
1115                 return(-1);
1116         }
1117
1118         /*
1119          * First try the neighbor nodes
1120          */
1121         if (GetCount(IgnetCfg) == 0) {
1122                 syslog(LOG_INFO, "IgnetCfg is empty!\n");
1123                 if (nexthop != NULL) {
1124                         *nexthop = NULL;
1125                 }
1126                 return(-1);
1127         }
1128
1129         /* try to find a neigbour with the name 'node' */
1130         if (GetHash(IgnetCfg, SKEY(node), &vNodeConf) && 
1131             (vNodeConf != NULL))
1132         {
1133                 TheNode = (CtdlNodeConf*)vNodeConf;
1134                 if (secret != NULL)
1135                         *secret = TheNode->Secret;
1136                 return 0;               /* yup, it's a direct neighbor */
1137         }
1138
1139         /*
1140          * If we get to this point we have to see if we know the next hop
1141          *//* TODO: is the NodeName Uniq? */
1142         if ((GetCount(the_netmap) > 0) &&
1143             (GetHash(the_netmap, SKEY(node), &vNetMap)))
1144         {
1145                 TheNetMap = (CtdlNetMap*)vNetMap;
1146                 if (nexthop != NULL)
1147                         *nexthop = TheNetMap->NextHop;
1148                 return(0);
1149         }
1150
1151         /*
1152          * If we get to this point, the supplied node name is bogus.
1153          */
1154         syslog(LOG_ERR, "Invalid node name <%s>\n", ChrPtr(node));
1155         return(-1);
1156 }
1157
1158
1159 void destroy_network_cfgs(void)
1160 {
1161         HashList *pCfgTypeHash = CfgTypeHash;
1162         HashList *pRoomConfigs = RoomConfigs;
1163
1164         CfgTypeHash = NULL;
1165         RoomConfigs = NULL;
1166         
1167         DeleteHash(&pCfgTypeHash);
1168         DeleteHash(&pRoomConfigs);
1169 }
1170
1171 /*
1172  * Module entry point
1173  */
1174 CTDL_MODULE_INIT(netconfig)
1175 {
1176         if (!threading)
1177         {
1178                 CtdlRegisterCleanupHook(destroy_network_cfgs);
1179                 LoadAllNetConfigs ();
1180                 CtdlRegisterProtoHook(cmd_gnet, "GNET", "Get network config");
1181                 CtdlRegisterProtoHook(cmd_snet, "SNET", "Set network config");
1182                 CtdlRegisterProtoHook(cmd_netp, "NETP", "Identify as network poller");
1183         }
1184         return "netconfig";
1185 }