2 * This module handles the expiry of old messages and the purging of old users.
4 * You might also see this module affectionately referred to as TDAP (The Dreaded Auto-Purger).
6 * Copyright (c) 1988-2020 by citadel.org (Art Cancro, Wilifried Goesgens, and others)
8 * This program is open source software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License as published
10 * by the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
28 #include <sys/types.h>
30 #if TIME_WITH_SYS_TIME
31 # include <sys/time.h>
35 # include <sys/time.h>
44 #include <libcitadel.h>
47 #include "citserver.h"
58 #include "ctdl_module.h"
62 struct PurgeList *next;
63 char name[ROOMNAMELEN]; /* use the larger of username or roomname */
67 struct VPurgeList *next;
74 struct ValidRoom *next;
80 struct ValidUser *next;
85 struct ctdlroomref *next;
90 struct UPurgeList *next;
95 struct EPurgeList *next;
101 struct PurgeList *UserPurgeList = NULL;
102 struct PurgeList *RoomPurgeList = NULL;
103 struct ValidRoom *ValidRoomList = NULL;
104 struct ValidUser *ValidUserList = NULL;
106 int users_not_purged;
107 char *users_corrupt_msg = NULL;
108 char *users_zero_msg = NULL;
109 struct ctdlroomref *rr = NULL;
110 int force_purge_now = 0; /* set to nonzero to force a run right now */
114 * First phase of message purge -- gather the locations of messages which
115 * qualify for purging and write them to a temp file.
117 void GatherPurgeMessages(struct ctdlroom *qrbuf, void *data) {
118 struct ExpirePolicy epbuf;
121 struct CtdlMessage *msg = NULL;
123 struct cdbdata *cdbfr;
124 long *msglist = NULL;
128 purgelist = (FILE *)data;
129 fprintf(purgelist, "r=%s\n", qrbuf->QRname);
132 GetExpirePolicy(&epbuf, qrbuf);
134 /* If the room is set to never expire messages ... do nothing */
135 if (epbuf.expire_mode == EXPIRE_NEXTLEVEL) return;
136 if (epbuf.expire_mode == EXPIRE_MANUAL) return;
138 /* Don't purge messages containing system configuration, dumbass. */
139 if (!strcasecmp(qrbuf->QRname, SYSCONFIGROOM)) return;
141 /* Ok, we got this far ... now let's see what's in the room */
142 cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf->QRnumber, sizeof(long));
145 msglist = malloc(cdbfr->len);
146 memcpy(msglist, cdbfr->ptr, cdbfr->len);
147 num_msgs = cdbfr->len / sizeof(long);
151 /* Nothing to do if there aren't any messages */
153 if (msglist != NULL) free(msglist);
157 /* If the room is set to expire by count, do that */
158 if (epbuf.expire_mode == EXPIRE_NUMMSGS) {
159 if (num_msgs > epbuf.expire_value) {
160 for (a=0; a<(num_msgs - epbuf.expire_value); ++a) {
161 fprintf(purgelist, "m=%ld\n", msglist[a]);
167 /* If the room is set to expire by age... */
168 if (epbuf.expire_mode == EXPIRE_AGE) {
169 for (a=0; a<num_msgs; ++a) {
172 msg = CtdlFetchMessage(delnum, 0); /* don't need body */
174 xtime = atol(msg->cm_fields[eTimestamp]);
181 && (now - xtime > (time_t)(epbuf.expire_value * 86400L))) {
182 fprintf(purgelist, "m=%ld\n", delnum);
188 if (msglist != NULL) free(msglist);
193 * Second phase of message purge -- read list of msgs from temp file and
196 void DoPurgeMessages(FILE *purgelist) {
197 char roomname[ROOMNAMELEN];
202 strcpy(roomname, "nonexistent room ___ ___");
203 while (fgets(buf, sizeof buf, purgelist) != NULL) {
204 buf[strlen(buf)-1]=0;
205 if (!strncasecmp(buf, "r=", 2)) {
206 strcpy(roomname, &buf[2]);
208 if (!strncasecmp(buf, "m=", 2)) {
209 msgnum = atol(&buf[2]);
211 CtdlDeleteMessages(roomname, &msgnum, 1, "");
218 void PurgeMessages(void) {
221 syslog(LOG_DEBUG, "PurgeMessages() called");
224 purgelist = tmpfile();
225 if (purgelist == NULL) {
226 syslog(LOG_CRIT, "Can't create purgelist temp file: %s", strerror(errno));
230 CtdlForEachRoom(GatherPurgeMessages, (void *)purgelist );
231 DoPurgeMessages(purgelist);
236 void AddValidUser(char *username, void *data) {
237 struct ValidUser *vuptr;
238 struct ctdluser usbuf;
240 if (CtdlGetUser(&usbuf, username) != 0) {
244 vuptr = (struct ValidUser *)malloc(sizeof(struct ValidUser));
245 vuptr->next = ValidUserList;
246 vuptr->vu_usernum = usbuf.usernum;
247 ValidUserList = vuptr;
250 void AddValidRoom(struct ctdlroom *qrbuf, void *data) {
251 struct ValidRoom *vrptr;
253 vrptr = (struct ValidRoom *)malloc(sizeof(struct ValidRoom));
254 vrptr->next = ValidRoomList;
255 vrptr->vr_roomnum = qrbuf->QRnumber;
256 vrptr->vr_roomgen = qrbuf->QRgen;
257 ValidRoomList = vrptr;
260 void DoPurgeRooms(struct ctdlroom *qrbuf, void *data) {
261 time_t age, purge_secs;
262 struct PurgeList *pptr;
263 struct ValidUser *vuptr;
266 /* For mailbox rooms, there's only one purging rule: if the user who
267 * owns the room still exists, we keep the room; otherwise, we purge
268 * it. Bypass any other rules.
270 if (qrbuf->QRflags & QR_MAILBOX) {
271 /* if user not found, do_purge will be 1 */
273 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
274 if (vuptr->vu_usernum == atol(qrbuf->QRname)) {
280 /* Any of these attributes render a room non-purgable */
281 if (qrbuf->QRflags & QR_PERMANENT) return;
282 if (qrbuf->QRflags & QR_DIRECTORY) return;
283 if (qrbuf->QRflags & QR_NETWORK) return;
284 if (qrbuf->QRflags2 & QR2_SYSTEM) return;
285 if (!strcasecmp(qrbuf->QRname, SYSCONFIGROOM)) return;
286 if (CtdlIsNonEditable(qrbuf)) return;
288 /* If we don't know the modification date, be safe and don't purge */
289 if (qrbuf->QRmtime <= (time_t)0) return;
291 /* If no room purge time is set, be safe and don't purge */
292 if (CtdlGetConfigLong("c_roompurge") < 0) return;
294 /* Otherwise, check the date of last modification */
295 age = time(NULL) - (qrbuf->QRmtime);
296 purge_secs = CtdlGetConfigLong("c_roompurge") * 86400;
297 if (purge_secs <= (time_t)0) return;
298 syslog(LOG_DEBUG, "<%s> is <%ld> seconds old", qrbuf->QRname, (long)age);
299 if (age > purge_secs) do_purge = 1;
303 pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
304 pptr->next = RoomPurgeList;
305 strcpy(pptr->name, qrbuf->QRname);
306 RoomPurgeList = pptr;
312 int PurgeRooms(void) {
313 struct PurgeList *pptr;
314 int num_rooms_purged = 0;
315 struct ctdlroom qrbuf;
316 struct ValidUser *vuptr;
317 char *transcript = NULL;
319 syslog(LOG_DEBUG, "PurgeRooms() called");
321 /* Load up a table full of valid user numbers so we can delete
322 * user-owned rooms for users who no longer exist */
323 ForEachUser(AddValidUser, NULL);
325 /* Then cycle through the room file */
326 CtdlForEachRoom(DoPurgeRooms, NULL);
328 /* Free the valid user list */
329 while (ValidUserList != NULL) {
330 vuptr = ValidUserList->next;
332 ValidUserList = vuptr;
335 transcript = malloc(SIZ);
336 strcpy(transcript, "The following rooms have been auto-purged:\n");
338 while (RoomPurgeList != NULL) {
339 if (CtdlGetRoom(&qrbuf, RoomPurgeList->name) == 0) {
340 transcript=realloc(transcript, strlen(transcript)+SIZ);
341 snprintf(&transcript[strlen(transcript)], SIZ, " %s\n",
343 CtdlDeleteRoom(&qrbuf);
345 pptr = RoomPurgeList->next;
347 RoomPurgeList = pptr;
351 if (num_rooms_purged > 0) CtdlAideMessage(transcript, "Room Autopurger Message");
354 syslog(LOG_DEBUG, "Purged %d rooms.", num_rooms_purged);
355 return(num_rooms_purged);
360 * Back end function to check user accounts for expiration.
362 void do_user_purge(char *username, void *data) {
366 struct PurgeList *pptr;
369 if (CtdlGetUser(&us, username) != 0) {
373 /* Set purge time; if the user overrides the system default, use it */
374 if (us.USuserpurge > 0) {
375 purge_time = ((time_t)us.USuserpurge) * 86400;
378 purge_time = CtdlGetConfigLong("c_userpurge") * 86400;
381 /* The default rule is to not purge. */
384 /* If the user hasn't called in two months and expiring of accounts is turned on, his/her account
385 * has expired, so purge the record.
387 if (CtdlGetConfigLong("c_userpurge") > 0)
390 if ((now - us.lastcall) > purge_time) purge = 1;
393 /* If the record is marked as permanent, don't purge it.
395 if (us.flags & US_PERM) purge = 0;
397 /* If the user is an Aide, don't purge him/her/it.
399 if (us.axlevel == 6) purge = 0;
401 /* If the access level is 0, the record should already have been
402 * deleted, but maybe the user was logged in at the time or something.
403 * Delete the record now.
405 if (us.axlevel == 0) purge = 1;
407 /* If the user set his/her password to 'deleteme', he/she
408 * wishes to be deleted, so purge the record.
409 * Moved this lower down so that aides and permanent users get purged if they ask to be.
411 if (!strcasecmp(us.password, "deleteme")) purge = 1;
413 /* 0 calls is impossible. If there are 0 calls, it must
414 * be a corrupted record, so purge it.
415 * Actually it is possible if an Aide created the user so now we check for less than 0 (DRW)
417 if (us.timescalled < 0) purge = 1;
419 /* any negative user number, is
422 if (us.usernum < 0L) purge = 1;
424 /* Don't purge user 0. That user is there for the system */
425 if (us.usernum == 0L)
427 /* FIXME: Temporary log message. Until we do unauth access with user 0 we should
428 * try to get rid of all user 0 occurences. Many will be remnants from old code so
429 * we will need to try and purge them from users data bases.Some will not have names but
430 * those with names should be purged.
432 syslog(LOG_DEBUG, "Auto purger found a user 0 with name <%s>", us.fullname);
436 /* If the user has no full name entry then we can't purge them
437 * since the actual purge can't find them.
438 * This shouldn't happen but does somehow.
440 if (IsEmptyStr(us.fullname))
447 if (users_corrupt_msg == NULL)
449 users_corrupt_msg = malloc(SIZ);
450 strcpy(users_corrupt_msg,
451 "The auto-purger found the following user numbers with no name.\n"
452 "The system has no way to purge a user with no name,"
453 " and should not be able to create them either.\n"
454 "This indicates corruption of the user DB or possibly a bug.\n"
455 "It may be a good idea to restore your DB from a backup.\n"
459 users_corrupt_msg=realloc(users_corrupt_msg, strlen(users_corrupt_msg)+30);
460 snprintf(&users_corrupt_msg[strlen(users_corrupt_msg)], 29, " %ld\n", us.usernum);
465 pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
466 pptr->next = UserPurgeList;
467 strcpy(pptr->name, us.fullname);
468 UserPurgeList = pptr;
477 int PurgeUsers(void) {
478 struct PurgeList *pptr;
479 int num_users_purged = 0;
480 char *transcript = NULL;
482 syslog(LOG_DEBUG, "PurgeUsers() called");
483 users_not_purged = 0;
485 switch(CtdlGetConfigInt("c_auth_mode")) {
486 case AUTHMODE_NATIVE:
487 ForEachUser(do_user_purge, NULL);
490 syslog(LOG_DEBUG, "User purge for auth mode %d is not implemented.", CtdlGetConfigInt("c_auth_mode"));
494 transcript = malloc(SIZ);
496 if (users_not_purged == 0) {
497 strcpy(transcript, "The auto-purger was told to purge every user. It is\n"
498 "refusing to do this because it usually indicates a problem\n"
499 "such as an inability to communicate with a name service.\n"
501 while (UserPurgeList != NULL) {
502 pptr = UserPurgeList->next;
504 UserPurgeList = pptr;
510 strcpy(transcript, "The following users have been auto-purged:\n");
511 while (UserPurgeList != NULL) {
512 transcript=realloc(transcript, strlen(transcript)+SIZ);
513 snprintf(&transcript[strlen(transcript)], SIZ, " %s\n",
514 UserPurgeList->name);
515 purge_user(UserPurgeList->name);
516 pptr = UserPurgeList->next;
518 UserPurgeList = pptr;
523 if (num_users_purged > 0) CtdlAideMessage(transcript, "User Purge Message");
526 if (users_corrupt_msg) {
527 CtdlAideMessage(users_corrupt_msg, "User Corruption Message");
528 free (users_corrupt_msg);
529 users_corrupt_msg = NULL;
533 CtdlAideMessage(users_zero_msg, "User Zero Message");
534 free (users_zero_msg);
535 users_zero_msg = NULL;
538 syslog(LOG_DEBUG, "Purged %d users.", num_users_purged);
539 return(num_users_purged);
546 * This is a really cumbersome "garbage collection" function. We have to
547 * delete visits which refer to rooms and/or users which no longer exist. In
548 * order to prevent endless traversals of the room and user files, we first
549 * build linked lists of rooms and users which _do_ exist on the system, then
550 * traverse the visit file, checking each record against those two lists and
551 * purging the ones that do not have a match on _both_ lists. (Remember, if
552 * either the room or user being referred to is no longer on the system, the
553 * record is completely useless.)
555 int PurgeVisits(void) {
556 struct cdbdata *cdbvisit;
558 struct VPurgeList *VisitPurgeList = NULL;
559 struct VPurgeList *vptr;
563 struct ValidRoom *vrptr;
564 struct ValidUser *vuptr;
565 int RoomIsValid, UserIsValid;
567 /* First, load up a table full of valid room/gen combinations */
568 CtdlForEachRoom(AddValidRoom, NULL);
570 /* Then load up a table full of valid user numbers */
571 ForEachUser(AddValidUser, NULL);
573 /* Now traverse through the visits, purging irrelevant records... */
574 cdb_rewind(CDB_VISIT);
575 while(cdbvisit = cdb_next_item(CDB_VISIT), cdbvisit != NULL) {
576 memset(&vbuf, 0, sizeof(visit));
577 memcpy(&vbuf, cdbvisit->ptr,
578 ( (cdbvisit->len > sizeof(visit)) ?
579 sizeof(visit) : cdbvisit->len) );
585 /* Check to see if the room exists */
586 for (vrptr=ValidRoomList; vrptr!=NULL; vrptr=vrptr->next) {
587 if ( (vrptr->vr_roomnum==vbuf.v_roomnum)
588 && (vrptr->vr_roomgen==vbuf.v_roomgen))
592 /* Check to see if the user exists */
593 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
594 if (vuptr->vu_usernum == vbuf.v_usernum)
598 /* Put the record on the purge list if it's dead */
599 if ((RoomIsValid==0) || (UserIsValid==0)) {
600 vptr = (struct VPurgeList *)
601 malloc(sizeof(struct VPurgeList));
602 vptr->next = VisitPurgeList;
603 vptr->vp_roomnum = vbuf.v_roomnum;
604 vptr->vp_roomgen = vbuf.v_roomgen;
605 vptr->vp_usernum = vbuf.v_usernum;
606 VisitPurgeList = vptr;
611 /* Free the valid room/gen combination list */
612 while (ValidRoomList != NULL) {
613 vrptr = ValidRoomList->next;
615 ValidRoomList = vrptr;
618 /* Free the valid user list */
619 while (ValidUserList != NULL) {
620 vuptr = ValidUserList->next;
622 ValidUserList = vuptr;
625 /* Now delete every visit on the purged list */
626 while (VisitPurgeList != NULL) {
627 IndexLen = GenerateRelationshipIndex(IndexBuf,
628 VisitPurgeList->vp_roomnum,
629 VisitPurgeList->vp_roomgen,
630 VisitPurgeList->vp_usernum);
631 cdb_delete(CDB_VISIT, IndexBuf, IndexLen);
632 vptr = VisitPurgeList->next;
633 free(VisitPurgeList);
634 VisitPurgeList = vptr;
643 * Purge the use table of old entries.
646 int PurgeUseTable(StrBuf *ErrMsg) {
648 struct cdbdata *cdbut;
650 struct UPurgeList *ul = NULL;
651 struct UPurgeList *uptr;
653 /* Phase 1: traverse through the table, discovering old records... */
655 syslog(LOG_DEBUG, "Purge use table: phase 1");
656 cdb_rewind(CDB_USETABLE);
657 while(cdbut = cdb_next_item(CDB_USETABLE), cdbut != NULL)
659 if (cdbut->len > sizeof(struct UseTable))
660 memcpy(&ut, cdbut->ptr, sizeof(struct UseTable));
663 memset(&ut, 0, sizeof(struct UseTable));
664 memcpy(&ut, cdbut->ptr, cdbut->len);
668 if ( (time(NULL) - ut.ut_timestamp) > USETABLE_RETAIN )
670 uptr = (struct UPurgeList *) malloc(sizeof(struct UPurgeList));
674 safestrncpy(uptr->up_key, ut.ut_msgid, sizeof uptr->up_key);
682 /* Phase 2: delete the records */
683 syslog(LOG_DEBUG, "Purge use table: phase 2");
685 cdb_delete(CDB_USETABLE, ul->up_key, strlen(ul->up_key));
691 syslog(LOG_DEBUG, "Purge use table: finished (purged %d records)", purged);
697 * Purge the EUID Index of old records.
700 int PurgeEuidIndexTable(void) {
702 struct cdbdata *cdbei;
703 struct EPurgeList *el = NULL;
704 struct EPurgeList *eptr;
706 struct CtdlMessage *msg = NULL;
708 /* Phase 1: traverse through the table, discovering old records... */
709 syslog(LOG_DEBUG, "Purge EUID index: phase 1");
710 cdb_rewind(CDB_EUIDINDEX);
711 while(cdbei = cdb_next_item(CDB_EUIDINDEX), cdbei != NULL) {
713 memcpy(&msgnum, cdbei->ptr, sizeof(long));
715 msg = CtdlFetchMessage(msgnum, 0);
717 CM_Free(msg); /* it still exists, so do nothing */
720 eptr = (struct EPurgeList *) malloc(sizeof(struct EPurgeList));
723 eptr->ep_keylen = cdbei->len - sizeof(long);
724 eptr->ep_key = malloc(cdbei->len);
725 memcpy(eptr->ep_key, &cdbei->ptr[sizeof(long)], eptr->ep_keylen);
735 /* Phase 2: delete the records */
736 syslog(LOG_DEBUG, "Purge euid index: phase 2");
738 cdb_delete(CDB_EUIDINDEX, el->ep_key, el->ep_keylen);
745 syslog(LOG_DEBUG, "Purge euid index: finished (purged %d records)", purged);
751 * Purge external auth assocations for missing users (theoretically this will never delete anything)
753 int PurgeStaleExtAuthAssociations(void) {
754 struct cdbdata *cdboi;
755 struct ctdluser usbuf;
756 HashList *keys = NULL;
758 char *deleteme = NULL;
765 keys = NewHash(1, NULL);
766 if (!keys) return(0);
769 cdb_rewind(CDB_EXTAUTH);
770 while (cdboi = cdb_next_item(CDB_EXTAUTH), cdboi != NULL) {
771 if (cdboi->len > sizeof(long)) {
772 memcpy(&usernum, cdboi->ptr, sizeof(long));
773 if (CtdlGetUserByNumber(&usbuf, usernum) != 0) {
774 deleteme = strdup(cdboi->ptr + sizeof(long)),
775 Put(keys, deleteme, strlen(deleteme), deleteme, NULL);
781 /* Go through the hash list, deleting keys we stored in it */
783 HashPos = GetNewHashPos(keys, 0);
784 while (GetNextHashPos(keys, HashPos, &len, &Key, &Value)!=0)
786 syslog(LOG_DEBUG, "Deleting associated external authenticator <%s>", (char*)Value);
787 cdb_delete(CDB_EXTAUTH, Value, strlen(Value));
788 /* note: don't free(Value) -- deleting the hash list will handle this for us */
791 DeleteHashPos(&HashPos);
797 void purge_databases(void)
800 static time_t last_purge = 0;
804 /* Do the auto-purge if the current hour equals the purge hour,
805 * but not if the operation has already been performed in the
806 * last twelve hours. This is usually enough granularity.
809 localtime_r(&now, &tm);
810 if (((tm.tm_hour != CtdlGetConfigInt("c_purge_hour")) || ((now - last_purge) < 43200)) && (force_purge_now == 0))
815 syslog(LOG_INFO, "Auto-purger: starting.");
817 if (!server_shutting_down)
819 retval = PurgeUsers();
820 syslog(LOG_NOTICE, "Purged %d users.", retval);
823 if (!server_shutting_down)
826 syslog(LOG_NOTICE, "Expired %d messages.", messages_purged);
829 if (!server_shutting_down)
831 retval = PurgeRooms();
832 syslog(LOG_NOTICE, "Expired %d rooms.", retval);
835 if (!server_shutting_down)
837 retval = PurgeVisits();
838 syslog(LOG_NOTICE, "Purged %d visits.", retval);
841 if (!server_shutting_down)
845 ErrMsg = NewStrBuf ();
846 retval = PurgeUseTable(ErrMsg);
847 syslog(LOG_NOTICE, "Purged %d entries from the use table.", retval);
851 if (!server_shutting_down)
853 retval = PurgeEuidIndexTable();
854 syslog(LOG_NOTICE, "Purged %d entries from the EUID index.", retval);
857 if (!server_shutting_down)
859 retval = PurgeStaleExtAuthAssociations();
860 syslog(LOG_NOTICE, "Purged %d stale external auth associations.", retval);
863 //if (!server_shutting_down)
865 // FIXME this is where we could do a non-interactive delete of zero-refcount messages
868 if ( (!server_shutting_down) && (CtdlGetConfigInt("c_shrink_db_files") != 0) )
870 cdb_compact(); // Shrink the DB files on disk
873 if (!server_shutting_down)
875 syslog(LOG_INFO, "Auto-purger: finished.");
876 last_purge = now; // So we don't do it again soon
880 syslog(LOG_INFO, "Auto-purger: STOPPED.");
886 * Manually initiate a run of The Dreaded Auto-Purger (tm)
888 void cmd_tdap(char *argbuf) {
889 if (CtdlAccessCheck(ac_aide)) return;
891 cprintf("%d Manually initiating a purger run now.\n", CIT_OK);
895 CTDL_MODULE_INIT(expire)
899 CtdlRegisterProtoHook(cmd_tdap, "TDAP", "Manually initiate auto-purger");
900 CtdlRegisterProtoHook(cmd_gpex, "GPEX", "Get expire policy");
901 CtdlRegisterProtoHook(cmd_spex, "SPEX", "Set expire policy");
902 CtdlRegisterSessionHook(purge_databases, EVT_TIMER, PRIO_CLEANUP + 20);
905 /* return our module name for the log */