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.
117 num_msgs = CtdlFetchMsgList(qrbuf->QRnumber, &msglist);
120 // Nothing to do if there aren't any messages
122 if (msglist != NULL) free(msglist);
126 // If the room is set to expire by count, do that.
127 if (epbuf.expire_mode == EXPIRE_NUMMSGS) {
129 if (num_msgs > epbuf.expire_value) {
130 for (a=0; a<(num_msgs - epbuf.expire_value); ++a) {
131 fprintf(purgelist, "m=%ld\n", msglist[a]);
137 // If the room is set to expire by age...
138 if (epbuf.expire_mode == EXPIRE_AGE) {
140 for (a=0; a<num_msgs; ++a) {
142 msg = CtdlFetchMessage(delnum, 0); // don't need the body
144 xtime = atol(msg->cm_fields[eTimestamp]);
151 if ((xtime > 0L) && (now - xtime > (time_t)(epbuf.expire_value * 86400L))) {
152 fprintf(purgelist, "m=%ld\n", delnum);
158 if (msglist != NULL) {
164 // Second phase of message purge -- read list of msgs from temp file and delete them.
165 void DoPurgeMessages(FILE *purgelist) {
166 char roomname[ROOMNAMELEN];
171 strcpy(roomname, "nonexistent room ___ ___");
172 while (fgets(buf, sizeof buf, purgelist) != NULL) {
173 buf[strlen(buf)-1]=0;
174 if (!strncasecmp(buf, "r=", 2)) {
175 strcpy(roomname, &buf[2]);
177 if (!strncasecmp(buf, "m=", 2)) {
178 msgnum = atol(&buf[2]);
180 CtdlDeleteMessages(roomname, &msgnum, 1, "");
187 void PurgeMessages(void) {
190 syslog(LOG_DEBUG, "PurgeMessages() called");
193 purgelist = tmpfile();
194 if (purgelist == NULL) {
195 syslog(LOG_CRIT, "Can't create purgelist temp file: %s", strerror(errno));
199 CtdlForEachRoom(GatherPurgeMessages, (void *)purgelist );
200 DoPurgeMessages(purgelist);
205 void AddValidUser(char *username, void *data) {
206 struct ValidUser *vuptr;
207 struct ctdluser usbuf;
209 if (CtdlGetUser(&usbuf, username) != 0) {
213 vuptr = (struct ValidUser *)malloc(sizeof(struct ValidUser));
214 vuptr->next = ValidUserList;
215 vuptr->vu_usernum = usbuf.usernum;
216 ValidUserList = vuptr;
220 void AddValidRoom(struct ctdlroom *qrbuf, void *data) {
221 struct ValidRoom *vrptr;
223 vrptr = (struct ValidRoom *)malloc(sizeof(struct ValidRoom));
224 vrptr->next = ValidRoomList;
225 vrptr->vr_roomnum = qrbuf->QRnumber;
226 vrptr->vr_roomgen = qrbuf->QRgen;
227 ValidRoomList = vrptr;
231 void DoPurgeRooms(struct ctdlroom *qrbuf, void *data) {
232 time_t age, purge_secs;
233 struct PurgeList *pptr;
234 struct ValidUser *vuptr;
237 // For mailbox rooms, there's only one purging rule: if the user who
238 // owns the room still exists, we keep the room; otherwise, we purge
239 // it. Bypass any other rules.
240 if (qrbuf->QRflags & QR_MAILBOX) {
241 // if user not found, do_purge will be 1
243 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
244 if (vuptr->vu_usernum == atol(qrbuf->QRname)) {
250 // Any of these attributes render a room non-purgable
251 if (qrbuf->QRflags & QR_PERMANENT) return;
252 if (qrbuf->QRflags & QR_DIRECTORY) return;
253 if (qrbuf->QRflags2 & QR2_SYSTEM) return;
254 if (!strcasecmp(qrbuf->QRname, SYSCONFIGROOM)) return;
255 if (CtdlIsNonEditable(qrbuf)) return;
257 // If we don't know the modification date, be safe and don't purge
258 if (qrbuf->QRmtime <= (time_t)0) return;
260 // If no room purge time is set, be safe and don't purge
261 if (CtdlGetConfigLong("c_roompurge") < 0) return;
263 // Otherwise, check the date of last modification
264 age = time(NULL) - (qrbuf->QRmtime);
265 purge_secs = CtdlGetConfigLong("c_roompurge") * 86400;
266 if (purge_secs <= (time_t)0) return;
267 syslog(LOG_DEBUG, "<%s> is <%ld> seconds old", qrbuf->QRname, (long)age);
268 if (age > purge_secs) do_purge = 1;
272 pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
273 pptr->next = RoomPurgeList;
274 strcpy(pptr->name, qrbuf->QRname);
275 RoomPurgeList = pptr;
281 int PurgeRooms(void) {
282 struct PurgeList *pptr;
283 int num_rooms_purged = 0;
284 struct ctdlroom qrbuf;
285 struct ValidUser *vuptr;
286 char *transcript = NULL;
288 syslog(LOG_DEBUG, "PurgeRooms() called");
290 // Load up a table full of valid user numbers so we can delete
291 // user-owned rooms for users who no longer exist
292 ForEachUser(AddValidUser, NULL);
294 // Then cycle through the room file
295 CtdlForEachRoom(DoPurgeRooms, NULL);
297 // Free the valid user list
298 while (ValidUserList != NULL) {
299 vuptr = ValidUserList->next;
301 ValidUserList = vuptr;
304 transcript = malloc(SIZ);
305 strcpy(transcript, "The following rooms have been auto-purged:\n");
307 while (RoomPurgeList != NULL) {
308 if (CtdlGetRoom(&qrbuf, RoomPurgeList->name) == 0) {
309 transcript=realloc(transcript, strlen(transcript)+SIZ);
310 snprintf(&transcript[strlen(transcript)], SIZ, " %s\n", qrbuf.QRname);
311 CtdlDeleteRoom(&qrbuf);
314 pptr = RoomPurgeList->next;
316 RoomPurgeList = pptr;
319 if (num_rooms_purged > 0) CtdlAideMessage(transcript, "Room Autopurger Message");
322 syslog(LOG_DEBUG, "Purged %d rooms.", num_rooms_purged);
323 return(num_rooms_purged);
327 // Back end function to check user accounts for expiration.
328 void do_user_purge(char *username, void *data) {
332 struct PurgeList *pptr;
335 if (CtdlGetUser(&us, username) != 0) {
339 // Set purge time; if the user overrides the system default, use it
340 if (us.USuserpurge > 0) {
341 purge_time = ((time_t)us.USuserpurge) * 86400;
344 purge_time = CtdlGetConfigLong("c_userpurge") * 86400;
347 // The default rule is to not purge.
350 // If the user has not logged in for the configured amount of time, expire the account.
351 if (CtdlGetConfigLong("c_userpurge") > 0) {
353 if ((now - us.lastcall) > purge_time) purge = 1;
356 // If the account is marked as permanent, don't purge it.
357 if (us.flags & US_PERM) purge = 0;
359 // If the account is an administrator, don't purge it.
360 if (us.axlevel == 6) purge = 0;
362 // If the access level is 0, the record should already have been
363 // deleted, but maybe the user was logged in at the time or something.
364 // Delete the record now.
365 if (us.axlevel == 0) purge = 1;
367 // If the user set his/her password to 'deleteme', he/she
368 // wishes to be deleted, so purge the record.
369 // Moved this lower down so that aides and permanent users get purged if they ask to be.
370 if (!strcasecmp(us.password, "deleteme")) purge = 1;
372 // any negative user number, is also impossible.
373 if (us.usernum < 0L) purge = 1;
375 // Don't purge user 0. That user is there for the system
376 if (us.usernum == 0L) purge = 0;
378 // If the user has no full name entry then we can't purge them since the actual purge can't find them.
379 // This shouldn't happen but does somehow.
380 if (IsEmptyStr(us.fullname)) {
383 if (us.usernum > 0L) {
385 if (users_corrupt_msg == NULL) {
386 users_corrupt_msg = malloc(SIZ);
387 strcpy(users_corrupt_msg,
388 "The auto-purger found the following user numbers with no name.\n"
389 "The system has no way to purge a user with no name,"
390 " and should not be able to create them either.\n"
391 "This indicates corruption of the user DB or possibly a bug.\n"
392 "It may be a good idea to restore your DB from a backup.\n"
396 users_corrupt_msg=realloc(users_corrupt_msg, strlen(users_corrupt_msg)+30);
397 snprintf(&users_corrupt_msg[strlen(users_corrupt_msg)], 29, " %ld\n", us.usernum);
402 pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
403 pptr->next = UserPurgeList;
404 strcpy(pptr->name, us.fullname);
405 UserPurgeList = pptr;
414 int PurgeUsers(void) {
415 struct PurgeList *pptr;
416 int num_users_purged = 0;
417 char *transcript = NULL;
419 syslog(LOG_DEBUG, "PurgeUsers() called");
420 users_not_purged = 0;
422 switch(CtdlGetConfigInt("c_auth_mode")) {
423 case AUTHMODE_NATIVE:
424 ForEachUser(do_user_purge, NULL);
427 syslog(LOG_DEBUG, "User purge for auth mode %d is not implemented.", CtdlGetConfigInt("c_auth_mode"));
431 transcript = malloc(SIZ);
433 if (users_not_purged == 0) {
434 strcpy(transcript, "The auto-purger was told to purge every user. It is\n"
435 "refusing to do this because it usually indicates a problem\n"
436 "such as an inability to communicate with a name service.\n"
438 while (UserPurgeList != NULL) {
439 pptr = UserPurgeList->next;
441 UserPurgeList = pptr;
447 strcpy(transcript, "The following users have been auto-purged:\n");
448 while (UserPurgeList != NULL) {
449 transcript=realloc(transcript, strlen(transcript)+SIZ);
450 snprintf(&transcript[strlen(transcript)], SIZ, " %s\n", UserPurgeList->name);
451 purge_user(UserPurgeList->name);
452 pptr = UserPurgeList->next;
454 UserPurgeList = pptr;
459 if (num_users_purged > 0) CtdlAideMessage(transcript, "User Purge Message");
462 if (users_corrupt_msg) {
463 CtdlAideMessage(users_corrupt_msg, "User Corruption Message");
464 free (users_corrupt_msg);
465 users_corrupt_msg = NULL;
469 CtdlAideMessage(users_zero_msg, "User Zero Message");
470 free (users_zero_msg);
471 users_zero_msg = NULL;
474 syslog(LOG_DEBUG, "Purged %d users.", num_users_purged);
475 return(num_users_purged);
481 // This is a really cumbersome "garbage collection" function. We have to
482 // delete visits which refer to rooms and/or users which no longer exist. In
483 // order to prevent endless traversals of the room and user files, we first
484 // build linked lists of rooms and users which _do_ exist on the system, then
485 // traverse the visit file, checking each record against those two lists and
486 // purging the ones that do not have a match on _both_ lists. (Remember, if
487 // either the room or user being referred to is no longer on the system, the
488 // record is useless and should be removed.)
490 int PurgeVisits(void) {
491 struct cdbdata *cdbvisit;
493 struct VPurgeList *VisitPurgeList = NULL;
494 struct VPurgeList *vptr;
498 struct ValidRoom *vrptr;
499 struct ValidUser *vuptr;
500 int RoomIsValid, UserIsValid;
502 // First, load up a table full of valid room/gen combinations
503 CtdlForEachRoom(AddValidRoom, NULL);
505 // Then load up a table full of valid user numbers
506 ForEachUser(AddValidUser, NULL);
508 // Now traverse through the visits, purging irrelevant records...
509 cdb_rewind(CDB_VISIT);
510 while(cdbvisit = cdb_next_item(CDB_VISIT), cdbvisit != NULL) {
511 memset(&vbuf, 0, sizeof(struct visit));
512 memcpy(&vbuf, cdbvisit->ptr,
513 ( (cdbvisit->len > sizeof(struct visit)) ?
514 sizeof(struct visit) : cdbvisit->len) );
520 // Check to see if the room exists
521 for (vrptr=ValidRoomList; vrptr!=NULL; vrptr=vrptr->next) {
522 if ( (vrptr->vr_roomnum==vbuf.v_roomnum)
523 && (vrptr->vr_roomgen==vbuf.v_roomgen))
527 // Check to see if the user exists
528 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
529 if (vuptr->vu_usernum == vbuf.v_usernum)
533 // Put the record on the purge list if it's dead
534 if ((RoomIsValid==0) || (UserIsValid==0)) {
535 vptr = (struct VPurgeList *)
536 malloc(sizeof(struct VPurgeList));
537 vptr->next = VisitPurgeList;
538 vptr->vp_roomnum = vbuf.v_roomnum;
539 vptr->vp_roomgen = vbuf.v_roomgen;
540 vptr->vp_usernum = vbuf.v_usernum;
541 VisitPurgeList = vptr;
546 // Free the valid room/gen combination list
547 while (ValidRoomList != NULL) {
548 vrptr = ValidRoomList->next;
550 ValidRoomList = vrptr;
553 // Free the valid user list
554 while (ValidUserList != NULL) {
555 vuptr = ValidUserList->next;
557 ValidUserList = vuptr;
560 // Now delete every visit on the purged list
561 while (VisitPurgeList != NULL) {
562 IndexLen = GenerateRelationshipIndex(IndexBuf,
563 VisitPurgeList->vp_roomnum,
564 VisitPurgeList->vp_roomgen,
565 VisitPurgeList->vp_usernum);
566 cdb_delete(CDB_VISIT, IndexBuf, IndexLen);
567 vptr = VisitPurgeList->next;
568 free(VisitPurgeList);
569 VisitPurgeList = vptr;
577 // Purge the use table of old entries.
578 // Holy crap, this is WAY better. We need to replace most linked lists with arrays.
579 int PurgeUseTable(StrBuf *ErrMsg) {
582 struct cdbdata *cdbut;
584 Array *purge_list = array_new(sizeof(int));
586 // Phase 1: traverse through the table, discovering old records...
588 syslog(LOG_DEBUG, "Purge use table: phase 1");
589 cdb_rewind(CDB_USETABLE);
590 while(cdbut = cdb_next_item(CDB_USETABLE), cdbut != NULL) {
592 if (cdbut->len > sizeof(struct UseTable))
593 memcpy(&ut, cdbut->ptr, sizeof(struct UseTable));
595 memset(&ut, 0, sizeof(struct UseTable));
596 memcpy(&ut, cdbut->ptr, cdbut->len);
600 if ( (time(NULL) - ut.timestamp) > USETABLE_RETAIN ) {
601 array_append(purge_list, &ut.hash);
606 // Phase 2: delete the records
607 syslog(LOG_DEBUG, "Purge use table: phase 2");
609 for (i=0; i<purged; ++i) {
610 struct UseTable *u = (struct UseTable *)array_get_element_at(purge_list, i);
611 cdb_delete(CDB_USETABLE, &u->hash, sizeof(int));
613 array_free(purge_list);
615 syslog(LOG_DEBUG, "Purge use table: finished (purged %d of %d records)", purged, total);
620 // Purge the EUID Index of old records.
621 int PurgeEuidIndexTable(void) {
623 struct cdbdata *cdbei;
624 struct EPurgeList *el = NULL;
625 struct EPurgeList *eptr;
627 struct CtdlMessage *msg = NULL;
629 // Phase 1: traverse through the table, discovering old records...
630 syslog(LOG_DEBUG, "Purge EUID index: phase 1");
631 cdb_rewind(CDB_EUIDINDEX);
632 while(cdbei = cdb_next_item(CDB_EUIDINDEX), cdbei != NULL) {
634 memcpy(&msgnum, cdbei->ptr, sizeof(long));
636 msg = CtdlFetchMessage(msgnum, 0);
638 CM_Free(msg); // it still exists, so do nothing
641 eptr = (struct EPurgeList *) malloc(sizeof(struct EPurgeList));
644 eptr->ep_keylen = cdbei->len - sizeof(long);
645 eptr->ep_key = malloc(cdbei->len);
646 memcpy(eptr->ep_key, &cdbei->ptr[sizeof(long)], eptr->ep_keylen);
656 // Phase 2: delete the records
657 syslog(LOG_DEBUG, "Purge euid index: phase 2");
659 cdb_delete(CDB_EUIDINDEX, el->ep_key, el->ep_keylen);
666 syslog(LOG_DEBUG, "Purge euid index: finished (purged %d records)", purged);
671 void purge_databases(void) {
673 static time_t last_purge = 0;
677 // Do the auto-purge if the current hour equals the purge hour,
678 // but not if the operation has already been performed in the
679 // last twelve hours. This is usually enough granularity.
681 localtime_r(&now, &tm);
682 if (((tm.tm_hour != CtdlGetConfigInt("c_purge_hour")) || ((now - last_purge) < 43200)) && (force_purge_now == 0)) {
686 syslog(LOG_INFO, "Auto-purger: starting.");
688 if (!server_shutting_down) {
689 retval = PurgeUsers();
690 syslog(LOG_NOTICE, "Purged %d users.", retval);
693 if (!server_shutting_down) {
695 syslog(LOG_NOTICE, "Expired %d messages.", messages_purged);
698 if (!server_shutting_down) {
699 retval = PurgeRooms();
700 syslog(LOG_NOTICE, "Expired %d rooms.", retval);
703 if (!server_shutting_down) {
704 retval = PurgeVisits();
705 syslog(LOG_NOTICE, "Purged %d visits.", retval);
708 if (!server_shutting_down) {
710 ErrMsg = NewStrBuf();
711 retval = PurgeUseTable(ErrMsg);
712 syslog(LOG_NOTICE, "Purged %d entries from the use table.", retval);
716 if (!server_shutting_down) {
717 retval = PurgeEuidIndexTable();
718 syslog(LOG_NOTICE, "Purged %d entries from the EUID index.", retval);
721 //if (!server_shutting_down) {
722 // FIXME this is where we could do a non-interactive delete of zero-refcount messages
725 if ( (!server_shutting_down) && (CtdlGetConfigInt("c_shrink_db_files") != 0) ) {
726 cdb_compact(); // Shrink the DB files on disk
729 if (!server_shutting_down) {
730 syslog(LOG_INFO, "Auto-purger: finished.");
731 last_purge = now; // So we don't do it again soon
735 syslog(LOG_INFO, "Auto-purger: STOPPED.");
740 // Manually initiate a run of The Dreaded Auto-Purger (tm)
741 void cmd_tdap(char *argbuf) {
742 if (CtdlAccessCheck(ac_aide)) return;
744 cprintf("%d Manually initiating a purger run now.\n", CIT_OK);
748 // Initialization function, called from modules_init.c
749 char *ctdl_module_init_expire(void) {
751 CtdlRegisterProtoHook(cmd_tdap, "TDAP", "Manually initiate auto-purger");
752 CtdlRegisterProtoHook(cmd_gpex, "GPEX", "Get expire policy");
753 CtdlRegisterProtoHook(cmd_spex, "SPEX", "Set expire policy");
754 CtdlRegisterSessionHook(purge_databases, EVT_TIMER, PRIO_CLEANUP + 20);
757 // return our module name for the log