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