33796ac97bf433f8a4845239949f9054b89f899e
[citadel.git] / citadel / server / serv_extensions.c
1 // This began as a framework written by Brian Costello (btx) that loaded server extensions as dynamic modules.
2 // We don't do it that way anymore but the concept lives on as a high degree of modularity in the server.
3 // The functions in this file handle registration and execution of the server hooks used by static linked modules.
4 //
5 // Copyright (c) 1987-2021 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 #include <stdlib.h>
11 #include <unistd.h>
12 #include <stdio.h>
13 #include <sys/stat.h>
14 #include <libcitadel.h>
15 #include "sysdep_decls.h"
16 #include "modules/crypto/serv_crypto.h" /* Needed until a universal crypto startup hook is implimented for CtdlStartTLS */
17 #include "serv_extensions.h"
18 #include "ctdl_module.h"
19 #include "config.h"
20
21
22 /*
23  * Structure defentitions for hook tables
24  */
25
26 typedef struct FixedOutputHook FixedOutputHook;
27 struct FixedOutputHook {
28         FixedOutputHook *next;
29         char content_type[64];
30         void (*h_function_pointer) (char *, int);
31 };
32 FixedOutputHook *FixedOutputTable = NULL;
33
34
35 /*
36  * SessionFunctionHook extensions are used for any type of hook for which
37  * the context in which it's being called (which is determined by the event
38  * type) will make it obvious for the hook function to know where to look for
39  * pertinent data.
40  */
41 typedef struct SessionFunctionHook SessionFunctionHook;
42 struct SessionFunctionHook {
43         SessionFunctionHook *next;
44         int Priority;
45         void (*h_function_pointer) (void);
46         int eventtype;
47 };
48 SessionFunctionHook *SessionHookTable = NULL;
49
50
51 /*
52  * UserFunctionHook extensions are used for any type of hook which implements
53  * an operation on a user or username (potentially) other than the one
54  * operating the current session.
55  */
56 typedef struct UserFunctionHook UserFunctionHook;
57 struct UserFunctionHook {
58         UserFunctionHook *next;
59         void (*h_function_pointer) (struct ctdluser *usbuf);
60         int eventtype;
61 };
62 UserFunctionHook *UserHookTable = NULL;
63
64
65 /*
66  * MessageFunctionHook extensions are used for hooks which implement handlers
67  * for various types of message operations (save, read, etc.)
68  */
69 typedef struct MessageFunctionHook MessageFunctionHook;
70 struct MessageFunctionHook {
71         MessageFunctionHook *next;
72         int (*h_function_pointer) (struct CtdlMessage *msg, struct recptypes *recps);
73         int eventtype;
74 };
75 MessageFunctionHook *MessageHookTable = NULL;
76
77
78 /*
79  * DeleteFunctionHook extensions are used for hooks which get called when a
80  * message is about to be deleted.
81  */
82 typedef struct DeleteFunctionHook DeleteFunctionHook;
83 struct DeleteFunctionHook {
84         DeleteFunctionHook *next;
85         void (*h_function_pointer) (char *target_room, long msgnum);
86 };
87 DeleteFunctionHook *DeleteHookTable = NULL;
88
89
90 /*
91  * ExpressMessageFunctionHook extensions are used for hooks which implement
92  * the sending of an instant message through various channels.  Any function
93  * registered should return the number of recipients to whom the message was
94  * successfully transmitted.
95  */
96 typedef struct XmsgFunctionHook XmsgFunctionHook;
97 struct XmsgFunctionHook {
98         XmsgFunctionHook *next;
99         int (*h_function_pointer) (char *, char *, char *, char *);
100         int order;
101 };
102 XmsgFunctionHook *XmsgHookTable = NULL;
103
104
105 /*
106  * RoomFunctionHook extensions are used for hooks which impliment room
107  * processing functions when new messages are added.
108  */
109 typedef struct RoomFunctionHook RoomFunctionHook;
110 struct RoomFunctionHook {
111         RoomFunctionHook *next;
112         int (*fcn_ptr) (struct ctdlroom *);
113 };
114 RoomFunctionHook *RoomHookTable = NULL;
115
116 ServiceFunctionHook *ServiceHookTable = NULL;
117
118 typedef struct ProtoFunctionHook ProtoFunctionHook;
119 struct ProtoFunctionHook {
120         void (*handler) (char *cmdbuf);
121         const char *cmd;
122         const char *desc;
123 };
124
125 HashList *ProtoHookList = NULL;
126
127
128 #define ERR_PORT (1 << 1)
129
130
131 static StrBuf *portlist = NULL;
132 static StrBuf *errormessages = NULL;
133
134
135 long   DetailErrorFlags;
136 ConstStr Empty = {HKEY("")};
137 char *ErrSubject = "Startup Problems";
138 ConstStr ErrGeneral[] = {
139         {HKEY("Citadel had trouble on starting up. ")},
140         {HKEY(" This means, Citadel won't be the service provider for a specific service you configured it to.\n\n"
141               "If you don't want Citadel to provide these services, turn them off in WebCit via: ")},
142         {HKEY("To make both ways actualy take place restart the citserver with \"sendcommand down\"\n\n"
143               "The errors returned by the system were:\n")},
144         {HKEY("You can recheck the above if you follow this faq item:\n"
145               "http://www.citadel.org/doku.php?id=faq:mastering_your_os:net#netstat")}
146 };
147
148 ConstStr ErrPortShort = { HKEY("We couldn't bind all ports you configured to be provided by Citadel Server.\n")};
149 ConstStr ErrPortWhere = { HKEY("\"Admin->System Preferences->Network\".\n\nThe failed ports and sockets are: ")};
150 ConstStr ErrPortHint  = { HKEY("If you want Citadel to provide you with that functionality, "
151                                "check the output of \"netstat -lnp\" on Linux, or \"netstat -na\" on BSD"
152                                " and disable the program that binds these ports.\n")};
153
154
155 void LogPrintMessages(long err) {
156         StrBuf *Message;
157         StrBuf *List, *DetailList;
158         ConstStr *Short, *Where, *Hint; 
159
160         
161         Message = NewStrBufPlain(NULL, StrLength(portlist) + StrLength(errormessages));
162         
163         DetailErrorFlags = DetailErrorFlags & ~err;
164
165         switch (err)
166         {
167         case ERR_PORT:
168                 Short = &ErrPortShort;
169                 Where = &ErrPortWhere;
170                 Hint  = &ErrPortHint;
171                 List  = portlist;
172                 DetailList = errormessages;
173                 break;
174         default:
175                 Short = &Empty;
176                 Where = &Empty;
177                 Hint  = &Empty;
178                 List  = NULL;
179                 DetailList = NULL;
180         }
181
182         StrBufAppendBufPlain(Message, CKEY(ErrGeneral[0]), 0);
183         StrBufAppendBufPlain(Message, CKEY(*Short), 0); 
184         StrBufAppendBufPlain(Message, CKEY(ErrGeneral[1]), 0);
185         StrBufAppendBufPlain(Message, CKEY(*Where), 0);
186         StrBufAppendBuf(Message, List, 0);
187         StrBufAppendBufPlain(Message, HKEY("\n\n"), 0);
188         StrBufAppendBufPlain(Message, CKEY(*Hint), 0);
189         StrBufAppendBufPlain(Message, HKEY("\n\n"), 0);
190         StrBufAppendBufPlain(Message, CKEY(ErrGeneral[2]), 0);
191         StrBufAppendBuf(Message, DetailList, 0);
192         StrBufAppendBufPlain(Message, HKEY("\n\n"), 0);
193         StrBufAppendBufPlain(Message, CKEY(ErrGeneral[3]), 0);
194
195         syslog(LOG_ERR, "extensions: %s", ChrPtr(Message));
196         syslog(LOG_ERR, "extensions: %s", ErrSubject);
197         quickie_message("Citadel", NULL, NULL, AIDEROOM, ChrPtr(Message), FMT_FIXED, ErrSubject);
198
199         FreeStrBuf(&Message);
200         FreeStrBuf(&List);
201         FreeStrBuf(&DetailList);
202 }
203
204
205 void AddPortError(char *Port, char *ErrorMessage) {
206         long len;
207
208         DetailErrorFlags |= ERR_PORT;
209
210         len = StrLength(errormessages);
211         if (len > 0) StrBufAppendBufPlain(errormessages, HKEY("; "), 0);
212         else errormessages = NewStrBuf();
213         StrBufAppendBufPlain(errormessages, ErrorMessage, -1, 0);
214
215
216         len = StrLength(portlist);
217         if (len > 0) StrBufAppendBufPlain(portlist, HKEY(";"), 0);
218         else portlist = NewStrBuf();
219         StrBufAppendBufPlain(portlist, Port, -1, 0);
220 }
221
222
223 int DLoader_Exec_Cmd(char *cmdbuf) {
224         void *vP;
225         ProtoFunctionHook *p;
226
227         if (GetHash(ProtoHookList, cmdbuf, 4, &vP) && (vP != NULL)) {
228                 p = (ProtoFunctionHook*) vP;
229                 p->handler(&cmdbuf[5]);
230                 return 1;
231         }
232         return 0;
233 }
234
235
236 void CtdlRegisterProtoHook(void (*handler) (char *), char *cmd, char *desc) {
237         ProtoFunctionHook *p;
238
239         if (ProtoHookList == NULL)
240                 ProtoHookList = NewHash (1, FourHash);
241
242
243         p = (ProtoFunctionHook *)
244                 malloc(sizeof(ProtoFunctionHook));
245
246         if (p == NULL) {
247                 fprintf(stderr, "can't malloc new ProtoFunctionHook\n");
248                 exit(EXIT_FAILURE);
249         }
250         p->handler = handler;
251         p->cmd = cmd;
252         p->desc = desc;
253
254         Put(ProtoHookList, cmd, 4, p, NULL);
255         syslog(LOG_DEBUG, "extensions: registered server command %s (%s)", cmd, desc);
256 }
257
258
259 void CtdlRegisterSessionHook(void (*fcn_ptr) (void), int EventType, int Priority)
260 {
261         SessionFunctionHook *newfcn;
262
263         newfcn = (SessionFunctionHook *)
264             malloc(sizeof(SessionFunctionHook));
265         newfcn->Priority = Priority;
266         newfcn->h_function_pointer = fcn_ptr;
267         newfcn->eventtype = EventType;
268
269         SessionFunctionHook **pfcn;
270         pfcn = &SessionHookTable;
271         while ((*pfcn != NULL) && 
272                ((*pfcn)->Priority < newfcn->Priority) &&
273                ((*pfcn)->next != NULL))
274                 pfcn = &(*pfcn)->next;
275                 
276         newfcn->next = *pfcn;
277         *pfcn = newfcn;
278         
279         syslog(LOG_DEBUG, "extensions: registered a new session function (type %d Priority %d)", EventType, Priority);
280 }
281
282
283 void CtdlRegisterUserHook(void (*fcn_ptr) (ctdluser *), int EventType)
284 {
285
286         UserFunctionHook *newfcn;
287
288         newfcn = (UserFunctionHook *)
289             malloc(sizeof(UserFunctionHook));
290         newfcn->next = UserHookTable;
291         newfcn->h_function_pointer = fcn_ptr;
292         newfcn->eventtype = EventType;
293         UserHookTable = newfcn;
294
295         syslog(LOG_DEBUG, "extensions: registered a new user function (type %d)",
296                    EventType);
297 }
298
299
300 void CtdlRegisterMessageHook(int (*handler)(struct CtdlMessage *, struct recptypes *), int EventType)
301 {
302
303         MessageFunctionHook *newfcn;
304
305         newfcn = (MessageFunctionHook *)
306             malloc(sizeof(MessageFunctionHook));
307         newfcn->next = MessageHookTable;
308         newfcn->h_function_pointer = handler;
309         newfcn->eventtype = EventType;
310         MessageHookTable = newfcn;
311
312         syslog(LOG_DEBUG, "extensions: registered a new message function (type %d)", EventType);
313 }
314
315
316 void CtdlRegisterRoomHook(int (*fcn_ptr)(struct ctdlroom *))
317 {
318         RoomFunctionHook *newfcn;
319
320         newfcn = (RoomFunctionHook *)
321             malloc(sizeof(RoomFunctionHook));
322         newfcn->next = RoomHookTable;
323         newfcn->fcn_ptr = fcn_ptr;
324         RoomHookTable = newfcn;
325
326         syslog(LOG_DEBUG, "extensions: registered a new room function");
327 }
328
329
330 void CtdlRegisterDeleteHook(void (*handler)(char *, long) )
331 {
332         DeleteFunctionHook *newfcn;
333
334         newfcn = (DeleteFunctionHook *)
335             malloc(sizeof(DeleteFunctionHook));
336         newfcn->next = DeleteHookTable;
337         newfcn->h_function_pointer = handler;
338         DeleteHookTable = newfcn;
339
340         syslog(LOG_DEBUG, "extensions: registered a new delete function");
341 }
342
343
344 void CtdlRegisterFixedOutputHook(char *content_type, void (*handler)(char *, int) )
345 {
346         FixedOutputHook *newfcn;
347
348         newfcn = (FixedOutputHook *)
349             malloc(sizeof(FixedOutputHook));
350         newfcn->next = FixedOutputTable;
351         newfcn->h_function_pointer = handler;
352         safestrncpy(newfcn->content_type, content_type, sizeof newfcn->content_type);
353         FixedOutputTable = newfcn;
354
355         syslog(LOG_DEBUG, "extensions: registered a new fixed output function for %s", newfcn->content_type);
356 }
357
358
359 /* returns nonzero if we found a hook and used it */
360 int PerformFixedOutputHooks(char *content_type, char *content, int content_length)
361 {
362         FixedOutputHook *fcn;
363
364         for (fcn = FixedOutputTable; fcn != NULL; fcn = fcn->next) {
365                 if (!strcasecmp(content_type, fcn->content_type)) {
366                         (*fcn->h_function_pointer) (content, content_length);
367                         return(1);
368                 }
369         }
370         return(0);
371 }
372
373
374 void CtdlRegisterXmsgHook(int (*fcn_ptr) (char *, char *, char *, char *), int order)
375 {
376
377         XmsgFunctionHook *newfcn;
378
379         newfcn = (XmsgFunctionHook *) malloc(sizeof(XmsgFunctionHook));
380         newfcn->next = XmsgHookTable;
381         newfcn->order = order;
382         newfcn->h_function_pointer = fcn_ptr;
383         XmsgHookTable = newfcn;
384         syslog(LOG_DEBUG, "extensions: registered a new x-msg function (priority %d)", order);
385 }
386
387
388 void CtdlRegisterServiceHook(int tcp_port,
389                              char *sockpath,
390                              void (*h_greeting_function) (void),
391                              void (*h_command_function) (void),
392                              void (*h_async_function) (void),
393                              const char *ServiceName)
394 {
395         ServiceFunctionHook *newfcn;
396         char *message;
397
398         newfcn = (ServiceFunctionHook *) malloc(sizeof(ServiceFunctionHook));
399         message = (char*) malloc (SIZ + SIZ);
400         
401         newfcn->next = ServiceHookTable;
402         newfcn->tcp_port = tcp_port;
403         newfcn->sockpath = sockpath;
404         newfcn->h_greeting_function = h_greeting_function;
405         newfcn->h_command_function = h_command_function;
406         newfcn->h_async_function = h_async_function;
407         newfcn->ServiceName = ServiceName;
408
409         if (sockpath != NULL) {
410                 newfcn->msock = ctdl_uds_server(sockpath, CtdlGetConfigInt("c_maxsessions"));
411                 snprintf(message, SIZ, "extensions: unix domain socket '%s': ", sockpath);
412         }
413         else if (tcp_port <= 0) {       /* port -1 to disable */
414                 syslog(LOG_INFO, "extensions: service %s has been manually disabled, skipping", ServiceName);
415                 free (message);
416                 free(newfcn);
417                 return;
418         }
419         else {
420                 newfcn->msock = ctdl_tcp_server(CtdlGetConfigStr("c_ip_addr"), tcp_port, CtdlGetConfigInt("c_maxsessions"));
421                 snprintf(message, SIZ, "extensions: TCP port %s:%d: (%s) ", 
422                          CtdlGetConfigStr("c_ip_addr"), tcp_port, ServiceName);
423         }
424
425         if (newfcn->msock > 0) {
426                 ServiceHookTable = newfcn;
427                 strcat(message, "registered.");
428                 syslog(LOG_INFO, "%s", message);
429         }
430         else {
431                 AddPortError(message, "failed");
432                 strcat(message, "FAILED.");
433                 syslog(LOG_ERR, "%s", message);
434                 free(newfcn);
435         }
436         free(message);
437 }
438
439
440 // During shutdown we can close all of the listening sockets.
441 void CtdlShutdownServiceHooks(void) {
442         ServiceFunctionHook *cur;
443
444         cur = ServiceHookTable;
445         while (cur != NULL) {
446                 if (cur->msock != -1) {
447                         close(cur->msock);
448                         cur->msock = -1;
449                         if (cur->sockpath != NULL){
450                                 syslog(LOG_INFO, "extensions: [%s] closed unix domain socket %s", cur->ServiceName, cur->sockpath);
451                                 unlink(cur->sockpath);
452                         } else {
453                                 syslog(LOG_INFO, "extensions: [%s] closing service", cur->ServiceName);
454                         }
455                 }
456                 cur = cur->next;
457         }
458 }
459
460
461 void PerformSessionHooks(int EventType) {
462         SessionFunctionHook *fcn = NULL;
463
464         for (fcn = SessionHookTable; fcn != NULL; fcn = fcn->next) {
465                 if (fcn->eventtype == EventType) {
466                         if (EventType == EVT_TIMER) {
467                                 pthread_setspecific(MyConKey, NULL);    /* for every hook */
468                         }
469                         (*fcn->h_function_pointer) ();
470                 }
471         }
472 }
473
474
475 void PerformUserHooks(ctdluser *usbuf, int EventType) {
476         UserFunctionHook *fcn = NULL;
477
478         for (fcn = UserHookTable; fcn != NULL; fcn = fcn->next) {
479                 if (fcn->eventtype == EventType) {
480                         (*fcn->h_function_pointer) (usbuf);
481                 }
482         }
483 }
484
485
486 int PerformMessageHooks(struct CtdlMessage *msg, struct recptypes *recps, int EventType) {
487         MessageFunctionHook *fcn = NULL;
488         int total_retval = 0;
489
490         /* Other code may elect to protect this message from server-side
491          * handlers; if this is the case, don't do anything.
492          */
493         if (msg->cm_flags & CM_SKIP_HOOKS) {
494                 return(0);
495         }
496
497         /* Otherwise, run all the hooks appropriate to this event type.
498          */
499         for (fcn = MessageHookTable; fcn != NULL; fcn = fcn->next) {
500                 if (fcn->eventtype == EventType) {
501                         total_retval = total_retval + (*fcn->h_function_pointer) (msg, recps);
502                 }
503         }
504
505         /* Return the sum of the return codes from the hook functions.  If
506          * this is an EVT_BEFORESAVE event, a nonzero return code will cause
507          * the save operation to abort.
508          */
509         return total_retval;
510 }
511
512
513 int PerformRoomHooks(struct ctdlroom *target_room) {
514         RoomFunctionHook *fcn;
515         int total_retval = 0;
516
517         syslog(LOG_DEBUG, "extensions: performing room hooks for <%s>", target_room->QRname);
518
519         for (fcn = RoomHookTable; fcn != NULL; fcn = fcn->next) {
520                 total_retval = total_retval + (*fcn->fcn_ptr) (target_room);
521         }
522
523         /* Return the sum of the return codes from the hook functions.
524          */
525         return total_retval;
526 }
527
528
529 void PerformDeleteHooks(char *room, long msgnum) {
530         DeleteFunctionHook *fcn;
531
532         for (fcn = DeleteHookTable; fcn != NULL; fcn = fcn->next) {
533                 (*fcn->h_function_pointer) (room, msgnum);
534         }
535 }
536
537
538 int PerformXmsgHooks(char *sender, char *sender_email, char *recp, char *msg) {
539         XmsgFunctionHook *fcn;
540         int total_sent = 0;
541         int p;
542
543         for (p=0; p<MAX_XMSG_PRI; ++p) {
544                 for (fcn = XmsgHookTable; fcn != NULL; fcn = fcn->next) {
545                         if (fcn->order == p) {
546                                 total_sent +=
547                                         (*fcn->h_function_pointer)
548                                                 (sender, sender_email, recp, msg);
549                         }
550                 }
551                 /* Break out of the loop if a higher-priority function
552                  * successfully delivered the message.  This prevents duplicate
553                  * deliveries to local users simultaneously signed onto
554                  * remote services.
555                  */
556                 if (total_sent) break;
557         }
558         return total_sent;
559 }
560
561
562 /*
563  * "Start TLS" function that is (hopefully) adaptable for any protocol
564  */
565 void CtdlModuleStartCryptoMsgs(char *ok_response, char *nosup_response, char *error_response) {
566 #ifdef HAVE_OPENSSL
567         CtdlStartTLS (ok_response, nosup_response, error_response);
568 #endif
569 }
570
571
572 CTDL_MODULE_INIT(modules) {
573         return "modules";
574 }