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