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