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