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 // any negative user number, is also impossible.
374 if (us.usernum < 0L) purge = 1;
376 // Don't purge user 0. That user is there for the system
377 if (us.usernum == 0L) purge = 0;
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)) {
384 if (us.usernum > 0L) {
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"
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);
403 pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
404 pptr->next = UserPurgeList;
405 strcpy(pptr->name, us.fullname);
406 UserPurgeList = pptr;
415 int PurgeUsers(void) {
416 struct PurgeList *pptr;
417 int num_users_purged = 0;
418 char *transcript = NULL;
420 syslog(LOG_DEBUG, "PurgeUsers() called");
421 users_not_purged = 0;
423 switch(CtdlGetConfigInt("c_auth_mode")) {
424 case AUTHMODE_NATIVE:
425 ForEachUser(do_user_purge, NULL);
428 syslog(LOG_DEBUG, "User purge for auth mode %d is not implemented.", CtdlGetConfigInt("c_auth_mode"));
432 transcript = malloc(SIZ);
434 if (users_not_purged == 0) {
435 strcpy(transcript, "The auto-purger was told to purge every user. It is\n"
436 "refusing to do this because it usually indicates a problem\n"
437 "such as an inability to communicate with a name service.\n"
439 while (UserPurgeList != NULL) {
440 pptr = UserPurgeList->next;
442 UserPurgeList = pptr;
448 strcpy(transcript, "The following users have been auto-purged:\n");
449 while (UserPurgeList != NULL) {
450 transcript=realloc(transcript, strlen(transcript)+SIZ);
451 snprintf(&transcript[strlen(transcript)], SIZ, " %s\n", UserPurgeList->name);
452 purge_user(UserPurgeList->name);
453 pptr = UserPurgeList->next;
455 UserPurgeList = pptr;
460 if (num_users_purged > 0) CtdlAideMessage(transcript, "User Purge Message");
463 if (users_corrupt_msg) {
464 CtdlAideMessage(users_corrupt_msg, "User Corruption Message");
465 free (users_corrupt_msg);
466 users_corrupt_msg = NULL;
470 CtdlAideMessage(users_zero_msg, "User Zero Message");
471 free (users_zero_msg);
472 users_zero_msg = NULL;
475 syslog(LOG_DEBUG, "Purged %d users.", num_users_purged);
476 return(num_users_purged);
482 // This is a really cumbersome "garbage collection" function. We have to
483 // delete visits which refer to rooms and/or users which no longer exist. In
484 // order to prevent endless traversals of the room and user files, we first
485 // build linked lists of rooms and users which _do_ exist on the system, then
486 // traverse the visit file, checking each record against those two lists and
487 // purging the ones that do not have a match on _both_ lists. (Remember, if
488 // either the room or user being referred to is no longer on the system, the
489 // record is useless and should be removed.)
491 int PurgeVisits(void) {
492 struct cdbdata *cdbvisit;
494 struct VPurgeList *VisitPurgeList = NULL;
495 struct VPurgeList *vptr;
499 struct ValidRoom *vrptr;
500 struct ValidUser *vuptr;
501 int RoomIsValid, UserIsValid;
503 // First, load up a table full of valid room/gen combinations
504 CtdlForEachRoom(AddValidRoom, NULL);
506 // Then load up a table full of valid user numbers
507 ForEachUser(AddValidUser, NULL);
509 // Now traverse through the visits, purging irrelevant records...
510 cdb_rewind(CDB_VISIT);
511 while(cdbvisit = cdb_next_item(CDB_VISIT), cdbvisit != NULL) {
512 memset(&vbuf, 0, sizeof(struct visit));
513 memcpy(&vbuf, cdbvisit->ptr,
514 ( (cdbvisit->len > sizeof(struct visit)) ?
515 sizeof(struct visit) : cdbvisit->len) );
521 // Check to see if the room exists
522 for (vrptr=ValidRoomList; vrptr!=NULL; vrptr=vrptr->next) {
523 if ( (vrptr->vr_roomnum==vbuf.v_roomnum)
524 && (vrptr->vr_roomgen==vbuf.v_roomgen))
528 // Check to see if the user exists
529 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
530 if (vuptr->vu_usernum == vbuf.v_usernum)
534 // Put the record on the purge list if it's dead
535 if ((RoomIsValid==0) || (UserIsValid==0)) {
536 vptr = (struct VPurgeList *)
537 malloc(sizeof(struct VPurgeList));
538 vptr->next = VisitPurgeList;
539 vptr->vp_roomnum = vbuf.v_roomnum;
540 vptr->vp_roomgen = vbuf.v_roomgen;
541 vptr->vp_usernum = vbuf.v_usernum;
542 VisitPurgeList = vptr;
547 // Free the valid room/gen combination list
548 while (ValidRoomList != NULL) {
549 vrptr = ValidRoomList->next;
551 ValidRoomList = vrptr;
554 // Free the valid user list
555 while (ValidUserList != NULL) {
556 vuptr = ValidUserList->next;
558 ValidUserList = vuptr;
561 // Now delete every visit on the purged list
562 while (VisitPurgeList != NULL) {
563 IndexLen = GenerateRelationshipIndex(IndexBuf,
564 VisitPurgeList->vp_roomnum,
565 VisitPurgeList->vp_roomgen,
566 VisitPurgeList->vp_usernum);
567 cdb_delete(CDB_VISIT, IndexBuf, IndexLen);
568 vptr = VisitPurgeList->next;
569 free(VisitPurgeList);
570 VisitPurgeList = vptr;
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) {
583 struct cdbdata *cdbut;
585 Array *purge_list = array_new(sizeof(int));
587 // Phase 1: traverse through the table, discovering old records...
589 syslog(LOG_DEBUG, "Purge use table: phase 1");
590 cdb_rewind(CDB_USETABLE);
591 while(cdbut = cdb_next_item(CDB_USETABLE), cdbut != NULL) {
593 if (cdbut->len > sizeof(struct UseTable))
594 memcpy(&ut, cdbut->ptr, sizeof(struct UseTable));
596 memset(&ut, 0, sizeof(struct UseTable));
597 memcpy(&ut, cdbut->ptr, cdbut->len);
601 if ( (time(NULL) - ut.timestamp) > USETABLE_RETAIN ) {
602 array_append(purge_list, &ut.hash);
607 // Phase 2: delete the records
608 syslog(LOG_DEBUG, "Purge use table: phase 2");
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));
614 array_free(purge_list);
616 syslog(LOG_DEBUG, "Purge use table: finished (purged %d of %d records)", purged, total);
621 // Purge the EUID Index of old records.
622 int PurgeEuidIndexTable(void) {
624 struct cdbdata *cdbei;
625 struct EPurgeList *el = NULL;
626 struct EPurgeList *eptr;
628 struct CtdlMessage *msg = NULL;
630 // Phase 1: traverse through the table, discovering old records...
631 syslog(LOG_DEBUG, "Purge EUID index: phase 1");
632 cdb_rewind(CDB_EUIDINDEX);
633 while(cdbei = cdb_next_item(CDB_EUIDINDEX), cdbei != NULL) {
635 memcpy(&msgnum, cdbei->ptr, sizeof(long));
637 msg = CtdlFetchMessage(msgnum, 0);
639 CM_Free(msg); // it still exists, so do nothing
642 eptr = (struct EPurgeList *) malloc(sizeof(struct EPurgeList));
645 eptr->ep_keylen = cdbei->len - sizeof(long);
646 eptr->ep_key = malloc(cdbei->len);
647 memcpy(eptr->ep_key, &cdbei->ptr[sizeof(long)], eptr->ep_keylen);
657 // Phase 2: delete the records
658 syslog(LOG_DEBUG, "Purge euid index: phase 2");
660 cdb_delete(CDB_EUIDINDEX, el->ep_key, el->ep_keylen);
667 syslog(LOG_DEBUG, "Purge euid index: finished (purged %d records)", purged);
672 void purge_databases(void) {
674 static time_t last_purge = 0;
678 // Do the auto-purge if the current hour equals the purge hour,
679 // but not if the operation has already been performed in the
680 // last twelve hours. This is usually enough granularity.
682 localtime_r(&now, &tm);
683 if (((tm.tm_hour != CtdlGetConfigInt("c_purge_hour")) || ((now - last_purge) < 43200)) && (force_purge_now == 0)) {
687 syslog(LOG_INFO, "Auto-purger: starting.");
689 if (!server_shutting_down) {
690 retval = PurgeUsers();
691 syslog(LOG_NOTICE, "Purged %d users.", retval);
694 if (!server_shutting_down) {
696 syslog(LOG_NOTICE, "Expired %d messages.", messages_purged);
699 if (!server_shutting_down) {
700 retval = PurgeRooms();
701 syslog(LOG_NOTICE, "Expired %d rooms.", retval);
704 if (!server_shutting_down) {
705 retval = PurgeVisits();
706 syslog(LOG_NOTICE, "Purged %d visits.", retval);
709 if (!server_shutting_down) {
711 ErrMsg = NewStrBuf();
712 retval = PurgeUseTable(ErrMsg);
713 syslog(LOG_NOTICE, "Purged %d entries from the use table.", retval);
717 if (!server_shutting_down) {
718 retval = PurgeEuidIndexTable();
719 syslog(LOG_NOTICE, "Purged %d entries from the EUID index.", retval);
722 //if (!server_shutting_down) {
723 // FIXME this is where we could do a non-interactive delete of zero-refcount messages
726 if ( (!server_shutting_down) && (CtdlGetConfigInt("c_shrink_db_files") != 0) ) {
727 cdb_compact(); // Shrink the DB files on disk
730 if (!server_shutting_down) {
731 syslog(LOG_INFO, "Auto-purger: finished.");
732 last_purge = now; // So we don't do it again soon
736 syslog(LOG_INFO, "Auto-purger: STOPPED.");
741 // Manually initiate a run of The Dreaded Auto-Purger (tm)
742 void cmd_tdap(char *argbuf) {
743 if (CtdlAccessCheck(ac_aide)) return;
745 cprintf("%d Manually initiating a purger run now.\n", CIT_OK);
749 // Initialization function, called from modules_init.c
750 char *ctdl_module_init_expire(void) {
752 CtdlRegisterProtoHook(cmd_tdap, "TDAP", "Manually initiate auto-purger");
753 CtdlRegisterProtoHook(cmd_gpex, "GPEX", "Get expire policy");
754 CtdlRegisterProtoHook(cmd_spex, "SPEX", "Set expire policy");
755 CtdlRegisterSessionHook(purge_databases, EVT_TIMER, PRIO_CLEANUP + 20);
758 // return our module name for the log