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-2022 by citadel.org (Art Cancro, Wilifried Goesgens, and others)
7 // This program is open source software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as published
9 // by the Free Software Foundation; either version 3 of the License, or
10 // (at your option) any later version.
12 // This program is distributed in the hope that it will be useful,
13 // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 // GNU General Public License for more details.
18 #include "../../sysdep.h"
26 #include <sys/types.h>
31 #include <libcitadel.h>
32 #include "../../citadel_defs.h"
33 #include "../../server.h"
34 #include "../../citserver.h"
35 #include "../../support.h"
36 #include "../../config.h"
38 #include "../../database.h"
39 #include "../../msgbase.h"
40 #include "../../user_ops.h"
41 #include "../../control.h"
42 #include "../../threads.h"
43 #include "../../context.h"
45 #include "../../ctdl_module.h"
49 struct PurgeList *next;
50 char name[ROOMNAMELEN]; // use the larger of username or roomname
54 struct VPurgeList *next;
61 struct ValidRoom *next;
67 struct ValidUser *next;
72 struct ctdlroomref *next;
77 struct UPurgeList *next;
82 struct EPurgeList *next;
88 struct PurgeList *UserPurgeList = NULL;
89 struct PurgeList *RoomPurgeList = NULL;
90 struct ValidRoom *ValidRoomList = NULL;
91 struct ValidUser *ValidUserList = NULL;
94 char *users_corrupt_msg = NULL;
95 char *users_zero_msg = NULL;
96 struct ctdlroomref *rr = NULL;
97 int force_purge_now = 0; // set to nonzero to force a run right now
100 // First phase of message purge -- gather the locations of messages which
101 // qualify for purging and write them to a temp file.
102 void GatherPurgeMessages(struct ctdlroom *qrbuf, void *data) {
103 struct ExpirePolicy epbuf;
106 struct CtdlMessage *msg = NULL;
108 struct cdbdata *cdbfr;
109 long *msglist = NULL;
113 purgelist = (FILE *)data;
114 fprintf(purgelist, "r=%s\n", qrbuf->QRname);
117 GetExpirePolicy(&epbuf, qrbuf);
119 // If the room is set to never expire messages ... do nothing
120 if (epbuf.expire_mode == EXPIRE_NEXTLEVEL) return;
121 if (epbuf.expire_mode == EXPIRE_MANUAL) return;
123 // Don't purge messages containing system configuration, dumbass.
124 if (!strcasecmp(qrbuf->QRname, SYSCONFIGROOM)) return;
126 // Ok, we got this far ... now let's see what's in the room.
127 cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf->QRnumber, sizeof(long));
130 msglist = malloc(cdbfr->len);
131 memcpy(msglist, cdbfr->ptr, cdbfr->len);
132 num_msgs = cdbfr->len / sizeof(long);
136 // Nothing to do if there aren't any messages
138 if (msglist != NULL) free(msglist);
142 // If the room is set to expire by count, do that.
143 if (epbuf.expire_mode == EXPIRE_NUMMSGS) {
144 if (num_msgs > epbuf.expire_value) {
145 for (a=0; a<(num_msgs - epbuf.expire_value); ++a) {
146 fprintf(purgelist, "m=%ld\n", msglist[a]);
152 // If the room is set to expire by age...
153 if (epbuf.expire_mode == EXPIRE_AGE) {
154 for (a=0; a<num_msgs; ++a) {
157 msg = CtdlFetchMessage(delnum, 0); // don't need the body
159 xtime = atol(msg->cm_fields[eTimestamp]);
166 if ((xtime > 0L) && (now - xtime > (time_t)(epbuf.expire_value * 86400L))) {
167 fprintf(purgelist, "m=%ld\n", delnum);
173 if (msglist != NULL) free(msglist);
177 // Second phase of message purge -- read list of msgs from temp file and delete them.
178 void DoPurgeMessages(FILE *purgelist) {
179 char roomname[ROOMNAMELEN];
184 strcpy(roomname, "nonexistent room ___ ___");
185 while (fgets(buf, sizeof buf, purgelist) != NULL) {
186 buf[strlen(buf)-1]=0;
187 if (!strncasecmp(buf, "r=", 2)) {
188 strcpy(roomname, &buf[2]);
190 if (!strncasecmp(buf, "m=", 2)) {
191 msgnum = atol(&buf[2]);
193 CtdlDeleteMessages(roomname, &msgnum, 1, "");
200 void PurgeMessages(void) {
203 syslog(LOG_DEBUG, "PurgeMessages() called");
206 purgelist = tmpfile();
207 if (purgelist == NULL) {
208 syslog(LOG_CRIT, "Can't create purgelist temp file: %s", strerror(errno));
212 CtdlForEachRoom(GatherPurgeMessages, (void *)purgelist );
213 DoPurgeMessages(purgelist);
218 void AddValidUser(char *username, void *data) {
219 struct ValidUser *vuptr;
220 struct ctdluser usbuf;
222 if (CtdlGetUser(&usbuf, username) != 0) {
226 vuptr = (struct ValidUser *)malloc(sizeof(struct ValidUser));
227 vuptr->next = ValidUserList;
228 vuptr->vu_usernum = usbuf.usernum;
229 ValidUserList = vuptr;
233 void AddValidRoom(struct ctdlroom *qrbuf, void *data) {
234 struct ValidRoom *vrptr;
236 vrptr = (struct ValidRoom *)malloc(sizeof(struct ValidRoom));
237 vrptr->next = ValidRoomList;
238 vrptr->vr_roomnum = qrbuf->QRnumber;
239 vrptr->vr_roomgen = qrbuf->QRgen;
240 ValidRoomList = vrptr;
244 void DoPurgeRooms(struct ctdlroom *qrbuf, void *data) {
245 time_t age, purge_secs;
246 struct PurgeList *pptr;
247 struct ValidUser *vuptr;
250 // For mailbox rooms, there's only one purging rule: if the user who
251 // owns the room still exists, we keep the room; otherwise, we purge
252 // it. Bypass any other rules.
253 if (qrbuf->QRflags & QR_MAILBOX) {
254 // if user not found, do_purge will be 1
256 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
257 if (vuptr->vu_usernum == atol(qrbuf->QRname)) {
263 // Any of these attributes render a room non-purgable
264 if (qrbuf->QRflags & QR_PERMANENT) return;
265 if (qrbuf->QRflags & QR_DIRECTORY) return;
266 if (qrbuf->QRflags2 & QR2_SYSTEM) return;
267 if (!strcasecmp(qrbuf->QRname, SYSCONFIGROOM)) return;
268 if (CtdlIsNonEditable(qrbuf)) return;
270 // If we don't know the modification date, be safe and don't purge
271 if (qrbuf->QRmtime <= (time_t)0) return;
273 // If no room purge time is set, be safe and don't purge
274 if (CtdlGetConfigLong("c_roompurge") < 0) return;
276 // Otherwise, check the date of last modification
277 age = time(NULL) - (qrbuf->QRmtime);
278 purge_secs = CtdlGetConfigLong("c_roompurge") * 86400;
279 if (purge_secs <= (time_t)0) return;
280 syslog(LOG_DEBUG, "<%s> is <%ld> seconds old", qrbuf->QRname, (long)age);
281 if (age > purge_secs) do_purge = 1;
285 pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
286 pptr->next = RoomPurgeList;
287 strcpy(pptr->name, qrbuf->QRname);
288 RoomPurgeList = pptr;
294 int PurgeRooms(void) {
295 struct PurgeList *pptr;
296 int num_rooms_purged = 0;
297 struct ctdlroom qrbuf;
298 struct ValidUser *vuptr;
299 char *transcript = NULL;
301 syslog(LOG_DEBUG, "PurgeRooms() called");
303 // Load up a table full of valid user numbers so we can delete
304 // user-owned rooms for users who no longer exist
305 ForEachUser(AddValidUser, NULL);
307 // Then cycle through the room file
308 CtdlForEachRoom(DoPurgeRooms, NULL);
310 // Free the valid user list
311 while (ValidUserList != NULL) {
312 vuptr = ValidUserList->next;
314 ValidUserList = vuptr;
317 transcript = malloc(SIZ);
318 strcpy(transcript, "The following rooms have been auto-purged:\n");
320 while (RoomPurgeList != NULL) {
321 if (CtdlGetRoom(&qrbuf, RoomPurgeList->name) == 0) {
322 transcript=realloc(transcript, strlen(transcript)+SIZ);
323 snprintf(&transcript[strlen(transcript)], SIZ, " %s\n", qrbuf.QRname);
324 CtdlDeleteRoom(&qrbuf);
327 pptr = RoomPurgeList->next;
329 RoomPurgeList = pptr;
332 if (num_rooms_purged > 0) CtdlAideMessage(transcript, "Room Autopurger Message");
335 syslog(LOG_DEBUG, "Purged %d rooms.", num_rooms_purged);
336 return(num_rooms_purged);
340 // Back end function to check user accounts for expiration.
341 void do_user_purge(char *username, void *data) {
345 struct PurgeList *pptr;
348 if (CtdlGetUser(&us, username) != 0) {
352 // Set purge time; if the user overrides the system default, use it
353 if (us.USuserpurge > 0) {
354 purge_time = ((time_t)us.USuserpurge) * 86400;
357 purge_time = CtdlGetConfigLong("c_userpurge") * 86400;
360 // The default rule is to not purge.
363 // If the user has not logged in for the configured amount of time, expire the account.
364 if (CtdlGetConfigLong("c_userpurge") > 0) {
366 if ((now - us.lastcall) > purge_time) purge = 1;
369 // If the account is marked as permanent, don't purge it.
370 if (us.flags & US_PERM) purge = 0;
372 // If the account is an administrator, don't purge it.
373 if (us.axlevel == 6) purge = 0;
375 // If the access level is 0, the record should already have been
376 // deleted, but maybe the user was logged in at the time or something.
377 // Delete the record now.
378 if (us.axlevel == 0) purge = 1;
380 // If the user set his/her password to 'deleteme', he/she
381 // wishes to be deleted, so purge the record.
382 // Moved this lower down so that aides and permanent users get purged if they ask to be.
383 if (!strcasecmp(us.password, "deleteme")) purge = 1;
385 // Fewer than zero calls is impossible, indicating a corrupted record.
386 if (us.timescalled < 0) purge = 1;
388 // any negative user number, is also impossible.
389 if (us.usernum < 0L) purge = 1;
391 // Don't purge user 0. That user is there for the system
392 if (us.usernum == 0L) purge = 0;
394 // If the user has no full name entry then we can't purge them since the actual purge can't find them.
395 // This shouldn't happen but does somehow.
396 if (IsEmptyStr(us.fullname)) {
399 if (us.usernum > 0L) {
401 if (users_corrupt_msg == NULL) {
402 users_corrupt_msg = malloc(SIZ);
403 strcpy(users_corrupt_msg,
404 "The auto-purger found the following user numbers with no name.\n"
405 "The system has no way to purge a user with no name,"
406 " and should not be able to create them either.\n"
407 "This indicates corruption of the user DB or possibly a bug.\n"
408 "It may be a good idea to restore your DB from a backup.\n"
412 users_corrupt_msg=realloc(users_corrupt_msg, strlen(users_corrupt_msg)+30);
413 snprintf(&users_corrupt_msg[strlen(users_corrupt_msg)], 29, " %ld\n", us.usernum);
418 pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
419 pptr->next = UserPurgeList;
420 strcpy(pptr->name, us.fullname);
421 UserPurgeList = pptr;
430 int PurgeUsers(void) {
431 struct PurgeList *pptr;
432 int num_users_purged = 0;
433 char *transcript = NULL;
435 syslog(LOG_DEBUG, "PurgeUsers() called");
436 users_not_purged = 0;
438 switch(CtdlGetConfigInt("c_auth_mode")) {
439 case AUTHMODE_NATIVE:
440 ForEachUser(do_user_purge, NULL);
443 syslog(LOG_DEBUG, "User purge for auth mode %d is not implemented.", CtdlGetConfigInt("c_auth_mode"));
447 transcript = malloc(SIZ);
449 if (users_not_purged == 0) {
450 strcpy(transcript, "The auto-purger was told to purge every user. It is\n"
451 "refusing to do this because it usually indicates a problem\n"
452 "such as an inability to communicate with a name service.\n"
454 while (UserPurgeList != NULL) {
455 pptr = UserPurgeList->next;
457 UserPurgeList = pptr;
463 strcpy(transcript, "The following users have been auto-purged:\n");
464 while (UserPurgeList != NULL) {
465 transcript=realloc(transcript, strlen(transcript)+SIZ);
466 snprintf(&transcript[strlen(transcript)], SIZ, " %s\n", UserPurgeList->name);
467 purge_user(UserPurgeList->name);
468 pptr = UserPurgeList->next;
470 UserPurgeList = pptr;
475 if (num_users_purged > 0) CtdlAideMessage(transcript, "User Purge Message");
478 if (users_corrupt_msg) {
479 CtdlAideMessage(users_corrupt_msg, "User Corruption Message");
480 free (users_corrupt_msg);
481 users_corrupt_msg = NULL;
485 CtdlAideMessage(users_zero_msg, "User Zero Message");
486 free (users_zero_msg);
487 users_zero_msg = NULL;
490 syslog(LOG_DEBUG, "Purged %d users.", num_users_purged);
491 return(num_users_purged);
497 // This is a really cumbersome "garbage collection" function. We have to
498 // delete visits which refer to rooms and/or users which no longer exist. In
499 // order to prevent endless traversals of the room and user files, we first
500 // build linked lists of rooms and users which _do_ exist on the system, then
501 // traverse the visit file, checking each record against those two lists and
502 // purging the ones that do not have a match on _both_ lists. (Remember, if
503 // either the room or user being referred to is no longer on the system, the
504 // record is useless and should be removed.)
506 int PurgeVisits(void) {
507 struct cdbdata *cdbvisit;
509 struct VPurgeList *VisitPurgeList = NULL;
510 struct VPurgeList *vptr;
514 struct ValidRoom *vrptr;
515 struct ValidUser *vuptr;
516 int RoomIsValid, UserIsValid;
518 // First, load up a table full of valid room/gen combinations
519 CtdlForEachRoom(AddValidRoom, NULL);
521 // Then load up a table full of valid user numbers
522 ForEachUser(AddValidUser, NULL);
524 // Now traverse through the visits, purging irrelevant records...
525 cdb_rewind(CDB_VISIT);
526 while(cdbvisit = cdb_next_item(CDB_VISIT), cdbvisit != NULL) {
527 memset(&vbuf, 0, sizeof(struct visit));
528 memcpy(&vbuf, cdbvisit->ptr,
529 ( (cdbvisit->len > sizeof(struct visit)) ?
530 sizeof(struct visit) : cdbvisit->len) );
536 // Check to see if the room exists
537 for (vrptr=ValidRoomList; vrptr!=NULL; vrptr=vrptr->next) {
538 if ( (vrptr->vr_roomnum==vbuf.v_roomnum)
539 && (vrptr->vr_roomgen==vbuf.v_roomgen))
543 // Check to see if the user exists
544 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
545 if (vuptr->vu_usernum == vbuf.v_usernum)
549 // Put the record on the purge list if it's dead
550 if ((RoomIsValid==0) || (UserIsValid==0)) {
551 vptr = (struct VPurgeList *)
552 malloc(sizeof(struct VPurgeList));
553 vptr->next = VisitPurgeList;
554 vptr->vp_roomnum = vbuf.v_roomnum;
555 vptr->vp_roomgen = vbuf.v_roomgen;
556 vptr->vp_usernum = vbuf.v_usernum;
557 VisitPurgeList = vptr;
562 // Free the valid room/gen combination list
563 while (ValidRoomList != NULL) {
564 vrptr = ValidRoomList->next;
566 ValidRoomList = vrptr;
569 // Free the valid user list
570 while (ValidUserList != NULL) {
571 vuptr = ValidUserList->next;
573 ValidUserList = vuptr;
576 // Now delete every visit on the purged list
577 while (VisitPurgeList != NULL) {
578 IndexLen = GenerateRelationshipIndex(IndexBuf,
579 VisitPurgeList->vp_roomnum,
580 VisitPurgeList->vp_roomgen,
581 VisitPurgeList->vp_usernum);
582 cdb_delete(CDB_VISIT, IndexBuf, IndexLen);
583 vptr = VisitPurgeList->next;
584 free(VisitPurgeList);
585 VisitPurgeList = vptr;
593 // Purge the use table of old entries.
594 int PurgeUseTable(StrBuf *ErrMsg) {
597 struct cdbdata *cdbut;
599 struct UPurgeList *ul = NULL;
600 struct UPurgeList *uptr;
602 // Phase 1: traverse through the table, discovering old records...
604 syslog(LOG_DEBUG, "Purge use table: phase 1");
605 cdb_rewind(CDB_USETABLE);
606 while(cdbut = cdb_next_item(CDB_USETABLE), cdbut != NULL) {
608 if (cdbut->len > sizeof(struct UseTable))
609 memcpy(&ut, cdbut->ptr, sizeof(struct UseTable));
611 memset(&ut, 0, sizeof(struct UseTable));
612 memcpy(&ut, cdbut->ptr, cdbut->len);
616 if ( (time(NULL) - ut.ut_timestamp) > USETABLE_RETAIN ) {
617 uptr = (struct UPurgeList *) malloc(sizeof(struct UPurgeList));
620 safestrncpy(uptr->up_key, ut.ut_msgid, sizeof uptr->up_key);
628 // Phase 2: delete the records
629 syslog(LOG_DEBUG, "Purge use table: phase 2");
631 cdb_delete(CDB_USETABLE, ul->up_key, strlen(ul->up_key));
637 syslog(LOG_DEBUG, "Purge use table: finished (purged %d of %d records)", purged, total);
642 // Purge the EUID Index of old records.
643 int PurgeEuidIndexTable(void) {
645 struct cdbdata *cdbei;
646 struct EPurgeList *el = NULL;
647 struct EPurgeList *eptr;
649 struct CtdlMessage *msg = NULL;
651 // Phase 1: traverse through the table, discovering old records...
652 syslog(LOG_DEBUG, "Purge EUID index: phase 1");
653 cdb_rewind(CDB_EUIDINDEX);
654 while(cdbei = cdb_next_item(CDB_EUIDINDEX), cdbei != NULL) {
656 memcpy(&msgnum, cdbei->ptr, sizeof(long));
658 msg = CtdlFetchMessage(msgnum, 0);
660 CM_Free(msg); // it still exists, so do nothing
663 eptr = (struct EPurgeList *) malloc(sizeof(struct EPurgeList));
666 eptr->ep_keylen = cdbei->len - sizeof(long);
667 eptr->ep_key = malloc(cdbei->len);
668 memcpy(eptr->ep_key, &cdbei->ptr[sizeof(long)], eptr->ep_keylen);
678 // Phase 2: delete the records
679 syslog(LOG_DEBUG, "Purge euid index: phase 2");
681 cdb_delete(CDB_EUIDINDEX, el->ep_key, el->ep_keylen);
688 syslog(LOG_DEBUG, "Purge euid index: finished (purged %d records)", purged);
693 // Purge external auth assocations for missing users (theoretically this will never delete anything)
694 int PurgeStaleExtAuthAssociations(void) {
695 struct cdbdata *cdboi;
696 struct ctdluser usbuf;
697 HashList *keys = NULL;
699 char *deleteme = NULL;
706 keys = NewHash(1, NULL);
707 if (!keys) return(0);
709 cdb_rewind(CDB_EXTAUTH);
710 while (cdboi = cdb_next_item(CDB_EXTAUTH), cdboi != NULL) {
711 if (cdboi->len > sizeof(long)) {
712 memcpy(&usernum, cdboi->ptr, sizeof(long));
713 if (CtdlGetUserByNumber(&usbuf, usernum) != 0) {
714 deleteme = strdup(cdboi->ptr + sizeof(long)),
715 Put(keys, deleteme, strlen(deleteme), deleteme, NULL);
721 // Go through the hash list, deleting keys we stored in it
723 HashPos = GetNewHashPos(keys, 0);
724 while (GetNextHashPos(keys, HashPos, &len, &Key, &Value)!=0) {
725 syslog(LOG_DEBUG, "Deleting associated external authenticator <%s>", (char*)Value);
726 cdb_delete(CDB_EXTAUTH, Value, strlen(Value));
727 // note: don't free(Value) -- deleting the hash list will handle this for us
730 DeleteHashPos(&HashPos);
736 void purge_databases(void) {
738 static time_t last_purge = 0;
742 // Do the auto-purge if the current hour equals the purge hour,
743 // but not if the operation has already been performed in the
744 // last twelve hours. This is usually enough granularity.
746 localtime_r(&now, &tm);
747 if (((tm.tm_hour != CtdlGetConfigInt("c_purge_hour")) || ((now - last_purge) < 43200)) && (force_purge_now == 0)) {
751 syslog(LOG_INFO, "Auto-purger: starting.");
753 if (!server_shutting_down) {
754 retval = PurgeUsers();
755 syslog(LOG_NOTICE, "Purged %d users.", retval);
758 if (!server_shutting_down) {
760 syslog(LOG_NOTICE, "Expired %d messages.", messages_purged);
763 if (!server_shutting_down) {
764 retval = PurgeRooms();
765 syslog(LOG_NOTICE, "Expired %d rooms.", retval);
768 if (!server_shutting_down) {
769 retval = PurgeVisits();
770 syslog(LOG_NOTICE, "Purged %d visits.", retval);
773 if (!server_shutting_down) {
775 ErrMsg = NewStrBuf();
776 retval = PurgeUseTable(ErrMsg);
777 syslog(LOG_NOTICE, "Purged %d entries from the use table.", retval);
781 if (!server_shutting_down) {
782 retval = PurgeEuidIndexTable();
783 syslog(LOG_NOTICE, "Purged %d entries from the EUID index.", retval);
786 if (!server_shutting_down) {
787 retval = PurgeStaleExtAuthAssociations();
788 syslog(LOG_NOTICE, "Purged %d stale external auth associations.", retval);
791 //if (!server_shutting_down) {
792 // FIXME this is where we could do a non-interactive delete of zero-refcount messages
795 if ( (!server_shutting_down) && (CtdlGetConfigInt("c_shrink_db_files") != 0) ) {
796 cdb_compact(); // Shrink the DB files on disk
799 if (!server_shutting_down) {
800 syslog(LOG_INFO, "Auto-purger: finished.");
801 last_purge = now; // So we don't do it again soon
805 syslog(LOG_INFO, "Auto-purger: STOPPED.");
810 // Manually initiate a run of The Dreaded Auto-Purger (tm)
811 void cmd_tdap(char *argbuf) {
812 if (CtdlAccessCheck(ac_aide)) return;
814 cprintf("%d Manually initiating a purger run now.\n", CIT_OK);
818 // Initialization function, called from modules_init.c
819 char *ctdl_module_init_expire(void) {
821 CtdlRegisterProtoHook(cmd_tdap, "TDAP", "Manually initiate auto-purger");
822 CtdlRegisterProtoHook(cmd_gpex, "GPEX", "Get expire policy");
823 CtdlRegisterProtoHook(cmd_spex, "SPEX", "Set expire policy");
824 CtdlRegisterSessionHook(purge_databases, EVT_TIMER, PRIO_CLEANUP + 20);
827 // return our module name for the log