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