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