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>
33 #include <libcitadel.h>
36 #include "citserver.h"
47 #include "ctdl_module.h"
51 struct PurgeList *next;
52 char name[ROOMNAMELEN]; /* use the larger of username or roomname */
56 struct VPurgeList *next;
63 struct ValidRoom *next;
69 struct ValidUser *next;
74 struct ctdlroomref *next;
79 struct UPurgeList *next;
84 struct EPurgeList *next;
90 struct PurgeList *UserPurgeList = NULL;
91 struct PurgeList *RoomPurgeList = NULL;
92 struct ValidRoom *ValidRoomList = NULL;
93 struct ValidUser *ValidUserList = NULL;
96 char *users_corrupt_msg = NULL;
97 char *users_zero_msg = NULL;
98 struct ctdlroomref *rr = NULL;
99 int force_purge_now = 0; /* set to nonzero to force a run right now */
103 * First phase of message purge -- gather the locations of messages which
104 * qualify for purging and write them to a temp file.
106 void GatherPurgeMessages(struct ctdlroom *qrbuf, void *data) {
107 struct ExpirePolicy epbuf;
110 struct CtdlMessage *msg = NULL;
112 struct cdbdata *cdbfr;
113 long *msglist = NULL;
117 purgelist = (FILE *)data;
118 fprintf(purgelist, "r=%s\n", qrbuf->QRname);
121 GetExpirePolicy(&epbuf, qrbuf);
123 /* If the room is set to never expire messages ... do nothing */
124 if (epbuf.expire_mode == EXPIRE_NEXTLEVEL) return;
125 if (epbuf.expire_mode == EXPIRE_MANUAL) return;
127 /* Don't purge messages containing system configuration, dumbass. */
128 if (!strcasecmp(qrbuf->QRname, SYSCONFIGROOM)) return;
130 /* Ok, we got this far ... now let's see what's in the room */
131 cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf->QRnumber, sizeof(long));
134 msglist = malloc(cdbfr->len);
135 memcpy(msglist, cdbfr->ptr, cdbfr->len);
136 num_msgs = cdbfr->len / sizeof(long);
140 /* Nothing to do if there aren't any messages */
142 if (msglist != NULL) free(msglist);
146 /* If the room is set to expire by count, do that */
147 if (epbuf.expire_mode == EXPIRE_NUMMSGS) {
148 if (num_msgs > epbuf.expire_value) {
149 for (a=0; a<(num_msgs - epbuf.expire_value); ++a) {
150 fprintf(purgelist, "m=%ld\n", msglist[a]);
156 /* If the room is set to expire by age... */
157 if (epbuf.expire_mode == EXPIRE_AGE) {
158 for (a=0; a<num_msgs; ++a) {
161 msg = CtdlFetchMessage(delnum, 0); /* don't need body */
163 xtime = atol(msg->cm_fields[eTimestamp]);
170 && (now - xtime > (time_t)(epbuf.expire_value * 86400L))) {
171 fprintf(purgelist, "m=%ld\n", delnum);
177 if (msglist != NULL) free(msglist);
182 * Second phase of message purge -- read list of msgs from temp file and
185 void DoPurgeMessages(FILE *purgelist) {
186 char roomname[ROOMNAMELEN];
191 strcpy(roomname, "nonexistent room ___ ___");
192 while (fgets(buf, sizeof buf, purgelist) != NULL) {
193 buf[strlen(buf)-1]=0;
194 if (!strncasecmp(buf, "r=", 2)) {
195 strcpy(roomname, &buf[2]);
197 if (!strncasecmp(buf, "m=", 2)) {
198 msgnum = atol(&buf[2]);
200 CtdlDeleteMessages(roomname, &msgnum, 1, "");
207 void PurgeMessages(void) {
210 syslog(LOG_DEBUG, "PurgeMessages() called");
213 purgelist = tmpfile();
214 if (purgelist == NULL) {
215 syslog(LOG_CRIT, "Can't create purgelist temp file: %s", strerror(errno));
219 CtdlForEachRoom(GatherPurgeMessages, (void *)purgelist );
220 DoPurgeMessages(purgelist);
225 void AddValidUser(char *username, void *data) {
226 struct ValidUser *vuptr;
227 struct ctdluser usbuf;
229 if (CtdlGetUser(&usbuf, username) != 0) {
233 vuptr = (struct ValidUser *)malloc(sizeof(struct ValidUser));
234 vuptr->next = ValidUserList;
235 vuptr->vu_usernum = usbuf.usernum;
236 ValidUserList = vuptr;
239 void AddValidRoom(struct ctdlroom *qrbuf, void *data) {
240 struct ValidRoom *vrptr;
242 vrptr = (struct ValidRoom *)malloc(sizeof(struct ValidRoom));
243 vrptr->next = ValidRoomList;
244 vrptr->vr_roomnum = qrbuf->QRnumber;
245 vrptr->vr_roomgen = qrbuf->QRgen;
246 ValidRoomList = vrptr;
249 void DoPurgeRooms(struct ctdlroom *qrbuf, void *data) {
250 time_t age, purge_secs;
251 struct PurgeList *pptr;
252 struct ValidUser *vuptr;
255 /* For mailbox rooms, there's only one purging rule: if the user who
256 * owns the room still exists, we keep the room; otherwise, we purge
257 * it. Bypass any other rules.
259 if (qrbuf->QRflags & QR_MAILBOX) {
260 /* if user not found, do_purge will be 1 */
262 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
263 if (vuptr->vu_usernum == atol(qrbuf->QRname)) {
269 /* Any of these attributes render a room non-purgable */
270 if (qrbuf->QRflags & QR_PERMANENT) return;
271 if (qrbuf->QRflags & QR_DIRECTORY) return;
272 if (qrbuf->QRflags & QR_NETWORK) return;
273 if (qrbuf->QRflags2 & QR2_SYSTEM) return;
274 if (!strcasecmp(qrbuf->QRname, SYSCONFIGROOM)) return;
275 if (CtdlIsNonEditable(qrbuf)) return;
277 /* If we don't know the modification date, be safe and don't purge */
278 if (qrbuf->QRmtime <= (time_t)0) return;
280 /* If no room purge time is set, be safe and don't purge */
281 if (CtdlGetConfigLong("c_roompurge") < 0) return;
283 /* Otherwise, check the date of last modification */
284 age = time(NULL) - (qrbuf->QRmtime);
285 purge_secs = CtdlGetConfigLong("c_roompurge") * 86400;
286 if (purge_secs <= (time_t)0) return;
287 syslog(LOG_DEBUG, "<%s> is <%ld> seconds old", qrbuf->QRname, (long)age);
288 if (age > purge_secs) do_purge = 1;
292 pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
293 pptr->next = RoomPurgeList;
294 strcpy(pptr->name, qrbuf->QRname);
295 RoomPurgeList = pptr;
301 int PurgeRooms(void) {
302 struct PurgeList *pptr;
303 int num_rooms_purged = 0;
304 struct ctdlroom qrbuf;
305 struct ValidUser *vuptr;
306 char *transcript = NULL;
308 syslog(LOG_DEBUG, "PurgeRooms() called");
310 /* Load up a table full of valid user numbers so we can delete
311 * user-owned rooms for users who no longer exist */
312 ForEachUser(AddValidUser, NULL);
314 /* Then cycle through the room file */
315 CtdlForEachRoom(DoPurgeRooms, NULL);
317 /* Free the valid user list */
318 while (ValidUserList != NULL) {
319 vuptr = ValidUserList->next;
321 ValidUserList = vuptr;
324 transcript = malloc(SIZ);
325 strcpy(transcript, "The following rooms have been auto-purged:\n");
327 while (RoomPurgeList != NULL) {
328 if (CtdlGetRoom(&qrbuf, RoomPurgeList->name) == 0) {
329 transcript=realloc(transcript, strlen(transcript)+SIZ);
330 snprintf(&transcript[strlen(transcript)], SIZ, " %s\n",
332 CtdlDeleteRoom(&qrbuf);
334 pptr = RoomPurgeList->next;
336 RoomPurgeList = pptr;
340 if (num_rooms_purged > 0) CtdlAideMessage(transcript, "Room Autopurger Message");
343 syslog(LOG_DEBUG, "Purged %d rooms.", num_rooms_purged);
344 return(num_rooms_purged);
349 * Back end function to check user accounts for expiration.
351 void do_user_purge(char *username, void *data) {
355 struct PurgeList *pptr;
358 if (CtdlGetUser(&us, username) != 0) {
362 /* Set purge time; if the user overrides the system default, use it */
363 if (us.USuserpurge > 0) {
364 purge_time = ((time_t)us.USuserpurge) * 86400;
367 purge_time = CtdlGetConfigLong("c_userpurge") * 86400;
370 /* The default rule is to not purge. */
373 /* If the user hasn't called in two months and expiring of accounts is turned on, his/her account
374 * has expired, so purge the record.
376 if (CtdlGetConfigLong("c_userpurge") > 0)
379 if ((now - us.lastcall) > purge_time) purge = 1;
382 /* If the record is marked as permanent, don't purge it.
384 if (us.flags & US_PERM) purge = 0;
386 /* If the user is an Aide, don't purge him/her/it.
388 if (us.axlevel == 6) purge = 0;
390 /* If the access level is 0, the record should already have been
391 * deleted, but maybe the user was logged in at the time or something.
392 * Delete the record now.
394 if (us.axlevel == 0) purge = 1;
396 /* If the user set his/her password to 'deleteme', he/she
397 * wishes to be deleted, so purge the record.
398 * Moved this lower down so that aides and permanent users get purged if they ask to be.
400 if (!strcasecmp(us.password, "deleteme")) purge = 1;
402 /* 0 calls is impossible. If there are 0 calls, it must
403 * be a corrupted record, so purge it.
404 * Actually it is possible if an Aide created the user so now we check for less than 0 (DRW)
406 if (us.timescalled < 0) purge = 1;
408 /* any negative user number, is
411 if (us.usernum < 0L) purge = 1;
413 /* Don't purge user 0. That user is there for the system */
414 if (us.usernum == 0L)
416 /* FIXME: Temporary log message. Until we do unauth access with user 0 we should
417 * try to get rid of all user 0 occurences. Many will be remnants from old code so
418 * we will need to try and purge them from users data bases.Some will not have names but
419 * those with names should be purged.
421 syslog(LOG_DEBUG, "Auto purger found a user 0 with name <%s>", us.fullname);
425 /* If the user has no full name entry then we can't purge them
426 * since the actual purge can't find them.
427 * This shouldn't happen but does somehow.
429 if (IsEmptyStr(us.fullname))
436 if (users_corrupt_msg == NULL)
438 users_corrupt_msg = malloc(SIZ);
439 strcpy(users_corrupt_msg,
440 "The auto-purger found the following user numbers with no name.\n"
441 "The system has no way to purge a user with no name,"
442 " and should not be able to create them either.\n"
443 "This indicates corruption of the user DB or possibly a bug.\n"
444 "It may be a good idea to restore your DB from a backup.\n"
448 users_corrupt_msg=realloc(users_corrupt_msg, strlen(users_corrupt_msg)+30);
449 snprintf(&users_corrupt_msg[strlen(users_corrupt_msg)], 29, " %ld\n", us.usernum);
454 pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
455 pptr->next = UserPurgeList;
456 strcpy(pptr->name, us.fullname);
457 UserPurgeList = pptr;
466 int PurgeUsers(void) {
467 struct PurgeList *pptr;
468 int num_users_purged = 0;
469 char *transcript = NULL;
471 syslog(LOG_DEBUG, "PurgeUsers() called");
472 users_not_purged = 0;
474 switch(CtdlGetConfigInt("c_auth_mode")) {
475 case AUTHMODE_NATIVE:
476 ForEachUser(do_user_purge, NULL);
479 syslog(LOG_DEBUG, "User purge for auth mode %d is not implemented.", CtdlGetConfigInt("c_auth_mode"));
483 transcript = malloc(SIZ);
485 if (users_not_purged == 0) {
486 strcpy(transcript, "The auto-purger was told to purge every user. It is\n"
487 "refusing to do this because it usually indicates a problem\n"
488 "such as an inability to communicate with a name service.\n"
490 while (UserPurgeList != NULL) {
491 pptr = UserPurgeList->next;
493 UserPurgeList = pptr;
499 strcpy(transcript, "The following users have been auto-purged:\n");
500 while (UserPurgeList != NULL) {
501 transcript=realloc(transcript, strlen(transcript)+SIZ);
502 snprintf(&transcript[strlen(transcript)], SIZ, " %s\n",
503 UserPurgeList->name);
504 purge_user(UserPurgeList->name);
505 pptr = UserPurgeList->next;
507 UserPurgeList = pptr;
512 if (num_users_purged > 0) CtdlAideMessage(transcript, "User Purge Message");
515 if (users_corrupt_msg) {
516 CtdlAideMessage(users_corrupt_msg, "User Corruption Message");
517 free (users_corrupt_msg);
518 users_corrupt_msg = NULL;
522 CtdlAideMessage(users_zero_msg, "User Zero Message");
523 free (users_zero_msg);
524 users_zero_msg = NULL;
527 syslog(LOG_DEBUG, "Purged %d users.", num_users_purged);
528 return(num_users_purged);
535 * This is a really cumbersome "garbage collection" function. We have to
536 * delete visits which refer to rooms and/or users which no longer exist. In
537 * order to prevent endless traversals of the room and user files, we first
538 * build linked lists of rooms and users which _do_ exist on the system, then
539 * traverse the visit file, checking each record against those two lists and
540 * purging the ones that do not have a match on _both_ lists. (Remember, if
541 * either the room or user being referred to is no longer on the system, the
542 * record is completely useless.)
544 int PurgeVisits(void) {
545 struct cdbdata *cdbvisit;
547 struct VPurgeList *VisitPurgeList = NULL;
548 struct VPurgeList *vptr;
552 struct ValidRoom *vrptr;
553 struct ValidUser *vuptr;
554 int RoomIsValid, UserIsValid;
556 /* First, load up a table full of valid room/gen combinations */
557 CtdlForEachRoom(AddValidRoom, NULL);
559 /* Then load up a table full of valid user numbers */
560 ForEachUser(AddValidUser, NULL);
562 /* Now traverse through the visits, purging irrelevant records... */
563 cdb_rewind(CDB_VISIT);
564 while(cdbvisit = cdb_next_item(CDB_VISIT), cdbvisit != NULL) {
565 memset(&vbuf, 0, sizeof(visit));
566 memcpy(&vbuf, cdbvisit->ptr,
567 ( (cdbvisit->len > sizeof(visit)) ?
568 sizeof(visit) : cdbvisit->len) );
574 /* Check to see if the room exists */
575 for (vrptr=ValidRoomList; vrptr!=NULL; vrptr=vrptr->next) {
576 if ( (vrptr->vr_roomnum==vbuf.v_roomnum)
577 && (vrptr->vr_roomgen==vbuf.v_roomgen))
581 /* Check to see if the user exists */
582 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
583 if (vuptr->vu_usernum == vbuf.v_usernum)
587 /* Put the record on the purge list if it's dead */
588 if ((RoomIsValid==0) || (UserIsValid==0)) {
589 vptr = (struct VPurgeList *)
590 malloc(sizeof(struct VPurgeList));
591 vptr->next = VisitPurgeList;
592 vptr->vp_roomnum = vbuf.v_roomnum;
593 vptr->vp_roomgen = vbuf.v_roomgen;
594 vptr->vp_usernum = vbuf.v_usernum;
595 VisitPurgeList = vptr;
600 /* Free the valid room/gen combination list */
601 while (ValidRoomList != NULL) {
602 vrptr = ValidRoomList->next;
604 ValidRoomList = vrptr;
607 /* Free the valid user list */
608 while (ValidUserList != NULL) {
609 vuptr = ValidUserList->next;
611 ValidUserList = vuptr;
614 /* Now delete every visit on the purged list */
615 while (VisitPurgeList != NULL) {
616 IndexLen = GenerateRelationshipIndex(IndexBuf,
617 VisitPurgeList->vp_roomnum,
618 VisitPurgeList->vp_roomgen,
619 VisitPurgeList->vp_usernum);
620 cdb_delete(CDB_VISIT, IndexBuf, IndexLen);
621 vptr = VisitPurgeList->next;
622 free(VisitPurgeList);
623 VisitPurgeList = vptr;
632 * Purge the use table of old entries.
635 int PurgeUseTable(StrBuf *ErrMsg) {
637 struct cdbdata *cdbut;
639 struct UPurgeList *ul = NULL;
640 struct UPurgeList *uptr;
642 /* Phase 1: traverse through the table, discovering old records... */
644 syslog(LOG_DEBUG, "Purge use table: phase 1");
645 cdb_rewind(CDB_USETABLE);
646 while(cdbut = cdb_next_item(CDB_USETABLE), cdbut != NULL)
648 if (cdbut->len > sizeof(struct UseTable))
649 memcpy(&ut, cdbut->ptr, sizeof(struct UseTable));
652 memset(&ut, 0, sizeof(struct UseTable));
653 memcpy(&ut, cdbut->ptr, cdbut->len);
657 if ( (time(NULL) - ut.ut_timestamp) > USETABLE_RETAIN )
659 uptr = (struct UPurgeList *) malloc(sizeof(struct UPurgeList));
663 safestrncpy(uptr->up_key, ut.ut_msgid, sizeof uptr->up_key);
671 /* Phase 2: delete the records */
672 syslog(LOG_DEBUG, "Purge use table: phase 2");
674 cdb_delete(CDB_USETABLE, ul->up_key, strlen(ul->up_key));
680 syslog(LOG_DEBUG, "Purge use table: finished (purged %d records)", purged);
686 * Purge the EUID Index of old records.
689 int PurgeEuidIndexTable(void) {
691 struct cdbdata *cdbei;
692 struct EPurgeList *el = NULL;
693 struct EPurgeList *eptr;
695 struct CtdlMessage *msg = NULL;
697 /* Phase 1: traverse through the table, discovering old records... */
698 syslog(LOG_DEBUG, "Purge EUID index: phase 1");
699 cdb_rewind(CDB_EUIDINDEX);
700 while(cdbei = cdb_next_item(CDB_EUIDINDEX), cdbei != NULL) {
702 memcpy(&msgnum, cdbei->ptr, sizeof(long));
704 msg = CtdlFetchMessage(msgnum, 0);
706 CM_Free(msg); /* it still exists, so do nothing */
709 eptr = (struct EPurgeList *) malloc(sizeof(struct EPurgeList));
712 eptr->ep_keylen = cdbei->len - sizeof(long);
713 eptr->ep_key = malloc(cdbei->len);
714 memcpy(eptr->ep_key, &cdbei->ptr[sizeof(long)], eptr->ep_keylen);
724 /* Phase 2: delete the records */
725 syslog(LOG_DEBUG, "Purge euid index: phase 2");
727 cdb_delete(CDB_EUIDINDEX, el->ep_key, el->ep_keylen);
734 syslog(LOG_DEBUG, "Purge euid index: finished (purged %d records)", purged);
740 * Purge external auth assocations for missing users (theoretically this will never delete anything)
742 int PurgeStaleExtAuthAssociations(void) {
743 struct cdbdata *cdboi;
744 struct ctdluser usbuf;
745 HashList *keys = NULL;
747 char *deleteme = NULL;
754 keys = NewHash(1, NULL);
755 if (!keys) return(0);
758 cdb_rewind(CDB_EXTAUTH);
759 while (cdboi = cdb_next_item(CDB_EXTAUTH), cdboi != NULL) {
760 if (cdboi->len > sizeof(long)) {
761 memcpy(&usernum, cdboi->ptr, sizeof(long));
762 if (CtdlGetUserByNumber(&usbuf, usernum) != 0) {
763 deleteme = strdup(cdboi->ptr + sizeof(long)),
764 Put(keys, deleteme, strlen(deleteme), deleteme, NULL);
770 /* Go through the hash list, deleting keys we stored in it */
772 HashPos = GetNewHashPos(keys, 0);
773 while (GetNextHashPos(keys, HashPos, &len, &Key, &Value)!=0)
775 syslog(LOG_DEBUG, "Deleting associated external authenticator <%s>", (char*)Value);
776 cdb_delete(CDB_EXTAUTH, Value, strlen(Value));
777 /* note: don't free(Value) -- deleting the hash list will handle this for us */
780 DeleteHashPos(&HashPos);
786 void purge_databases(void)
789 static time_t last_purge = 0;
793 /* Do the auto-purge if the current hour equals the purge hour,
794 * but not if the operation has already been performed in the
795 * last twelve hours. This is usually enough granularity.
798 localtime_r(&now, &tm);
799 if (((tm.tm_hour != CtdlGetConfigInt("c_purge_hour")) || ((now - last_purge) < 43200)) && (force_purge_now == 0)) {
803 syslog(LOG_INFO, "Auto-purger: starting.");
805 if (!server_shutting_down) {
806 retval = PurgeUsers();
807 syslog(LOG_NOTICE, "Purged %d users.", retval);
810 if (!server_shutting_down) {
812 syslog(LOG_NOTICE, "Expired %d messages.", messages_purged);
815 if (!server_shutting_down) {
816 retval = PurgeRooms();
817 syslog(LOG_NOTICE, "Expired %d rooms.", retval);
820 if (!server_shutting_down) {
821 retval = PurgeVisits();
822 syslog(LOG_NOTICE, "Purged %d visits.", retval);
825 if (!server_shutting_down) {
827 ErrMsg = NewStrBuf();
828 retval = PurgeUseTable(ErrMsg);
829 syslog(LOG_NOTICE, "Purged %d entries from the use table.", retval);
833 if (!server_shutting_down) {
834 retval = PurgeEuidIndexTable();
835 syslog(LOG_NOTICE, "Purged %d entries from the EUID index.", retval);
838 if (!server_shutting_down) {
839 retval = PurgeStaleExtAuthAssociations();
840 syslog(LOG_NOTICE, "Purged %d stale external auth associations.", retval);
843 //if (!server_shutting_down) {
844 // FIXME this is where we could do a non-interactive delete of zero-refcount messages
847 if ( (!server_shutting_down) && (CtdlGetConfigInt("c_shrink_db_files") != 0) ) {
848 cdb_compact(); // Shrink the DB files on disk
851 if (!server_shutting_down) {
852 syslog(LOG_INFO, "Auto-purger: finished.");
853 last_purge = now; // So we don't do it again soon
857 syslog(LOG_INFO, "Auto-purger: STOPPED.");
863 * Manually initiate a run of The Dreaded Auto-Purger (tm)
865 void cmd_tdap(char *argbuf) {
866 if (CtdlAccessCheck(ac_aide)) return;
868 cprintf("%d Manually initiating a purger run now.\n", CIT_OK);
872 CTDL_MODULE_INIT(expire)
876 CtdlRegisterProtoHook(cmd_tdap, "TDAP", "Manually initiate auto-purger");
877 CtdlRegisterProtoHook(cmd_gpex, "GPEX", "Get expire policy");
878 CtdlRegisterProtoHook(cmd_spex, "SPEX", "Set expire policy");
879 CtdlRegisterSessionHook(purge_databases, EVT_TIMER, PRIO_CLEANUP + 20);
882 /* return our module name for the log */