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-2023 by citadel.org (Art Cancro, Wilifried Goesgens, and others)
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.
11 #include "../../sysdep.h"
19 #include <sys/types.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"
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"
39 #include "../../ctdl_module.h"
43 struct PurgeList *next;
44 char name[ROOMNAMELEN]; // use the larger of username or roomname
48 struct VPurgeList *next;
55 struct ValidRoom *next;
61 struct ValidUser *next;
66 struct ctdlroomref *next;
71 struct EPurgeList *next;
77 struct PurgeList *UserPurgeList = NULL;
78 struct PurgeList *RoomPurgeList = NULL;
79 struct ValidRoom *ValidRoomList = NULL;
80 struct ValidUser *ValidUserList = NULL;
83 struct ctdlroomref *rr = NULL;
84 int force_purge_now = 0; // set to nonzero to force a run right now
87 // First phase of message purge -- gather the locations of messages which
88 // qualify for purging and write them to a temp file.
89 void GatherPurgeMessages(struct ctdlroom *qrbuf, void *data) {
90 struct ExpirePolicy epbuf;
93 struct CtdlMessage *msg = NULL;
99 purgelist = (FILE *)data;
100 fprintf(purgelist, "r=%s\n", qrbuf->QRname);
103 GetExpirePolicy(&epbuf, qrbuf);
104 syslog(LOG_DEBUG, "expire: scanning room %ld (%s), policy %d", qrbuf->QRnumber, qrbuf->QRname, epbuf.expire_mode);
106 // If the room is set to never expire messages ... do nothing
107 if (epbuf.expire_mode == EXPIRE_NEXTLEVEL) return;
108 if (epbuf.expire_mode == EXPIRE_MANUAL) return;
110 // Don't purge messages containing system configuration, dumbass.
111 if (!strcasecmp(qrbuf->QRname, SYSCONFIGROOM)) return;
113 // Ok, we got this far ... now let's see what's in the room.
114 num_msgs = CtdlFetchMsgList(qrbuf->QRnumber, &msglist);
116 // Nothing to do if there aren't any messages
122 // If the room is set to expire by count, do that.
123 if (epbuf.expire_mode == EXPIRE_NUMMSGS) {
125 if (num_msgs > epbuf.expire_value) {
126 for (a=0; a<(num_msgs - epbuf.expire_value); ++a) {
127 fprintf(purgelist, "m=%ld\n", msglist[a]);
133 // If the room is set to expire by age...
134 if (epbuf.expire_mode == EXPIRE_AGE) {
136 for (a=0; a<num_msgs; ++a) {
138 msg = CtdlFetchMessage(delnum, 0); // don't need the body
140 xtime = atol(msg->cm_fields[eTimestamp]);
147 if ((xtime > 0L) && (now - xtime > (time_t)(epbuf.expire_value * 86400L))) {
148 fprintf(purgelist, "m=%ld\n", delnum);
154 if (msglist != NULL) {
160 // Second phase of message purge -- read list of msgs from temp file and delete them.
161 void DoPurgeMessages(FILE *purgelist) {
162 char roomname[ROOMNAMELEN];
167 strcpy(roomname, "nonexistent room ___ ___");
168 while (fgets(buf, sizeof buf, purgelist) != NULL) {
169 buf[strlen(buf)-1]=0;
170 if (!strncasecmp(buf, "r=", 2)) {
171 strcpy(roomname, &buf[2]);
173 if (!strncasecmp(buf, "m=", 2)) {
174 msgnum = atol(&buf[2]);
176 CtdlDeleteMessages(roomname, &msgnum, 1, "");
183 void PurgeMessages(void) {
186 syslog(LOG_DEBUG, "PurgeMessages() called");
189 purgelist = tmpfile();
190 if (purgelist == NULL) {
191 syslog(LOG_CRIT, "Can't create purgelist temp file: %s", strerror(errno));
195 CtdlForEachRoom(GatherPurgeMessages, (void *)purgelist );
196 DoPurgeMessages(purgelist);
201 void AddValidUser(char *username, void *data) {
202 struct ValidUser *vuptr;
203 struct ctdluser usbuf;
205 if (CtdlGetUser(&usbuf, username) != 0) {
209 vuptr = (struct ValidUser *)malloc(sizeof(struct ValidUser));
211 vuptr->next = ValidUserList;
212 vuptr->vu_usernum = usbuf.usernum;
213 ValidUserList = vuptr;
217 void AddValidRoom(struct ctdlroom *qrbuf, void *data) {
218 struct ValidRoom *vrptr;
220 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;
229 void DoPurgeRooms(struct ctdlroom *qrbuf, void *data) {
230 time_t age, purge_secs;
231 struct PurgeList *pptr;
232 struct ValidUser *vuptr;
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
241 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
242 if (vuptr->vu_usernum == atol(qrbuf->QRname)) {
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;
255 // If we don't know the modification date, be safe and don't purge
256 if (qrbuf->QRmtime <= (time_t)0) return;
258 // If no room purge time is set, be safe and don't purge
259 if (CtdlGetConfigLong("c_roompurge") < 0) return;
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;
270 pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
272 pptr->next = RoomPurgeList;
273 strcpy(pptr->name, qrbuf->QRname);
274 RoomPurgeList = pptr;
280 int PurgeRooms(void) {
281 struct PurgeList *pptr;
282 int num_rooms_purged = 0;
283 struct ctdlroom qrbuf;
284 struct ValidUser *vuptr;
286 syslog(LOG_DEBUG, "PurgeRooms() called");
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);
292 // Then cycle through the room file
293 CtdlForEachRoom(DoPurgeRooms, NULL);
295 // Free the valid user list
296 while (ValidUserList != NULL) {
297 vuptr = ValidUserList->next;
299 ValidUserList = vuptr;
302 while (RoomPurgeList != NULL) {
303 if (CtdlGetRoom(&qrbuf, RoomPurgeList->name) == 0) {
304 CtdlDeleteRoom(&qrbuf);
307 pptr = RoomPurgeList->next;
309 RoomPurgeList = pptr;
312 syslog(LOG_DEBUG, "Purged %d rooms.", num_rooms_purged);
313 return(num_rooms_purged);
317 // Back end function to check user accounts for expiration.
318 void do_user_purge(char *username, void *data) {
322 struct PurgeList *pptr;
325 if (CtdlGetUser(&us, username) != 0) {
329 // Set purge time; if the user overrides the system default, use it
330 if (us.USuserpurge > 0) {
331 purge_time = ((time_t)us.USuserpurge) * 86400;
334 purge_time = CtdlGetConfigLong("c_userpurge") * 86400;
337 // The default rule is to not purge.
340 // If the user has not logged in for the configured amount of time, expire the account.
341 if (CtdlGetConfigLong("c_userpurge") > 0) {
343 if ((now - us.lastcall) > purge_time) purge = 1;
346 // If the account is marked as permanent, don't purge it.
347 if (us.flags & US_PERM) purge = 0;
349 // If the account is an administrator, don't purge it.
350 if (us.axlevel == 6) purge = 0;
352 // If the access level is 0, the record should already have been
353 // deleted, but maybe the user was logged in at the time or something.
354 // Delete the record now.
355 if (us.axlevel == 0) purge = 1;
357 // If the user set his/her password to 'deleteme', he/she
358 // wishes to be deleted, so purge the record.
359 // Moved this lower down so that aides and permanent users get purged if they ask to be.
360 if (!strcasecmp(us.password, "deleteme")) purge = 1;
362 // any negative user number, is also impossible.
363 if (us.usernum < 0L) purge = 1;
365 // Don't purge user 0. That user is there for the system
366 if (us.usernum == 0L) purge = 0;
368 // If the user has no full name entry then we can't purge them since the actual purge can't find them.
369 // This shouldn't happen but does somehow.
370 if (IsEmptyStr(us.fullname)) {
372 if (us.usernum > 0L) {
374 syslog(LOG_INFO, "expire: refusing to purge user %ld who has no name", us.usernum);
379 pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
381 pptr->next = UserPurgeList;
382 strcpy(pptr->name, us.fullname);
383 UserPurgeList = pptr;
392 int PurgeUsers(void) {
393 struct PurgeList *pptr;
394 int num_users_purged = 0;
396 syslog(LOG_DEBUG, "PurgeUsers() called");
397 users_not_purged = 0;
399 switch(CtdlGetConfigInt("c_auth_mode")) {
400 case AUTHMODE_NATIVE:
401 ForEachUser(do_user_purge, NULL);
404 syslog(LOG_DEBUG, "User purge for auth mode %d is not implemented.", CtdlGetConfigInt("c_auth_mode"));
408 if (users_not_purged == 0) {
409 syslog(LOG_INFO, "expire: refusing to purge all users because this usually indicates an error");
410 while (UserPurgeList != NULL) {
411 pptr = UserPurgeList->next;
413 UserPurgeList = pptr;
418 while (UserPurgeList != NULL) {
419 purge_user(UserPurgeList->name);
420 pptr = UserPurgeList->next;
422 UserPurgeList = pptr;
427 syslog(LOG_DEBUG, "Purged %d users.", num_users_purged);
428 return(num_users_purged);
434 // This is a really cumbersome "garbage collection" function. We have to
435 // delete visits which refer to rooms and/or users which no longer exist. In
436 // order to prevent endless traversals of the room and user files, we first
437 // build linked lists of rooms and users which _do_ exist on the system, then
438 // traverse the visit file, checking each record against those two lists and
439 // purging the ones that do not have a match on _both_ lists. (Remember, if
440 // either the room or user being referred to is no longer on the system, the
441 // record is useless and should be removed.)
443 int PurgeVisits(void) {
444 struct cdbkeyval cdbvisit;
446 struct VPurgeList *VisitPurgeList = NULL;
447 struct VPurgeList *vptr;
451 struct ValidRoom *vrptr;
452 struct ValidUser *vuptr;
453 int RoomIsValid, UserIsValid;
455 // First, load up a table full of valid room/gen combinations
456 CtdlForEachRoom(AddValidRoom, NULL);
458 // Then load up a table full of valid user numbers
459 ForEachUser(AddValidUser, NULL);
461 // Now traverse through the visits, purging irrelevant records...
462 cdb_rewind(CDB_VISIT);
463 while(cdbvisit = cdb_next_item(CDB_VISIT), cdbvisit.val.ptr!=NULL) { // always read through to the end
464 memset(&vbuf, 0, sizeof(struct visit));
465 memcpy(&vbuf, cdbvisit.val.ptr, ((cdbvisit.val.len > sizeof(struct visit)) ? sizeof(struct visit) : cdbvisit.val.len));
469 // Check to see if the room exists
470 for (vrptr=ValidRoomList; vrptr!=NULL; vrptr=vrptr->next) {
471 if ( (vrptr->vr_roomnum==vbuf.v_roomnum) && (vrptr->vr_roomgen==vbuf.v_roomgen)) {
476 // Check to see if the user exists
477 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
478 if (vuptr->vu_usernum == vbuf.v_usernum) {
483 // Put the record on the purge list if it's dead
484 if ((RoomIsValid==0) || (UserIsValid==0)) {
485 vptr = (struct VPurgeList *) malloc(sizeof(struct VPurgeList));
487 vptr->next = VisitPurgeList;
488 vptr->vp_roomnum = vbuf.v_roomnum;
489 vptr->vp_roomgen = vbuf.v_roomgen;
490 vptr->vp_usernum = vbuf.v_usernum;
491 VisitPurgeList = vptr;
496 // Free the valid room/gen combination list
497 while (ValidRoomList != NULL) {
498 vrptr = ValidRoomList->next;
500 ValidRoomList = vrptr;
503 // Free the valid user list
504 while (ValidUserList != NULL) {
505 vuptr = ValidUserList->next;
507 ValidUserList = vuptr;
510 // Now delete every visit on the purged list
511 cdb_begin_transaction();
512 while (VisitPurgeList != NULL) {
513 IndexLen = GenerateRelationshipIndex(IndexBuf,
514 VisitPurgeList->vp_roomnum,
515 VisitPurgeList->vp_roomgen,
516 VisitPurgeList->vp_usernum);
517 cdb_delete(CDB_VISIT, IndexBuf, IndexLen);
518 vptr = VisitPurgeList->next;
519 free(VisitPurgeList);
520 VisitPurgeList = vptr;
523 cdb_end_transaction();
529 // Purge the use table of old entries.
530 // Holy crap, this is WAY better. We need to replace most linked lists with arrays.
531 int PurgeUseTable(StrBuf *ErrMsg) {
534 struct cdbkeyval cdbut;
536 Array *purge_list = array_new(sizeof(int));
538 // Phase 1: traverse through the table, discovering old records...
540 syslog(LOG_DEBUG, "Purge use table: phase 1");
541 cdb_rewind(CDB_USETABLE);
542 while(cdbut = cdb_next_item(CDB_USETABLE), cdbut.val.ptr!=NULL) { // always read through to the end
544 if (cdbut.val.len > sizeof(struct UseTable))
545 memcpy(&ut, cdbut.val.ptr, sizeof(struct UseTable));
547 memset(&ut, 0, sizeof(struct UseTable));
548 memcpy(&ut, cdbut.val.ptr, cdbut.val.len);
551 if ( (time(NULL) - ut.timestamp) > USETABLE_RETAIN ) {
552 array_append(purge_list, &ut.hash);
557 // Phase 2: delete the records
558 syslog(LOG_DEBUG, "Purge use table: phase 2");
560 cdb_begin_transaction();
561 for (i=0; i<purged; ++i) {
562 struct UseTable *u = (struct UseTable *)array_get_element_at(purge_list, i);
563 cdb_delete(CDB_USETABLE, &u->hash, sizeof(int));
565 cdb_end_transaction();
566 array_free(purge_list);
568 syslog(LOG_DEBUG, "Purge use table: finished (purged %d of %d records)", purged, total);
573 // Purge the EUID Index of old records.
574 int PurgeEuidIndexTable(void) {
576 struct cdbkeyval cdbei;
577 struct EPurgeList *el = NULL;
578 struct EPurgeList *eptr;
580 struct CtdlMessage *msg = NULL;
582 // Phase 1: traverse through the table, discovering old records...
583 syslog(LOG_DEBUG, "Purge EUID index: phase 1");
584 cdb_rewind(CDB_EUIDINDEX);
585 while(cdbei = cdb_next_item(CDB_EUIDINDEX), cdbei.val.ptr!=NULL) { // always read through to the end
587 memcpy(&msgnum, cdbei.val.ptr, sizeof(long));
589 msg = CtdlFetchMessage(msgnum, 0);
591 CM_Free(msg); // it still exists, so do nothing
594 eptr = (struct EPurgeList *) malloc(sizeof(struct EPurgeList));
598 eptr->ep_keylen = cdbei.val.len - sizeof(long);
599 eptr->ep_key = malloc(cdbei.val.len);
600 if (!eptr->ep_key) abort();
601 memcpy(eptr->ep_key, &cdbei.val.ptr[sizeof(long)], eptr->ep_keylen);
610 // Phase 2: delete the records
611 syslog(LOG_DEBUG, "Purge euid index: phase 2");
612 cdb_begin_transaction();
614 cdb_delete(CDB_EUIDINDEX, el->ep_key, el->ep_keylen);
620 cdb_end_transaction();
622 syslog(LOG_DEBUG, "Purge euid index: finished (purged %d records)", purged);
627 void purge_databases(void) {
628 static time_t last_purge = 0;
631 int users_purged, rooms_purged, visits_purged, usete_purged, euidindices_purged = 0;
633 // Do the auto-purge if the current hour equals the purge hour,
634 // but not if the operation has already been performed in the
635 // last twelve hours. This is usually enough granularity.
637 localtime_r(&now, &tm);
638 if (((tm.tm_hour != CtdlGetConfigInt("c_purge_hour")) || ((now - last_purge) < 43200)) && (force_purge_now == 0)) {
642 syslog(LOG_INFO, "Auto-purger: starting.");
644 if (!server_shutting_down) {
645 users_purged = PurgeUsers();
646 syslog(LOG_NOTICE, "Purged %d users.", users_purged);
649 if (!server_shutting_down) {
651 syslog(LOG_NOTICE, "Expired %d messages.", messages_purged);
654 if (!server_shutting_down) {
655 rooms_purged = PurgeRooms();
656 syslog(LOG_NOTICE, "Expired %d rooms.", rooms_purged);
659 if (!server_shutting_down) {
660 visits_purged = PurgeVisits();
661 syslog(LOG_NOTICE, "Purged %d visits.", visits_purged);
664 if (!server_shutting_down) {
666 ErrMsg = NewStrBuf();
667 usete_purged = PurgeUseTable(ErrMsg);
668 syslog(LOG_NOTICE, "Purged %d entries from the use table.", usete_purged);
672 if (!server_shutting_down) {
673 euidindices_purged = PurgeEuidIndexTable();
674 syslog(LOG_NOTICE, "Purged %d entries from the EUID index.", euidindices_purged);
677 if (users_purged + messages_purged + rooms_purged + visits_purged + usete_purged + euidindices_purged != 0) {
679 snprintf(msg, sizeof msg,
680 "Citadel Server has deleted %d users, %d messages, %d rooms, %d visit records, %d use table entries, "
681 "and %d EUID indices due to expire policy set on those objects.\n",
682 users_purged, messages_purged, rooms_purged, visits_purged, usete_purged, euidindices_purged
684 CtdlAideMessage(msg, "Expired Objects Report");
687 //if (!server_shutting_down) {
688 // FIXME this is where we could do a non-interactive delete of zero-refcount messages
691 if ( (!server_shutting_down) && (CtdlGetConfigInt("c_shrink_db_files") != 0) ) {
692 cdb_compact(); // Shrink the DB files on disk
695 if (!server_shutting_down) {
696 syslog(LOG_INFO, "Auto-purger: finished.");
697 last_purge = now; // So we don't do it again soon
701 syslog(LOG_INFO, "Auto-purger: STOPPED.");
706 // Manually initiate a run of The Dreaded Auto-Purger (tm)
707 void cmd_tdap(char *argbuf) {
708 if (CtdlAccessCheck(ac_aide)) return;
710 cprintf("%d Manually initiating a purger run now.\n", CIT_OK);
714 // Initialization function, called from modules_init.c
715 char *ctdl_module_init_expire(void) {
717 CtdlRegisterProtoHook(cmd_tdap, "TDAP", "Manually initiate auto-purger");
718 CtdlRegisterProtoHook(cmd_gpex, "GPEX", "Get expire policy");
719 CtdlRegisterProtoHook(cmd_spex, "SPEX", "Set expire policy");
720 CtdlRegisterSessionHook(purge_databases, EVT_TIMER, PRIO_CLEANUP + 20);
723 // return our module name for the log