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 "../../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 char *users_corrupt_msg = NULL;
83 char *users_zero_msg = NULL;
84 struct ctdlroomref *rr = NULL;
85 int force_purge_now = 0; // set to nonzero to force a run right now
88 // First phase of message purge -- gather the locations of messages which
89 // qualify for purging and write them to a temp file.
90 void GatherPurgeMessages(struct ctdlroom *qrbuf, void *data) {
91 struct ExpirePolicy epbuf;
94 struct CtdlMessage *msg = NULL;
96 struct cdbdata *cdbfr;
101 purgelist = (FILE *)data;
102 fprintf(purgelist, "r=%s\n", qrbuf->QRname);
105 GetExpirePolicy(&epbuf, qrbuf);
107 // If the room is set to never expire messages ... do nothing
108 if (epbuf.expire_mode == EXPIRE_NEXTLEVEL) return;
109 if (epbuf.expire_mode == EXPIRE_MANUAL) return;
111 // Don't purge messages containing system configuration, dumbass.
112 if (!strcasecmp(qrbuf->QRname, SYSCONFIGROOM)) return;
114 // Ok, we got this far ... now let's see what's in the room.
115 cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf->QRnumber, sizeof(long));
118 msglist = malloc(cdbfr->len);
119 memcpy(msglist, cdbfr->ptr, cdbfr->len);
120 num_msgs = cdbfr->len / sizeof(long);
124 // Nothing to do if there aren't any messages
126 if (msglist != NULL) free(msglist);
130 // If the room is set to expire by count, do that.
131 if (epbuf.expire_mode == EXPIRE_NUMMSGS) {
132 if (num_msgs > epbuf.expire_value) {
133 for (a=0; a<(num_msgs - epbuf.expire_value); ++a) {
134 fprintf(purgelist, "m=%ld\n", msglist[a]);
140 // If the room is set to expire by age...
141 if (epbuf.expire_mode == EXPIRE_AGE) {
142 for (a=0; a<num_msgs; ++a) {
145 msg = CtdlFetchMessage(delnum, 0); // don't need the body
147 xtime = atol(msg->cm_fields[eTimestamp]);
154 if ((xtime > 0L) && (now - xtime > (time_t)(epbuf.expire_value * 86400L))) {
155 fprintf(purgelist, "m=%ld\n", delnum);
161 if (msglist != NULL) free(msglist);
165 // Second phase of message purge -- read list of msgs from temp file and delete them.
166 void DoPurgeMessages(FILE *purgelist) {
167 char roomname[ROOMNAMELEN];
172 strcpy(roomname, "nonexistent room ___ ___");
173 while (fgets(buf, sizeof buf, purgelist) != NULL) {
174 buf[strlen(buf)-1]=0;
175 if (!strncasecmp(buf, "r=", 2)) {
176 strcpy(roomname, &buf[2]);
178 if (!strncasecmp(buf, "m=", 2)) {
179 msgnum = atol(&buf[2]);
181 CtdlDeleteMessages(roomname, &msgnum, 1, "");
188 void PurgeMessages(void) {
191 syslog(LOG_DEBUG, "PurgeMessages() called");
194 purgelist = tmpfile();
195 if (purgelist == NULL) {
196 syslog(LOG_CRIT, "Can't create purgelist temp file: %s", strerror(errno));
200 CtdlForEachRoom(GatherPurgeMessages, (void *)purgelist );
201 DoPurgeMessages(purgelist);
206 void AddValidUser(char *username, void *data) {
207 struct ValidUser *vuptr;
208 struct ctdluser usbuf;
210 if (CtdlGetUser(&usbuf, username) != 0) {
214 vuptr = (struct ValidUser *)malloc(sizeof(struct ValidUser));
215 vuptr->next = ValidUserList;
216 vuptr->vu_usernum = usbuf.usernum;
217 ValidUserList = vuptr;
221 void AddValidRoom(struct ctdlroom *qrbuf, void *data) {
222 struct ValidRoom *vrptr;
224 vrptr = (struct ValidRoom *)malloc(sizeof(struct ValidRoom));
225 vrptr->next = ValidRoomList;
226 vrptr->vr_roomnum = qrbuf->QRnumber;
227 vrptr->vr_roomgen = qrbuf->QRgen;
228 ValidRoomList = vrptr;
232 void DoPurgeRooms(struct ctdlroom *qrbuf, void *data) {
233 time_t age, purge_secs;
234 struct PurgeList *pptr;
235 struct ValidUser *vuptr;
238 // For mailbox rooms, there's only one purging rule: if the user who
239 // owns the room still exists, we keep the room; otherwise, we purge
240 // it. Bypass any other rules.
241 if (qrbuf->QRflags & QR_MAILBOX) {
242 // if user not found, do_purge will be 1
244 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
245 if (vuptr->vu_usernum == atol(qrbuf->QRname)) {
251 // Any of these attributes render a room non-purgable
252 if (qrbuf->QRflags & QR_PERMANENT) return;
253 if (qrbuf->QRflags & QR_DIRECTORY) return;
254 if (qrbuf->QRflags2 & QR2_SYSTEM) return;
255 if (!strcasecmp(qrbuf->QRname, SYSCONFIGROOM)) return;
256 if (CtdlIsNonEditable(qrbuf)) return;
258 // If we don't know the modification date, be safe and don't purge
259 if (qrbuf->QRmtime <= (time_t)0) return;
261 // If no room purge time is set, be safe and don't purge
262 if (CtdlGetConfigLong("c_roompurge") < 0) return;
264 // Otherwise, check the date of last modification
265 age = time(NULL) - (qrbuf->QRmtime);
266 purge_secs = CtdlGetConfigLong("c_roompurge") * 86400;
267 if (purge_secs <= (time_t)0) return;
268 syslog(LOG_DEBUG, "<%s> is <%ld> seconds old", qrbuf->QRname, (long)age);
269 if (age > purge_secs) do_purge = 1;
273 pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
274 pptr->next = RoomPurgeList;
275 strcpy(pptr->name, qrbuf->QRname);
276 RoomPurgeList = pptr;
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;
289 syslog(LOG_DEBUG, "PurgeRooms() called");
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);
295 // Then cycle through the room file
296 CtdlForEachRoom(DoPurgeRooms, NULL);
298 // Free the valid user list
299 while (ValidUserList != NULL) {
300 vuptr = ValidUserList->next;
302 ValidUserList = vuptr;
305 transcript = malloc(SIZ);
306 strcpy(transcript, "The following rooms have been auto-purged:\n");
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);
315 pptr = RoomPurgeList->next;
317 RoomPurgeList = pptr;
320 if (num_rooms_purged > 0) CtdlAideMessage(transcript, "Room Autopurger Message");
323 syslog(LOG_DEBUG, "Purged %d rooms.", num_rooms_purged);
324 return(num_rooms_purged);
328 // Back end function to check user accounts for expiration.
329 void do_user_purge(char *username, void *data) {
333 struct PurgeList *pptr;
336 if (CtdlGetUser(&us, username) != 0) {
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;
345 purge_time = CtdlGetConfigLong("c_userpurge") * 86400;
348 // The default rule is to not purge.
351 // If the user has not logged in for the configured amount of time, expire the account.
352 if (CtdlGetConfigLong("c_userpurge") > 0) {
354 if ((now - us.lastcall) > purge_time) purge = 1;
357 // If the account is marked as permanent, don't purge it.
358 if (us.flags & US_PERM) purge = 0;
360 // If the account is an administrator, don't purge it.
361 if (us.axlevel == 6) purge = 0;
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;
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;
373 // Fewer than zero calls is impossible, indicating a corrupted record.
374 if (us.timescalled < 0) purge = 1;
376 // any negative user number, is also impossible.
377 if (us.usernum < 0L) purge = 1;
379 // Don't purge user 0. That user is there for the system
380 if (us.usernum == 0L) purge = 0;
382 // If the user has no full name entry then we can't purge them since the actual purge can't find them.
383 // This shouldn't happen but does somehow.
384 if (IsEmptyStr(us.fullname)) {
387 if (us.usernum > 0L) {
389 if (users_corrupt_msg == NULL) {
390 users_corrupt_msg = malloc(SIZ);
391 strcpy(users_corrupt_msg,
392 "The auto-purger found the following user numbers with no name.\n"
393 "The system has no way to purge a user with no name,"
394 " and should not be able to create them either.\n"
395 "This indicates corruption of the user DB or possibly a bug.\n"
396 "It may be a good idea to restore your DB from a backup.\n"
400 users_corrupt_msg=realloc(users_corrupt_msg, strlen(users_corrupt_msg)+30);
401 snprintf(&users_corrupt_msg[strlen(users_corrupt_msg)], 29, " %ld\n", us.usernum);
406 pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
407 pptr->next = UserPurgeList;
408 strcpy(pptr->name, us.fullname);
409 UserPurgeList = pptr;
418 int PurgeUsers(void) {
419 struct PurgeList *pptr;
420 int num_users_purged = 0;
421 char *transcript = NULL;
423 syslog(LOG_DEBUG, "PurgeUsers() called");
424 users_not_purged = 0;
426 switch(CtdlGetConfigInt("c_auth_mode")) {
427 case AUTHMODE_NATIVE:
428 ForEachUser(do_user_purge, NULL);
431 syslog(LOG_DEBUG, "User purge for auth mode %d is not implemented.", CtdlGetConfigInt("c_auth_mode"));
435 transcript = malloc(SIZ);
437 if (users_not_purged == 0) {
438 strcpy(transcript, "The auto-purger was told to purge every user. It is\n"
439 "refusing to do this because it usually indicates a problem\n"
440 "such as an inability to communicate with a name service.\n"
442 while (UserPurgeList != NULL) {
443 pptr = UserPurgeList->next;
445 UserPurgeList = pptr;
451 strcpy(transcript, "The following users have been auto-purged:\n");
452 while (UserPurgeList != NULL) {
453 transcript=realloc(transcript, strlen(transcript)+SIZ);
454 snprintf(&transcript[strlen(transcript)], SIZ, " %s\n", UserPurgeList->name);
455 purge_user(UserPurgeList->name);
456 pptr = UserPurgeList->next;
458 UserPurgeList = pptr;
463 if (num_users_purged > 0) CtdlAideMessage(transcript, "User Purge Message");
466 if (users_corrupt_msg) {
467 CtdlAideMessage(users_corrupt_msg, "User Corruption Message");
468 free (users_corrupt_msg);
469 users_corrupt_msg = NULL;
473 CtdlAideMessage(users_zero_msg, "User Zero Message");
474 free (users_zero_msg);
475 users_zero_msg = NULL;
478 syslog(LOG_DEBUG, "Purged %d users.", num_users_purged);
479 return(num_users_purged);
485 // This is a really cumbersome "garbage collection" function. We have to
486 // delete visits which refer to rooms and/or users which no longer exist. In
487 // order to prevent endless traversals of the room and user files, we first
488 // build linked lists of rooms and users which _do_ exist on the system, then
489 // traverse the visit file, checking each record against those two lists and
490 // purging the ones that do not have a match on _both_ lists. (Remember, if
491 // either the room or user being referred to is no longer on the system, the
492 // record is useless and should be removed.)
494 int PurgeVisits(void) {
495 struct cdbdata *cdbvisit;
497 struct VPurgeList *VisitPurgeList = NULL;
498 struct VPurgeList *vptr;
502 struct ValidRoom *vrptr;
503 struct ValidUser *vuptr;
504 int RoomIsValid, UserIsValid;
506 // First, load up a table full of valid room/gen combinations
507 CtdlForEachRoom(AddValidRoom, NULL);
509 // Then load up a table full of valid user numbers
510 ForEachUser(AddValidUser, NULL);
512 // Now traverse through the visits, purging irrelevant records...
513 cdb_rewind(CDB_VISIT);
514 while(cdbvisit = cdb_next_item(CDB_VISIT), cdbvisit != NULL) {
515 memset(&vbuf, 0, sizeof(struct visit));
516 memcpy(&vbuf, cdbvisit->ptr,
517 ( (cdbvisit->len > sizeof(struct visit)) ?
518 sizeof(struct visit) : cdbvisit->len) );
524 // Check to see if the room exists
525 for (vrptr=ValidRoomList; vrptr!=NULL; vrptr=vrptr->next) {
526 if ( (vrptr->vr_roomnum==vbuf.v_roomnum)
527 && (vrptr->vr_roomgen==vbuf.v_roomgen))
531 // Check to see if the user exists
532 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
533 if (vuptr->vu_usernum == vbuf.v_usernum)
537 // Put the record on the purge list if it's dead
538 if ((RoomIsValid==0) || (UserIsValid==0)) {
539 vptr = (struct VPurgeList *)
540 malloc(sizeof(struct VPurgeList));
541 vptr->next = VisitPurgeList;
542 vptr->vp_roomnum = vbuf.v_roomnum;
543 vptr->vp_roomgen = vbuf.v_roomgen;
544 vptr->vp_usernum = vbuf.v_usernum;
545 VisitPurgeList = vptr;
550 // Free the valid room/gen combination list
551 while (ValidRoomList != NULL) {
552 vrptr = ValidRoomList->next;
554 ValidRoomList = vrptr;
557 // Free the valid user list
558 while (ValidUserList != NULL) {
559 vuptr = ValidUserList->next;
561 ValidUserList = vuptr;
564 // Now delete every visit on the purged list
565 while (VisitPurgeList != NULL) {
566 IndexLen = GenerateRelationshipIndex(IndexBuf,
567 VisitPurgeList->vp_roomnum,
568 VisitPurgeList->vp_roomgen,
569 VisitPurgeList->vp_usernum);
570 cdb_delete(CDB_VISIT, IndexBuf, IndexLen);
571 vptr = VisitPurgeList->next;
572 free(VisitPurgeList);
573 VisitPurgeList = vptr;
581 // Purge the use table of old entries.
582 // Holy crap, this is WAY better. We need to replace most linked lists with arrays.
583 int PurgeUseTable(StrBuf *ErrMsg) {
586 struct cdbdata *cdbut;
588 Array *purge_list = array_new(sizeof(int));
590 // Phase 1: traverse through the table, discovering old records...
592 syslog(LOG_DEBUG, "Purge use table: phase 1");
593 cdb_rewind(CDB_USETABLE);
594 while(cdbut = cdb_next_item(CDB_USETABLE), cdbut != NULL) {
596 if (cdbut->len > sizeof(struct UseTable))
597 memcpy(&ut, cdbut->ptr, sizeof(struct UseTable));
599 memset(&ut, 0, sizeof(struct UseTable));
600 memcpy(&ut, cdbut->ptr, cdbut->len);
604 if ( (time(NULL) - ut.timestamp) > USETABLE_RETAIN ) {
605 array_append(purge_list, &ut.hash);
610 // Phase 2: delete the records
611 syslog(LOG_DEBUG, "Purge use table: phase 2");
613 for (i=0; i<purged; ++i) {
614 struct UseTable *u = (struct UseTable *)array_get_element_at(purge_list, i);
615 cdb_delete(CDB_USETABLE, &u->hash, sizeof(int));
617 array_free(purge_list);
619 syslog(LOG_DEBUG, "Purge use table: finished (purged %d of %d records)", purged, total);
624 // Purge the EUID Index of old records.
625 int PurgeEuidIndexTable(void) {
627 struct cdbdata *cdbei;
628 struct EPurgeList *el = NULL;
629 struct EPurgeList *eptr;
631 struct CtdlMessage *msg = NULL;
633 // Phase 1: traverse through the table, discovering old records...
634 syslog(LOG_DEBUG, "Purge EUID index: phase 1");
635 cdb_rewind(CDB_EUIDINDEX);
636 while(cdbei = cdb_next_item(CDB_EUIDINDEX), cdbei != NULL) {
638 memcpy(&msgnum, cdbei->ptr, sizeof(long));
640 msg = CtdlFetchMessage(msgnum, 0);
642 CM_Free(msg); // it still exists, so do nothing
645 eptr = (struct EPurgeList *) malloc(sizeof(struct EPurgeList));
648 eptr->ep_keylen = cdbei->len - sizeof(long);
649 eptr->ep_key = malloc(cdbei->len);
650 memcpy(eptr->ep_key, &cdbei->ptr[sizeof(long)], eptr->ep_keylen);
660 // Phase 2: delete the records
661 syslog(LOG_DEBUG, "Purge euid index: phase 2");
663 cdb_delete(CDB_EUIDINDEX, el->ep_key, el->ep_keylen);
670 syslog(LOG_DEBUG, "Purge euid index: finished (purged %d records)", purged);
675 void purge_databases(void) {
677 static time_t last_purge = 0;
681 // Do the auto-purge if the current hour equals the purge hour,
682 // but not if the operation has already been performed in the
683 // last twelve hours. This is usually enough granularity.
685 localtime_r(&now, &tm);
686 if (((tm.tm_hour != CtdlGetConfigInt("c_purge_hour")) || ((now - last_purge) < 43200)) && (force_purge_now == 0)) {
690 syslog(LOG_INFO, "Auto-purger: starting.");
692 if (!server_shutting_down) {
693 retval = PurgeUsers();
694 syslog(LOG_NOTICE, "Purged %d users.", retval);
697 if (!server_shutting_down) {
699 syslog(LOG_NOTICE, "Expired %d messages.", messages_purged);
702 if (!server_shutting_down) {
703 retval = PurgeRooms();
704 syslog(LOG_NOTICE, "Expired %d rooms.", retval);
707 if (!server_shutting_down) {
708 retval = PurgeVisits();
709 syslog(LOG_NOTICE, "Purged %d visits.", retval);
712 if (!server_shutting_down) {
714 ErrMsg = NewStrBuf();
715 retval = PurgeUseTable(ErrMsg);
716 syslog(LOG_NOTICE, "Purged %d entries from the use table.", retval);
720 if (!server_shutting_down) {
721 retval = PurgeEuidIndexTable();
722 syslog(LOG_NOTICE, "Purged %d entries from the EUID index.", retval);
725 //if (!server_shutting_down) {
726 // FIXME this is where we could do a non-interactive delete of zero-refcount messages
729 if ( (!server_shutting_down) && (CtdlGetConfigInt("c_shrink_db_files") != 0) ) {
730 cdb_compact(); // Shrink the DB files on disk
733 if (!server_shutting_down) {
734 syslog(LOG_INFO, "Auto-purger: finished.");
735 last_purge = now; // So we don't do it again soon
739 syslog(LOG_INFO, "Auto-purger: STOPPED.");
744 // Manually initiate a run of The Dreaded Auto-Purger (tm)
745 void cmd_tdap(char *argbuf) {
746 if (CtdlAccessCheck(ac_aide)) return;
748 cprintf("%d Manually initiating a purger run now.\n", CIT_OK);
752 // Initialization function, called from modules_init.c
753 char *ctdl_module_init_expire(void) {
755 CtdlRegisterProtoHook(cmd_tdap, "TDAP", "Manually initiate auto-purger");
756 CtdlRegisterProtoHook(cmd_gpex, "GPEX", "Get expire policy");
757 CtdlRegisterProtoHook(cmd_spex, "SPEX", "Set expire policy");
758 CtdlRegisterSessionHook(purge_databases, EVT_TIMER, PRIO_CLEANUP + 20);
761 // return our module name for the log