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.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->QRflags & QR_NETWORK) return;
267 if (qrbuf->QRflags2 & QR2_SYSTEM) return;
268 if (!strcasecmp(qrbuf->QRname, SYSCONFIGROOM)) return;
269 if (CtdlIsNonEditable(qrbuf)) return;
271 // If we don't know the modification date, be safe and don't purge
272 if (qrbuf->QRmtime <= (time_t)0) return;
274 // If no room purge time is set, be safe and don't purge
275 if (CtdlGetConfigLong("c_roompurge") < 0) return;
277 // Otherwise, check the date of last modification
278 age = time(NULL) - (qrbuf->QRmtime);
279 purge_secs = CtdlGetConfigLong("c_roompurge") * 86400;
280 if (purge_secs <= (time_t)0) return;
281 syslog(LOG_DEBUG, "<%s> is <%ld> seconds old", qrbuf->QRname, (long)age);
282 if (age > purge_secs) do_purge = 1;
286 pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
287 pptr->next = RoomPurgeList;
288 strcpy(pptr->name, qrbuf->QRname);
289 RoomPurgeList = pptr;
295 int PurgeRooms(void) {
296 struct PurgeList *pptr;
297 int num_rooms_purged = 0;
298 struct ctdlroom qrbuf;
299 struct ValidUser *vuptr;
300 char *transcript = NULL;
302 syslog(LOG_DEBUG, "PurgeRooms() called");
304 // Load up a table full of valid user numbers so we can delete
305 // user-owned rooms for users who no longer exist
306 ForEachUser(AddValidUser, NULL);
308 // Then cycle through the room file
309 CtdlForEachRoom(DoPurgeRooms, NULL);
311 // Free the valid user list
312 while (ValidUserList != NULL) {
313 vuptr = ValidUserList->next;
315 ValidUserList = vuptr;
318 transcript = malloc(SIZ);
319 strcpy(transcript, "The following rooms have been auto-purged:\n");
321 while (RoomPurgeList != NULL) {
322 if (CtdlGetRoom(&qrbuf, RoomPurgeList->name) == 0) {
323 transcript=realloc(transcript, strlen(transcript)+SIZ);
324 snprintf(&transcript[strlen(transcript)], SIZ, " %s\n",
326 CtdlDeleteRoom(&qrbuf);
328 pptr = RoomPurgeList->next;
330 RoomPurgeList = pptr;
334 if (num_rooms_purged > 0) CtdlAideMessage(transcript, "Room Autopurger Message");
337 syslog(LOG_DEBUG, "Purged %d rooms.", num_rooms_purged);
338 return(num_rooms_purged);
342 // Back end function to check user accounts for expiration.
343 void do_user_purge(char *username, void *data) {
347 struct PurgeList *pptr;
350 if (CtdlGetUser(&us, username) != 0) {
354 // Set purge time; if the user overrides the system default, use it
355 if (us.USuserpurge > 0) {
356 purge_time = ((time_t)us.USuserpurge) * 86400;
359 purge_time = CtdlGetConfigLong("c_userpurge") * 86400;
362 // The default rule is to not purge.
365 // If the user has not logged in for the configured amount of time, expire the account.
366 if (CtdlGetConfigLong("c_userpurge") > 0) {
368 if ((now - us.lastcall) > purge_time) purge = 1;
371 // If the account is marked as permanent, don't purge it.
372 if (us.flags & US_PERM) purge = 0;
374 // If the account is an administrator, don't purge it.
375 if (us.axlevel == 6) purge = 0;
377 // If the access level is 0, the record should already have been
378 // deleted, but maybe the user was logged in at the time or something.
379 // Delete the record now.
380 if (us.axlevel == 0) purge = 1;
382 // If the user set his/her password to 'deleteme', he/she
383 // wishes to be deleted, so purge the record.
384 // Moved this lower down so that aides and permanent users get purged if they ask to be.
385 if (!strcasecmp(us.password, "deleteme")) purge = 1;
387 // Fewer than zero calls is impossible, indicating a corrupted record.
388 if (us.timescalled < 0) purge = 1;
390 // any negative user number, is also impossible.
391 if (us.usernum < 0L) purge = 1;
393 // Don't purge user 0. That user is there for the system
394 if (us.usernum == 0L) purge = 0;
396 // If the user has no full name entry then we can't purge them since the actual purge can't find them.
397 // This shouldn't happen but does somehow.
398 if (IsEmptyStr(us.fullname)) {
401 if (us.usernum > 0L) {
403 if (users_corrupt_msg == NULL) {
404 users_corrupt_msg = malloc(SIZ);
405 strcpy(users_corrupt_msg,
406 "The auto-purger found the following user numbers with no name.\n"
407 "The system has no way to purge a user with no name,"
408 " and should not be able to create them either.\n"
409 "This indicates corruption of the user DB or possibly a bug.\n"
410 "It may be a good idea to restore your DB from a backup.\n"
414 users_corrupt_msg=realloc(users_corrupt_msg, strlen(users_corrupt_msg)+30);
415 snprintf(&users_corrupt_msg[strlen(users_corrupt_msg)], 29, " %ld\n", us.usernum);
420 pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
421 pptr->next = UserPurgeList;
422 strcpy(pptr->name, us.fullname);
423 UserPurgeList = pptr;
432 int PurgeUsers(void) {
433 struct PurgeList *pptr;
434 int num_users_purged = 0;
435 char *transcript = NULL;
437 syslog(LOG_DEBUG, "PurgeUsers() called");
438 users_not_purged = 0;
440 switch(CtdlGetConfigInt("c_auth_mode")) {
441 case AUTHMODE_NATIVE:
442 ForEachUser(do_user_purge, NULL);
445 syslog(LOG_DEBUG, "User purge for auth mode %d is not implemented.", CtdlGetConfigInt("c_auth_mode"));
449 transcript = malloc(SIZ);
451 if (users_not_purged == 0) {
452 strcpy(transcript, "The auto-purger was told to purge every user. It is\n"
453 "refusing to do this because it usually indicates a problem\n"
454 "such as an inability to communicate with a name service.\n"
456 while (UserPurgeList != NULL) {
457 pptr = UserPurgeList->next;
459 UserPurgeList = pptr;
465 strcpy(transcript, "The following users have been auto-purged:\n");
466 while (UserPurgeList != NULL) {
467 transcript=realloc(transcript, strlen(transcript)+SIZ);
468 snprintf(&transcript[strlen(transcript)], SIZ, " %s\n",
469 UserPurgeList->name);
470 purge_user(UserPurgeList->name);
471 pptr = UserPurgeList->next;
473 UserPurgeList = pptr;
478 if (num_users_purged > 0) CtdlAideMessage(transcript, "User Purge Message");
481 if (users_corrupt_msg) {
482 CtdlAideMessage(users_corrupt_msg, "User Corruption Message");
483 free (users_corrupt_msg);
484 users_corrupt_msg = NULL;
488 CtdlAideMessage(users_zero_msg, "User Zero Message");
489 free (users_zero_msg);
490 users_zero_msg = NULL;
493 syslog(LOG_DEBUG, "Purged %d users.", num_users_purged);
494 return(num_users_purged);
500 // This is a really cumbersome "garbage collection" function. We have to
501 // delete visits which refer to rooms and/or users which no longer exist. In
502 // order to prevent endless traversals of the room and user files, we first
503 // build linked lists of rooms and users which _do_ exist on the system, then
504 // traverse the visit file, checking each record against those two lists and
505 // purging the ones that do not have a match on _both_ lists. (Remember, if
506 // either the room or user being referred to is no longer on the system, the
507 // record is completely useless.)
509 int PurgeVisits(void) {
510 struct cdbdata *cdbvisit;
512 struct VPurgeList *VisitPurgeList = NULL;
513 struct VPurgeList *vptr;
517 struct ValidRoom *vrptr;
518 struct ValidUser *vuptr;
519 int RoomIsValid, UserIsValid;
521 // First, load up a table full of valid room/gen combinations
522 CtdlForEachRoom(AddValidRoom, NULL);
524 // Then load up a table full of valid user numbers
525 ForEachUser(AddValidUser, NULL);
527 // Now traverse through the visits, purging irrelevant records...
528 cdb_rewind(CDB_VISIT);
529 while(cdbvisit = cdb_next_item(CDB_VISIT), cdbvisit != NULL) {
530 memset(&vbuf, 0, sizeof(visit));
531 memcpy(&vbuf, cdbvisit->ptr,
532 ( (cdbvisit->len > sizeof(visit)) ?
533 sizeof(visit) : cdbvisit->len) );
539 // Check to see if the room exists
540 for (vrptr=ValidRoomList; vrptr!=NULL; vrptr=vrptr->next) {
541 if ( (vrptr->vr_roomnum==vbuf.v_roomnum)
542 && (vrptr->vr_roomgen==vbuf.v_roomgen))
546 // Check to see if the user exists
547 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
548 if (vuptr->vu_usernum == vbuf.v_usernum)
552 // Put the record on the purge list if it's dead
553 if ((RoomIsValid==0) || (UserIsValid==0)) {
554 vptr = (struct VPurgeList *)
555 malloc(sizeof(struct VPurgeList));
556 vptr->next = VisitPurgeList;
557 vptr->vp_roomnum = vbuf.v_roomnum;
558 vptr->vp_roomgen = vbuf.v_roomgen;
559 vptr->vp_usernum = vbuf.v_usernum;
560 VisitPurgeList = vptr;
565 // Free the valid room/gen combination list
566 while (ValidRoomList != NULL) {
567 vrptr = ValidRoomList->next;
569 ValidRoomList = vrptr;
572 // Free the valid user list
573 while (ValidUserList != NULL) {
574 vuptr = ValidUserList->next;
576 ValidUserList = vuptr;
579 // Now delete every visit on the purged list
580 while (VisitPurgeList != NULL) {
581 IndexLen = GenerateRelationshipIndex(IndexBuf,
582 VisitPurgeList->vp_roomnum,
583 VisitPurgeList->vp_roomgen,
584 VisitPurgeList->vp_usernum);
585 cdb_delete(CDB_VISIT, IndexBuf, IndexLen);
586 vptr = VisitPurgeList->next;
587 free(VisitPurgeList);
588 VisitPurgeList = vptr;
596 // Purge the use table of old entries.
597 int PurgeUseTable(StrBuf *ErrMsg) {
599 struct cdbdata *cdbut;
601 struct UPurgeList *ul = NULL;
602 struct UPurgeList *uptr;
604 // Phase 1: traverse through the table, discovering old records...
606 syslog(LOG_DEBUG, "Purge use table: phase 1");
607 cdb_rewind(CDB_USETABLE);
608 while(cdbut = cdb_next_item(CDB_USETABLE), cdbut != NULL) {
609 if (cdbut->len > sizeof(struct UseTable))
610 memcpy(&ut, cdbut->ptr, sizeof(struct UseTable));
612 memset(&ut, 0, sizeof(struct UseTable));
613 memcpy(&ut, cdbut->ptr, cdbut->len);
617 if ( (time(NULL) - ut.ut_timestamp) > USETABLE_RETAIN ) {
618 uptr = (struct UPurgeList *) malloc(sizeof(struct UPurgeList));
621 safestrncpy(uptr->up_key, ut.ut_msgid, sizeof uptr->up_key);
629 // Phase 2: delete the records
630 syslog(LOG_DEBUG, "Purge use table: phase 2");
632 cdb_delete(CDB_USETABLE, ul->up_key, strlen(ul->up_key));
638 syslog(LOG_DEBUG, "Purge use table: finished (purged %d records)", purged);
643 // Purge the EUID Index of old records.
644 int PurgeEuidIndexTable(void) {
646 struct cdbdata *cdbei;
647 struct EPurgeList *el = NULL;
648 struct EPurgeList *eptr;
650 struct CtdlMessage *msg = NULL;
652 // Phase 1: traverse through the table, discovering old records...
653 syslog(LOG_DEBUG, "Purge EUID index: phase 1");
654 cdb_rewind(CDB_EUIDINDEX);
655 while(cdbei = cdb_next_item(CDB_EUIDINDEX), cdbei != NULL) {
657 memcpy(&msgnum, cdbei->ptr, sizeof(long));
659 msg = CtdlFetchMessage(msgnum, 0);
661 CM_Free(msg); // it still exists, so do nothing
664 eptr = (struct EPurgeList *) malloc(sizeof(struct EPurgeList));
667 eptr->ep_keylen = cdbei->len - sizeof(long);
668 eptr->ep_key = malloc(cdbei->len);
669 memcpy(eptr->ep_key, &cdbei->ptr[sizeof(long)], eptr->ep_keylen);
679 // Phase 2: delete the records
680 syslog(LOG_DEBUG, "Purge euid index: phase 2");
682 cdb_delete(CDB_EUIDINDEX, el->ep_key, el->ep_keylen);
689 syslog(LOG_DEBUG, "Purge euid index: finished (purged %d records)", purged);
694 // Purge external auth assocations for missing users (theoretically this will never delete anything)
695 int PurgeStaleExtAuthAssociations(void) {
696 struct cdbdata *cdboi;
697 struct ctdluser usbuf;
698 HashList *keys = NULL;
700 char *deleteme = NULL;
707 keys = NewHash(1, NULL);
708 if (!keys) return(0);
710 cdb_rewind(CDB_EXTAUTH);
711 while (cdboi = cdb_next_item(CDB_EXTAUTH), cdboi != NULL) {
712 if (cdboi->len > sizeof(long)) {
713 memcpy(&usernum, cdboi->ptr, sizeof(long));
714 if (CtdlGetUserByNumber(&usbuf, usernum) != 0) {
715 deleteme = strdup(cdboi->ptr + sizeof(long)),
716 Put(keys, deleteme, strlen(deleteme), deleteme, NULL);
722 // Go through the hash list, deleting keys we stored in it
724 HashPos = GetNewHashPos(keys, 0);
725 while (GetNextHashPos(keys, HashPos, &len, &Key, &Value)!=0) {
726 syslog(LOG_DEBUG, "Deleting associated external authenticator <%s>", (char*)Value);
727 cdb_delete(CDB_EXTAUTH, Value, strlen(Value));
728 // note: don't free(Value) -- deleting the hash list will handle this for us
731 DeleteHashPos(&HashPos);
737 void purge_databases(void) {
739 static time_t last_purge = 0;
743 // Do the auto-purge if the current hour equals the purge hour,
744 // but not if the operation has already been performed in the
745 // last twelve hours. This is usually enough granularity.
747 localtime_r(&now, &tm);
748 if (((tm.tm_hour != CtdlGetConfigInt("c_purge_hour")) || ((now - last_purge) < 43200)) && (force_purge_now == 0)) {
752 syslog(LOG_INFO, "Auto-purger: starting.");
754 if (!server_shutting_down) {
755 retval = PurgeUsers();
756 syslog(LOG_NOTICE, "Purged %d users.", retval);
759 if (!server_shutting_down) {
761 syslog(LOG_NOTICE, "Expired %d messages.", messages_purged);
764 if (!server_shutting_down) {
765 retval = PurgeRooms();
766 syslog(LOG_NOTICE, "Expired %d rooms.", retval);
769 if (!server_shutting_down) {
770 retval = PurgeVisits();
771 syslog(LOG_NOTICE, "Purged %d visits.", retval);
774 if (!server_shutting_down) {
776 ErrMsg = NewStrBuf();
777 retval = PurgeUseTable(ErrMsg);
778 syslog(LOG_NOTICE, "Purged %d entries from the use table.", retval);
782 if (!server_shutting_down) {
783 retval = PurgeEuidIndexTable();
784 syslog(LOG_NOTICE, "Purged %d entries from the EUID index.", retval);
787 if (!server_shutting_down) {
788 retval = PurgeStaleExtAuthAssociations();
789 syslog(LOG_NOTICE, "Purged %d stale external auth associations.", retval);
792 //if (!server_shutting_down) {
793 // FIXME this is where we could do a non-interactive delete of zero-refcount messages
796 if ( (!server_shutting_down) && (CtdlGetConfigInt("c_shrink_db_files") != 0) ) {
797 cdb_compact(); // Shrink the DB files on disk
800 if (!server_shutting_down) {
801 syslog(LOG_INFO, "Auto-purger: finished.");
802 last_purge = now; // So we don't do it again soon
806 syslog(LOG_INFO, "Auto-purger: STOPPED.");
811 // Manually initiate a run of The Dreaded Auto-Purger (tm)
812 void cmd_tdap(char *argbuf) {
813 if (CtdlAccessCheck(ac_aide)) return;
815 cprintf("%d Manually initiating a purger run now.\n", CIT_OK);
819 // Initialization function, called from modules_init.c
820 char *ctdl_module_init_expire(void) {
822 CtdlRegisterProtoHook(cmd_tdap, "TDAP", "Manually initiate auto-purger");
823 CtdlRegisterProtoHook(cmd_gpex, "GPEX", "Get expire policy");
824 CtdlRegisterProtoHook(cmd_spex, "SPEX", "Set expire policy");
825 CtdlRegisterSessionHook(purge_databases, EVT_TIMER, PRIO_CLEANUP + 20);
828 // return our module name for the log