cf1270cc6f7f4263027405adf887bb610b67070c
[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                 cur->h_function_pointer();
583                 free(cur);
584                 cur = p;
585         }
586         EVCleanupHookTable = NULL;
587 }
588
589
590 void CtdlRegisterSessionHook(void (*fcn_ptr) (void), int EventType, int Priority)
591 {
592         SessionFunctionHook *newfcn;
593
594         newfcn = (SessionFunctionHook *)
595             malloc(sizeof(SessionFunctionHook));
596         newfcn->Priority = Priority;
597         newfcn->h_function_pointer = fcn_ptr;
598         newfcn->eventtype = EventType;
599
600         SessionFunctionHook **pfcn;
601         pfcn = &SessionHookTable;
602         while ((*pfcn != NULL) && 
603                ((*pfcn)->Priority < newfcn->Priority) &&
604                ((*pfcn)->next != NULL))
605                 pfcn = &(*pfcn)->next;
606                 
607         newfcn->next = *pfcn;
608         *pfcn = newfcn;
609         
610         MOD_syslog(LOG_DEBUG, "Registered a new session function (type %d Priority %d)\n",
611                    EventType, Priority);
612 }
613
614
615 void CtdlUnregisterSessionHook(void (*fcn_ptr) (void), int EventType)
616 {
617         SessionFunctionHook *cur, *p, *last;
618         last = NULL;
619         cur = SessionHookTable;
620         while  (cur != NULL) {
621                 if ((fcn_ptr == cur->h_function_pointer) &&
622                     (EventType == cur->eventtype))
623                 {
624                         MOD_syslog(LOG_DEBUG, "Unregistered session function (type %d)\n",
625                                    EventType);
626                         p = cur->next;
627
628                         free(cur);
629                         cur = NULL;
630
631                         if (last != NULL)
632                                 last->next = p;
633                         else 
634                                 SessionHookTable = p;
635                         cur = p;
636                 }
637                 else {
638                         last = cur;
639                         cur = cur->next;
640                 }
641         }
642 }
643
644 void CtdlDestroySessionHooks(void)
645 {
646         SessionFunctionHook *cur, *p;
647
648         cur = SessionHookTable;
649         while (cur != NULL)
650         {
651                 MODM_syslog(LOG_DEBUG, "Destroyed session function\n");
652                 p = cur->next;
653                 free(cur);
654                 cur = p;
655         }
656         SessionHookTable = NULL;
657 }
658
659
660 void CtdlRegisterUserHook(void (*fcn_ptr) (ctdluser *), int EventType)
661 {
662
663         UserFunctionHook *newfcn;
664
665         newfcn = (UserFunctionHook *)
666             malloc(sizeof(UserFunctionHook));
667         newfcn->next = UserHookTable;
668         newfcn->h_function_pointer = fcn_ptr;
669         newfcn->eventtype = EventType;
670         UserHookTable = newfcn;
671
672         MOD_syslog(LOG_DEBUG, "Registered a new user function (type %d)\n",
673                    EventType);
674 }
675
676
677 void CtdlUnregisterUserHook(void (*fcn_ptr) (struct ctdluser *), int EventType)
678 {
679         UserFunctionHook *cur, *p, *last;
680         last = NULL;
681         cur = UserHookTable;
682         while (cur != NULL) {
683                 if ((fcn_ptr == cur->h_function_pointer) &&
684                     (EventType == cur->eventtype))
685                 {
686                         MOD_syslog(LOG_DEBUG, "Unregistered user function (type %d)\n",
687                                    EventType);
688                         p = cur->next;
689
690                         free(cur);
691                         cur = NULL;
692
693                         if (last != NULL)
694                                 last->next = p;
695                         else 
696                                 UserHookTable = p;
697                         cur = p;
698                 }
699                 else {
700                         last = cur;
701                         cur = cur->next;
702                 }
703         }
704 }
705
706 void CtdlDestroyUserHooks(void)
707 {
708         UserFunctionHook *cur, *p;
709
710         cur = UserHookTable;
711         while (cur != NULL)
712         {
713                 MODM_syslog(LOG_DEBUG, "Destroyed user function \n");
714                 p = cur->next;
715                 free(cur);
716                 cur = p;
717         }
718         UserHookTable = NULL;
719 }
720
721
722 void CtdlRegisterMessageHook(int (*handler)(struct CtdlMessage *),
723                                 int EventType)
724 {
725
726         MessageFunctionHook *newfcn;
727
728         newfcn = (MessageFunctionHook *)
729             malloc(sizeof(MessageFunctionHook));
730         newfcn->next = MessageHookTable;
731         newfcn->h_function_pointer = handler;
732         newfcn->eventtype = EventType;
733         MessageHookTable = newfcn;
734
735         MOD_syslog(LOG_DEBUG, "Registered a new message function (type %d)\n",
736                    EventType);
737 }
738
739
740 void CtdlUnregisterMessageHook(int (*handler)(struct CtdlMessage *),
741                 int EventType)
742 {
743         MessageFunctionHook *cur, *p, *last;
744         last = NULL;
745         cur = MessageHookTable;
746         while (cur != NULL) {
747                 if ((handler == cur->h_function_pointer) &&
748                     (EventType == cur->eventtype))
749                 {
750                         MOD_syslog(LOG_DEBUG, "Unregistered message function (type %d)\n",
751                                    EventType);
752                         p = cur->next;
753                         free(cur);
754                         cur = NULL;
755
756                         if (last != NULL)
757                                 last->next = p;
758                         else 
759                                 MessageHookTable = p;
760                         cur = p;
761                 }
762                 else {
763                         last = cur;
764                         cur = cur->next;
765                 }
766         }
767 }
768
769 void CtdlDestroyMessageHook(void)
770 {
771         MessageFunctionHook *cur, *p;
772
773         cur = MessageHookTable; 
774         while (cur != NULL)
775         {
776                 MOD_syslog(LOG_DEBUG, "Destroyed message function (type %d)\n", cur->eventtype);
777                 p = cur->next;
778                 free(cur);
779                 cur = p;
780         }
781         MessageHookTable = NULL;
782 }
783
784
785 void CtdlRegisterRoomHook(int (*fcn_ptr)(struct ctdlroom *))
786 {
787         RoomFunctionHook *newfcn;
788
789         newfcn = (RoomFunctionHook *)
790             malloc(sizeof(RoomFunctionHook));
791         newfcn->next = RoomHookTable;
792         newfcn->fcn_ptr = fcn_ptr;
793         RoomHookTable = newfcn;
794
795         MODM_syslog(LOG_DEBUG, "Registered a new room function\n");
796 }
797
798
799 void CtdlUnregisterRoomHook(int (*fcn_ptr)(struct ctdlroom *))
800 {
801         RoomFunctionHook *cur, *p, *last;
802         last = NULL;
803         cur = RoomHookTable;
804         while (cur != NULL)
805         {
806                 if (fcn_ptr == cur->fcn_ptr) {
807                         MODM_syslog(LOG_DEBUG, "Unregistered room function\n");
808                         p = cur->next;
809
810                         free(cur);
811                         cur = NULL;
812
813                         if (last != NULL)
814                                 last->next = p;
815                         else 
816                                 RoomHookTable = p;
817                         cur = p;
818                 }
819                 else {
820                         last = cur;
821                         cur = cur->next;
822                 }
823         }
824 }
825
826
827 void CtdlDestroyRoomHooks(void)
828 {
829         RoomFunctionHook *cur, *p;
830
831         cur = RoomHookTable;
832         while (cur != NULL)
833         {
834                 MODM_syslog(LOG_DEBUG, "Destroyed room function\n");
835                 p = cur->next;
836                 free(cur);
837                 cur = p;
838         }
839         RoomHookTable = NULL;
840 }
841
842 void CtdlRegisterNetprocHook(int (*handler)(struct CtdlMessage *, char *) )
843 {
844         NetprocFunctionHook *newfcn;
845
846         newfcn = (NetprocFunctionHook *)
847             malloc(sizeof(NetprocFunctionHook));
848         newfcn->next = NetprocHookTable;
849         newfcn->h_function_pointer = handler;
850         NetprocHookTable = newfcn;
851
852         MODM_syslog(LOG_DEBUG, "Registered a new netproc function\n");
853 }
854
855
856 void CtdlUnregisterNetprocHook(int (*handler)(struct CtdlMessage *, char *) )
857 {
858         NetprocFunctionHook *cur, *p, *last;
859
860         cur = NetprocHookTable;
861         last = NULL;
862
863         while (cur != NULL) {
864                 if (handler == cur->h_function_pointer)
865                 {
866                         MODM_syslog(LOG_DEBUG, "Unregistered netproc function\n");
867                         p = cur->next;
868                         free(cur);
869                         if (last != NULL) {
870                                 last->next = p;
871                         }
872                         else {
873                                 NetprocHookTable = p;
874                         }
875                         cur = p;
876                 }
877                 else {
878                         last = cur;
879                         cur = cur->next;
880                 }
881         }
882 }
883
884 void CtdlDestroyNetprocHooks(void)
885 {
886         NetprocFunctionHook *cur, *p;
887
888         cur = NetprocHookTable;
889         while (cur != NULL)
890         {
891                 MODM_syslog(LOG_DEBUG, "Destroyed netproc function\n");
892                 p = cur->next;
893                 free(cur);
894                 cur = p;
895         }
896         NetprocHookTable = NULL;
897 }
898
899
900 void CtdlRegisterDeleteHook(void (*handler)(char *, long) )
901 {
902         DeleteFunctionHook *newfcn;
903
904         newfcn = (DeleteFunctionHook *)
905             malloc(sizeof(DeleteFunctionHook));
906         newfcn->next = DeleteHookTable;
907         newfcn->h_function_pointer = handler;
908         DeleteHookTable = newfcn;
909
910         MODM_syslog(LOG_DEBUG, "Registered a new delete function\n");
911 }
912
913
914 void CtdlUnregisterDeleteHook(void (*handler)(char *, long) )
915 {
916         DeleteFunctionHook *cur, *p, *last;
917
918         last = NULL;
919         cur = DeleteHookTable;
920         while (cur != NULL) {
921                 if (handler == cur->h_function_pointer )
922                 {
923                         MODM_syslog(LOG_DEBUG, "Unregistered delete function\n");
924                         p = cur->next;
925                         free(cur);
926
927                         if (last != NULL)
928                                 last->next = p;
929                         else
930                                 DeleteHookTable = p;
931
932                         cur = p;
933                 }
934                 else {
935                         last = cur;
936                         cur = cur->next;
937                 }
938         }
939 }
940 void CtdlDestroyDeleteHooks(void)
941 {
942         DeleteFunctionHook *cur, *p;
943
944         cur = DeleteHookTable;
945         while (cur != NULL)
946         {
947                 MODM_syslog(LOG_DEBUG, "Destroyed delete function\n");
948                 p = cur->next;
949                 free(cur);
950                 cur = p;                
951         }
952         DeleteHookTable = NULL;
953 }
954
955
956
957
958 void CtdlRegisterFixedOutputHook(char *content_type, void (*handler)(char *, int) )
959 {
960         FixedOutputHook *newfcn;
961
962         newfcn = (FixedOutputHook *)
963             malloc(sizeof(FixedOutputHook));
964         newfcn->next = FixedOutputTable;
965         newfcn->h_function_pointer = handler;
966         safestrncpy(newfcn->content_type, content_type, sizeof newfcn->content_type);
967         FixedOutputTable = newfcn;
968
969         MOD_syslog(LOG_DEBUG, "Registered a new fixed output function for %s\n", newfcn->content_type);
970 }
971
972
973 void CtdlUnregisterFixedOutputHook(char *content_type)
974 {
975         FixedOutputHook *cur, *p, *last;
976
977         last = NULL;
978         cur = FixedOutputTable;
979         while (cur != NULL) {
980                 /* This will also remove duplicates if any */
981                 if (!strcasecmp(content_type, cur->content_type)) {
982                         MOD_syslog(LOG_DEBUG,
983                                    "Unregistered fixed output function for %s\n",
984                                    content_type);
985
986                         p = cur->next;
987                         free(cur);
988
989                         if (last != NULL)
990                                 last->next = p;
991                         else
992                                 FixedOutputTable = p;
993                         
994                         cur = p;
995                 }
996                 else
997                 {
998                         last = cur;
999                         cur = cur->next;
1000                 }
1001         }
1002 }
1003
1004 void CtdlDestroyFixedOutputHooks(void)
1005 {
1006         FixedOutputHook *cur, *p;
1007
1008         cur = FixedOutputTable; 
1009         while (cur != NULL)
1010         {
1011                 MOD_syslog(LOG_DEBUG, "Destroyed fixed output function for %s\n", cur->content_type);
1012                 p = cur->next;
1013                 free(cur);
1014                 cur = p;
1015                 
1016         }
1017         FixedOutputTable = NULL;
1018 }
1019
1020 /* returns nonzero if we found a hook and used it */
1021 int PerformFixedOutputHooks(char *content_type, char *content, int content_length)
1022 {
1023         FixedOutputHook *fcn;
1024
1025         for (fcn = FixedOutputTable; fcn != NULL; fcn = fcn->next) {
1026                 if (!strcasecmp(content_type, fcn->content_type)) {
1027                         (*fcn->h_function_pointer) (content, content_length);
1028                         return(1);
1029                 }
1030         }
1031         return(0);
1032 }
1033
1034
1035
1036
1037
1038 void CtdlRegisterXmsgHook(int (*fcn_ptr) (char *, char *, char *, char *), int order)
1039 {
1040
1041         XmsgFunctionHook *newfcn;
1042
1043         newfcn = (XmsgFunctionHook *) malloc(sizeof(XmsgFunctionHook));
1044         newfcn->next = XmsgHookTable;
1045         newfcn->order = order;
1046         newfcn->h_function_pointer = fcn_ptr;
1047         XmsgHookTable = newfcn;
1048         MOD_syslog(LOG_DEBUG, "Registered a new x-msg function (priority %d)\n", order);
1049 }
1050
1051
1052 void CtdlUnregisterXmsgHook(int (*fcn_ptr) (char *, char *, char *, char *), int order)
1053 {
1054         XmsgFunctionHook *cur, *p, *last;
1055
1056         last = NULL;
1057         cur = XmsgHookTable;
1058         while (cur != NULL) {
1059                 /* This will also remove duplicates if any */
1060                 if (fcn_ptr == cur->h_function_pointer &&
1061                     order == cur->order) {
1062                         MOD_syslog(LOG_DEBUG, "Unregistered x-msg function "
1063                                    "(priority %d)\n", order);
1064                         p = cur->next;
1065                         free(cur);
1066
1067                         if (last != NULL)
1068                                 last->next = p;
1069                         else
1070                                 XmsgHookTable = p;
1071                         
1072                         cur = p;
1073                 }
1074                 else {
1075                         last = cur;
1076                         cur = cur->next;
1077                 }
1078         }
1079 }
1080
1081 void CtdlDestroyXmsgHooks(void)
1082 {
1083         XmsgFunctionHook *cur, *p;
1084
1085         cur = XmsgHookTable;
1086         while (cur != NULL)
1087         {
1088                 MOD_syslog(LOG_DEBUG, "Destroyed x-msg function "
1089                         "(priority %d)\n", cur->order);
1090                 p = cur->next;
1091                         
1092                 free(cur);
1093                 cur = p;
1094         }
1095         XmsgHookTable = NULL;
1096 }
1097
1098
1099 void CtdlRegisterServiceHook(int tcp_port,
1100                              char *sockpath,
1101                              void (*h_greeting_function) (void),
1102                              void (*h_command_function) (void),
1103                              void (*h_async_function) (void),
1104                              const char *ServiceName)
1105 {
1106         ServiceFunctionHook *newfcn;
1107         char *message;
1108         char error[SIZ];
1109
1110         strcpy(error, "");
1111         newfcn = (ServiceFunctionHook *) malloc(sizeof(ServiceFunctionHook));
1112         message = (char*) malloc (SIZ + SIZ);
1113         
1114         newfcn->next = ServiceHookTable;
1115         newfcn->tcp_port = tcp_port;
1116         newfcn->sockpath = sockpath;
1117         newfcn->h_greeting_function = h_greeting_function;
1118         newfcn->h_command_function = h_command_function;
1119         newfcn->h_async_function = h_async_function;
1120         newfcn->ServiceName = ServiceName;
1121
1122         if (sockpath != NULL) {
1123                 newfcn->msock = ctdl_uds_server(sockpath, config.c_maxsessions, error);
1124                 snprintf(message, SIZ, "Unix domain socket '%s': ", sockpath);
1125         }
1126         else if (tcp_port <= 0) {       /* port -1 to disable */
1127                 MOD_syslog(LOG_INFO, "Service %s has been manually disabled, skipping\n", ServiceName);
1128                 free (message);
1129                 free(newfcn);
1130                 return;
1131         }
1132         else {
1133                 newfcn->msock = ctdl_tcp_server(config.c_ip_addr,
1134                                               tcp_port,
1135                                               config.c_maxsessions, 
1136                                               error);
1137                 snprintf(message, SIZ, "TCP port %s:%d: (%s) ", 
1138                          config.c_ip_addr, tcp_port, ServiceName);
1139         }
1140
1141         if (newfcn->msock > 0) {
1142                 ServiceHookTable = newfcn;
1143                 strcat(message, "registered.");
1144                 MOD_syslog(LOG_INFO, "%s\n", message);
1145         }
1146         else {
1147                 AddPortError(message, error);
1148                 strcat(message, "FAILED.");
1149                 MOD_syslog(LOG_CRIT, "%s\n", message);
1150                 free(newfcn);
1151         }
1152         free(message);
1153 }
1154
1155
1156 void CtdlUnregisterServiceHook(int tcp_port, char *sockpath,
1157                         void (*h_greeting_function) (void),
1158                         void (*h_command_function) (void),
1159                         void (*h_async_function) (void)
1160                         )
1161 {
1162         ServiceFunctionHook *cur, *p, *last;
1163
1164         last = NULL;
1165         cur = ServiceHookTable;
1166         while (cur != NULL) {
1167                 /* This will also remove duplicates if any */
1168                 if (h_greeting_function == cur->h_greeting_function &&
1169                     h_command_function == cur->h_command_function &&
1170                     h_async_function == cur->h_async_function &&
1171                     tcp_port == cur->tcp_port && 
1172                     !(sockpath && cur->sockpath && strcmp(sockpath, cur->sockpath)) )
1173                 {
1174                         if (cur->msock > 0)
1175                                 close(cur->msock);
1176                         if (sockpath) {
1177                                 MOD_syslog(LOG_INFO, "Closed UNIX domain socket %s\n",
1178                                            sockpath);
1179                                 unlink(sockpath);
1180                         } else if (tcp_port) {
1181                                 MOD_syslog(LOG_INFO, "Closed TCP port %d\n", tcp_port);
1182                         } else {
1183                                 MOD_syslog(LOG_INFO, "Unregistered service \"%s\"\n", cur->ServiceName);
1184                         }
1185                         p = cur->next;
1186                         free(cur);
1187                         if (last != NULL)
1188                                 last->next = p;
1189                         else
1190                                 ServiceHookTable = p;
1191                         cur = p;
1192                 }
1193                 else {
1194                         last = cur;
1195                         cur = cur->next;
1196                 }
1197         }
1198 }
1199
1200
1201 void CtdlShutdownServiceHooks(void)
1202 {
1203         /* sort of a duplicate of close_masters() but called earlier */
1204         ServiceFunctionHook *cur;
1205
1206         cur = ServiceHookTable;
1207         while (cur != NULL) 
1208         {
1209                 if (cur->msock != -1)
1210                 {
1211                         close(cur->msock);
1212                         cur->msock = -1;
1213                         if (cur->sockpath != NULL){
1214                                 MOD_syslog(LOG_INFO, "[%s] Closed UNIX domain socket %s\n",
1215                                            cur->ServiceName,
1216                                            cur->sockpath);
1217                                 unlink(cur->sockpath);
1218                         } else {
1219                                 MOD_syslog(LOG_INFO, "[%s] closing service\n", 
1220                                            cur->ServiceName);
1221                         }
1222                 }
1223                 cur = cur->next;
1224         }
1225 }
1226
1227 void CtdlDestroyServiceHook(void)
1228 {
1229         ServiceFunctionHook *cur, *p;
1230
1231         cur = ServiceHookTable;
1232         while (cur != NULL)
1233         {
1234                 close(cur->msock);
1235                 if (cur->sockpath) {
1236                         MOD_syslog(LOG_INFO, "Closed UNIX domain socket %s\n",
1237                                    cur->sockpath);
1238                         unlink(cur->sockpath);
1239                 } else if (cur->tcp_port) {
1240                         MOD_syslog(LOG_INFO, "Closed TCP port %d\n", cur->tcp_port);
1241                 } else {
1242                         MOD_syslog(LOG_INFO, "Destroyed service \"%s\"\n", cur->ServiceName);
1243                 }
1244                 p = cur->next;
1245                 free(cur);
1246                 cur = p;
1247         }
1248         ServiceHookTable = NULL;
1249 }
1250
1251 void CtdlRegisterSearchFuncHook(void (*fcn_ptr)(int *, long **, const char *), char *name)
1252 {
1253         SearchFunctionHook *newfcn;
1254
1255         if (!name || !fcn_ptr) {
1256                 return;
1257         }
1258         
1259         newfcn = (SearchFunctionHook *)
1260             malloc(sizeof(SearchFunctionHook));
1261         newfcn->next = SearchFunctionHookTable;
1262         newfcn->name = name;
1263         newfcn->fcn_ptr = fcn_ptr;
1264         SearchFunctionHookTable = newfcn;
1265
1266         MOD_syslog(LOG_DEBUG, "Registered a new search function (%s)\n", name);
1267 }
1268
1269 void CtdlUnregisterSearchFuncHook(void (*fcn_ptr)(int *, long **, const char *), char *name)
1270 {
1271         SearchFunctionHook *cur, *p, *last;
1272         
1273         last = NULL;
1274         cur = SearchFunctionHookTable;
1275         while (cur != NULL) {
1276                 if (fcn_ptr &&
1277                     (cur->fcn_ptr == fcn_ptr) &&
1278                     name && !strcmp(name, cur->name))
1279                 {
1280                         MOD_syslog(LOG_DEBUG, "Unregistered search function(%s)\n", name);
1281                         p = cur->next;
1282                         free (cur);
1283                         if (last != NULL)
1284                                 last->next = p;
1285                         else
1286                                 SearchFunctionHookTable = p;
1287                         cur = p;
1288                 }
1289                 else {
1290                         last = cur;
1291                         cur = cur->next;
1292                 }
1293         }
1294 }
1295
1296 void CtdlDestroySearchHooks(void)
1297 {
1298         SearchFunctionHook *cur, *p;
1299
1300         cur = SearchFunctionHookTable;
1301         SearchFunctionHookTable = NULL;
1302         while (cur != NULL) {
1303                 p = cur->next;
1304                 free(cur);
1305                 cur = p;
1306         }
1307 }
1308
1309 void CtdlModuleDoSearch(int *num_msgs, long **search_msgs, const char *search_string, const char *func_name)
1310 {
1311         SearchFunctionHook *fcn = NULL;
1312
1313         for (fcn = SearchFunctionHookTable; fcn != NULL; fcn = fcn->next) {
1314                 if (!func_name || !strcmp(func_name, fcn->name)) {
1315                         (*fcn->fcn_ptr) (num_msgs, search_msgs, search_string);
1316                         return;
1317                 }
1318         }
1319         *num_msgs = 0;
1320 }
1321
1322
1323 void PerformSessionHooks(int EventType)
1324 {
1325         SessionFunctionHook *fcn = NULL;
1326
1327         for (fcn = SessionHookTable; fcn != NULL; fcn = fcn->next) {
1328                 if (fcn->eventtype == EventType) {
1329                         if (EventType == EVT_TIMER) {
1330                                 pthread_setspecific(MyConKey, NULL);    /* for every hook */
1331                         }
1332                         (*fcn->h_function_pointer) ();
1333                 }
1334         }
1335 }
1336
1337 void PerformUserHooks(ctdluser *usbuf, int EventType)
1338 {
1339         UserFunctionHook *fcn = NULL;
1340
1341         for (fcn = UserHookTable; fcn != NULL; fcn = fcn->next) {
1342                 if (fcn->eventtype == EventType) {
1343                         (*fcn->h_function_pointer) (usbuf);
1344                 }
1345         }
1346 }
1347
1348 int PerformMessageHooks(struct CtdlMessage *msg, int EventType)
1349 {
1350         MessageFunctionHook *fcn = NULL;
1351         int total_retval = 0;
1352
1353         /* Other code may elect to protect this message from server-side
1354          * handlers; if this is the case, don't do anything.
1355         MOD_syslog(LOG_DEBUG, "** Event type is %d, flags are %d\n", EventType, msg->cm_flags);
1356          */
1357         if (msg->cm_flags & CM_SKIP_HOOKS) {
1358                 MODM_syslog(LOG_DEBUG, "Skipping hooks\n");
1359                 return(0);
1360         }
1361
1362         /* Otherwise, run all the hooks appropriate to this event type.
1363          */
1364         for (fcn = MessageHookTable; fcn != NULL; fcn = fcn->next) {
1365                 if (fcn->eventtype == EventType) {
1366                         total_retval = total_retval + (*fcn->h_function_pointer) (msg);
1367                 }
1368         }
1369
1370         /* Return the sum of the return codes from the hook functions.  If
1371          * this is an EVT_BEFORESAVE event, a nonzero return code will cause
1372          * the save operation to abort.
1373          */
1374         return total_retval;
1375 }
1376
1377
1378 int PerformRoomHooks(struct ctdlroom *target_room)
1379 {
1380         RoomFunctionHook *fcn;
1381         int total_retval = 0;
1382
1383         MOD_syslog(LOG_DEBUG, "Performing room hooks for <%s>\n", target_room->QRname);
1384
1385         for (fcn = RoomHookTable; fcn != NULL; fcn = fcn->next) {
1386                 total_retval = total_retval + (*fcn->fcn_ptr) (target_room);
1387         }
1388
1389         /* Return the sum of the return codes from the hook functions.
1390          */
1391         return total_retval;
1392 }
1393
1394
1395 int PerformNetprocHooks(struct CtdlMessage *msg, char *target_room)
1396 {
1397         NetprocFunctionHook *fcn;
1398         int total_retval = 0;
1399
1400         for (fcn = NetprocHookTable; fcn != NULL; fcn = fcn->next) {
1401                 total_retval = total_retval +
1402                         (*fcn->h_function_pointer) (msg, target_room);
1403         }
1404
1405         /* Return the sum of the return codes from the hook functions.
1406          * A nonzero return code will cause the message to *not* be imported.
1407          */
1408         return total_retval;
1409 }
1410
1411
1412 void PerformDeleteHooks(char *room, long msgnum)
1413 {
1414         DeleteFunctionHook *fcn;
1415
1416         for (fcn = DeleteHookTable; fcn != NULL; fcn = fcn->next) {
1417                 (*fcn->h_function_pointer) (room, msgnum);
1418         }
1419 }
1420
1421
1422
1423
1424
1425 int PerformXmsgHooks(char *sender, char *sender_email, char *recp, char *msg)
1426 {
1427         XmsgFunctionHook *fcn;
1428         int total_sent = 0;
1429         int p;
1430
1431         for (p=0; p<MAX_XMSG_PRI; ++p) {
1432                 for (fcn = XmsgHookTable; fcn != NULL; fcn = fcn->next) {
1433                         if (fcn->order == p) {
1434                                 total_sent +=
1435                                         (*fcn->h_function_pointer)
1436                                                 (sender, sender_email, recp, msg);
1437                         }
1438                 }
1439                 /* Break out of the loop if a higher-priority function
1440                  * successfully delivered the message.  This prevents duplicate
1441                  * deliveries to local users simultaneously signed onto
1442                  * remote services.
1443                  */
1444                 if (total_sent) break;
1445         }
1446         return total_sent;
1447 }
1448
1449
1450 /*
1451  * Dirty hack until we impliment a hook mechanism for this
1452  */
1453 void CtdlModuleStartCryptoMsgs(char *ok_response, char *nosup_response, char *error_response)
1454 {
1455 #ifdef HAVE_OPENSSL
1456         CtdlStartTLS (ok_response, nosup_response, error_response);
1457 #endif
1458 }
1459
1460 void DebugModulesEnable(const int n)
1461 {
1462         DebugModules = n;
1463 }
1464 CTDL_MODULE_INIT(modules)
1465 {
1466         if (!threading) {
1467                 CtdlRegisterDebugFlagHook(HKEY("modules"), DebugModulesEnable, &DebugModules);
1468
1469                 CtdlRegisterProtoHook(cmd_log_get, "LOGP", "Print Log-parameters");
1470                 CtdlRegisterProtoHook(cmd_log_set, "LOGS", "Set Log-parameters");
1471         }
1472         return "modules";
1473 }