fb00e3d64a7f9cc0cbed51fcaa12a528b0c8a901
[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         if (!vuptr) abort();
213         vuptr->next = ValidUserList;
214         vuptr->vu_usernum = usbuf.usernum;
215         ValidUserList = vuptr;
216 }
217
218
219 void AddValidRoom(struct ctdlroom *qrbuf, void *data) {
220         struct ValidRoom *vrptr;
221
222         vrptr = (struct ValidRoom *)malloc(sizeof(struct ValidRoom));
223         if (!vrptr) abort();
224         vrptr->next = ValidRoomList;
225         vrptr->vr_roomnum = qrbuf->QRnumber;
226         vrptr->vr_roomgen = qrbuf->QRgen;
227         ValidRoomList = vrptr;
228 }
229
230
231 void DoPurgeRooms(struct ctdlroom *qrbuf, void *data) {
232         time_t age, purge_secs;
233         struct PurgeList *pptr;
234         struct ValidUser *vuptr;
235         int do_purge = 0;
236
237         // For mailbox rooms, there's only one purging rule: if the user who
238         // owns the room still exists, we keep the room; otherwise, we purge
239         // it.  Bypass any other rules.
240         if (qrbuf->QRflags & QR_MAILBOX) {
241                 // if user not found, do_purge will be 1
242                 do_purge = 1;
243                 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
244                         if (vuptr->vu_usernum == atol(qrbuf->QRname)) {
245                                 do_purge = 0;
246                         }
247                 }
248         }
249         else {
250                 // Any of these attributes render a room non-purgable
251                 if (qrbuf->QRflags & QR_PERMANENT) return;
252                 if (qrbuf->QRflags & QR_DIRECTORY) return;
253                 if (qrbuf->QRflags2 & QR2_SYSTEM) return;
254                 if (!strcasecmp(qrbuf->QRname, SYSCONFIGROOM)) return;
255                 if (CtdlIsNonEditable(qrbuf)) return;
256
257                 // If we don't know the modification date, be safe and don't purge
258                 if (qrbuf->QRmtime <= (time_t)0) return;
259
260                 // If no room purge time is set, be safe and don't purge
261                 if (CtdlGetConfigLong("c_roompurge") < 0) return;
262
263                 // Otherwise, check the date of last modification
264                 age = time(NULL) - (qrbuf->QRmtime);
265                 purge_secs = CtdlGetConfigLong("c_roompurge") * 86400;
266                 if (purge_secs <= (time_t)0) return;
267                 syslog(LOG_DEBUG, "<%s> is <%ld> seconds old", qrbuf->QRname, (long)age);
268                 if (age > purge_secs) do_purge = 1;
269         } // !QR_MAILBOX
270
271         if (do_purge) {
272                 pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
273                 if (!pptr) abort();
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         // any negative user number, is also impossible.
374         if (us.usernum < 0L) purge = 1;
375         
376         // Don't purge user 0. That user is there for the system
377         if (us.usernum == 0L) purge = 0;
378         
379         // If the user has no full name entry then we can't purge them since the actual purge can't find them.
380         // This shouldn't happen but does somehow.
381         if (IsEmptyStr(us.fullname)) {
382                 purge = 0;
383                 
384                 if (us.usernum > 0L) {
385                         purge=0;
386                         if (users_corrupt_msg == NULL) {
387                                 users_corrupt_msg = malloc(SIZ);
388                                 strcpy(users_corrupt_msg,
389                                         "The auto-purger found the following user numbers with no name.\n"
390                                         "The system has no way to purge a user with no name,"
391                                         " and should not be able to create them either.\n"
392                                         "This indicates corruption of the user DB or possibly a bug.\n"
393                                         "It may be a good idea to restore your DB from a backup.\n"
394                                 );
395                         }
396                 
397                         users_corrupt_msg=realloc(users_corrupt_msg, strlen(users_corrupt_msg)+30);
398                         snprintf(&users_corrupt_msg[strlen(users_corrupt_msg)], 29, " %ld\n", us.usernum);
399                 }
400         }
401
402         if (purge == 1) {
403                 pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
404                 if (!pptr) abort();
405                 pptr->next = UserPurgeList;
406                 strcpy(pptr->name, us.fullname);
407                 UserPurgeList = pptr;
408         }
409         else {
410                 ++users_not_purged;
411         }
412
413 }
414
415
416 int PurgeUsers(void) {
417         struct PurgeList *pptr;
418         int num_users_purged = 0;
419         char *transcript = NULL;
420
421         syslog(LOG_DEBUG, "PurgeUsers() called");
422         users_not_purged = 0;
423
424         switch(CtdlGetConfigInt("c_auth_mode")) {
425                 case AUTHMODE_NATIVE:
426                         ForEachUser(do_user_purge, NULL);
427                         break;
428                 default:
429                         syslog(LOG_DEBUG, "User purge for auth mode %d is not implemented.", CtdlGetConfigInt("c_auth_mode"));
430                         break;
431         }
432
433         transcript = malloc(SIZ);
434
435         if (users_not_purged == 0) {
436                 strcpy(transcript, "The auto-purger was told to purge every user.  It is\n"
437                                 "refusing to do this because it usually indicates a problem\n"
438                                 "such as an inability to communicate with a name service.\n"
439                 );
440                 while (UserPurgeList != NULL) {
441                         pptr = UserPurgeList->next;
442                         free(UserPurgeList);
443                         UserPurgeList = pptr;
444                         ++num_users_purged;
445                 }
446         }
447
448         else {
449                 strcpy(transcript, "The following users have been auto-purged:\n");
450                 while (UserPurgeList != NULL) {
451                         transcript=realloc(transcript, strlen(transcript)+SIZ);
452                         snprintf(&transcript[strlen(transcript)], SIZ, " %s\n", UserPurgeList->name);
453                         purge_user(UserPurgeList->name);
454                         pptr = UserPurgeList->next;
455                         free(UserPurgeList);
456                         UserPurgeList = pptr;
457                         ++num_users_purged;
458                 }
459         }
460
461         if (num_users_purged > 0) CtdlAideMessage(transcript, "User Purge Message");
462         free(transcript);
463
464         if (users_corrupt_msg) {
465                 CtdlAideMessage(users_corrupt_msg, "User Corruption Message");
466                 free (users_corrupt_msg);
467                 users_corrupt_msg = NULL;
468         }
469         
470         if(users_zero_msg) {
471                 CtdlAideMessage(users_zero_msg, "User Zero Message");
472                 free (users_zero_msg);
473                 users_zero_msg = NULL;
474         }
475                 
476         syslog(LOG_DEBUG, "Purged %d users.", num_users_purged);
477         return(num_users_purged);
478 }
479
480
481 // Purge visits
482 //
483 // This is a really cumbersome "garbage collection" function.  We have to
484 // delete visits which refer to rooms and/or users which no longer exist.  In
485 // order to prevent endless traversals of the room and user files, we first
486 // build linked lists of rooms and users which _do_ exist on the system, then
487 // traverse the visit file, checking each record against those two lists and
488 // purging the ones that do not have a match on _both_ lists.  (Remember, if
489 // either the room or user being referred to is no longer on the system, the
490 // record is useless and should be removed.)
491 //
492 int PurgeVisits(void) {
493         struct cdbkeyval cdbvisit;
494         struct visit vbuf;
495         struct VPurgeList *VisitPurgeList = NULL;
496         struct VPurgeList *vptr;
497         int purged = 0;
498         char IndexBuf[32];
499         int IndexLen;
500         struct ValidRoom *vrptr;
501         struct ValidUser *vuptr;
502         int RoomIsValid, UserIsValid;
503
504         // First, load up a table full of valid room/gen combinations
505         CtdlForEachRoom(AddValidRoom, NULL);
506
507         // Then load up a table full of valid user numbers
508         ForEachUser(AddValidUser, NULL);
509
510         // Now traverse through the visits, purging irrelevant records...
511         cdb_rewind(CDB_VISIT);
512         while(cdbvisit = cdb_next_item(CDB_VISIT), cdbvisit.val.ptr!=NULL) {            // always read through to the end
513                 memset(&vbuf, 0, sizeof(struct visit));
514                 memcpy(&vbuf, cdbvisit.val.ptr, ((cdbvisit.val.len > sizeof(struct visit)) ? sizeof(struct visit) : cdbvisit.val.len));
515                 RoomIsValid = 0;
516                 UserIsValid = 0;
517
518                 // Check to see if the room exists
519                 for (vrptr=ValidRoomList; vrptr!=NULL; vrptr=vrptr->next) {
520                         if ( (vrptr->vr_roomnum==vbuf.v_roomnum) && (vrptr->vr_roomgen==vbuf.v_roomgen)) {
521                                 RoomIsValid = 1;
522                         }
523                 }
524
525                 // Check to see if the user exists
526                 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
527                         if (vuptr->vu_usernum == vbuf.v_usernum) {
528                                 UserIsValid = 1;
529                         }
530                 }
531
532                 // Put the record on the purge list if it's dead
533                 if ((RoomIsValid==0) || (UserIsValid==0)) {
534                         vptr = (struct VPurgeList *) malloc(sizeof(struct VPurgeList));
535                         if (!vptr) abort();
536                         vptr->next = VisitPurgeList;
537                         vptr->vp_roomnum = vbuf.v_roomnum;
538                         vptr->vp_roomgen = vbuf.v_roomgen;
539                         vptr->vp_usernum = vbuf.v_usernum;
540                         VisitPurgeList = vptr;
541                 }
542
543         }
544
545         // Free the valid room/gen combination list
546         while (ValidRoomList != NULL) {
547                 vrptr = ValidRoomList->next;
548                 free(ValidRoomList);
549                 ValidRoomList = vrptr;
550         }
551
552         // Free the valid user list
553         while (ValidUserList != NULL) {
554                 vuptr = ValidUserList->next;
555                 free(ValidUserList);
556                 ValidUserList = vuptr;
557         }
558
559         // Now delete every visit on the purged list
560         cdb_begin_transaction();
561         while (VisitPurgeList != NULL) {
562                 IndexLen = GenerateRelationshipIndex(IndexBuf,
563                                 VisitPurgeList->vp_roomnum,
564                                 VisitPurgeList->vp_roomgen,
565                                 VisitPurgeList->vp_usernum);
566                 cdb_delete(CDB_VISIT, IndexBuf, IndexLen);
567                 vptr = VisitPurgeList->next;
568                 free(VisitPurgeList);
569                 VisitPurgeList = vptr;
570                 ++purged;
571         }
572         cdb_end_transaction();
573
574         return(purged);
575 }
576
577
578 // Purge the use table of old entries.
579 // Holy crap, this is WAY better.  We need to replace most linked lists with arrays.
580 int PurgeUseTable(StrBuf *ErrMsg) {
581         int purged = 0;
582         int total = 0;
583         struct cdbkeyval cdbut;
584         struct UseTable ut;
585         Array *purge_list = array_new(sizeof(int));
586
587         // Phase 1: traverse through the table, discovering old records...
588
589         syslog(LOG_DEBUG, "Purge use table: phase 1");
590         cdb_rewind(CDB_USETABLE);
591         while(cdbut = cdb_next_item(CDB_USETABLE), cdbut.val.ptr!=NULL) {               // always read through to the end
592                 ++total;
593                 if (cdbut.val.len > sizeof(struct UseTable))
594                         memcpy(&ut, cdbut.val.ptr, sizeof(struct UseTable));
595                 else {
596                         memset(&ut, 0, sizeof(struct UseTable));
597                         memcpy(&ut, cdbut.val.ptr, cdbut.val.len);
598                 }
599
600                 if ( (time(NULL) - ut.timestamp) > USETABLE_RETAIN ) {
601                         array_append(purge_list, &ut.hash);
602                         ++purged;
603                 }
604         }
605
606         // Phase 2: delete the records
607         syslog(LOG_DEBUG, "Purge use table: phase 2");
608         int i;
609         cdb_begin_transaction();
610         for (i=0; i<purged; ++i) {
611                 struct UseTable *u = (struct UseTable *)array_get_element_at(purge_list, i);
612                 cdb_delete(CDB_USETABLE, &u->hash, sizeof(int));
613         }
614         cdb_end_transaction();
615         array_free(purge_list);
616
617         syslog(LOG_DEBUG, "Purge use table: finished (purged %d of %d records)", purged, total);
618         return(purged);
619 }
620
621
622 // Purge the EUID Index of old records.
623 int PurgeEuidIndexTable(void) {
624         int purged = 0;
625         struct cdbkeyval cdbei;
626         struct EPurgeList *el = NULL;
627         struct EPurgeList *eptr; 
628         long msgnum;
629         struct CtdlMessage *msg = NULL;
630
631         // Phase 1: traverse through the table, discovering old records...
632         syslog(LOG_DEBUG, "Purge EUID index: phase 1");
633         cdb_rewind(CDB_EUIDINDEX);
634         while(cdbei = cdb_next_item(CDB_EUIDINDEX), cdbei.val.ptr!=NULL) {      // always read through to the end
635
636                 memcpy(&msgnum, cdbei.val.ptr, sizeof(long));
637
638                 msg = CtdlFetchMessage(msgnum, 0);
639                 if (msg != NULL) {
640                         CM_Free(msg);   // it still exists, so do nothing
641                 }
642                 else {
643                         eptr = (struct EPurgeList *) malloc(sizeof(struct EPurgeList));
644                         if (!eptr) abort();
645                         if (eptr != NULL) {
646                                 eptr->next = el;
647                                 eptr->ep_keylen = cdbei.val.len - sizeof(long);
648                                 eptr->ep_key = malloc(cdbei.val.len);
649                                 if (!eptr->ep_key) abort();
650                                 memcpy(eptr->ep_key, &cdbei.val.ptr[sizeof(long)], eptr->ep_keylen);
651                                 el = eptr;
652                         }
653                         ++purged;
654                 }
655
656
657         }
658
659         // Phase 2: delete the records
660         syslog(LOG_DEBUG, "Purge euid index: phase 2");
661         cdb_begin_transaction();
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         cdb_end_transaction();
670
671         syslog(LOG_DEBUG, "Purge euid index: finished (purged %d records)", purged);
672         return(purged);
673 }
674
675
676 void purge_databases(void) {
677         int retval;
678         static time_t last_purge = 0;
679         time_t now;
680         struct tm tm;
681
682         // Do the auto-purge if the current hour equals the purge hour,
683         // but not if the operation has already been performed in the
684         // last twelve hours.  This is usually enough granularity.
685         now = time(NULL);
686         localtime_r(&now, &tm);
687         if (((tm.tm_hour != CtdlGetConfigInt("c_purge_hour")) || ((now - last_purge) < 43200)) && (force_purge_now == 0)) {
688                 return;
689         }
690
691         syslog(LOG_INFO, "Auto-purger: starting.");
692
693         if (!server_shutting_down) {
694                 retval = PurgeUsers();
695                 syslog(LOG_NOTICE, "Purged %d users.", retval);
696         }
697                 
698         if (!server_shutting_down) {
699                 PurgeMessages();
700                 syslog(LOG_NOTICE, "Expired %d messages.", messages_purged);
701         }
702
703         if (!server_shutting_down) {
704                 retval = PurgeRooms();
705                 syslog(LOG_NOTICE, "Expired %d rooms.", retval);
706         }
707
708         if (!server_shutting_down) {
709                 retval = PurgeVisits();
710                 syslog(LOG_NOTICE, "Purged %d visits.", retval);
711         }
712
713         if (!server_shutting_down) {
714                 StrBuf *ErrMsg;
715                 ErrMsg = NewStrBuf();
716                 retval = PurgeUseTable(ErrMsg);
717                 syslog(LOG_NOTICE, "Purged %d entries from the use table.", retval);
718                 FreeStrBuf(&ErrMsg);
719         }
720
721         if (!server_shutting_down) {
722                 retval = PurgeEuidIndexTable();
723                 syslog(LOG_NOTICE, "Purged %d entries from the EUID index.", retval);
724         }
725
726         //if (!server_shutting_down) {
727         //      FIXME this is where we could do a non-interactive delete of zero-refcount messages
728         //}
729
730         if ( (!server_shutting_down) && (CtdlGetConfigInt("c_shrink_db_files") != 0) ) {
731                 cdb_compact();                                  // Shrink the DB files on disk
732         }
733
734         if (!server_shutting_down) {
735                 syslog(LOG_INFO, "Auto-purger: finished.");
736                 last_purge = now;                               // So we don't do it again soon
737                 force_purge_now = 0;
738         }
739         else {
740                 syslog(LOG_INFO, "Auto-purger: STOPPED.");
741         }
742 }
743
744
745 // Manually initiate a run of The Dreaded Auto-Purger (tm)
746 void cmd_tdap(char *argbuf) {
747         if (CtdlAccessCheck(ac_aide)) return;
748         force_purge_now = 1;
749         cprintf("%d Manually initiating a purger run now.\n", CIT_OK);
750 }
751
752
753 // Initialization function, called from modules_init.c
754 char *ctdl_module_init_expire(void) {
755         if (!threading) {
756                 CtdlRegisterProtoHook(cmd_tdap, "TDAP", "Manually initiate auto-purger");
757                 CtdlRegisterProtoHook(cmd_gpex, "GPEX", "Get expire policy");
758                 CtdlRegisterProtoHook(cmd_spex, "SPEX", "Set expire policy");
759                 CtdlRegisterSessionHook(purge_databases, EVT_TIMER, PRIO_CLEANUP + 20);
760         }
761
762         // return our module name for the log
763         return "expire";
764 }