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