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