dee82748d13053bf27d62217b1fce1fc56a91649
[citadel.git] / citadel / serv_extensions.c
1 /*
2  * Citadel Dynamic Loading Module
3  * Written by Brian Costello <btx@calyx.net>
4  *
5  * Copyright (c) 1987-2011 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 #include "sysdep.h"
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <unistd.h>
20 #include <sys/types.h>
21 #include <dirent.h>
22 #include <string.h>
23 #include <limits.h>
24 #include <ctype.h>
25 #include <syslog.h>
26 #include <libcitadel.h>
27 #include "citadel.h"
28 #include "server.h"
29 #include "serv_extensions.h"
30 #include "sysdep_decls.h"
31 #include "msgbase.h"
32 #include "config.h"
33
34 #include "modules/crypto/serv_crypto.h" /* Needed until a universal crypto startup hook is implimented for CtdlStartTLS */
35
36 #include "ctdl_module.h"
37
38
39 int DebugModules = 0;
40  
41 /*
42  * Structure defentitions for hook tables
43  */
44
45 typedef struct __LogDebugEntry {
46         CtdlDbgFunction F;
47         const char *Name;
48         long Len;
49         const int *LogP;
50 } LogDebugEntry;
51 HashList *LogDebugEntryTable = NULL;
52
53 typedef struct LogFunctionHook LogFunctionHook;
54 struct LogFunctionHook {
55         LogFunctionHook *next;
56         int loglevel;
57         void (*h_function_pointer) (char *);
58 };
59 extern LogFunctionHook *LogHookTable;
60
61 typedef struct FixedOutputHook FixedOutputHook;
62 struct FixedOutputHook {
63         FixedOutputHook *next;
64         char content_type[64];
65         void (*h_function_pointer) (char *, int);
66 };
67 extern FixedOutputHook *FixedOutputTable;
68
69
70
71 /*
72  * SessionFunctionHook extensions are used for any type of hook for which
73  * the context in which it's being called (which is determined by the event
74  * type) will make it obvious for the hook function to know where to look for
75  * pertinent data.
76  */
77 typedef struct SessionFunctionHook SessionFunctionHook;
78 struct SessionFunctionHook {
79         SessionFunctionHook *next;
80         int Priority;
81         void (*h_function_pointer) (void);
82         int eventtype;
83 };
84 extern SessionFunctionHook *SessionHookTable;
85
86
87 /*
88  * UserFunctionHook extensions are used for any type of hook which implements
89  * an operation on a user or username (potentially) other than the one
90  * operating the current session.
91  */
92 typedef struct UserFunctionHook UserFunctionHook;
93 struct UserFunctionHook {
94         UserFunctionHook *next;
95         void (*h_function_pointer) (struct ctdluser *usbuf);
96         int eventtype;
97 };
98 extern UserFunctionHook *UserHookTable;
99
100 /*
101  * MessageFunctionHook extensions are used for hooks which implement handlers
102  * for various types of message operations (save, read, etc.)
103  */
104 typedef struct MessageFunctionHook MessageFunctionHook;
105 struct MessageFunctionHook {
106         MessageFunctionHook *next;
107         int (*h_function_pointer) (struct CtdlMessage *msg);
108         int eventtype;
109 };
110 extern MessageFunctionHook *MessageHookTable;
111
112
113 /*
114  * NetprocFunctionHook extensions are used for hooks which implement handlers
115  * for incoming network messages.
116  */
117 typedef struct NetprocFunctionHook NetprocFunctionHook;
118 struct NetprocFunctionHook {
119         NetprocFunctionHook *next;
120         int (*h_function_pointer) (struct CtdlMessage *msg, char *target_room);
121 };
122 extern NetprocFunctionHook *NetprocHookTable;
123
124
125 /*
126  * DeleteFunctionHook extensions are used for hooks which get called when a
127  * message is about to be deleted.
128  */
129 typedef struct DeleteFunctionHook DeleteFunctionHook;
130 struct DeleteFunctionHook {
131         DeleteFunctionHook *next;
132         void (*h_function_pointer) (char *target_room, long msgnum);
133 };
134 extern DeleteFunctionHook *DeleteHookTable;
135
136
137 /*
138  * ExpressMessageFunctionHook extensions are used for hooks which implement
139  * the sending of an instant message through various channels.  Any function
140  * registered should return the number of recipients to whom the message was
141  * successfully transmitted.
142  */
143 typedef struct XmsgFunctionHook XmsgFunctionHook;
144 struct XmsgFunctionHook {
145         XmsgFunctionHook *next;
146         int (*h_function_pointer) (char *, char *, char *, char *);
147         int order;
148 };
149 extern XmsgFunctionHook *XmsgHookTable;
150
151
152
153
154 /*
155  * RoomFunctionHook extensions are used for hooks which impliment room
156  * processing functions when new messages are added EG. SIEVE.
157  */
158 typedef struct RoomFunctionHook RoomFunctionHook;
159 struct RoomFunctionHook {
160         RoomFunctionHook *next;
161         int (*fcn_ptr) (struct ctdlroom *);
162 };
163 extern RoomFunctionHook *RoomHookTable;
164
165
166
167 typedef struct SearchFunctionHook SearchFunctionHook;
168 struct SearchFunctionHook {
169         SearchFunctionHook *next;
170         void (*fcn_ptr) (int *, long **, const char *);
171         char *name;
172 };
173 extern SearchFunctionHook *SearchFunctionHookTable;
174
175
176 CleanupFunctionHook *CleanupHookTable = NULL;
177 CleanupFunctionHook *EVCleanupHookTable = NULL;
178 SessionFunctionHook *SessionHookTable = NULL;
179 UserFunctionHook *UserHookTable = NULL;
180 XmsgFunctionHook *XmsgHookTable = NULL;
181 MessageFunctionHook *MessageHookTable = NULL;
182 NetprocFunctionHook *NetprocHookTable = NULL;
183 DeleteFunctionHook *DeleteHookTable = NULL;
184 ServiceFunctionHook *ServiceHookTable = NULL;
185 FixedOutputHook *FixedOutputTable = NULL;
186 RoomFunctionHook *RoomHookTable = NULL;
187 SearchFunctionHook *SearchFunctionHookTable = NULL;
188
189 typedef struct ProtoFunctionHook ProtoFunctionHook;
190 struct ProtoFunctionHook {
191         void (*handler) (char *cmdbuf);
192         const char *cmd;
193         const char *desc;
194 };
195
196 HashList *ProtoHookList = NULL;
197
198
199 #define ERR_PORT (1 << 1)
200
201
202 static StrBuf *portlist = NULL;
203
204 static StrBuf *errormessages = NULL;
205
206
207 long   DetailErrorFlags;
208 ConstStr Empty = {HKEY("")};
209 char *ErrSubject = "Startup Problems";
210 ConstStr ErrGeneral[] = {
211         {HKEY("Citadel had trouble on starting up. ")},
212         {HKEY(" This means, citadel won't be the service provider for a specific service you configured it to.\n\n"
213               "If you don't want citadel to provide these services, turn them off in WebCit via: ")},
214         {HKEY("To make both ways actualy take place restart the citserver with \"sendcommand down\"\n\n"
215               "The errors returned by the system were:\n")},
216         {HKEY("You can recheck the above if you follow this faq item:\n"
217               "http://www.citadel.org/doku.php?id=faq:mastering_your_os:net#netstat")}
218 };
219
220 ConstStr ErrPortShort = { HKEY("We couldn't bind all ports you configured to be provided by citadel server.\n")};
221 ConstStr ErrPortWhere = { HKEY("\"Admin->System Preferences->Network\".\n\nThe failed ports and sockets are: ")};
222 ConstStr ErrPortHint  = { HKEY("If you want citadel to provide you with that functionality, "
223                                "check the output of \"netstat -lnp\" on linux Servers or \"netstat -na\" on *BSD"
224                                " and stop the program that binds these ports.\n You should eventually remove "
225                                " their initscripts in /etc/init.d so that you won't get this trouble once more.\n"
226                                " After that goto \"Administration -> Shutdown Citadel\" to make Citadel restart & retry to bind this port.\n")};
227
228
229 void LogPrintMessages(long err)
230 {
231         StrBuf *Message;
232         StrBuf *List, *DetailList;
233         ConstStr *Short, *Where, *Hint; 
234
235         
236         Message = NewStrBufPlain(NULL, 
237                                  StrLength(portlist) + StrLength(errormessages));
238         
239         DetailErrorFlags = DetailErrorFlags & ~err;
240
241         switch (err)
242         {
243         case ERR_PORT:
244                 Short = &ErrPortShort;
245                 Where = &ErrPortWhere;
246                 Hint  = &ErrPortHint;
247                 List  = portlist;
248                 DetailList = errormessages;
249                 break;
250         default:
251                 Short = &Empty;
252                 Where = &Empty;
253                 Hint  = &Empty;
254                 List  = NULL;
255                 DetailList = NULL;
256         }
257
258         StrBufAppendBufPlain(Message, CKEY(ErrGeneral[0]), 0);
259         StrBufAppendBufPlain(Message, CKEY(*Short), 0); 
260         StrBufAppendBufPlain(Message, CKEY(ErrGeneral[1]), 0);
261         StrBufAppendBufPlain(Message, CKEY(*Where), 0);
262         StrBufAppendBuf(Message, List, 0);
263         StrBufAppendBufPlain(Message, HKEY("\n\n"), 0);
264         StrBufAppendBufPlain(Message, CKEY(*Hint), 0);
265         StrBufAppendBufPlain(Message, HKEY("\n\n"), 0);
266         StrBufAppendBufPlain(Message, CKEY(ErrGeneral[2]), 0);
267         StrBufAppendBuf(Message, DetailList, 0);
268         StrBufAppendBufPlain(Message, HKEY("\n\n"), 0);
269         StrBufAppendBufPlain(Message, CKEY(ErrGeneral[3]), 0);
270
271         MOD_syslog(LOG_EMERG, "%s", ChrPtr(Message));
272         MOD_syslog(LOG_EMERG, "%s", ErrSubject);
273         quickie_message("Citadel", NULL, NULL, AIDEROOM, ChrPtr(Message), FMT_FIXED, ErrSubject);
274
275         FreeStrBuf(&Message);
276         FreeStrBuf(&List);
277         FreeStrBuf(&DetailList);
278 }
279
280
281 void AddPortError(char *Port, char *ErrorMessage)
282 {
283         long len;
284
285         DetailErrorFlags |= ERR_PORT;
286
287         len = StrLength(errormessages);
288         if (len > 0) StrBufAppendBufPlain(errormessages, HKEY("; "), 0);
289         else errormessages = NewStrBuf();
290         StrBufAppendBufPlain(errormessages, ErrorMessage, -1, 0);
291
292
293         len = StrLength(portlist);
294         if (len > 0) StrBufAppendBufPlain(portlist, HKEY(";"), 0);
295         else portlist = NewStrBuf();
296         StrBufAppendBufPlain(portlist, Port, -1, 0);
297 }
298
299
300 int DLoader_Exec_Cmd(char *cmdbuf)
301 {
302         void *vP;
303         ProtoFunctionHook *p;
304
305         if (GetHash(ProtoHookList, cmdbuf, 4, &vP) && (vP != NULL)) {
306                 p = (ProtoFunctionHook*) vP;
307                 p->handler(&cmdbuf[5]);
308                 return 1;
309         }
310         return 0;
311 }
312
313 long FourHash(const char *key, long length) 
314 {
315         int i;
316         int ret = 0;
317         const unsigned char *ptr = (const unsigned char*)key;
318
319         for (i = 0; i < 4; i++, ptr ++) 
320                 ret = (ret << 8) | 
321                         ( ((*ptr >= 'a') &&
322                            (*ptr <= 'z'))? 
323                           *ptr - 'a' + 'A': 
324                           *ptr);
325
326         return ret;
327 }
328
329 void CtdlRegisterDebugFlagHook(const char *Name, long Len, CtdlDbgFunction F, const int *LogP)
330 {
331         LogDebugEntry *E;
332         if (LogDebugEntryTable == NULL)
333                 LogDebugEntryTable = NewHash(1, NULL);
334         E = (LogDebugEntry*) malloc(sizeof(LogDebugEntry));
335         E->F = F;
336         E->Name = Name;
337         E->Len = Len;
338         E->LogP = LogP;
339         Put(LogDebugEntryTable, Name, Len, E, NULL);
340         
341 }
342 void CtdlSetDebugLogFacilities(const char **Str, long n)
343 {
344         StrBuf *Token = NULL;
345         StrBuf *Buf = NULL;
346         const char *ch;
347         int i;
348         int DoAll = 0;
349         void *vptr;
350
351         for (i=0; i < n; i++){
352                 if ((Str[i] != NULL) && !IsEmptyStr(Str[i])) {
353                         if (strcmp(Str[i], "all") == 0) {
354                                 DoAll = 1;
355                                 continue;
356                         }
357                         Buf = NewStrBufPlain(Str[i], -1);
358                         ch = NULL;
359                         if (Token == NULL)
360                                 Token = NewStrBufPlain(NULL, StrLength(Buf));
361                         while ((ch != StrBufNOTNULL) &&
362                                StrBufExtract_NextToken(Token, Buf, &ch, ',')) {
363                                 if (GetHash(LogDebugEntryTable, SKEY(Token), &vptr) && 
364                                     (vptr != NULL))
365                                 {
366                                         LogDebugEntry *E = (LogDebugEntry*)vptr;
367                                         E->F(1);
368                                 }
369                         }
370                 }
371                 FreeStrBuf(&Buf);
372         }
373         FreeStrBuf(&Token);
374         if (DoAll) {
375                 long HKLen;
376                 const char *ch;
377                 HashPos *Pos;
378
379                 Pos = GetNewHashPos(LogDebugEntryTable, 0);
380                 while (GetNextHashPos(LogDebugEntryTable, Pos, &HKLen, &ch, &vptr)) {
381                         LogDebugEntry *E = (LogDebugEntry*)vptr;
382                         E->F(1);
383                 }
384
385                 DeleteHashPos(&Pos);
386         }
387 }
388 void cmd_log_get(char *argbuf)
389 {
390         long HKLen;
391         const char *ch;
392         HashPos *Pos;
393         void *vptr;
394
395         if (CtdlAccessCheck(ac_aide)) return;
396
397         cprintf("%d Log modules enabled:\n", LISTING_FOLLOWS);
398
399         Pos = GetNewHashPos(LogDebugEntryTable, 0);
400
401         while (GetNextHashPos(LogDebugEntryTable, Pos, &HKLen, &ch, &vptr)) {
402                 LogDebugEntry *E = (LogDebugEntry*)vptr;
403                 cprintf("%s|%d\n", ch, *E->LogP);
404         }
405         
406         DeleteHashPos(&Pos);
407         cprintf("000\n");
408 }
409 void cmd_log_set(char *argbuf)
410 {
411         void *vptr;
412         int lset;
413         int wlen;
414         char which[SIZ] = "";
415
416         if (CtdlAccessCheck(ac_aide)) return;
417
418         wlen = extract_token(which, argbuf, 0, '|', sizeof(which));
419         if (wlen < 0) wlen = 0;
420         lset = extract_int(argbuf, 1);
421         if (lset != 0) lset = 1;
422         if (GetHash(LogDebugEntryTable, which, wlen, &vptr) && 
423             (vptr != NULL))
424         {
425                 LogDebugEntry *E = (LogDebugEntry*)vptr;
426                 E->F(lset);
427                 cprintf("%d %s|%d\n", CIT_OK, which, lset);
428         }
429         else {
430                 cprintf("%d Log setting %s not known\n", 
431                         ERROR, which);
432         }
433 }
434 void CtdlDestroyDebugTable(void)
435 {
436
437         DeleteHash(&LogDebugEntryTable);
438 }
439
440 void CtdlRegisterProtoHook(void (*handler) (char *), char *cmd, char *desc)
441 {
442         ProtoFunctionHook *p;
443
444         if (ProtoHookList == NULL)
445                 ProtoHookList = NewHash (1, FourHash);
446
447
448         p = (ProtoFunctionHook *)
449                 malloc(sizeof(ProtoFunctionHook));
450
451         if (p == NULL) {
452                 fprintf(stderr, "can't malloc new ProtoFunctionHook\n");
453                 exit(EXIT_FAILURE);
454         }
455         p->handler = handler;
456         p->cmd = cmd;
457         p->desc = desc;
458
459         Put(ProtoHookList, cmd, 4, p, NULL);
460         MOD_syslog(LOG_DEBUG, "Registered server command %s (%s)\n", cmd, desc);
461 }
462
463 void CtdlDestroyProtoHooks(void)
464 {
465
466         DeleteHash(&ProtoHookList);
467 }
468
469
470 void CtdlRegisterCleanupHook(void (*fcn_ptr) (void))
471 {
472
473         CleanupFunctionHook *newfcn;
474
475         newfcn = (CleanupFunctionHook *)
476             malloc(sizeof(CleanupFunctionHook));
477         newfcn->next = CleanupHookTable;
478         newfcn->h_function_pointer = fcn_ptr;
479         CleanupHookTable = newfcn;
480
481         MODM_syslog(LOG_DEBUG, "Registered a new cleanup function\n");
482 }
483
484
485 void CtdlUnregisterCleanupHook(void (*fcn_ptr) (void))
486 {
487         CleanupFunctionHook *cur, *p, *last;
488         last = NULL;
489         cur = CleanupHookTable;
490         while (cur != NULL)
491         {
492                 if (fcn_ptr == cur->h_function_pointer)
493                 {
494                         MODM_syslog(LOG_DEBUG, "Unregistered cleanup function\n");
495                         p = cur->next;
496
497                         free(cur);
498                         cur = NULL;
499
500                         if (last != NULL)
501                                 last->next = p;
502                         else 
503                                 CleanupHookTable = p;
504                         cur = p;
505                 }
506                 else {
507                         last = cur;
508                         cur = cur->next;
509                 }
510         }
511 }
512
513
514 void CtdlDestroyCleanupHooks(void)
515 {
516         CleanupFunctionHook *cur, *p;
517
518         cur = CleanupHookTable;
519         while (cur != NULL)
520         {
521                 MODM_syslog(LOG_DEBUG, "Destroyed cleanup function\n");
522                 p = cur->next;
523                 free(cur);
524                 cur = p;
525         }
526         CleanupHookTable = NULL;
527 }
528
529 void CtdlRegisterEVCleanupHook(void (*fcn_ptr) (void))
530 {
531
532         CleanupFunctionHook *newfcn;
533
534         newfcn = (CleanupFunctionHook *)
535             malloc(sizeof(CleanupFunctionHook));
536         newfcn->next = EVCleanupHookTable;
537         newfcn->h_function_pointer = fcn_ptr;
538         EVCleanupHookTable = newfcn;
539
540         MODM_syslog(LOG_DEBUG, "Registered a new cleanup function\n");
541 }
542
543
544 void CtdlUnregisterEVCleanupHook(void (*fcn_ptr) (void))
545 {
546         CleanupFunctionHook *cur, *p, *last;
547         last = NULL;
548         cur = EVCleanupHookTable;
549         while (cur != NULL)
550         {
551                 if (fcn_ptr == cur->h_function_pointer)
552                 {
553                         MODM_syslog(LOG_DEBUG, "Unregistered cleanup function\n");
554                         p = cur->next;
555
556                         free(cur);
557                         cur = NULL;
558
559                         if (last != NULL)
560                                 last->next = p;
561                         else 
562                                 EVCleanupHookTable = p;
563                         cur = p;
564                 }
565                 else {
566                         last = cur;
567                         cur = cur->next;
568                 }
569         }
570 }
571
572
573 void CtdlDestroyEVCleanupHooks(void)
574 {
575         CleanupFunctionHook *cur, *p;
576
577         cur = EVCleanupHookTable;
578         while (cur != NULL)
579         {
580                 MODM_syslog(LOG_DEBUG, "Destroyed cleanup function\n");
581                 p = cur->next;
582                 free(cur);
583                 cur = p;
584         }
585         EVCleanupHookTable = NULL;
586 }
587
588
589 void CtdlRegisterSessionHook(void (*fcn_ptr) (void), int EventType, int Priority)
590 {
591         SessionFunctionHook *newfcn;
592
593         newfcn = (SessionFunctionHook *)
594             malloc(sizeof(SessionFunctionHook));
595         newfcn->Priority = Priority;
596         newfcn->h_function_pointer = fcn_ptr;
597         newfcn->eventtype = EventType;
598
599         SessionFunctionHook **pfcn;
600         pfcn = &SessionHookTable;
601         while ((*pfcn != NULL) && 
602                ((*pfcn)->Priority < newfcn->Priority) &&
603                ((*pfcn)->next != NULL))
604                 pfcn = &(*pfcn)->next;
605                 
606         newfcn->next = *pfcn;
607         *pfcn = newfcn;
608         
609         MOD_syslog(LOG_DEBUG, "Registered a new session function (type %d Priority %d)\n",
610                    EventType, Priority);
611 }
612
613
614 void CtdlUnregisterSessionHook(void (*fcn_ptr) (void), int EventType)
615 {
616         SessionFunctionHook *cur, *p, *last;
617         last = NULL;
618         cur = SessionHookTable;
619         while  (cur != NULL) {
620                 if ((fcn_ptr == cur->h_function_pointer) &&
621                     (EventType == cur->eventtype))
622                 {
623                         MOD_syslog(LOG_DEBUG, "Unregistered session function (type %d)\n",
624                                    EventType);
625                         p = cur->next;
626
627                         free(cur);
628                         cur = NULL;
629
630                         if (last != NULL)
631                                 last->next = p;
632                         else 
633                                 SessionHookTable = p;
634                         cur = p;
635                 }
636                 else {
637                         last = cur;
638                         cur = cur->next;
639                 }
640         }
641 }
642
643 void CtdlDestroySessionHooks(void)
644 {
645         SessionFunctionHook *cur, *p;
646
647         cur = SessionHookTable;
648         while (cur != NULL)
649         {
650                 MODM_syslog(LOG_DEBUG, "Destroyed session function\n");
651                 p = cur->next;
652                 free(cur);
653                 cur = p;
654         }
655         SessionHookTable = NULL;
656 }
657
658
659 void CtdlRegisterUserHook(void (*fcn_ptr) (ctdluser *), int EventType)
660 {
661
662         UserFunctionHook *newfcn;
663
664         newfcn = (UserFunctionHook *)
665             malloc(sizeof(UserFunctionHook));
666         newfcn->next = UserHookTable;
667         newfcn->h_function_pointer = fcn_ptr;
668         newfcn->eventtype = EventType;
669         UserHookTable = newfcn;
670
671         MOD_syslog(LOG_DEBUG, "Registered a new user function (type %d)\n",
672                    EventType);
673 }
674
675
676 void CtdlUnregisterUserHook(void (*fcn_ptr) (struct ctdluser *), int EventType)
677 {
678         UserFunctionHook *cur, *p, *last;
679         last = NULL;
680         cur = UserHookTable;
681         while (cur != NULL) {
682                 if ((fcn_ptr == cur->h_function_pointer) &&
683                     (EventType == cur->eventtype))
684                 {
685                         MOD_syslog(LOG_DEBUG, "Unregistered user function (type %d)\n",
686                                    EventType);
687                         p = cur->next;
688
689                         free(cur);
690                         cur = NULL;
691
692                         if (last != NULL)
693                                 last->next = p;
694                         else 
695                                 UserHookTable = p;
696                         cur = p;
697                 }
698                 else {
699                         last = cur;
700                         cur = cur->next;
701                 }
702         }
703 }
704
705 void CtdlDestroyUserHooks(void)
706 {
707         UserFunctionHook *cur, *p;
708
709         cur = UserHookTable;
710         while (cur != NULL)
711         {
712                 MODM_syslog(LOG_DEBUG, "Destroyed user function \n");
713                 p = cur->next;
714                 free(cur);
715                 cur = p;
716         }
717         UserHookTable = NULL;
718 }
719
720
721 void CtdlRegisterMessageHook(int (*handler)(struct CtdlMessage *),
722                                 int EventType)
723 {
724
725         MessageFunctionHook *newfcn;
726
727         newfcn = (MessageFunctionHook *)
728             malloc(sizeof(MessageFunctionHook));
729         newfcn->next = MessageHookTable;
730         newfcn->h_function_pointer = handler;
731         newfcn->eventtype = EventType;
732         MessageHookTable = newfcn;
733
734         MOD_syslog(LOG_DEBUG, "Registered a new message function (type %d)\n",
735                    EventType);
736 }
737
738
739 void CtdlUnregisterMessageHook(int (*handler)(struct CtdlMessage *),
740                 int EventType)
741 {
742         MessageFunctionHook *cur, *p, *last;
743         last = NULL;
744         cur = MessageHookTable;
745         while (cur != NULL) {
746                 if ((handler == cur->h_function_pointer) &&
747                     (EventType == cur->eventtype))
748                 {
749                         MOD_syslog(LOG_DEBUG, "Unregistered message function (type %d)\n",
750                                    EventType);
751                         p = cur->next;
752                         free(cur);
753                         cur = NULL;
754
755                         if (last != NULL)
756                                 last->next = p;
757                         else 
758                                 MessageHookTable = p;
759                         cur = p;
760                 }
761                 else {
762                         last = cur;
763                         cur = cur->next;
764                 }
765         }
766 }
767
768 void CtdlDestroyMessageHook(void)
769 {
770         MessageFunctionHook *cur, *p;
771
772         cur = MessageHookTable; 
773         while (cur != NULL)
774         {
775                 MOD_syslog(LOG_DEBUG, "Destroyed message function (type %d)\n", cur->eventtype);
776                 p = cur->next;
777                 free(cur);
778                 cur = p;
779         }
780         MessageHookTable = NULL;
781 }
782
783
784 void CtdlRegisterRoomHook(int (*fcn_ptr)(struct ctdlroom *))
785 {
786         RoomFunctionHook *newfcn;
787
788         newfcn = (RoomFunctionHook *)
789             malloc(sizeof(RoomFunctionHook));
790         newfcn->next = RoomHookTable;
791         newfcn->fcn_ptr = fcn_ptr;
792         RoomHookTable = newfcn;
793
794         MODM_syslog(LOG_DEBUG, "Registered a new room function\n");
795 }
796
797
798 void CtdlUnregisterRoomHook(int (*fcn_ptr)(struct ctdlroom *))
799 {
800         RoomFunctionHook *cur, *p, *last;
801         last = NULL;
802         cur = RoomHookTable;
803         while (cur != NULL)
804         {
805                 if (fcn_ptr == cur->fcn_ptr) {
806                         MODM_syslog(LOG_DEBUG, "Unregistered room function\n");
807                         p = cur->next;
808
809                         free(cur);
810                         cur = NULL;
811
812                         if (last != NULL)
813                                 last->next = p;
814                         else 
815                                 RoomHookTable = p;
816                         cur = p;
817                 }
818                 else {
819                         last = cur;
820                         cur = cur->next;
821                 }
822         }
823 }
824
825
826 void CtdlDestroyRoomHooks(void)
827 {
828         RoomFunctionHook *cur, *p;
829
830         cur = RoomHookTable;
831         while (cur != NULL)
832         {
833                 MODM_syslog(LOG_DEBUG, "Destroyed room function\n");
834                 p = cur->next;
835                 free(cur);
836                 cur = p;
837         }
838         RoomHookTable = NULL;
839 }
840
841 void CtdlRegisterNetprocHook(int (*handler)(struct CtdlMessage *, char *) )
842 {
843         NetprocFunctionHook *newfcn;
844
845         newfcn = (NetprocFunctionHook *)
846             malloc(sizeof(NetprocFunctionHook));
847         newfcn->next = NetprocHookTable;
848         newfcn->h_function_pointer = handler;
849         NetprocHookTable = newfcn;
850
851         MODM_syslog(LOG_DEBUG, "Registered a new netproc function\n");
852 }
853
854
855 void CtdlUnregisterNetprocHook(int (*handler)(struct CtdlMessage *, char *) )
856 {
857         NetprocFunctionHook *cur, *p, *last;
858
859         cur = NetprocHookTable;
860         last = NULL;
861
862         while (cur != NULL) {
863                 if (handler == cur->h_function_pointer)
864                 {
865                         MODM_syslog(LOG_DEBUG, "Unregistered netproc function\n");
866                         p = cur->next;
867                         free(cur);
868                         if (last != NULL) {
869                                 last->next = p;
870                         }
871                         else {
872                                 NetprocHookTable = p;
873                         }
874                         cur = p;
875                 }
876                 else {
877                         last = cur;
878                         cur = cur->next;
879                 }
880         }
881 }
882
883 void CtdlDestroyNetprocHooks(void)
884 {
885         NetprocFunctionHook *cur, *p;
886
887         cur = NetprocHookTable;
888         while (cur != NULL)
889         {
890                 MODM_syslog(LOG_DEBUG, "Destroyed netproc function\n");
891                 p = cur->next;
892                 free(cur);
893                 cur = p;
894         }
895         NetprocHookTable = NULL;
896 }
897
898
899 void CtdlRegisterDeleteHook(void (*handler)(char *, long) )
900 {
901         DeleteFunctionHook *newfcn;
902
903         newfcn = (DeleteFunctionHook *)
904             malloc(sizeof(DeleteFunctionHook));
905         newfcn->next = DeleteHookTable;
906         newfcn->h_function_pointer = handler;
907         DeleteHookTable = newfcn;
908
909         MODM_syslog(LOG_DEBUG, "Registered a new delete function\n");
910 }
911
912
913 void CtdlUnregisterDeleteHook(void (*handler)(char *, long) )
914 {
915         DeleteFunctionHook *cur, *p, *last;
916
917         last = NULL;
918         cur = DeleteHookTable;
919         while (cur != NULL) {
920                 if (handler == cur->h_function_pointer )
921                 {
922                         MODM_syslog(LOG_DEBUG, "Unregistered delete function\n");
923                         p = cur->next;
924                         free(cur);
925
926                         if (last != NULL)
927                                 last->next = p;
928                         else
929                                 DeleteHookTable = p;
930
931                         cur = p;
932                 }
933                 else {
934                         last = cur;
935                         cur = cur->next;
936                 }
937         }
938 }
939 void CtdlDestroyDeleteHooks(void)
940 {
941         DeleteFunctionHook *cur, *p;
942
943         cur = DeleteHookTable;
944         while (cur != NULL)
945         {
946                 MODM_syslog(LOG_DEBUG, "Destroyed delete function\n");
947                 p = cur->next;
948                 free(cur);
949                 cur = p;                
950         }
951         DeleteHookTable = NULL;
952 }
953
954
955
956
957 void CtdlRegisterFixedOutputHook(char *content_type, void (*handler)(char *, int) )
958 {
959         FixedOutputHook *newfcn;
960
961         newfcn = (FixedOutputHook *)
962             malloc(sizeof(FixedOutputHook));
963         newfcn->next = FixedOutputTable;
964         newfcn->h_function_pointer = handler;
965         safestrncpy(newfcn->content_type, content_type, sizeof newfcn->content_type);
966         FixedOutputTable = newfcn;
967
968         MOD_syslog(LOG_DEBUG, "Registered a new fixed output function for %s\n", newfcn->content_type);
969 }
970
971
972 void CtdlUnregisterFixedOutputHook(char *content_type)
973 {
974         FixedOutputHook *cur, *p, *last;
975
976         last = NULL;
977         cur = FixedOutputTable;
978         while (cur != NULL) {
979                 /* This will also remove duplicates if any */
980                 if (!strcasecmp(content_type, cur->content_type)) {
981                         MOD_syslog(LOG_DEBUG,
982                                    "Unregistered fixed output function for %s\n",
983                                    content_type);
984
985                         p = cur->next;
986                         free(cur);
987
988                         if (last != NULL)
989                                 last->next = p;
990                         else
991                                 FixedOutputTable = p;
992                         
993                         cur = p;
994                 }
995                 else
996                 {
997                         last = cur;
998                         cur = cur->next;
999                 }
1000         }
1001 }
1002
1003 void CtdlDestroyFixedOutputHooks(void)
1004 {
1005         FixedOutputHook *cur, *p;
1006
1007         cur = FixedOutputTable; 
1008         while (cur != NULL)
1009         {
1010                 MOD_syslog(LOG_DEBUG, "Destroyed fixed output function for %s\n", cur->content_type);
1011                 p = cur->next;
1012                 free(cur);
1013                 cur = p;
1014                 
1015         }
1016         FixedOutputTable = NULL;
1017 }
1018
1019 /* returns nonzero if we found a hook and used it */
1020 int PerformFixedOutputHooks(char *content_type, char *content, int content_length)
1021 {
1022         FixedOutputHook *fcn;
1023
1024         for (fcn = FixedOutputTable; fcn != NULL; fcn = fcn->next) {
1025                 if (!strcasecmp(content_type, fcn->content_type)) {
1026                         (*fcn->h_function_pointer) (content, content_length);
1027                         return(1);
1028                 }
1029         }
1030         return(0);
1031 }
1032
1033
1034
1035
1036
1037 void CtdlRegisterXmsgHook(int (*fcn_ptr) (char *, char *, char *, char *), int order)
1038 {
1039
1040         XmsgFunctionHook *newfcn;
1041
1042         newfcn = (XmsgFunctionHook *) malloc(sizeof(XmsgFunctionHook));
1043         newfcn->next = XmsgHookTable;
1044         newfcn->order = order;
1045         newfcn->h_function_pointer = fcn_ptr;
1046         XmsgHookTable = newfcn;
1047         MOD_syslog(LOG_DEBUG, "Registered a new x-msg function (priority %d)\n", order);
1048 }
1049
1050
1051 void CtdlUnregisterXmsgHook(int (*fcn_ptr) (char *, char *, char *, char *), int order)
1052 {
1053         XmsgFunctionHook *cur, *p, *last;
1054
1055         last = NULL;
1056         cur = XmsgHookTable;
1057         while (cur != NULL) {
1058                 /* This will also remove duplicates if any */
1059                 if (fcn_ptr == cur->h_function_pointer &&
1060                     order == cur->order) {
1061                         MOD_syslog(LOG_DEBUG, "Unregistered x-msg function "
1062                                    "(priority %d)\n", order);
1063                         p = cur->next;
1064                         free(cur);
1065
1066                         if (last != NULL)
1067                                 last->next = p;
1068                         else
1069                                 XmsgHookTable = p;
1070                         
1071                         cur = p;
1072                 }
1073                 else {
1074                         last = cur;
1075                         cur = cur->next;
1076                 }
1077         }
1078 }
1079
1080 void CtdlDestroyXmsgHooks(void)
1081 {
1082         XmsgFunctionHook *cur, *p;
1083
1084         cur = XmsgHookTable;
1085         while (cur != NULL)
1086         {
1087                 MOD_syslog(LOG_DEBUG, "Destroyed x-msg function "
1088                         "(priority %d)\n", cur->order);
1089                 p = cur->next;
1090                         
1091                 free(cur);
1092                 cur = p;
1093         }
1094         XmsgHookTable = NULL;
1095 }
1096
1097
1098 void CtdlRegisterServiceHook(int tcp_port,
1099                              char *sockpath,
1100                              void (*h_greeting_function) (void),
1101                              void (*h_command_function) (void),
1102                              void (*h_async_function) (void),
1103                              const char *ServiceName)
1104 {
1105         ServiceFunctionHook *newfcn;
1106         char *message;
1107         char error[SIZ];
1108
1109         strcpy(error, "");
1110         newfcn = (ServiceFunctionHook *) malloc(sizeof(ServiceFunctionHook));
1111         message = (char*) malloc (SIZ + SIZ);
1112         
1113         newfcn->next = ServiceHookTable;
1114         newfcn->tcp_port = tcp_port;
1115         newfcn->sockpath = sockpath;
1116         newfcn->h_greeting_function = h_greeting_function;
1117         newfcn->h_command_function = h_command_function;
1118         newfcn->h_async_function = h_async_function;
1119         newfcn->ServiceName = ServiceName;
1120
1121         if (sockpath != NULL) {
1122                 newfcn->msock = ctdl_uds_server(sockpath, config.c_maxsessions, error);
1123                 snprintf(message, SIZ, "Unix domain socket '%s': ", sockpath);
1124         }
1125         else if (tcp_port <= 0) {       /* port -1 to disable */
1126                 MOD_syslog(LOG_INFO, "Service %s has been manually disabled, skipping\n", ServiceName);
1127                 free (message);
1128                 free(newfcn);
1129                 return;
1130         }
1131         else {
1132                 newfcn->msock = ctdl_tcp_server(config.c_ip_addr,
1133                                               tcp_port,
1134                                               config.c_maxsessions, 
1135                                               error);
1136                 snprintf(message, SIZ, "TCP port %s:%d: (%s) ", 
1137                          config.c_ip_addr, tcp_port, ServiceName);
1138         }
1139
1140         if (newfcn->msock > 0) {
1141                 ServiceHookTable = newfcn;
1142                 strcat(message, "registered.");
1143                 MOD_syslog(LOG_INFO, "%s\n", message);
1144         }
1145         else {
1146                 AddPortError(message, error);
1147                 strcat(message, "FAILED.");
1148                 MOD_syslog(LOG_CRIT, "%s\n", message);
1149                 free(newfcn);
1150         }
1151         free(message);
1152 }
1153
1154
1155 void CtdlUnregisterServiceHook(int tcp_port, char *sockpath,
1156                         void (*h_greeting_function) (void),
1157                         void (*h_command_function) (void),
1158                         void (*h_async_function) (void)
1159                         )
1160 {
1161         ServiceFunctionHook *cur, *p, *last;
1162
1163         last = NULL;
1164         cur = ServiceHookTable;
1165         while (cur != NULL) {
1166                 /* This will also remove duplicates if any */
1167                 if (h_greeting_function == cur->h_greeting_function &&
1168                     h_command_function == cur->h_command_function &&
1169                     h_async_function == cur->h_async_function &&
1170                     tcp_port == cur->tcp_port && 
1171                     !(sockpath && cur->sockpath && strcmp(sockpath, cur->sockpath)) )
1172                 {
1173                         if (cur->msock > 0)
1174                                 close(cur->msock);
1175                         if (sockpath) {
1176                                 MOD_syslog(LOG_INFO, "Closed UNIX domain socket %s\n",
1177                                            sockpath);
1178                                 unlink(sockpath);
1179                         } else if (tcp_port) {
1180                                 MOD_syslog(LOG_INFO, "Closed TCP port %d\n", tcp_port);
1181                         } else {
1182                                 MOD_syslog(LOG_INFO, "Unregistered service \"%s\"\n", cur->ServiceName);
1183                         }
1184                         p = cur->next;
1185                         free(cur);
1186                         if (last != NULL)
1187                                 last->next = p;
1188                         else
1189                                 ServiceHookTable = p;
1190                         cur = p;
1191                 }
1192                 else {
1193                         last = cur;
1194                         cur = cur->next;
1195                 }
1196         }
1197 }
1198
1199
1200 void CtdlShutdownServiceHooks(void)
1201 {
1202         /* sort of a duplicate of close_masters() but called earlier */
1203         ServiceFunctionHook *cur;
1204
1205         cur = ServiceHookTable;
1206         while (cur != NULL) 
1207         {
1208                 if (cur->msock != -1)
1209                 {
1210                         close(cur->msock);
1211                         cur->msock = -1;
1212                         if (cur->sockpath != NULL){
1213                                 MOD_syslog(LOG_INFO, "[%s] Closed UNIX domain socket %s\n",
1214                                            cur->ServiceName,
1215                                            cur->sockpath);
1216                                 unlink(cur->sockpath);
1217                         } else {
1218                                 MOD_syslog(LOG_INFO, "[%s] closing service\n", 
1219                                            cur->ServiceName);
1220                         }
1221                 }
1222                 cur = cur->next;
1223         }
1224 }
1225
1226 void CtdlDestroyServiceHook(void)
1227 {
1228         ServiceFunctionHook *cur, *p;
1229
1230         cur = ServiceHookTable;
1231         while (cur != NULL)
1232         {
1233                 close(cur->msock);
1234                 if (cur->sockpath) {
1235                         MOD_syslog(LOG_INFO, "Closed UNIX domain socket %s\n",
1236                                    cur->sockpath);
1237                         unlink(cur->sockpath);
1238                 } else if (cur->tcp_port) {
1239                         MOD_syslog(LOG_INFO, "Closed TCP port %d\n", cur->tcp_port);
1240                 } else {
1241                         MOD_syslog(LOG_INFO, "Destroyed service \"%s\"\n", cur->ServiceName);
1242                 }
1243                 p = cur->next;
1244                 free(cur);
1245                 cur = p;
1246         }
1247         ServiceHookTable = NULL;
1248 }
1249
1250 void CtdlRegisterSearchFuncHook(void (*fcn_ptr)(int *, long **, const char *), char *name)
1251 {
1252         SearchFunctionHook *newfcn;
1253
1254         if (!name || !fcn_ptr) {
1255                 return;
1256         }
1257         
1258         newfcn = (SearchFunctionHook *)
1259             malloc(sizeof(SearchFunctionHook));
1260         newfcn->next = SearchFunctionHookTable;
1261         newfcn->name = name;
1262         newfcn->fcn_ptr = fcn_ptr;
1263         SearchFunctionHookTable = newfcn;
1264
1265         MOD_syslog(LOG_DEBUG, "Registered a new search function (%s)\n", name);
1266 }
1267
1268 void CtdlUnregisterSearchFuncHook(void (*fcn_ptr)(int *, long **, const char *), char *name)
1269 {
1270         SearchFunctionHook *cur, *p, *last;
1271         
1272         last = NULL;
1273         cur = SearchFunctionHookTable;
1274         while (cur != NULL) {
1275                 if (fcn_ptr &&
1276                     (cur->fcn_ptr == fcn_ptr) &&
1277                     name && !strcmp(name, cur->name))
1278                 {
1279                         MOD_syslog(LOG_DEBUG, "Unregistered search function(%s)\n", name);
1280                         p = cur->next;
1281                         free (cur);
1282                         if (last != NULL)
1283                                 last->next = p;
1284                         else
1285                                 SearchFunctionHookTable = p;
1286                         cur = p;
1287                 }
1288                 else {
1289                         last = cur;
1290                         cur = cur->next;
1291                 }
1292         }
1293 }
1294
1295 void CtdlDestroySearchHooks(void)
1296 {
1297         SearchFunctionHook *cur, *p;
1298
1299         cur = SearchFunctionHookTable;
1300         SearchFunctionHookTable = NULL;
1301         while (cur != NULL) {
1302                 p = cur->next;
1303                 free(cur);
1304                 cur = p;
1305         }
1306 }
1307
1308 void CtdlModuleDoSearch(int *num_msgs, long **search_msgs, const char *search_string, const char *func_name)
1309 {
1310         SearchFunctionHook *fcn = NULL;
1311
1312         for (fcn = SearchFunctionHookTable; fcn != NULL; fcn = fcn->next) {
1313                 if (!func_name || !strcmp(func_name, fcn->name)) {
1314                         (*fcn->fcn_ptr) (num_msgs, search_msgs, search_string);
1315                         return;
1316                 }
1317         }
1318         *num_msgs = 0;
1319 }
1320
1321
1322 void PerformSessionHooks(int EventType)
1323 {
1324         SessionFunctionHook *fcn = NULL;
1325
1326         for (fcn = SessionHookTable; fcn != NULL; fcn = fcn->next) {
1327                 if (fcn->eventtype == EventType) {
1328                         if (EventType == EVT_TIMER) {
1329                                 pthread_setspecific(MyConKey, NULL);    /* for every hook */
1330                         }
1331                         (*fcn->h_function_pointer) ();
1332                 }
1333         }
1334 }
1335
1336 void PerformUserHooks(ctdluser *usbuf, int EventType)
1337 {
1338         UserFunctionHook *fcn = NULL;
1339
1340         for (fcn = UserHookTable; fcn != NULL; fcn = fcn->next) {
1341                 if (fcn->eventtype == EventType) {
1342                         (*fcn->h_function_pointer) (usbuf);
1343                 }
1344         }
1345 }
1346
1347 int PerformMessageHooks(struct CtdlMessage *msg, int EventType)
1348 {
1349         MessageFunctionHook *fcn = NULL;
1350         int total_retval = 0;
1351
1352         /* Other code may elect to protect this message from server-side
1353          * handlers; if this is the case, don't do anything.
1354         MOD_syslog(LOG_DEBUG, "** Event type is %d, flags are %d\n", EventType, msg->cm_flags);
1355          */
1356         if (msg->cm_flags & CM_SKIP_HOOKS) {
1357                 MODM_syslog(LOG_DEBUG, "Skipping hooks\n");
1358                 return(0);
1359         }
1360
1361         /* Otherwise, run all the hooks appropriate to this event type.
1362          */
1363         for (fcn = MessageHookTable; fcn != NULL; fcn = fcn->next) {
1364                 if (fcn->eventtype == EventType) {
1365                         total_retval = total_retval + (*fcn->h_function_pointer) (msg);
1366                 }
1367         }
1368
1369         /* Return the sum of the return codes from the hook functions.  If
1370          * this is an EVT_BEFORESAVE event, a nonzero return code will cause
1371          * the save operation to abort.
1372          */
1373         return total_retval;
1374 }
1375
1376
1377 int PerformRoomHooks(struct ctdlroom *target_room)
1378 {
1379         RoomFunctionHook *fcn;
1380         int total_retval = 0;
1381
1382         MOD_syslog(LOG_DEBUG, "Performing room hooks for <%s>\n", target_room->QRname);
1383
1384         for (fcn = RoomHookTable; fcn != NULL; fcn = fcn->next) {
1385                 total_retval = total_retval + (*fcn->fcn_ptr) (target_room);
1386         }
1387
1388         /* Return the sum of the return codes from the hook functions.
1389          */
1390         return total_retval;
1391 }
1392
1393
1394 int PerformNetprocHooks(struct CtdlMessage *msg, char *target_room)
1395 {
1396         NetprocFunctionHook *fcn;
1397         int total_retval = 0;
1398
1399         for (fcn = NetprocHookTable; fcn != NULL; fcn = fcn->next) {
1400                 total_retval = total_retval +
1401                         (*fcn->h_function_pointer) (msg, target_room);
1402         }
1403
1404         /* Return the sum of the return codes from the hook functions.
1405          * A nonzero return code will cause the message to *not* be imported.
1406          */
1407         return total_retval;
1408 }
1409
1410
1411 void PerformDeleteHooks(char *room, long msgnum)
1412 {
1413         DeleteFunctionHook *fcn;
1414
1415         for (fcn = DeleteHookTable; fcn != NULL; fcn = fcn->next) {
1416                 (*fcn->h_function_pointer) (room, msgnum);
1417         }
1418 }
1419
1420
1421
1422
1423
1424 int PerformXmsgHooks(char *sender, char *sender_email, char *recp, char *msg)
1425 {
1426         XmsgFunctionHook *fcn;
1427         int total_sent = 0;
1428         int p;
1429
1430         for (p=0; p<MAX_XMSG_PRI; ++p) {
1431                 for (fcn = XmsgHookTable; fcn != NULL; fcn = fcn->next) {
1432                         if (fcn->order == p) {
1433                                 total_sent +=
1434                                         (*fcn->h_function_pointer)
1435                                                 (sender, sender_email, recp, msg);
1436                         }
1437                 }
1438                 /* Break out of the loop if a higher-priority function
1439                  * successfully delivered the message.  This prevents duplicate
1440                  * deliveries to local users simultaneously signed onto
1441                  * remote services.
1442                  */
1443                 if (total_sent) break;
1444         }
1445         return total_sent;
1446 }
1447
1448
1449 /*
1450  * Dirty hack until we impliment a hook mechanism for this
1451  */
1452 void CtdlModuleStartCryptoMsgs(char *ok_response, char *nosup_response, char *error_response)
1453 {
1454 #ifdef HAVE_OPENSSL
1455         CtdlStartTLS (ok_response, nosup_response, error_response);
1456 #endif
1457 }
1458
1459 void DebugModulesEnable(const int n)
1460 {
1461         DebugModules = n;
1462 }
1463 CTDL_MODULE_INIT(modules)
1464 {
1465         if (!threading) {
1466                 CtdlRegisterDebugFlagHook(HKEY("modules"), DebugModulesEnable, &DebugModules);
1467
1468                 CtdlRegisterProtoHook(cmd_log_get, "LOGP", "Print Log-parameters");
1469                 CtdlRegisterProtoHook(cmd_log_set, "LOGS", "Set Log-parameters");
1470         }
1471         return "modules";
1472 }