1 // This module handles the expiry of old messages and the purging of old users.
3 // You might also see this module affectionately referred to as TDAP (The Dreaded Auto-Purger).
5 // Copyright (c) 1988-2024 by citadel.org (Art Cancro et al.)
7 // This program is open source software. Use, duplication, or disclosure is subject to the GNU General Public License, version 3.
10 #include "../../sysdep.h"
18 #include <sys/types.h>
23 #include <libcitadel.h>
24 #include "../../citadel_defs.h"
25 #include "../../server.h"
26 #include "../../citserver.h"
27 #include "../../support.h"
28 #include "../../config.h"
30 #include "../../database.h"
31 #include "../../msgbase.h"
32 #include "../../user_ops.h"
33 #include "../../room_ops.h"
34 #include "../../control.h"
35 #include "../../threads.h"
36 #include "../../context.h"
38 #include "../../ctdl_module.h"
42 struct PurgeList *next;
43 char name[ROOMNAMELEN]; // use the larger of username or roomname
47 struct VPurgeList *next;
54 struct ValidRoom *next;
60 struct ValidUser *next;
65 struct ctdlroomref *next;
70 struct EPurgeList *next;
76 struct PurgeList *UserPurgeList = NULL;
77 struct PurgeList *RoomPurgeList = NULL;
78 struct ValidRoom *ValidRoomList = NULL;
79 struct ValidUser *ValidUserList = NULL;
82 struct ctdlroomref *rr = NULL;
83 int force_purge_now = 0; // set to nonzero to force a run right now
86 // First phase of message purge -- gather the locations of messages which
87 // qualify for purging and write them to a temp file.
88 void GatherPurgeMessages(struct ctdlroom *qrbuf, void *data) {
89 struct ExpirePolicy epbuf;
92 struct CtdlMessage *msg = NULL;
98 purgelist = (FILE *)data;
99 fprintf(purgelist, "r=%s\n", qrbuf->QRname);
102 GetExpirePolicy(&epbuf, qrbuf);
103 syslog(LOG_DEBUG, "expire: scanning room %ld (%s), policy %d", qrbuf->QRnumber, qrbuf->QRname, epbuf.expire_mode);
105 // If the room is set to never expire messages ... do nothing
106 if (epbuf.expire_mode == EXPIRE_NEXTLEVEL) return;
107 if (epbuf.expire_mode == EXPIRE_MANUAL) return;
109 // Don't purge messages containing system configuration, dumbass.
110 if (!strcasecmp(qrbuf->QRname, SYSCONFIGROOM)) return;
112 // Ok, we got this far ... now let's see what's in the room.
113 num_msgs = CtdlFetchMsgList(qrbuf->QRnumber, &msglist);
115 // Nothing to do if there aren't any messages
121 // If the room is set to expire by count, do that.
122 if (epbuf.expire_mode == EXPIRE_NUMMSGS) {
123 if (num_msgs > epbuf.expire_value) {
124 for (a=0; a<(num_msgs - epbuf.expire_value); ++a) {
125 fprintf(purgelist, "m=%ld\n", msglist[a]);
131 // If the room is set to expire by age...
132 if (epbuf.expire_mode == EXPIRE_AGE) {
133 for (a=0; a<num_msgs; ++a) {
135 msg = CtdlFetchMessage(delnum, 0); // don't need the body
137 xtime = atol(msg->cm_fields[eTimestamp]);
144 if ((xtime > 0L) && (now - xtime > (time_t)(epbuf.expire_value * 86400L))) {
145 fprintf(purgelist, "m=%ld\n", delnum);
151 if (msglist != NULL) {
157 // Second phase of message purge -- read list of msgs from temp file and delete them.
158 void DoPurgeMessages(FILE *purgelist) {
159 char roomname[ROOMNAMELEN];
164 strcpy(roomname, "nonexistent room ___ ___");
165 while (fgets(buf, sizeof buf, purgelist) != NULL) {
166 buf[strlen(buf)-1]=0;
167 if (!strncasecmp(buf, "r=", 2)) {
168 strcpy(roomname, &buf[2]);
170 if (!strncasecmp(buf, "m=", 2)) {
171 msgnum = atol(&buf[2]);
173 CtdlDeleteMessages(roomname, &msgnum, 1, "");
180 void PurgeMessages(void) {
183 syslog(LOG_DEBUG, "PurgeMessages() called");
186 purgelist = tmpfile();
187 if (purgelist == NULL) {
188 syslog(LOG_CRIT, "Can't create purgelist temp file: %s", strerror(errno));
192 CtdlForEachRoom(GatherPurgeMessages, (void *)purgelist );
193 DoPurgeMessages(purgelist);
198 void AddValidUser(char *username, void *data) {
199 struct ValidUser *vuptr;
200 struct ctdluser usbuf;
202 if (CtdlGetUser(&usbuf, username) != 0) {
206 vuptr = (struct ValidUser *)malloc(sizeof(struct ValidUser));
208 vuptr->next = ValidUserList;
209 vuptr->vu_usernum = usbuf.usernum;
210 ValidUserList = vuptr;
214 void AddValidRoom(struct ctdlroom *qrbuf, void *data) {
215 struct ValidRoom *vrptr;
217 vrptr = (struct ValidRoom *)malloc(sizeof(struct ValidRoom));
219 vrptr->next = ValidRoomList;
220 vrptr->vr_roomnum = qrbuf->QRnumber;
221 vrptr->vr_roomgen = qrbuf->QRgen;
222 ValidRoomList = vrptr;
226 void DoPurgeRooms(struct ctdlroom *qrbuf, void *data) {
227 time_t age, purge_secs;
228 struct PurgeList *pptr;
229 struct ValidUser *vuptr;
232 // For mailbox rooms, there's only one purging rule: if the user who
233 // owns the room still exists, we keep the room; otherwise, we purge
234 // it. Bypass any other rules.
235 if (qrbuf->QRflags & QR_MAILBOX) {
236 // if user not found, do_purge will be 1
238 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
239 if (vuptr->vu_usernum == atol(qrbuf->QRname)) {
245 // Any of these attributes render a room non-purgable
246 if (qrbuf->QRflags & QR_PERMANENT) return;
247 if (qrbuf->QRflags & QR_DIRECTORY) return;
248 if (qrbuf->QRflags2 & QR2_SYSTEM) return;
249 if (!strcasecmp(qrbuf->QRname, SYSCONFIGROOM)) return;
250 if (CtdlIsNonEditable(qrbuf)) return;
252 // If we don't know the modification date, be safe and don't purge
253 if (qrbuf->QRmtime <= (time_t)0) return;
255 // If no room purge time is set, be safe and don't purge
256 if (CtdlGetConfigLong("c_roompurge") < 0) return;
258 // Otherwise, check the date of last modification
259 age = time(NULL) - (qrbuf->QRmtime);
260 purge_secs = CtdlGetConfigLong("c_roompurge") * 86400;
261 if (purge_secs <= (time_t)0) return;
262 syslog(LOG_DEBUG, "<%s> is <%ld> seconds old", qrbuf->QRname, (long)age);
263 if (age > purge_secs) do_purge = 1;
267 pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
269 pptr->next = RoomPurgeList;
270 strcpy(pptr->name, qrbuf->QRname);
271 RoomPurgeList = pptr;
277 int PurgeRooms(void) {
278 struct PurgeList *pptr;
279 int num_rooms_purged = 0;
280 struct ctdlroom qrbuf;
281 struct ValidUser *vuptr;
283 syslog(LOG_DEBUG, "PurgeRooms() called");
285 // Load up a table full of valid user numbers so we can delete
286 // user-owned rooms for users who no longer exist
287 ForEachUser(AddValidUser, NULL);
289 // Then cycle through the room file
290 CtdlForEachRoom(DoPurgeRooms, NULL);
292 // Free the valid user list
293 while (ValidUserList != NULL) {
294 vuptr = ValidUserList->next;
296 ValidUserList = vuptr;
299 while (RoomPurgeList != NULL) {
300 if (CtdlGetRoom(&qrbuf, RoomPurgeList->name) == 0) {
301 CtdlDeleteRoom(&qrbuf);
304 pptr = RoomPurgeList->next;
306 RoomPurgeList = pptr;
309 syslog(LOG_DEBUG, "Purged %d rooms.", num_rooms_purged);
310 return(num_rooms_purged);
314 // Back end function to check user accounts for expiration.
315 void do_user_purge(char *username, void *data) {
319 struct PurgeList *pptr;
322 if (CtdlGetUser(&us, username) != 0) {
326 // Set purge time; if the user overrides the system default, use it
327 if (us.USuserpurge > 0) {
328 purge_time = ((time_t)us.USuserpurge) * 86400;
331 purge_time = CtdlGetConfigLong("c_userpurge") * 86400;
334 // The default rule is to not purge.
337 // If the user has not logged in for the configured amount of time, expire the account.
338 if (CtdlGetConfigLong("c_userpurge") > 0) {
340 if ((now - us.lastcall) > purge_time) purge = 1;
343 // If the account is marked as permanent, don't purge it.
344 if (us.flags & US_PERM) purge = 0;
346 // If the account is an administrator, don't purge it.
347 if (us.axlevel == 6) purge = 0;
349 // If the access level is 0, the record should already have been
350 // deleted, but maybe the user was logged in at the time or something.
351 // Delete the record now.
352 if (us.axlevel == 0) purge = 1;
354 // If the user set his/her password to 'deleteme', he/she
355 // wishes to be deleted, so purge the record.
356 // Moved this lower down so that aides and permanent users get purged if they ask to be.
357 if (!strcasecmp(us.password, "deleteme")) purge = 1;
359 // any negative user number, is also impossible.
360 if (us.usernum < 0L) purge = 1;
362 // Don't purge user 0. That user is there for the system
363 if (us.usernum == 0L) purge = 0;
365 // If the user has no full name entry then we can't purge them since the actual purge can't find them.
366 // This shouldn't happen but does somehow.
367 if (IsEmptyStr(us.fullname)) {
369 if (us.usernum > 0L) {
371 syslog(LOG_INFO, "expire: refusing to purge user %ld who has no name", us.usernum);
376 pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
378 pptr->next = UserPurgeList;
379 strcpy(pptr->name, us.fullname);
380 UserPurgeList = pptr;
389 int PurgeUsers(void) {
390 struct PurgeList *pptr;
391 int num_users_purged = 0;
393 syslog(LOG_DEBUG, "PurgeUsers() called");
394 users_not_purged = 0;
396 switch(CtdlGetConfigInt("c_auth_mode")) {
397 case AUTHMODE_NATIVE:
398 ForEachUser(do_user_purge, NULL);
401 syslog(LOG_DEBUG, "User purge for auth mode %d is not implemented.", CtdlGetConfigInt("c_auth_mode"));
405 if (users_not_purged == 0) {
406 syslog(LOG_INFO, "expire: refusing to purge all users because this usually indicates an error");
407 while (UserPurgeList != NULL) {
408 pptr = UserPurgeList->next;
410 UserPurgeList = pptr;
415 while (UserPurgeList != NULL) {
416 purge_user(UserPurgeList->name);
417 pptr = UserPurgeList->next;
419 UserPurgeList = pptr;
424 syslog(LOG_DEBUG, "Purged %d users.", num_users_purged);
425 return(num_users_purged);
431 // This is a really cumbersome "garbage collection" function. We have to
432 // delete visits which refer to rooms and/or users which no longer exist. In
433 // order to prevent endless traversals of the room and user files, we first
434 // build linked lists of rooms and users which _do_ exist on the system, then
435 // traverse the visit file, checking each record against those two lists and
436 // purging the ones that do not have a match on _both_ lists. (Remember, if
437 // either the room or user being referred to is no longer on the system, the
438 // record is useless and should be removed.)
440 int PurgeVisits(void) {
441 struct cdbkeyval cdbvisit;
443 struct VPurgeList *VisitPurgeList = NULL;
444 struct VPurgeList *vptr;
448 struct ValidRoom *vrptr;
449 struct ValidUser *vuptr;
450 int RoomIsValid, UserIsValid;
452 // First, load up a table full of valid room/gen combinations
453 CtdlForEachRoom(AddValidRoom, NULL);
455 // Then load up a table full of valid user numbers
456 ForEachUser(AddValidUser, NULL);
458 // Now traverse through the visits, purging irrelevant records...
459 cdb_rewind(CDB_VISIT);
460 while(cdbvisit = cdb_next_item(CDB_VISIT), cdbvisit.val.ptr!=NULL) { // always read through to the end
461 memset(&vbuf, 0, sizeof(struct visit));
462 memcpy(&vbuf, cdbvisit.val.ptr, ((cdbvisit.val.len > sizeof(struct visit)) ? sizeof(struct visit) : cdbvisit.val.len));
466 // Check to see if the room exists
467 for (vrptr=ValidRoomList; vrptr!=NULL; vrptr=vrptr->next) {
468 if ( (vrptr->vr_roomnum==vbuf.v_roomnum) && (vrptr->vr_roomgen==vbuf.v_roomgen)) {
473 // Check to see if the user exists
474 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
475 if (vuptr->vu_usernum == vbuf.v_usernum) {
480 // Put the record on the purge list if it's dead
481 if ((RoomIsValid==0) || (UserIsValid==0)) {
482 vptr = (struct VPurgeList *) malloc(sizeof(struct VPurgeList));
484 vptr->next = VisitPurgeList;
485 vptr->vp_roomnum = vbuf.v_roomnum;
486 vptr->vp_roomgen = vbuf.v_roomgen;
487 vptr->vp_usernum = vbuf.v_usernum;
488 VisitPurgeList = vptr;
493 // Free the valid room/gen combination list
494 while (ValidRoomList != NULL) {
495 vrptr = ValidRoomList->next;
497 ValidRoomList = vrptr;
500 // Free the valid user list
501 while (ValidUserList != NULL) {
502 vuptr = ValidUserList->next;
504 ValidUserList = vuptr;
507 // Now delete every visit on the purged list
508 cdb_begin_transaction();
509 while (VisitPurgeList != NULL) {
510 IndexLen = GenerateRelationshipIndex(IndexBuf,
511 VisitPurgeList->vp_roomnum,
512 VisitPurgeList->vp_roomgen,
513 VisitPurgeList->vp_usernum);
514 cdb_delete(CDB_VISIT, IndexBuf, IndexLen);
515 vptr = VisitPurgeList->next;
516 free(VisitPurgeList);
517 VisitPurgeList = vptr;
520 cdb_end_transaction();
526 // Purge the use table of old entries.
527 // Holy crap, this is WAY better. We need to replace most linked lists with arrays.
528 int PurgeUseTable(StrBuf *ErrMsg) {
531 struct cdbkeyval cdbut;
533 Array *purge_list = array_new(sizeof(int));
535 // Phase 1: traverse through the table, discovering old records...
537 syslog(LOG_DEBUG, "Purge use table: phase 1");
538 cdb_rewind(CDB_USETABLE);
539 while(cdbut = cdb_next_item(CDB_USETABLE), cdbut.val.ptr!=NULL) { // always read through to the end
541 if (cdbut.val.len > sizeof(struct UseTable))
542 memcpy(&ut, cdbut.val.ptr, sizeof(struct UseTable));
544 memset(&ut, 0, sizeof(struct UseTable));
545 memcpy(&ut, cdbut.val.ptr, cdbut.val.len);
548 if ( (time(NULL) - ut.timestamp) > USETABLE_RETAIN ) {
549 array_append(purge_list, &ut.hash);
554 // Phase 2: delete the records
555 syslog(LOG_DEBUG, "Purge use table: phase 2");
557 cdb_begin_transaction();
558 for (i=0; i<purged; ++i) {
559 struct UseTable *u = (struct UseTable *)array_get_element_at(purge_list, i);
560 cdb_delete(CDB_USETABLE, &u->hash, sizeof(int));
562 cdb_end_transaction();
563 array_free(purge_list);
565 syslog(LOG_DEBUG, "Purge use table: finished (purged %d of %d records)", purged, total);
570 // Purge the EUID Index of old records.
571 int PurgeEuidIndexTable(void) {
573 struct cdbkeyval cdbei;
574 struct EPurgeList *el = NULL;
575 struct EPurgeList *eptr;
577 struct CtdlMessage *msg = NULL;
579 // Phase 1: traverse through the table, discovering old records...
580 syslog(LOG_DEBUG, "Purge EUID index: phase 1");
581 cdb_rewind(CDB_EUIDINDEX);
582 while(cdbei = cdb_next_item(CDB_EUIDINDEX), cdbei.val.ptr!=NULL) { // always read through to the end
584 memcpy(&msgnum, cdbei.val.ptr, sizeof(long));
586 msg = CtdlFetchMessage(msgnum, 0);
588 CM_Free(msg); // it still exists, so do nothing
591 eptr = (struct EPurgeList *) malloc(sizeof(struct EPurgeList));
595 eptr->ep_keylen = cdbei.val.len - sizeof(long);
596 eptr->ep_key = malloc(cdbei.val.len);
597 if (!eptr->ep_key) abort();
598 memcpy(eptr->ep_key, &cdbei.val.ptr[sizeof(long)], eptr->ep_keylen);
607 // Phase 2: delete the records
608 syslog(LOG_DEBUG, "Purge euid index: phase 2");
609 cdb_begin_transaction();
611 cdb_delete(CDB_EUIDINDEX, el->ep_key, el->ep_keylen);
617 cdb_end_transaction();
619 syslog(LOG_DEBUG, "Purge euid index: finished (purged %d records)", purged);
624 void purge_databases(void) {
625 static time_t last_purge = 0;
628 int users_purged, rooms_purged, visits_purged, usete_purged, euidindices_purged = 0;
630 // Do the auto-purge if the current hour equals the purge hour,
631 // but not if the operation has already been performed in the
632 // last twelve hours. This is usually enough granularity.
634 localtime_r(&now, &tm);
635 if (((tm.tm_hour != CtdlGetConfigInt("c_purge_hour")) || ((now - last_purge) < 43200)) && (force_purge_now == 0)) {
639 syslog(LOG_INFO, "Auto-purger: starting.");
641 if (!server_shutting_down) {
642 users_purged = PurgeUsers();
643 syslog(LOG_NOTICE, "Purged %d users.", users_purged);
646 if (!server_shutting_down) {
648 syslog(LOG_NOTICE, "Expired %d messages.", messages_purged);
651 if (!server_shutting_down) {
652 rooms_purged = PurgeRooms();
653 syslog(LOG_NOTICE, "Expired %d rooms.", rooms_purged);
656 if (!server_shutting_down) {
657 visits_purged = PurgeVisits();
658 syslog(LOG_NOTICE, "Purged %d visits.", visits_purged);
661 if (!server_shutting_down) {
663 ErrMsg = NewStrBuf();
664 usete_purged = PurgeUseTable(ErrMsg);
665 syslog(LOG_NOTICE, "Purged %d entries from the use table.", usete_purged);
669 if (!server_shutting_down) {
670 euidindices_purged = PurgeEuidIndexTable();
671 syslog(LOG_NOTICE, "Purged %d entries from the EUID index.", euidindices_purged);
674 if (users_purged + messages_purged + rooms_purged + visits_purged + usete_purged + euidindices_purged != 0) {
676 snprintf(msg, sizeof msg,
677 "Citadel Server has deleted %d users, %d messages, %d rooms, %d visit records, %d use table entries, "
678 "and %d EUID indices due to expire policy set on those objects.\n",
679 users_purged, messages_purged, rooms_purged, visits_purged, usete_purged, euidindices_purged
681 CtdlAideMessage(msg, "Expired Objects Report");
684 //if (!server_shutting_down) {
685 // FIXME this is where we could do a non-interactive delete of zero-refcount messages
688 if ( (!server_shutting_down) && (CtdlGetConfigInt("c_shrink_db_files") != 0) ) {
689 cdb_compact(); // Shrink the DB files on disk
692 if (!server_shutting_down) {
693 syslog(LOG_INFO, "Auto-purger: finished.");
694 last_purge = now; // So we don't do it again soon
698 syslog(LOG_INFO, "Auto-purger: STOPPED.");
703 // Manually initiate a run of The Dreaded Auto-Purger (tm)
704 void cmd_tdap(char *argbuf) {
705 if (CtdlAccessCheck(ac_aide)) return;
707 cprintf("%d Manually initiating a purger run now.\n", CIT_OK);
711 // Initialization function, called from modules_init.c
712 char *ctdl_module_init_expire(void) {
714 CtdlRegisterProtoHook(cmd_tdap, "TDAP", "Manually initiate auto-purger");
715 CtdlRegisterProtoHook(cmd_gpex, "GPEX", "Get expire policy");
716 CtdlRegisterProtoHook(cmd_spex, "SPEX", "Set expire policy");
717 CtdlRegisterSessionHook(purge_databases, EVT_TIMER, PRIO_CLEANUP + 20);
720 // return our module name for the log