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