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 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
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;
95 struct CtdlMessage *msg = NULL;
101 purgelist = (FILE *)data;
102 fprintf(purgelist, "r=%s\n", qrbuf->QRname);
105 GetExpirePolicy(&epbuf, qrbuf);
106 syslog(LOG_DEBUG, "expire: scanning room %ld (%s), policy %d", qrbuf->QRnumber, qrbuf->QRname, epbuf.expire_mode);
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;
112 // Don't purge messages containing system configuration, dumbass.
113 if (!strcasecmp(qrbuf->QRname, SYSCONFIGROOM)) return;
115 // Ok, we got this far ... now let's see what's in the room.
116 num_msgs = CtdlFetchMsgList(qrbuf->QRnumber, &msglist);
118 // Nothing to do if there aren't any messages
124 // If the room is set to expire by count, do that.
125 if (epbuf.expire_mode == EXPIRE_NUMMSGS) {
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]);
135 // If the room is set to expire by age...
136 if (epbuf.expire_mode == EXPIRE_AGE) {
138 for (a=0; a<num_msgs; ++a) {
140 msg = CtdlFetchMessage(delnum, 0); // don't need the body
142 xtime = atol(msg->cm_fields[eTimestamp]);
149 if ((xtime > 0L) && (now - xtime > (time_t)(epbuf.expire_value * 86400L))) {
150 fprintf(purgelist, "m=%ld\n", delnum);
156 if (msglist != NULL) {
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];
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]);
175 if (!strncasecmp(buf, "m=", 2)) {
176 msgnum = atol(&buf[2]);
178 CtdlDeleteMessages(roomname, &msgnum, 1, "");
185 void PurgeMessages(void) {
188 syslog(LOG_DEBUG, "PurgeMessages() called");
191 purgelist = tmpfile();
192 if (purgelist == NULL) {
193 syslog(LOG_CRIT, "Can't create purgelist temp file: %s", strerror(errno));
197 CtdlForEachRoom(GatherPurgeMessages, (void *)purgelist );
198 DoPurgeMessages(purgelist);
203 void AddValidUser(char *username, void *data) {
204 struct ValidUser *vuptr;
205 struct ctdluser usbuf;
207 if (CtdlGetUser(&usbuf, username) != 0) {
211 vuptr = (struct ValidUser *)malloc(sizeof(struct ValidUser));
212 vuptr->next = ValidUserList;
213 vuptr->vu_usernum = usbuf.usernum;
214 ValidUserList = vuptr;
218 void AddValidRoom(struct ctdlroom *qrbuf, void *data) {
219 struct ValidRoom *vrptr;
221 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));
271 pptr->next = RoomPurgeList;
272 strcpy(pptr->name, qrbuf->QRname);
273 RoomPurgeList = pptr;
279 int PurgeRooms(void) {
280 struct PurgeList *pptr;
281 int num_rooms_purged = 0;
282 struct ctdlroom qrbuf;
283 struct ValidUser *vuptr;
284 char *transcript = NULL;
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 transcript = malloc(SIZ);
303 strcpy(transcript, "The following rooms have been auto-purged:\n");
305 while (RoomPurgeList != NULL) {
306 if (CtdlGetRoom(&qrbuf, RoomPurgeList->name) == 0) {
307 transcript=realloc(transcript, strlen(transcript)+SIZ);
308 snprintf(&transcript[strlen(transcript)], SIZ, " %s\n", qrbuf.QRname);
309 CtdlDeleteRoom(&qrbuf);
312 pptr = RoomPurgeList->next;
314 RoomPurgeList = pptr;
317 if (num_rooms_purged > 0) CtdlAideMessage(transcript, "Room Autopurger Message");
320 syslog(LOG_DEBUG, "Purged %d rooms.", num_rooms_purged);
321 return(num_rooms_purged);
325 // Back end function to check user accounts for expiration.
326 void do_user_purge(char *username, void *data) {
330 struct PurgeList *pptr;
333 if (CtdlGetUser(&us, username) != 0) {
337 // Set purge time; if the user overrides the system default, use it
338 if (us.USuserpurge > 0) {
339 purge_time = ((time_t)us.USuserpurge) * 86400;
342 purge_time = CtdlGetConfigLong("c_userpurge") * 86400;
345 // The default rule is to not purge.
348 // If the user has not logged in for the configured amount of time, expire the account.
349 if (CtdlGetConfigLong("c_userpurge") > 0) {
351 if ((now - us.lastcall) > purge_time) purge = 1;
354 // If the account is marked as permanent, don't purge it.
355 if (us.flags & US_PERM) purge = 0;
357 // If the account is an administrator, don't purge it.
358 if (us.axlevel == 6) purge = 0;
360 // If the access level is 0, the record should already have been
361 // deleted, but maybe the user was logged in at the time or something.
362 // Delete the record now.
363 if (us.axlevel == 0) purge = 1;
365 // If the user set his/her password to 'deleteme', he/she
366 // wishes to be deleted, so purge the record.
367 // Moved this lower down so that aides and permanent users get purged if they ask to be.
368 if (!strcasecmp(us.password, "deleteme")) purge = 1;
370 // any negative user number, is also impossible.
371 if (us.usernum < 0L) purge = 1;
373 // Don't purge user 0. That user is there for the system
374 if (us.usernum == 0L) purge = 0;
376 // If the user has no full name entry then we can't purge them since the actual purge can't find them.
377 // This shouldn't happen but does somehow.
378 if (IsEmptyStr(us.fullname)) {
381 if (us.usernum > 0L) {
383 if (users_corrupt_msg == NULL) {
384 users_corrupt_msg = malloc(SIZ);
385 strcpy(users_corrupt_msg,
386 "The auto-purger found the following user numbers with no name.\n"
387 "The system has no way to purge a user with no name,"
388 " and should not be able to create them either.\n"
389 "This indicates corruption of the user DB or possibly a bug.\n"
390 "It may be a good idea to restore your DB from a backup.\n"
394 users_corrupt_msg=realloc(users_corrupt_msg, strlen(users_corrupt_msg)+30);
395 snprintf(&users_corrupt_msg[strlen(users_corrupt_msg)], 29, " %ld\n", us.usernum);
400 pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
401 pptr->next = UserPurgeList;
402 strcpy(pptr->name, us.fullname);
403 UserPurgeList = pptr;
412 int PurgeUsers(void) {
413 struct PurgeList *pptr;
414 int num_users_purged = 0;
415 char *transcript = NULL;
417 syslog(LOG_DEBUG, "PurgeUsers() called");
418 users_not_purged = 0;
420 switch(CtdlGetConfigInt("c_auth_mode")) {
421 case AUTHMODE_NATIVE:
422 ForEachUser(do_user_purge, NULL);
425 syslog(LOG_DEBUG, "User purge for auth mode %d is not implemented.", CtdlGetConfigInt("c_auth_mode"));
429 transcript = malloc(SIZ);
431 if (users_not_purged == 0) {
432 strcpy(transcript, "The auto-purger was told to purge every user. It is\n"
433 "refusing to do this because it usually indicates a problem\n"
434 "such as an inability to communicate with a name service.\n"
436 while (UserPurgeList != NULL) {
437 pptr = UserPurgeList->next;
439 UserPurgeList = pptr;
445 strcpy(transcript, "The following users have been auto-purged:\n");
446 while (UserPurgeList != NULL) {
447 transcript=realloc(transcript, strlen(transcript)+SIZ);
448 snprintf(&transcript[strlen(transcript)], SIZ, " %s\n", UserPurgeList->name);
449 purge_user(UserPurgeList->name);
450 pptr = UserPurgeList->next;
452 UserPurgeList = pptr;
457 if (num_users_purged > 0) CtdlAideMessage(transcript, "User Purge Message");
460 if (users_corrupt_msg) {
461 CtdlAideMessage(users_corrupt_msg, "User Corruption Message");
462 free (users_corrupt_msg);
463 users_corrupt_msg = NULL;
467 CtdlAideMessage(users_zero_msg, "User Zero Message");
468 free (users_zero_msg);
469 users_zero_msg = NULL;
472 syslog(LOG_DEBUG, "Purged %d users.", num_users_purged);
473 return(num_users_purged);
479 // This is a really cumbersome "garbage collection" function. We have to
480 // delete visits which refer to rooms and/or users which no longer exist. In
481 // order to prevent endless traversals of the room and user files, we first
482 // build linked lists of rooms and users which _do_ exist on the system, then
483 // traverse the visit file, checking each record against those two lists and
484 // purging the ones that do not have a match on _both_ lists. (Remember, if
485 // either the room or user being referred to is no longer on the system, the
486 // record is useless and should be removed.)
488 int PurgeVisits(void) {
489 struct cdbdata cdbvisit;
491 struct VPurgeList *VisitPurgeList = NULL;
492 struct VPurgeList *vptr;
496 struct ValidRoom *vrptr;
497 struct ValidUser *vuptr;
498 int RoomIsValid, UserIsValid;
500 // First, load up a table full of valid room/gen combinations
501 CtdlForEachRoom(AddValidRoom, NULL);
503 // Then load up a table full of valid user numbers
504 ForEachUser(AddValidUser, NULL);
506 // Now traverse through the visits, purging irrelevant records...
507 cdb_rewind(CDB_VISIT);
508 while(cdbvisit = cdb_next_item(CDB_VISIT), cdbvisit.ptr!=NULL) {
509 memset(&vbuf, 0, sizeof(struct visit));
510 memcpy(&vbuf, cdbvisit.ptr,
511 ( (cdbvisit.len > sizeof(struct visit)) ?
512 sizeof(struct visit) : cdbvisit.len) );
517 // Check to see if the room exists
518 for (vrptr=ValidRoomList; vrptr!=NULL; vrptr=vrptr->next) {
519 if ( (vrptr->vr_roomnum==vbuf.v_roomnum)
520 && (vrptr->vr_roomgen==vbuf.v_roomgen))
524 // Check to see if the user exists
525 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
526 if (vuptr->vu_usernum == vbuf.v_usernum)
530 // Put the record on the purge list if it's dead
531 if ((RoomIsValid==0) || (UserIsValid==0)) {
532 vptr = (struct VPurgeList *)
533 malloc(sizeof(struct VPurgeList));
534 vptr->next = VisitPurgeList;
535 vptr->vp_roomnum = vbuf.v_roomnum;
536 vptr->vp_roomgen = vbuf.v_roomgen;
537 vptr->vp_usernum = vbuf.v_usernum;
538 VisitPurgeList = vptr;
543 // Free the valid room/gen combination list
544 while (ValidRoomList != NULL) {
545 vrptr = ValidRoomList->next;
547 ValidRoomList = vrptr;
550 // Free the valid user list
551 while (ValidUserList != NULL) {
552 vuptr = ValidUserList->next;
554 ValidUserList = vuptr;
557 // Now delete every visit on the purged list
558 while (VisitPurgeList != NULL) {
559 IndexLen = GenerateRelationshipIndex(IndexBuf,
560 VisitPurgeList->vp_roomnum,
561 VisitPurgeList->vp_roomgen,
562 VisitPurgeList->vp_usernum);
563 cdb_delete(CDB_VISIT, IndexBuf, IndexLen);
564 vptr = VisitPurgeList->next;
565 free(VisitPurgeList);
566 VisitPurgeList = vptr;
574 // Purge the use table of old entries.
575 // Holy crap, this is WAY better. We need to replace most linked lists with arrays.
576 int PurgeUseTable(StrBuf *ErrMsg) {
579 struct cdbdata cdbut;
581 Array *purge_list = array_new(sizeof(int));
583 // Phase 1: traverse through the table, discovering old records...
585 syslog(LOG_DEBUG, "Purge use table: phase 1");
586 cdb_rewind(CDB_USETABLE);
587 while(cdbut = cdb_next_item(CDB_USETABLE), cdbut.ptr!=NULL) {
589 if (cdbut.len > sizeof(struct UseTable))
590 memcpy(&ut, cdbut.ptr, sizeof(struct UseTable));
592 memset(&ut, 0, sizeof(struct UseTable));
593 memcpy(&ut, cdbut.ptr, cdbut.len);
596 if ( (time(NULL) - ut.timestamp) > USETABLE_RETAIN ) {
597 array_append(purge_list, &ut.hash);
602 // Phase 2: delete the records
603 syslog(LOG_DEBUG, "Purge use table: phase 2");
605 for (i=0; i<purged; ++i) {
606 struct UseTable *u = (struct UseTable *)array_get_element_at(purge_list, i);
607 cdb_delete(CDB_USETABLE, &u->hash, sizeof(int));
609 array_free(purge_list);
611 syslog(LOG_DEBUG, "Purge use table: finished (purged %d of %d records)", purged, total);
616 // Purge the EUID Index of old records.
617 int PurgeEuidIndexTable(void) {
619 struct cdbdata cdbei;
620 struct EPurgeList *el = NULL;
621 struct EPurgeList *eptr;
623 struct CtdlMessage *msg = NULL;
625 // Phase 1: traverse through the table, discovering old records...
626 syslog(LOG_DEBUG, "Purge EUID index: phase 1");
627 cdb_rewind(CDB_EUIDINDEX);
628 while(cdbei = cdb_next_item(CDB_EUIDINDEX), cdbei.ptr!=NULL) {
630 memcpy(&msgnum, cdbei.ptr, sizeof(long));
632 msg = CtdlFetchMessage(msgnum, 0);
634 CM_Free(msg); // it still exists, so do nothing
637 eptr = (struct EPurgeList *) malloc(sizeof(struct EPurgeList));
640 eptr->ep_keylen = cdbei.len - sizeof(long);
641 eptr->ep_key = malloc(cdbei.len);
642 memcpy(eptr->ep_key, &cdbei.ptr[sizeof(long)], eptr->ep_keylen);
651 // Phase 2: delete the records
652 syslog(LOG_DEBUG, "Purge euid index: phase 2");
654 cdb_delete(CDB_EUIDINDEX, el->ep_key, el->ep_keylen);
661 syslog(LOG_DEBUG, "Purge euid index: finished (purged %d records)", purged);
666 void purge_databases(void) {
668 static time_t last_purge = 0;
672 // Do the auto-purge if the current hour equals the purge hour,
673 // but not if the operation has already been performed in the
674 // last twelve hours. This is usually enough granularity.
676 localtime_r(&now, &tm);
677 if (((tm.tm_hour != CtdlGetConfigInt("c_purge_hour")) || ((now - last_purge) < 43200)) && (force_purge_now == 0)) {
681 syslog(LOG_INFO, "Auto-purger: starting.");
683 if (!server_shutting_down) {
684 retval = PurgeUsers();
685 syslog(LOG_NOTICE, "Purged %d users.", retval);
688 if (!server_shutting_down) {
690 syslog(LOG_NOTICE, "Expired %d messages.", messages_purged);
693 if (!server_shutting_down) {
694 retval = PurgeRooms();
695 syslog(LOG_NOTICE, "Expired %d rooms.", retval);
698 if (!server_shutting_down) {
699 retval = PurgeVisits();
700 syslog(LOG_NOTICE, "Purged %d visits.", retval);
703 if (!server_shutting_down) {
705 ErrMsg = NewStrBuf();
706 retval = PurgeUseTable(ErrMsg);
707 syslog(LOG_NOTICE, "Purged %d entries from the use table.", retval);
711 if (!server_shutting_down) {
712 retval = PurgeEuidIndexTable();
713 syslog(LOG_NOTICE, "Purged %d entries from the EUID index.", retval);
716 //if (!server_shutting_down) {
717 // FIXME this is where we could do a non-interactive delete of zero-refcount messages
720 if ( (!server_shutting_down) && (CtdlGetConfigInt("c_shrink_db_files") != 0) ) {
721 cdb_compact(); // Shrink the DB files on disk
724 if (!server_shutting_down) {
725 syslog(LOG_INFO, "Auto-purger: finished.");
726 last_purge = now; // So we don't do it again soon
730 syslog(LOG_INFO, "Auto-purger: STOPPED.");
735 // Manually initiate a run of The Dreaded Auto-Purger (tm)
736 void cmd_tdap(char *argbuf) {
737 if (CtdlAccessCheck(ac_aide)) return;
739 cprintf("%d Manually initiating a purger run now.\n", CIT_OK);
743 // Initialization function, called from modules_init.c
744 char *ctdl_module_init_expire(void) {
746 CtdlRegisterProtoHook(cmd_tdap, "TDAP", "Manually initiate auto-purger");
747 CtdlRegisterProtoHook(cmd_gpex, "GPEX", "Get expire policy");
748 CtdlRegisterProtoHook(cmd_spex, "SPEX", "Set expire policy");
749 CtdlRegisterSessionHook(purge_databases, EVT_TIMER, PRIO_CLEANUP + 20);
752 // return our module name for the log