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) {
395 // FIXME: Temporary log message. Until we do unauth access with user 0 we should
396 // try to get rid of all user 0 occurences. Many will be remnants from old code so
397 // we will need to try and purge them from users data bases.Some will not have names but
398 // those with names should be purged.
399 syslog(LOG_DEBUG, "Auto purger found a user 0 with name <%s>", us.fullname);
403 // If the user has no full name entry then we can't purge them since the actual purge can't find them.
404 // This shouldn't happen but does somehow.
405 if (IsEmptyStr(us.fullname)) {
408 if (us.usernum > 0L) {
410 if (users_corrupt_msg == NULL) {
411 users_corrupt_msg = malloc(SIZ);
412 strcpy(users_corrupt_msg,
413 "The auto-purger found the following user numbers with no name.\n"
414 "The system has no way to purge a user with no name,"
415 " and should not be able to create them either.\n"
416 "This indicates corruption of the user DB or possibly a bug.\n"
417 "It may be a good idea to restore your DB from a backup.\n"
421 users_corrupt_msg=realloc(users_corrupt_msg, strlen(users_corrupt_msg)+30);
422 snprintf(&users_corrupt_msg[strlen(users_corrupt_msg)], 29, " %ld\n", us.usernum);
427 pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
428 pptr->next = UserPurgeList;
429 strcpy(pptr->name, us.fullname);
430 UserPurgeList = pptr;
439 int PurgeUsers(void) {
440 struct PurgeList *pptr;
441 int num_users_purged = 0;
442 char *transcript = NULL;
444 syslog(LOG_DEBUG, "PurgeUsers() called");
445 users_not_purged = 0;
447 switch(CtdlGetConfigInt("c_auth_mode")) {
448 case AUTHMODE_NATIVE:
449 ForEachUser(do_user_purge, NULL);
452 syslog(LOG_DEBUG, "User purge for auth mode %d is not implemented.", CtdlGetConfigInt("c_auth_mode"));
456 transcript = malloc(SIZ);
458 if (users_not_purged == 0) {
459 strcpy(transcript, "The auto-purger was told to purge every user. It is\n"
460 "refusing to do this because it usually indicates a problem\n"
461 "such as an inability to communicate with a name service.\n"
463 while (UserPurgeList != NULL) {
464 pptr = UserPurgeList->next;
466 UserPurgeList = pptr;
472 strcpy(transcript, "The following users have been auto-purged:\n");
473 while (UserPurgeList != NULL) {
474 transcript=realloc(transcript, strlen(transcript)+SIZ);
475 snprintf(&transcript[strlen(transcript)], SIZ, " %s\n",
476 UserPurgeList->name);
477 purge_user(UserPurgeList->name);
478 pptr = UserPurgeList->next;
480 UserPurgeList = pptr;
485 if (num_users_purged > 0) CtdlAideMessage(transcript, "User Purge Message");
488 if (users_corrupt_msg) {
489 CtdlAideMessage(users_corrupt_msg, "User Corruption Message");
490 free (users_corrupt_msg);
491 users_corrupt_msg = NULL;
495 CtdlAideMessage(users_zero_msg, "User Zero Message");
496 free (users_zero_msg);
497 users_zero_msg = NULL;
500 syslog(LOG_DEBUG, "Purged %d users.", num_users_purged);
501 return(num_users_purged);
507 // This is a really cumbersome "garbage collection" function. We have to
508 // delete visits which refer to rooms and/or users which no longer exist. In
509 // order to prevent endless traversals of the room and user files, we first
510 // build linked lists of rooms and users which _do_ exist on the system, then
511 // traverse the visit file, checking each record against those two lists and
512 // purging the ones that do not have a match on _both_ lists. (Remember, if
513 // either the room or user being referred to is no longer on the system, the
514 // record is completely useless.)
516 int PurgeVisits(void) {
517 struct cdbdata *cdbvisit;
519 struct VPurgeList *VisitPurgeList = NULL;
520 struct VPurgeList *vptr;
524 struct ValidRoom *vrptr;
525 struct ValidUser *vuptr;
526 int RoomIsValid, UserIsValid;
528 // First, load up a table full of valid room/gen combinations
529 CtdlForEachRoom(AddValidRoom, NULL);
531 // Then load up a table full of valid user numbers
532 ForEachUser(AddValidUser, NULL);
534 // Now traverse through the visits, purging irrelevant records...
535 cdb_rewind(CDB_VISIT);
536 while(cdbvisit = cdb_next_item(CDB_VISIT), cdbvisit != NULL) {
537 memset(&vbuf, 0, sizeof(visit));
538 memcpy(&vbuf, cdbvisit->ptr,
539 ( (cdbvisit->len > sizeof(visit)) ?
540 sizeof(visit) : cdbvisit->len) );
546 // Check to see if the room exists
547 for (vrptr=ValidRoomList; vrptr!=NULL; vrptr=vrptr->next) {
548 if ( (vrptr->vr_roomnum==vbuf.v_roomnum)
549 && (vrptr->vr_roomgen==vbuf.v_roomgen))
553 // Check to see if the user exists
554 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
555 if (vuptr->vu_usernum == vbuf.v_usernum)
559 // Put the record on the purge list if it's dead
560 if ((RoomIsValid==0) || (UserIsValid==0)) {
561 vptr = (struct VPurgeList *)
562 malloc(sizeof(struct VPurgeList));
563 vptr->next = VisitPurgeList;
564 vptr->vp_roomnum = vbuf.v_roomnum;
565 vptr->vp_roomgen = vbuf.v_roomgen;
566 vptr->vp_usernum = vbuf.v_usernum;
567 VisitPurgeList = vptr;
572 // Free the valid room/gen combination list
573 while (ValidRoomList != NULL) {
574 vrptr = ValidRoomList->next;
576 ValidRoomList = vrptr;
579 // Free the valid user list
580 while (ValidUserList != NULL) {
581 vuptr = ValidUserList->next;
583 ValidUserList = vuptr;
586 // Now delete every visit on the purged list
587 while (VisitPurgeList != NULL) {
588 IndexLen = GenerateRelationshipIndex(IndexBuf,
589 VisitPurgeList->vp_roomnum,
590 VisitPurgeList->vp_roomgen,
591 VisitPurgeList->vp_usernum);
592 cdb_delete(CDB_VISIT, IndexBuf, IndexLen);
593 vptr = VisitPurgeList->next;
594 free(VisitPurgeList);
595 VisitPurgeList = vptr;
603 // Purge the use table of old entries.
604 int PurgeUseTable(StrBuf *ErrMsg) {
606 struct cdbdata *cdbut;
608 struct UPurgeList *ul = NULL;
609 struct UPurgeList *uptr;
611 // Phase 1: traverse through the table, discovering old records...
613 syslog(LOG_DEBUG, "Purge use table: phase 1");
614 cdb_rewind(CDB_USETABLE);
615 while(cdbut = cdb_next_item(CDB_USETABLE), cdbut != NULL) {
616 if (cdbut->len > sizeof(struct UseTable))
617 memcpy(&ut, cdbut->ptr, sizeof(struct UseTable));
619 memset(&ut, 0, sizeof(struct UseTable));
620 memcpy(&ut, cdbut->ptr, cdbut->len);
624 if ( (time(NULL) - ut.ut_timestamp) > USETABLE_RETAIN ) {
625 uptr = (struct UPurgeList *) malloc(sizeof(struct UPurgeList));
628 safestrncpy(uptr->up_key, ut.ut_msgid, sizeof uptr->up_key);
636 // Phase 2: delete the records
637 syslog(LOG_DEBUG, "Purge use table: phase 2");
639 cdb_delete(CDB_USETABLE, ul->up_key, strlen(ul->up_key));
645 syslog(LOG_DEBUG, "Purge use table: finished (purged %d records)", purged);
650 // Purge the EUID Index of old records.
651 int PurgeEuidIndexTable(void) {
653 struct cdbdata *cdbei;
654 struct EPurgeList *el = NULL;
655 struct EPurgeList *eptr;
657 struct CtdlMessage *msg = NULL;
659 // Phase 1: traverse through the table, discovering old records...
660 syslog(LOG_DEBUG, "Purge EUID index: phase 1");
661 cdb_rewind(CDB_EUIDINDEX);
662 while(cdbei = cdb_next_item(CDB_EUIDINDEX), cdbei != NULL) {
664 memcpy(&msgnum, cdbei->ptr, sizeof(long));
666 msg = CtdlFetchMessage(msgnum, 0);
668 CM_Free(msg); // it still exists, so do nothing
671 eptr = (struct EPurgeList *) malloc(sizeof(struct EPurgeList));
674 eptr->ep_keylen = cdbei->len - sizeof(long);
675 eptr->ep_key = malloc(cdbei->len);
676 memcpy(eptr->ep_key, &cdbei->ptr[sizeof(long)], eptr->ep_keylen);
686 // Phase 2: delete the records
687 syslog(LOG_DEBUG, "Purge euid index: phase 2");
689 cdb_delete(CDB_EUIDINDEX, el->ep_key, el->ep_keylen);
696 syslog(LOG_DEBUG, "Purge euid index: finished (purged %d records)", purged);
701 // Purge external auth assocations for missing users (theoretically this will never delete anything)
702 int PurgeStaleExtAuthAssociations(void) {
703 struct cdbdata *cdboi;
704 struct ctdluser usbuf;
705 HashList *keys = NULL;
707 char *deleteme = NULL;
714 keys = NewHash(1, NULL);
715 if (!keys) return(0);
717 cdb_rewind(CDB_EXTAUTH);
718 while (cdboi = cdb_next_item(CDB_EXTAUTH), cdboi != NULL) {
719 if (cdboi->len > sizeof(long)) {
720 memcpy(&usernum, cdboi->ptr, sizeof(long));
721 if (CtdlGetUserByNumber(&usbuf, usernum) != 0) {
722 deleteme = strdup(cdboi->ptr + sizeof(long)),
723 Put(keys, deleteme, strlen(deleteme), deleteme, NULL);
729 // Go through the hash list, deleting keys we stored in it
731 HashPos = GetNewHashPos(keys, 0);
732 while (GetNextHashPos(keys, HashPos, &len, &Key, &Value)!=0) {
733 syslog(LOG_DEBUG, "Deleting associated external authenticator <%s>", (char*)Value);
734 cdb_delete(CDB_EXTAUTH, Value, strlen(Value));
735 // note: don't free(Value) -- deleting the hash list will handle this for us
738 DeleteHashPos(&HashPos);
744 void purge_databases(void) {
746 static time_t last_purge = 0;
750 // Do the auto-purge if the current hour equals the purge hour,
751 // but not if the operation has already been performed in the
752 // last twelve hours. This is usually enough granularity.
754 localtime_r(&now, &tm);
755 if (((tm.tm_hour != CtdlGetConfigInt("c_purge_hour")) || ((now - last_purge) < 43200)) && (force_purge_now == 0)) {
759 syslog(LOG_INFO, "Auto-purger: starting.");
761 if (!server_shutting_down) {
762 retval = PurgeUsers();
763 syslog(LOG_NOTICE, "Purged %d users.", retval);
766 if (!server_shutting_down) {
768 syslog(LOG_NOTICE, "Expired %d messages.", messages_purged);
771 if (!server_shutting_down) {
772 retval = PurgeRooms();
773 syslog(LOG_NOTICE, "Expired %d rooms.", retval);
776 if (!server_shutting_down) {
777 retval = PurgeVisits();
778 syslog(LOG_NOTICE, "Purged %d visits.", retval);
781 if (!server_shutting_down) {
783 ErrMsg = NewStrBuf();
784 retval = PurgeUseTable(ErrMsg);
785 syslog(LOG_NOTICE, "Purged %d entries from the use table.", retval);
789 if (!server_shutting_down) {
790 retval = PurgeEuidIndexTable();
791 syslog(LOG_NOTICE, "Purged %d entries from the EUID index.", retval);
794 if (!server_shutting_down) {
795 retval = PurgeStaleExtAuthAssociations();
796 syslog(LOG_NOTICE, "Purged %d stale external auth associations.", retval);
799 //if (!server_shutting_down) {
800 // FIXME this is where we could do a non-interactive delete of zero-refcount messages
803 if ( (!server_shutting_down) && (CtdlGetConfigInt("c_shrink_db_files") != 0) ) {
804 cdb_compact(); // Shrink the DB files on disk
807 if (!server_shutting_down) {
808 syslog(LOG_INFO, "Auto-purger: finished.");
809 last_purge = now; // So we don't do it again soon
813 syslog(LOG_INFO, "Auto-purger: STOPPED.");
818 // Manually initiate a run of The Dreaded Auto-Purger (tm)
819 void cmd_tdap(char *argbuf) {
820 if (CtdlAccessCheck(ac_aide)) return;
822 cprintf("%d Manually initiating a purger run now.\n", CIT_OK);
826 // Initialization function, called from modules_init.c
827 char *ctdl_module_init_expire(void) {
829 CtdlRegisterProtoHook(cmd_tdap, "TDAP", "Manually initiate auto-purger");
830 CtdlRegisterProtoHook(cmd_gpex, "GPEX", "Get expire policy");
831 CtdlRegisterProtoHook(cmd_spex, "SPEX", "Set expire policy");
832 CtdlRegisterSessionHook(purge_databases, EVT_TIMER, PRIO_CLEANUP + 20);
835 // return our module name for the log