014dfa6c7768478b4fe07073b176a7ba772e9bd0
[citadel.git] / citadel / server / modules / expire / serv_expire.c
1 // This module handles the expiry of old messages and the purging of old users.
2 //
3 // You might also see this module affectionately referred to as TDAP (The Dreaded Auto-Purger).
4 //
5 // Copyright (c) 1988-2023 by citadel.org (Art Cancro, Wilifried Goesgens, and others)
6 //
7 // This program is open source software.  Use, duplication, or disclosure
8 // is subject to the terms of the GNU General Public License, version 3.
9
10
11 #include "../../sysdep.h"
12 #include <stdlib.h>
13 #include <unistd.h>
14 #include <stdio.h>
15 #include <fcntl.h>
16 #include <signal.h>
17 #include <pwd.h>
18 #include <errno.h>
19 #include <sys/types.h>
20 #include <time.h>
21 #include <sys/wait.h>
22 #include <string.h>
23 #include <limits.h>
24 #include <libcitadel.h>
25 #include "../../citadel_defs.h"
26 #include "../../server.h"
27 #include "../../citserver.h"
28 #include "../../support.h"
29 #include "../../config.h"
30 #include "policy.h"
31 #include "../../database.h"
32 #include "../../msgbase.h"
33 #include "../../user_ops.h"
34 #include "../../control.h"
35 #include "../../threads.h"
36 #include "../../context.h"
37
38 #include "../../ctdl_module.h"
39
40
41 struct PurgeList {
42         struct PurgeList *next;
43         char name[ROOMNAMELEN];         // use the larger of username or roomname
44 };
45
46 struct VPurgeList {
47         struct VPurgeList *next;
48         long vp_roomnum;
49         long vp_roomgen;
50         long vp_usernum;
51 };
52
53 struct ValidRoom {
54         struct ValidRoom *next;
55         long vr_roomnum;
56         long vr_roomgen;
57 };
58
59 struct ValidUser {
60         struct ValidUser *next;
61         long vu_usernum;
62 };
63
64 struct ctdlroomref {
65         struct ctdlroomref *next;
66         long msgnum;
67 };
68
69 struct UPurgeList {
70         struct UPurgeList *next;
71         char up_key[256];
72 };
73
74 struct EPurgeList {
75         struct EPurgeList *next;
76         int ep_keylen;
77         char *ep_key;
78 };
79
80
81 struct PurgeList *UserPurgeList = NULL;
82 struct PurgeList *RoomPurgeList = NULL;
83 struct ValidRoom *ValidRoomList = NULL;
84 struct ValidUser *ValidUserList = NULL;
85 int messages_purged;
86 int users_not_purged;
87 char *users_corrupt_msg = NULL;
88 char *users_zero_msg = NULL;
89 struct ctdlroomref *rr = NULL;
90 int force_purge_now = 0;                        // set to nonzero to force a run right now
91
92
93 // First phase of message purge -- gather the locations of messages which
94 // qualify for purging and write them to a temp file.
95 void GatherPurgeMessages(struct ctdlroom *qrbuf, void *data) {
96         struct ExpirePolicy epbuf;
97         long delnum;
98         time_t xtime, now;
99         struct CtdlMessage *msg = NULL;
100         int a;
101         struct cdbdata *cdbfr;
102         long *msglist = NULL;
103         int num_msgs = 0;
104         FILE *purgelist;
105
106         purgelist = (FILE *)data;
107         fprintf(purgelist, "r=%s\n", qrbuf->QRname);
108
109         time(&now);
110         GetExpirePolicy(&epbuf, qrbuf);
111
112         // If the room is set to never expire messages ... do nothing
113         if (epbuf.expire_mode == EXPIRE_NEXTLEVEL) return;
114         if (epbuf.expire_mode == EXPIRE_MANUAL) return;
115
116         // Don't purge messages containing system configuration, dumbass.
117         if (!strcasecmp(qrbuf->QRname, SYSCONFIGROOM)) return;
118
119         // Ok, we got this far ... now let's see what's in the room.
120         cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf->QRnumber, sizeof(long));
121
122         if (cdbfr != NULL) {
123                 msglist = malloc(cdbfr->len);
124                 memcpy(msglist, cdbfr->ptr, cdbfr->len);
125                 num_msgs = cdbfr->len / sizeof(long);
126                 cdb_free(cdbfr);
127         }
128
129         // Nothing to do if there aren't any messages
130         if (num_msgs == 0) {
131                 if (msglist != NULL) free(msglist);
132                 return;
133         }
134
135         // If the room is set to expire by count, do that.
136         if (epbuf.expire_mode == EXPIRE_NUMMSGS) {
137                 if (num_msgs > epbuf.expire_value) {
138                         for (a=0; a<(num_msgs - epbuf.expire_value); ++a) {
139                                 fprintf(purgelist, "m=%ld\n", msglist[a]);
140                                 ++messages_purged;
141                         }
142                 }
143         }
144
145         // If the room is set to expire by age...
146         if (epbuf.expire_mode == EXPIRE_AGE) {
147                 for (a=0; a<num_msgs; ++a) {
148                         delnum = msglist[a];
149
150                         msg = CtdlFetchMessage(delnum, 0);      // don't need the body
151                         if (msg != NULL) {
152                                 xtime = atol(msg->cm_fields[eTimestamp]);
153                                 CM_Free(msg);
154                         }
155                         else {
156                                 xtime = 0L;
157                         }
158
159                         if ((xtime > 0L) && (now - xtime > (time_t)(epbuf.expire_value * 86400L))) {
160                                 fprintf(purgelist, "m=%ld\n", delnum);
161                                 ++messages_purged;
162                         }
163                 }
164         }
165
166         if (msglist != NULL) free(msglist);
167 }
168
169
170 // Second phase of message purge -- read list of msgs from temp file and delete them.
171 void DoPurgeMessages(FILE *purgelist) {
172         char roomname[ROOMNAMELEN];
173         long msgnum;
174         char buf[SIZ];
175
176         rewind(purgelist);
177         strcpy(roomname, "nonexistent room ___ ___");
178         while (fgets(buf, sizeof buf, purgelist) != NULL) {
179                 buf[strlen(buf)-1]=0;
180                 if (!strncasecmp(buf, "r=", 2)) {
181                         strcpy(roomname, &buf[2]);
182                 }
183                 if (!strncasecmp(buf, "m=", 2)) {
184                         msgnum = atol(&buf[2]);
185                         if (msgnum > 0L) {
186                                 CtdlDeleteMessages(roomname, &msgnum, 1, "");
187                         }
188                 }
189         }
190 }
191
192
193 void PurgeMessages(void) {
194         FILE *purgelist;
195
196         syslog(LOG_DEBUG, "PurgeMessages() called");
197         messages_purged = 0;
198
199         purgelist = tmpfile();
200         if (purgelist == NULL) {
201                 syslog(LOG_CRIT, "Can't create purgelist temp file: %s", strerror(errno));
202                 return;
203         }
204
205         CtdlForEachRoom(GatherPurgeMessages, (void *)purgelist );
206         DoPurgeMessages(purgelist);
207         fclose(purgelist);
208 }
209
210
211 void AddValidUser(char *username, void *data) {
212         struct ValidUser *vuptr;
213         struct ctdluser usbuf;
214
215         if (CtdlGetUser(&usbuf, username) != 0) {
216                 return;
217         }
218
219         vuptr = (struct ValidUser *)malloc(sizeof(struct ValidUser));
220         vuptr->next = ValidUserList;
221         vuptr->vu_usernum = usbuf.usernum;
222         ValidUserList = vuptr;
223 }
224
225
226 void AddValidRoom(struct ctdlroom *qrbuf, void *data) {
227         struct ValidRoom *vrptr;
228
229         vrptr = (struct ValidRoom *)malloc(sizeof(struct ValidRoom));
230         vrptr->next = ValidRoomList;
231         vrptr->vr_roomnum = qrbuf->QRnumber;
232         vrptr->vr_roomgen = qrbuf->QRgen;
233         ValidRoomList = vrptr;
234 }
235
236
237 void DoPurgeRooms(struct ctdlroom *qrbuf, void *data) {
238         time_t age, purge_secs;
239         struct PurgeList *pptr;
240         struct ValidUser *vuptr;
241         int do_purge = 0;
242
243         // For mailbox rooms, there's only one purging rule: if the user who
244         // owns the room still exists, we keep the room; otherwise, we purge
245         // it.  Bypass any other rules.
246         if (qrbuf->QRflags & QR_MAILBOX) {
247                 // if user not found, do_purge will be 1
248                 do_purge = 1;
249                 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
250                         if (vuptr->vu_usernum == atol(qrbuf->QRname)) {
251                                 do_purge = 0;
252                         }
253                 }
254         }
255         else {
256                 // Any of these attributes render a room non-purgable
257                 if (qrbuf->QRflags & QR_PERMANENT) return;
258                 if (qrbuf->QRflags & QR_DIRECTORY) return;
259                 if (qrbuf->QRflags2 & QR2_SYSTEM) return;
260                 if (!strcasecmp(qrbuf->QRname, SYSCONFIGROOM)) return;
261                 if (CtdlIsNonEditable(qrbuf)) return;
262
263                 // If we don't know the modification date, be safe and don't purge
264                 if (qrbuf->QRmtime <= (time_t)0) return;
265
266                 // If no room purge time is set, be safe and don't purge
267                 if (CtdlGetConfigLong("c_roompurge") < 0) return;
268
269                 // Otherwise, check the date of last modification
270                 age = time(NULL) - (qrbuf->QRmtime);
271                 purge_secs = CtdlGetConfigLong("c_roompurge") * 86400;
272                 if (purge_secs <= (time_t)0) return;
273                 syslog(LOG_DEBUG, "<%s> is <%ld> seconds old", qrbuf->QRname, (long)age);
274                 if (age > purge_secs) do_purge = 1;
275         } // !QR_MAILBOX
276
277         if (do_purge) {
278                 pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
279                 pptr->next = RoomPurgeList;
280                 strcpy(pptr->name, qrbuf->QRname);
281                 RoomPurgeList = pptr;
282         }
283
284 }
285
286
287 int PurgeRooms(void) {
288         struct PurgeList *pptr;
289         int num_rooms_purged = 0;
290         struct ctdlroom qrbuf;
291         struct ValidUser *vuptr;
292         char *transcript = NULL;
293
294         syslog(LOG_DEBUG, "PurgeRooms() called");
295
296         // Load up a table full of valid user numbers so we can delete
297         // user-owned rooms for users who no longer exist
298         ForEachUser(AddValidUser, NULL);
299
300         // Then cycle through the room file
301         CtdlForEachRoom(DoPurgeRooms, NULL);
302
303         // Free the valid user list
304         while (ValidUserList != NULL) {
305                 vuptr = ValidUserList->next;
306                 free(ValidUserList);
307                 ValidUserList = vuptr;
308         }
309
310         transcript = malloc(SIZ);
311         strcpy(transcript, "The following rooms have been auto-purged:\n");
312
313         while (RoomPurgeList != NULL) {
314                 if (CtdlGetRoom(&qrbuf, RoomPurgeList->name) == 0) {
315                         transcript=realloc(transcript, strlen(transcript)+SIZ);
316                         snprintf(&transcript[strlen(transcript)], SIZ, " %s\n", qrbuf.QRname);
317                         CtdlDeleteRoom(&qrbuf);
318                         ++num_rooms_purged;
319                 }
320                 pptr = RoomPurgeList->next;
321                 free(RoomPurgeList);
322                 RoomPurgeList = pptr;
323         }
324
325         if (num_rooms_purged > 0) CtdlAideMessage(transcript, "Room Autopurger Message");
326         free(transcript);
327
328         syslog(LOG_DEBUG, "Purged %d rooms.", num_rooms_purged);
329         return(num_rooms_purged);
330 }
331
332
333 // Back end function to check user accounts for expiration.
334 void do_user_purge(char *username, void *data) {
335         int purge;
336         time_t now;
337         time_t purge_time;
338         struct PurgeList *pptr;
339         struct ctdluser us;
340
341         if (CtdlGetUser(&us, username) != 0) {
342                 return;
343         }
344
345         // Set purge time; if the user overrides the system default, use it
346         if (us.USuserpurge > 0) {
347                 purge_time = ((time_t)us.USuserpurge) * 86400;
348         }
349         else {
350                 purge_time = CtdlGetConfigLong("c_userpurge") * 86400;
351         }
352
353         // The default rule is to not purge.
354         purge = 0;
355         
356         // If the user has not logged in for the configured amount of time, expire the account.
357         if (CtdlGetConfigLong("c_userpurge") > 0) {
358                 now = time(NULL);
359                 if ((now - us.lastcall) > purge_time) purge = 1;
360         }
361
362         // If the account is marked as permanent, don't purge it.
363         if (us.flags & US_PERM) purge = 0;
364
365         // If the account is an administrator, don't purge it.
366         if (us.axlevel == 6) purge = 0;
367
368         // If the access level is 0, the record should already have been
369         // deleted, but maybe the user was logged in at the time or something.
370         // Delete the record now.
371         if (us.axlevel == 0) purge = 1;
372
373         // If the user set his/her password to 'deleteme', he/she
374         // wishes to be deleted, so purge the record.
375         // Moved this lower down so that aides and permanent users get purged if they ask to be.
376         if (!strcasecmp(us.password, "deleteme")) purge = 1;
377         
378         // Fewer than zero calls is impossible, indicating a corrupted record.
379         if (us.timescalled < 0) purge = 1;
380
381         // any negative user number, is also impossible.
382         if (us.usernum < 0L) purge = 1;
383         
384         // Don't purge user 0. That user is there for the system
385         if (us.usernum == 0L) purge = 0;
386         
387         // If the user has no full name entry then we can't purge them since the actual purge can't find them.
388         // This shouldn't happen but does somehow.
389         if (IsEmptyStr(us.fullname)) {
390                 purge = 0;
391                 
392                 if (us.usernum > 0L) {
393                         purge=0;
394                         if (users_corrupt_msg == NULL) {
395                                 users_corrupt_msg = malloc(SIZ);
396                                 strcpy(users_corrupt_msg,
397                                         "The auto-purger found the following user numbers with no name.\n"
398                                         "The system has no way to purge a user with no name,"
399                                         " and should not be able to create them either.\n"
400                                         "This indicates corruption of the user DB or possibly a bug.\n"
401                                         "It may be a good idea to restore your DB from a backup.\n"
402                                 );
403                         }
404                 
405                         users_corrupt_msg=realloc(users_corrupt_msg, strlen(users_corrupt_msg)+30);
406                         snprintf(&users_corrupt_msg[strlen(users_corrupt_msg)], 29, " %ld\n", us.usernum);
407                 }
408         }
409
410         if (purge == 1) {
411                 pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
412                 pptr->next = UserPurgeList;
413                 strcpy(pptr->name, us.fullname);
414                 UserPurgeList = pptr;
415         }
416         else {
417                 ++users_not_purged;
418         }
419
420 }
421
422
423 int PurgeUsers(void) {
424         struct PurgeList *pptr;
425         int num_users_purged = 0;
426         char *transcript = NULL;
427
428         syslog(LOG_DEBUG, "PurgeUsers() called");
429         users_not_purged = 0;
430
431         switch(CtdlGetConfigInt("c_auth_mode")) {
432                 case AUTHMODE_NATIVE:
433                         ForEachUser(do_user_purge, NULL);
434                         break;
435                 default:
436                         syslog(LOG_DEBUG, "User purge for auth mode %d is not implemented.", CtdlGetConfigInt("c_auth_mode"));
437                         break;
438         }
439
440         transcript = malloc(SIZ);
441
442         if (users_not_purged == 0) {
443                 strcpy(transcript, "The auto-purger was told to purge every user.  It is\n"
444                                 "refusing to do this because it usually indicates a problem\n"
445                                 "such as an inability to communicate with a name service.\n"
446                 );
447                 while (UserPurgeList != NULL) {
448                         pptr = UserPurgeList->next;
449                         free(UserPurgeList);
450                         UserPurgeList = pptr;
451                         ++num_users_purged;
452                 }
453         }
454
455         else {
456                 strcpy(transcript, "The following users have been auto-purged:\n");
457                 while (UserPurgeList != NULL) {
458                         transcript=realloc(transcript, strlen(transcript)+SIZ);
459                         snprintf(&transcript[strlen(transcript)], SIZ, " %s\n", UserPurgeList->name);
460                         purge_user(UserPurgeList->name);
461                         pptr = UserPurgeList->next;
462                         free(UserPurgeList);
463                         UserPurgeList = pptr;
464                         ++num_users_purged;
465                 }
466         }
467
468         if (num_users_purged > 0) CtdlAideMessage(transcript, "User Purge Message");
469         free(transcript);
470
471         if (users_corrupt_msg) {
472                 CtdlAideMessage(users_corrupt_msg, "User Corruption Message");
473                 free (users_corrupt_msg);
474                 users_corrupt_msg = NULL;
475         }
476         
477         if(users_zero_msg) {
478                 CtdlAideMessage(users_zero_msg, "User Zero Message");
479                 free (users_zero_msg);
480                 users_zero_msg = NULL;
481         }
482                 
483         syslog(LOG_DEBUG, "Purged %d users.", num_users_purged);
484         return(num_users_purged);
485 }
486
487
488 // Purge visits
489 //
490 // This is a really cumbersome "garbage collection" function.  We have to
491 // delete visits which refer to rooms and/or users which no longer exist.  In
492 // order to prevent endless traversals of the room and user files, we first
493 // build linked lists of rooms and users which _do_ exist on the system, then
494 // traverse the visit file, checking each record against those two lists and
495 // purging the ones that do not have a match on _both_ lists.  (Remember, if
496 // either the room or user being referred to is no longer on the system, the
497 // record is useless and should be removed.)
498 //
499 int PurgeVisits(void) {
500         struct cdbdata *cdbvisit;
501         struct visit vbuf;
502         struct VPurgeList *VisitPurgeList = NULL;
503         struct VPurgeList *vptr;
504         int purged = 0;
505         char IndexBuf[32];
506         int IndexLen;
507         struct ValidRoom *vrptr;
508         struct ValidUser *vuptr;
509         int RoomIsValid, UserIsValid;
510
511         // First, load up a table full of valid room/gen combinations
512         CtdlForEachRoom(AddValidRoom, NULL);
513
514         // Then load up a table full of valid user numbers
515         ForEachUser(AddValidUser, NULL);
516
517         // Now traverse through the visits, purging irrelevant records...
518         cdb_rewind(CDB_VISIT);
519         while(cdbvisit = cdb_next_item(CDB_VISIT), cdbvisit != NULL) {
520                 memset(&vbuf, 0, sizeof(struct visit));
521                 memcpy(&vbuf, cdbvisit->ptr,
522                         ( (cdbvisit->len > sizeof(struct visit)) ?
523                           sizeof(struct visit) : cdbvisit->len) );
524                 cdb_free(cdbvisit);
525
526                 RoomIsValid = 0;
527                 UserIsValid = 0;
528
529                 // Check to see if the room exists
530                 for (vrptr=ValidRoomList; vrptr!=NULL; vrptr=vrptr->next) {
531                         if ( (vrptr->vr_roomnum==vbuf.v_roomnum)
532                              && (vrptr->vr_roomgen==vbuf.v_roomgen))
533                                 RoomIsValid = 1;
534                 }
535
536                 // Check to see if the user exists
537                 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
538                         if (vuptr->vu_usernum == vbuf.v_usernum)
539                                 UserIsValid = 1;
540                 }
541
542                 // Put the record on the purge list if it's dead
543                 if ((RoomIsValid==0) || (UserIsValid==0)) {
544                         vptr = (struct VPurgeList *)
545                                 malloc(sizeof(struct VPurgeList));
546                         vptr->next = VisitPurgeList;
547                         vptr->vp_roomnum = vbuf.v_roomnum;
548                         vptr->vp_roomgen = vbuf.v_roomgen;
549                         vptr->vp_usernum = vbuf.v_usernum;
550                         VisitPurgeList = vptr;
551                 }
552
553         }
554
555         // Free the valid room/gen combination list
556         while (ValidRoomList != NULL) {
557                 vrptr = ValidRoomList->next;
558                 free(ValidRoomList);
559                 ValidRoomList = vrptr;
560         }
561
562         // Free the valid user list
563         while (ValidUserList != NULL) {
564                 vuptr = ValidUserList->next;
565                 free(ValidUserList);
566                 ValidUserList = vuptr;
567         }
568
569         // Now delete every visit on the purged list
570         while (VisitPurgeList != NULL) {
571                 IndexLen = GenerateRelationshipIndex(IndexBuf,
572                                 VisitPurgeList->vp_roomnum,
573                                 VisitPurgeList->vp_roomgen,
574                                 VisitPurgeList->vp_usernum);
575                 cdb_delete(CDB_VISIT, IndexBuf, IndexLen);
576                 vptr = VisitPurgeList->next;
577                 free(VisitPurgeList);
578                 VisitPurgeList = vptr;
579                 ++purged;
580         }
581
582         return(purged);
583 }
584
585
586 // Purge the use table of old entries.
587 int PurgeUseTable(StrBuf *ErrMsg) {
588         int purged = 0;
589         int total = 0;
590         struct cdbdata *cdbut;
591         struct UseTable ut;
592         struct UPurgeList *ul = NULL;
593         struct UPurgeList *uptr; 
594
595         // Phase 1: traverse through the table, discovering old records...
596
597         syslog(LOG_DEBUG, "Purge use table: phase 1");
598         cdb_rewind(CDB_USETABLE);
599         while(cdbut = cdb_next_item(CDB_USETABLE), cdbut != NULL) {
600                 ++total;
601                 if (cdbut->len > sizeof(struct UseTable))
602                         memcpy(&ut, cdbut->ptr, sizeof(struct UseTable));
603                 else {
604                         memset(&ut, 0, sizeof(struct UseTable));
605                         memcpy(&ut, cdbut->ptr, cdbut->len);
606                 }
607                 cdb_free(cdbut);
608
609                 if ( (time(NULL) - ut.ut_timestamp) > USETABLE_RETAIN ) {
610                         uptr = (struct UPurgeList *) malloc(sizeof(struct UPurgeList));
611                         if (uptr != NULL) {
612                                 uptr->next = ul;
613                                 safestrncpy(uptr->up_key, ut.ut_msgid, sizeof uptr->up_key);
614                                 ul = uptr;
615                         }
616                         ++purged;
617                 }
618
619         }
620
621         // Phase 2: delete the records
622         syslog(LOG_DEBUG, "Purge use table: phase 2");
623         while (ul != NULL) {
624                 cdb_delete(CDB_USETABLE, ul->up_key, strlen(ul->up_key));
625                 uptr = ul->next;
626                 free(ul);
627                 ul = uptr;
628         }
629
630         syslog(LOG_DEBUG, "Purge use table: finished (purged %d of %d records)", purged, total);
631         return(purged);
632 }
633
634
635 // Purge the EUID Index of old records.
636 int PurgeEuidIndexTable(void) {
637         int purged = 0;
638         struct cdbdata *cdbei;
639         struct EPurgeList *el = NULL;
640         struct EPurgeList *eptr; 
641         long msgnum;
642         struct CtdlMessage *msg = NULL;
643
644         // Phase 1: traverse through the table, discovering old records...
645         syslog(LOG_DEBUG, "Purge EUID index: phase 1");
646         cdb_rewind(CDB_EUIDINDEX);
647         while(cdbei = cdb_next_item(CDB_EUIDINDEX), cdbei != NULL) {
648
649                 memcpy(&msgnum, cdbei->ptr, sizeof(long));
650
651                 msg = CtdlFetchMessage(msgnum, 0);
652                 if (msg != NULL) {
653                         CM_Free(msg);   // it still exists, so do nothing
654                 }
655                 else {
656                         eptr = (struct EPurgeList *) malloc(sizeof(struct EPurgeList));
657                         if (eptr != NULL) {
658                                 eptr->next = el;
659                                 eptr->ep_keylen = cdbei->len - sizeof(long);
660                                 eptr->ep_key = malloc(cdbei->len);
661                                 memcpy(eptr->ep_key, &cdbei->ptr[sizeof(long)], eptr->ep_keylen);
662                                 el = eptr;
663                         }
664                         ++purged;
665                 }
666
667                cdb_free(cdbei);
668
669         }
670
671         // Phase 2: delete the records
672         syslog(LOG_DEBUG, "Purge euid index: phase 2");
673         while (el != NULL) {
674                 cdb_delete(CDB_EUIDINDEX, el->ep_key, el->ep_keylen);
675                 free(el->ep_key);
676                 eptr = el->next;
677                 free(el);
678                 el = eptr;
679         }
680
681         syslog(LOG_DEBUG, "Purge euid index: finished (purged %d records)", purged);
682         return(purged);
683 }
684
685
686 void purge_databases(void) {
687         int retval;
688         static time_t last_purge = 0;
689         time_t now;
690         struct tm tm;
691
692         // Do the auto-purge if the current hour equals the purge hour,
693         // but not if the operation has already been performed in the
694         // last twelve hours.  This is usually enough granularity.
695         now = time(NULL);
696         localtime_r(&now, &tm);
697         if (((tm.tm_hour != CtdlGetConfigInt("c_purge_hour")) || ((now - last_purge) < 43200)) && (force_purge_now == 0)) {
698                 return;
699         }
700
701         syslog(LOG_INFO, "Auto-purger: starting.");
702
703         if (!server_shutting_down) {
704                 retval = PurgeUsers();
705                 syslog(LOG_NOTICE, "Purged %d users.", retval);
706         }
707                 
708         if (!server_shutting_down) {
709                 PurgeMessages();
710                 syslog(LOG_NOTICE, "Expired %d messages.", messages_purged);
711         }
712
713         if (!server_shutting_down) {
714                 retval = PurgeRooms();
715                 syslog(LOG_NOTICE, "Expired %d rooms.", retval);
716         }
717
718         if (!server_shutting_down) {
719                 retval = PurgeVisits();
720                 syslog(LOG_NOTICE, "Purged %d visits.", retval);
721         }
722
723         if (!server_shutting_down) {
724                 StrBuf *ErrMsg;
725                 ErrMsg = NewStrBuf();
726                 retval = PurgeUseTable(ErrMsg);
727                 syslog(LOG_NOTICE, "Purged %d entries from the use table.", retval);
728                 FreeStrBuf(&ErrMsg);
729         }
730
731         if (!server_shutting_down) {
732                 retval = PurgeEuidIndexTable();
733                 syslog(LOG_NOTICE, "Purged %d entries from the EUID index.", retval);
734         }
735
736         //if (!server_shutting_down) {
737         //      FIXME this is where we could do a non-interactive delete of zero-refcount messages
738         //}
739
740         if ( (!server_shutting_down) && (CtdlGetConfigInt("c_shrink_db_files") != 0) ) {
741                 cdb_compact();                                  // Shrink the DB files on disk
742         }
743
744         if (!server_shutting_down) {
745                 syslog(LOG_INFO, "Auto-purger: finished.");
746                 last_purge = now;                               // So we don't do it again soon
747                 force_purge_now = 0;
748         }
749         else {
750                 syslog(LOG_INFO, "Auto-purger: STOPPED.");
751         }
752 }
753
754
755 // Manually initiate a run of The Dreaded Auto-Purger (tm)
756 void cmd_tdap(char *argbuf) {
757         if (CtdlAccessCheck(ac_aide)) return;
758         force_purge_now = 1;
759         cprintf("%d Manually initiating a purger run now.\n", CIT_OK);
760 }
761
762
763 // Initialization function, called from modules_init.c
764 char *ctdl_module_init_expire(void) {
765         if (!threading) {
766                 CtdlRegisterProtoHook(cmd_tdap, "TDAP", "Manually initiate auto-purger");
767                 CtdlRegisterProtoHook(cmd_gpex, "GPEX", "Get expire policy");
768                 CtdlRegisterProtoHook(cmd_spex, "SPEX", "Set expire policy");
769                 CtdlRegisterSessionHook(purge_databases, EVT_TIMER, PRIO_CLEANUP + 20);
770         }
771
772         // return our module name for the log
773         return "expire";
774 }