4 * This module handles the expiry of old messages and the purging of old users.
10 * A brief technical discussion:
12 * Several of the purge operations found in this module operate in two
13 * stages: the first stage generates a linked list of objects to be deleted,
14 * then the second stage deletes all listed objects from the database.
16 * At first glance this may seem cumbersome and unnecessary. The reason it is
17 * implemented in this way is because Berkeley DB, and possibly other backends
18 * we may hook into in the future, explicitly do _not_ support the deletion of
19 * records from a file while the file is being traversed. The delete operation
20 * will succeed, but the traversal is not guaranteed to visit every object if
21 * this is done. Therefore we utilize the two-stage purge.
23 * When using Berkeley DB, there's another reason for the two-phase purge: we
24 * don't want the entire thing being done as one huge transaction.
36 #include <sys/types.h>
38 #if TIME_WITH_SYS_TIME
39 # include <sys/time.h>
43 # include <sys/time.h>
52 #include <libcitadel.h>
55 #include "citserver.h"
64 #include "serv_network.h" /* Needed for defenition of UseTable */
67 #include "ctdl_module.h"
71 struct PurgeList *next;
72 char name[ROOMNAMELEN]; /* use the larger of username or roomname */
76 struct VPurgeList *next;
83 struct ValidRoom *next;
89 struct ValidUser *next;
95 struct ctdlroomref *next;
100 struct UPurgeList *next;
105 struct EPurgeList *next;
111 struct PurgeList *UserPurgeList = NULL;
112 struct PurgeList *RoomPurgeList = NULL;
113 struct ValidRoom *ValidRoomList = NULL;
114 struct ValidUser *ValidUserList = NULL;
116 int users_not_purged;
117 char *users_corrupt_msg = NULL;
119 struct ctdlroomref *rr = NULL;
121 extern struct CitContext *ContextList;
125 * First phase of message purge -- gather the locations of messages which
126 * qualify for purging and write them to a temp file.
128 void GatherPurgeMessages(struct ctdlroom *qrbuf, void *data) {
129 struct ExpirePolicy epbuf;
132 struct CtdlMessage *msg = NULL;
134 struct cdbdata *cdbfr;
135 long *msglist = NULL;
139 purgelist = (FILE *)data;
140 fprintf(purgelist, "r=%s\n", qrbuf->QRname);
143 GetExpirePolicy(&epbuf, qrbuf);
145 /* If the room is set to never expire messages ... do nothing */
146 if (epbuf.expire_mode == EXPIRE_NEXTLEVEL) return;
147 if (epbuf.expire_mode == EXPIRE_MANUAL) return;
149 cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf->QRnumber, sizeof(long));
152 msglist = malloc(cdbfr->len);
153 memcpy(msglist, cdbfr->ptr, cdbfr->len);
154 num_msgs = cdbfr->len / sizeof(long);
158 /* Nothing to do if there aren't any messages */
160 if (msglist != NULL) free(msglist);
164 /* If the room is set to expire by count, do that */
165 if (epbuf.expire_mode == EXPIRE_NUMMSGS) {
166 if (num_msgs > epbuf.expire_value) {
167 for (a=0; a<(num_msgs - epbuf.expire_value); ++a) {
168 fprintf(purgelist, "m=%ld\n", msglist[a]);
174 /* If the room is set to expire by age... */
175 if (epbuf.expire_mode == EXPIRE_AGE) {
176 for (a=0; a<num_msgs; ++a) {
179 msg = CtdlFetchMessage(delnum, 0); /* dont need body */
181 xtime = atol(msg->cm_fields['T']);
182 CtdlFreeMessage(msg);
188 && (now - xtime > (time_t)(epbuf.expire_value * 86400L))) {
189 fprintf(purgelist, "m=%ld\n", delnum);
195 if (msglist != NULL) free(msglist);
200 * Second phase of message purge -- read list of msgs from temp file and
203 void DoPurgeMessages(FILE *purgelist) {
204 char roomname[ROOMNAMELEN];
209 strcpy(roomname, "nonexistent room ___ ___");
210 while (fgets(buf, sizeof buf, purgelist) != NULL) {
211 buf[strlen(buf)-1]=0;
212 if (!strncasecmp(buf, "r=", 2)) {
213 strcpy(roomname, &buf[2]);
215 if (!strncasecmp(buf, "m=", 2)) {
216 msgnum = atol(&buf[2]);
218 CtdlDeleteMessages(roomname, &msgnum, 1, "");
225 void PurgeMessages(void) {
228 CtdlLogPrintf(CTDL_DEBUG, "PurgeMessages() called\n");
231 purgelist = tmpfile();
232 if (purgelist == NULL) {
233 CtdlLogPrintf(CTDL_CRIT, "Can't create purgelist temp file: %s\n",
238 ForEachRoom(GatherPurgeMessages, (void *)purgelist );
239 DoPurgeMessages(purgelist);
244 void AddValidUser(struct ctdluser *usbuf, void *data) {
245 struct ValidUser *vuptr;
247 vuptr = (struct ValidUser *)malloc(sizeof(struct ValidUser));
248 vuptr->next = ValidUserList;
249 vuptr->vu_usernum = usbuf->usernum;
250 ValidUserList = vuptr;
253 void AddValidRoom(struct ctdlroom *qrbuf, void *data) {
254 struct ValidRoom *vrptr;
256 vrptr = (struct ValidRoom *)malloc(sizeof(struct ValidRoom));
257 vrptr->next = ValidRoomList;
258 vrptr->vr_roomnum = qrbuf->QRnumber;
259 vrptr->vr_roomgen = qrbuf->QRgen;
260 ValidRoomList = vrptr;
263 void DoPurgeRooms(struct ctdlroom *qrbuf, void *data) {
264 time_t age, purge_secs;
265 struct PurgeList *pptr;
266 struct ValidUser *vuptr;
269 /* For mailbox rooms, there's only one purging rule: if the user who
270 * owns the room still exists, we keep the room; otherwise, we purge
271 * it. Bypass any other rules.
273 if (qrbuf->QRflags & QR_MAILBOX) {
274 /* if user not found, do_purge will be 1 */
276 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
277 if (vuptr->vu_usernum == atol(qrbuf->QRname)) {
283 /* Any of these attributes render a room non-purgable */
284 if (qrbuf->QRflags & QR_PERMANENT) return;
285 if (qrbuf->QRflags & QR_DIRECTORY) return;
286 if (qrbuf->QRflags & QR_NETWORK) return;
287 if (!strcasecmp(qrbuf->QRname, SYSCONFIGROOM)) return;
288 if (is_noneditable(qrbuf)) return;
290 /* If we don't know the modification date, be safe and don't purge */
291 if (qrbuf->QRmtime <= (time_t)0) return;
293 /* If no room purge time is set, be safe and don't purge */
294 if (config.c_roompurge < 0) return;
296 /* Otherwise, check the date of last modification */
297 age = time(NULL) - (qrbuf->QRmtime);
298 purge_secs = (time_t)config.c_roompurge * (time_t)86400;
299 if (purge_secs <= (time_t)0) return;
300 CtdlLogPrintf(CTDL_DEBUG, "<%s> is <%ld> seconds old\n", qrbuf->QRname, (long)age);
301 if (age > purge_secs) do_purge = 1;
305 pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
306 pptr->next = RoomPurgeList;
307 strcpy(pptr->name, qrbuf->QRname);
308 RoomPurgeList = pptr;
315 int PurgeRooms(void) {
316 struct PurgeList *pptr;
317 int num_rooms_purged = 0;
318 struct ctdlroom qrbuf;
319 struct ValidUser *vuptr;
320 char *transcript = NULL;
322 CtdlLogPrintf(CTDL_DEBUG, "PurgeRooms() called\n");
325 /* Load up a table full of valid user numbers so we can delete
326 * user-owned rooms for users who no longer exist */
327 ForEachUser(AddValidUser, NULL);
329 /* Then cycle through the room file */
330 ForEachRoom(DoPurgeRooms, NULL);
332 /* Free the valid user list */
333 while (ValidUserList != NULL) {
334 vuptr = ValidUserList->next;
336 ValidUserList = vuptr;
340 transcript = malloc(SIZ);
341 strcpy(transcript, "The following rooms have been auto-purged:\n");
343 while (RoomPurgeList != NULL) {
344 if (getroom(&qrbuf, RoomPurgeList->name) == 0) {
345 transcript=realloc(transcript, strlen(transcript)+SIZ);
346 snprintf(&transcript[strlen(transcript)], SIZ, " %s\n",
350 pptr = RoomPurgeList->next;
352 RoomPurgeList = pptr;
356 if (num_rooms_purged > 0) aide_message(transcript, "Room Autopurger Message");
359 CtdlLogPrintf(CTDL_DEBUG, "Purged %d rooms.\n", num_rooms_purged);
360 return(num_rooms_purged);
365 * Back end function to check user accounts for associated Unix accounts
366 * which no longer exist. (Only relevant for host auth mode.)
368 void do_uid_user_purge(struct ctdluser *us, void *data) {
369 struct PurgeList *pptr;
371 if ((us->uid != (-1)) && (us->uid != CTDLUID)) {
372 if (getpwuid(us->uid) == NULL) {
373 pptr = (struct PurgeList *)
374 malloc(sizeof(struct PurgeList));
375 pptr->next = UserPurgeList;
376 strcpy(pptr->name, us->fullname);
377 UserPurgeList = pptr;
389 * Back end function to check user accounts for expiration.
391 void do_user_purge(struct ctdluser *us, void *data) {
395 struct PurgeList *pptr;
397 /* Set purge time; if the user overrides the system default, use it */
398 if (us->USuserpurge > 0) {
399 purge_time = ((time_t)us->USuserpurge) * 86400L;
402 purge_time = ((time_t)config.c_userpurge) * 86400L;
405 /* The default rule is to not purge. */
408 /* If the user hasn't called in two months and expiring of accounts is turned on, his/her account
409 * has expired, so purge the record.
411 if (config.c_userpurge > 0)
414 if ((now - us->lastcall) > purge_time) purge = 1;
417 /* If the record is marked as permanent, don't purge it.
419 if (us->flags & US_PERM) purge = 0;
421 /* If the user is an Aide, don't purge him/her/it.
423 if (us->axlevel == 6) purge = 0;
425 /* If the access level is 0, the record should already have been
426 * deleted, but maybe the user was logged in at the time or something.
427 * Delete the record now.
429 if (us->axlevel == 0) purge = 1;
431 /* If the user set his/her password to 'deleteme', he/she
432 * wishes to be deleted, so purge the record.
433 * Moved this lower down so that aides and permanent users get purged if they ask to be.
435 if (!strcasecmp(us->password, "deleteme")) purge = 1;
437 /* 0 calls is impossible. If there are 0 calls, it must
438 * be a corrupted record, so purge it.
439 * Actually it is possible if an Aide created the user so now we check for less than 0 (DRW)
441 if (us->timescalled < 0) purge = 1;
443 /* User number 0, as well as any negative user number, is
446 if (us->usernum < 1L) purge = 1;
448 /* If the user has no full name entry then we can't purge them
449 * since the actual purge can't find them.
450 * This shouldn't happen but does somehow.
451 * So we make an Aide message to alert to it but don't add it to the purge list
453 if (IsEmptyStr(us->fullname))
456 if (users_corrupt_msg == NULL)
458 users_corrupt_msg = malloc(SIZ);
459 strcpy(users_corrupt_msg, "The auto-purger found the following user numbers with no name.\n"
460 "Unfortunately the auto-purger is not yet able to fix this problem.\n"
461 "This problem is not considered serious since a user with no name can\n"
465 users_corrupt_msg=realloc(users_corrupt_msg, strlen(users_corrupt_msg)+SIZ);
466 snprintf(&users_corrupt_msg[strlen(users_corrupt_msg)], SIZ, " %ld\n", us->usernum);
471 pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
472 pptr->next = UserPurgeList;
473 strcpy(pptr->name, us->fullname);
474 UserPurgeList = pptr;
484 int PurgeUsers(void) {
485 struct PurgeList *pptr;
486 int num_users_purged = 0;
487 char *transcript = NULL;
489 CtdlLogPrintf(CTDL_DEBUG, "PurgeUsers() called\n");
490 users_not_purged = 0;
492 switch(config.c_auth_mode) {
493 case AUTHMODE_NATIVE:
494 ForEachUser(do_user_purge, NULL);
497 ForEachUser(do_uid_user_purge, NULL);
500 CtdlLogPrintf(CTDL_DEBUG, "Unknown authentication mode!\n");
504 transcript = malloc(SIZ);
506 if (users_not_purged == 0) {
507 strcpy(transcript, "The auto-purger was told to purge every user. It is\n"
508 "refusing to do this because it usually indicates a problem\n"
509 "such as an inability to communicate with a name service.\n"
511 while (UserPurgeList != NULL) {
512 pptr = UserPurgeList->next;
514 UserPurgeList = pptr;
520 strcpy(transcript, "The following users have been auto-purged:\n");
521 while (UserPurgeList != NULL) {
522 transcript=realloc(transcript, strlen(transcript)+SIZ);
523 snprintf(&transcript[strlen(transcript)], SIZ, " %s\n",
524 UserPurgeList->name);
525 purge_user(UserPurgeList->name);
526 pptr = UserPurgeList->next;
528 UserPurgeList = pptr;
533 if (num_users_purged > 0) aide_message(transcript, "User Purge Message");
536 if(users_corrupt_msg)
538 aide_message(users_corrupt_msg, "User Corruption Message");
539 free (users_corrupt_msg);
540 users_corrupt_msg = NULL;
544 CtdlLogPrintf(CTDL_DEBUG, "Purged %d users.\n", num_users_purged);
545 return(num_users_purged);
552 * This is a really cumbersome "garbage collection" function. We have to
553 * delete visits which refer to rooms and/or users which no longer exist. In
554 * order to prevent endless traversals of the room and user files, we first
555 * build linked lists of rooms and users which _do_ exist on the system, then
556 * traverse the visit file, checking each record against those two lists and
557 * purging the ones that do not have a match on _both_ lists. (Remember, if
558 * either the room or user being referred to is no longer on the system, the
559 * record is completely useless.)
561 int PurgeVisits(void) {
562 struct cdbdata *cdbvisit;
564 struct VPurgeList *VisitPurgeList = NULL;
565 struct VPurgeList *vptr;
569 struct ValidRoom *vrptr;
570 struct ValidUser *vuptr;
571 int RoomIsValid, UserIsValid;
573 /* First, load up a table full of valid room/gen combinations */
574 ForEachRoom(AddValidRoom, NULL);
576 /* Then load up a table full of valid user numbers */
577 ForEachUser(AddValidUser, NULL);
579 /* Now traverse through the visits, purging irrelevant records... */
580 cdb_rewind(CDB_VISIT);
581 while(cdbvisit = cdb_next_item(CDB_VISIT), cdbvisit != NULL) {
582 memset(&vbuf, 0, sizeof(struct visit));
583 memcpy(&vbuf, cdbvisit->ptr,
584 ( (cdbvisit->len > sizeof(struct visit)) ?
585 sizeof(struct visit) : cdbvisit->len) );
591 /* Check to see if the room exists */
592 for (vrptr=ValidRoomList; vrptr!=NULL; vrptr=vrptr->next) {
593 if ( (vrptr->vr_roomnum==vbuf.v_roomnum)
594 && (vrptr->vr_roomgen==vbuf.v_roomgen))
598 /* Check to see if the user exists */
599 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
600 if (vuptr->vu_usernum == vbuf.v_usernum)
604 /* Put the record on the purge list if it's dead */
605 if ((RoomIsValid==0) || (UserIsValid==0)) {
606 vptr = (struct VPurgeList *)
607 malloc(sizeof(struct VPurgeList));
608 vptr->next = VisitPurgeList;
609 vptr->vp_roomnum = vbuf.v_roomnum;
610 vptr->vp_roomgen = vbuf.v_roomgen;
611 vptr->vp_usernum = vbuf.v_usernum;
612 VisitPurgeList = vptr;
617 /* Free the valid room/gen combination list */
618 while (ValidRoomList != NULL) {
619 vrptr = ValidRoomList->next;
621 ValidRoomList = vrptr;
624 /* Free the valid user list */
625 while (ValidUserList != NULL) {
626 vuptr = ValidUserList->next;
628 ValidUserList = vuptr;
631 /* Now delete every visit on the purged list */
632 while (VisitPurgeList != NULL) {
633 IndexLen = GenerateRelationshipIndex(IndexBuf,
634 VisitPurgeList->vp_roomnum,
635 VisitPurgeList->vp_roomgen,
636 VisitPurgeList->vp_usernum);
637 cdb_delete(CDB_VISIT, IndexBuf, IndexLen);
638 vptr = VisitPurgeList->next;
639 free(VisitPurgeList);
640 VisitPurgeList = vptr;
648 * Purge the use table of old entries.
651 int PurgeUseTable(void) {
653 struct cdbdata *cdbut;
655 struct UPurgeList *ul = NULL;
656 struct UPurgeList *uptr;
658 /* Phase 1: traverse through the table, discovering old records... */
659 CtdlLogPrintf(CTDL_DEBUG, "Purge use table: phase 1\n");
660 cdb_rewind(CDB_USETABLE);
661 while(cdbut = cdb_next_item(CDB_USETABLE), cdbut != NULL) {
664 * TODODRW: change this to create a new function time_t cdb_get_timestamp( struct cdbdata *)
665 * this will release this file from the serv_network.h
666 * Maybe it could be a macro that extracts and casts the reult
668 memcpy(&ut, cdbut->ptr,
669 ((cdbut->len > sizeof(struct UseTable)) ?
670 sizeof(struct UseTable) : cdbut->len));
673 if ( (time(NULL) - ut.ut_timestamp) > USETABLE_RETAIN ) {
674 uptr = (struct UPurgeList *) malloc(sizeof(struct UPurgeList));
677 safestrncpy(uptr->up_key, ut.ut_msgid, sizeof uptr->up_key);
685 /* Phase 2: delete the records */
686 CtdlLogPrintf(CTDL_DEBUG, "Purge use table: phase 2\n");
688 cdb_delete(CDB_USETABLE, ul->up_key, strlen(ul->up_key));
694 CtdlLogPrintf(CTDL_DEBUG, "Purge use table: finished (purged %d records)\n", purged);
701 * Purge the EUID Index of old records.
704 int PurgeEuidIndexTable(void) {
706 struct cdbdata *cdbei;
707 struct EPurgeList *el = NULL;
708 struct EPurgeList *eptr;
710 struct CtdlMessage *msg = NULL;
712 /* Phase 1: traverse through the table, discovering old records... */
713 CtdlLogPrintf(CTDL_DEBUG, "Purge EUID index: phase 1\n");
714 cdb_rewind(CDB_EUIDINDEX);
715 while(cdbei = cdb_next_item(CDB_EUIDINDEX), cdbei != NULL) {
717 memcpy(&msgnum, cdbei->ptr, sizeof(long));
719 msg = CtdlFetchMessage(msgnum, 0);
721 CtdlFreeMessage(msg); /* it still exists, so do nothing */
724 eptr = (struct EPurgeList *) malloc(sizeof(struct EPurgeList));
727 eptr->ep_keylen = cdbei->len - sizeof(long);
728 eptr->ep_key = malloc(cdbei->len);
729 memcpy(eptr->ep_key, &cdbei->ptr[sizeof(long)], eptr->ep_keylen);
739 /* Phase 2: delete the records */
740 CtdlLogPrintf(CTDL_DEBUG, "Purge euid index: phase 2\n");
742 cdb_delete(CDB_EUIDINDEX, el->ep_key, el->ep_keylen);
749 CtdlLogPrintf(CTDL_DEBUG, "Purge euid index: finished (purged %d records)\n", purged);
754 void *purge_databases(void *args)
757 static time_t last_purge = 0;
760 struct CitContext purgerCC;
762 CtdlLogPrintf(CTDL_DEBUG, "Auto-purger_thread() initializing\n");
764 memset(&purgerCC, 0, sizeof(struct CitContext));
765 purgerCC.internal_pgm = 1;
767 pthread_setspecific(MyConKey, (void *)&purgerCC );
769 while (!CtdlThreadCheckStop()) {
770 /* Do the auto-purge if the current hour equals the purge hour,
771 * but not if the operation has already been performed in the
772 * last twelve hours. This is usually enough granularity.
775 localtime_r(&now, &tm);
776 if ((tm.tm_hour != config.c_purge_hour) || ((now - last_purge) < 43200)) {
782 CtdlLogPrintf(CTDL_INFO, "Auto-purger: starting.\n");
784 if (!CtdlThreadCheckStop())
786 retval = PurgeUsers();
787 CtdlLogPrintf(CTDL_NOTICE, "Purged %d users.\n", retval);
790 if (!CtdlThreadCheckStop())
793 CtdlLogPrintf(CTDL_NOTICE, "Expired %d messages.\n", messages_purged);
796 if (!CtdlThreadCheckStop())
798 retval = PurgeRooms();
799 CtdlLogPrintf(CTDL_NOTICE, "Expired %d rooms.\n", retval);
802 if (!CtdlThreadCheckStop())
804 retval = PurgeVisits();
805 CtdlLogPrintf(CTDL_NOTICE, "Purged %d visits.\n", retval);
808 if (!CtdlThreadCheckStop())
810 retval = PurgeUseTable();
811 CtdlLogPrintf(CTDL_NOTICE, "Purged %d entries from the use table.\n", retval);
814 if (!CtdlThreadCheckStop())
816 retval = PurgeEuidIndexTable();
817 CtdlLogPrintf(CTDL_NOTICE, "Purged %d entries from the EUID index.\n", retval);
820 if (!CtdlThreadCheckStop())
822 retval = TDAP_ProcessAdjRefCountQueue();
823 CtdlLogPrintf(CTDL_NOTICE, "Processed %d message reference count adjustments.\n", retval);
826 if (!CtdlThreadCheckStop())
828 CtdlLogPrintf(CTDL_INFO, "Auto-purger: finished.\n");
829 last_purge = now; /* So we don't do it again soon */
832 CtdlLogPrintf(CTDL_INFO, "Auto-purger: STOPPED.\n");
837 /*****************************************************************************/
840 void do_fsck_msg(long msgnum, void *userdata) {
841 struct ctdlroomref *ptr;
843 ptr = (struct ctdlroomref *)malloc(sizeof(struct ctdlroomref));
845 ptr->msgnum = msgnum;
849 void do_fsck_room(struct ctdlroom *qrbuf, void *data)
851 getroom(&CC->room, qrbuf->QRname);
852 CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL, do_fsck_msg, NULL);
856 * Check message reference counts
858 void cmd_fsck(char *argbuf) {
860 struct cdbdata *cdbmsg;
862 struct ctdlroomref *ptr;
865 if (CtdlAccessCheck(ac_aide)) return;
867 /* Lame way of checking whether anyone else is doing this now */
869 cprintf("%d Another FSCK is already running.\n", ERROR + RESOURCE_BUSY);
873 cprintf("%d Checking message reference counts\n", LISTING_FOLLOWS);
875 cprintf("\nThis could take a while. Please be patient!\n\n");
876 cprintf("Gathering pointers...\n");
877 ForEachRoom(do_fsck_room, NULL);
880 cprintf("Checking message base...\n");
881 for (msgnum = 0L; msgnum <= CitControl.MMhighest; ++msgnum) {
883 cdbmsg = cdb_fetch(CDB_MSGMAIN, &msgnum, sizeof(long));
884 if (cdbmsg != NULL) {
886 cprintf("Message %7ld ", msgnum);
888 GetMetaData(&smi, msgnum);
889 cprintf("refcount=%-2d ", smi.meta_refcount);
892 for (ptr = rr; ptr != NULL; ptr = ptr->next) {
893 if (ptr->msgnum == msgnum) ++realcount;
895 cprintf("realcount=%-2d\n", realcount);
897 if ( (smi.meta_refcount != realcount)
898 || (realcount == 0) ) {
899 AdjRefCount(msgnum, (smi.meta_refcount - realcount));
906 cprintf("Freeing memory...\n");
921 /*****************************************************************************/
923 CTDL_MODULE_INIT(expire)
927 CtdlRegisterProtoHook(cmd_fsck, "FSCK", "Check message ref counts");
930 CtdlThreadCreate("Auto Purger", CTDLTHREAD_BIGSTACK, purge_databases, NULL);
931 /* return our Subversion id for the Log */