Now the autopurger will always attempt to purge users regardless of the
[citadel.git] / citadel / modules / expire / serv_expire.c
1 /*
2  * $Id$
3  *
4  * This module handles the expiry of old messages and the purging of old users.
5  *
6  */
7
8
9 /*
10  * A brief technical discussion:
11  *
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.
15  *
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.
22  *
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.
25  */
26
27
28 #include "sysdep.h"
29 #include <stdlib.h>
30 #include <unistd.h>
31 #include <stdio.h>
32 #include <fcntl.h>
33 #include <signal.h>
34 #include <pwd.h>
35 #include <errno.h>
36 #include <sys/types.h>
37
38 #if TIME_WITH_SYS_TIME
39 # include <sys/time.h>
40 # include <time.h>
41 #else
42 # if HAVE_SYS_TIME_H
43 #  include <sys/time.h>
44 # else
45 #  include <time.h>
46 # endif
47 #endif
48
49 #include <sys/wait.h>
50 #include <string.h>
51 #include <limits.h>
52 #include <libcitadel.h>
53 #include "citadel.h"
54 #include "server.h"
55 #include "citserver.h"
56 #include "support.h"
57 #include "config.h"
58 #include "room_ops.h"
59 #include "policy.h"
60 #include "database.h"
61 #include "msgbase.h"
62 #include "user_ops.h"
63 #include "control.h"
64 #include "serv_network.h"       /* Needed for defenition of UseTable */
65 #include "threads.h"
66
67 #include "ctdl_module.h"
68
69
70 struct PurgeList {
71         struct PurgeList *next;
72         char name[ROOMNAMELEN]; /* use the larger of username or roomname */
73 };
74
75 struct VPurgeList {
76         struct VPurgeList *next;
77         long vp_roomnum;
78         long vp_roomgen;
79         long vp_usernum;
80 };
81
82 struct ValidRoom {
83         struct ValidRoom *next;
84         long vr_roomnum;
85         long vr_roomgen;
86 };
87
88 struct ValidUser {
89         struct ValidUser *next;
90         long vu_usernum;
91 };
92
93
94 struct ctdlroomref {
95         struct ctdlroomref *next;
96         long msgnum;
97 };
98
99 struct UPurgeList {
100         struct UPurgeList *next;
101         char up_key[256];
102 };
103
104 struct EPurgeList {
105         struct EPurgeList *next;
106         int ep_keylen;
107         char *ep_key;
108 };
109
110
111 struct PurgeList *UserPurgeList = NULL;
112 struct PurgeList *RoomPurgeList = NULL;
113 struct ValidRoom *ValidRoomList = NULL;
114 struct ValidUser *ValidUserList = NULL;
115 int messages_purged;
116 int users_not_purged;
117
118 struct ctdlroomref *rr = NULL;
119
120 extern struct CitContext *ContextList;
121
122
123 /*
124  * First phase of message purge -- gather the locations of messages which
125  * qualify for purging and write them to a temp file.
126  */
127 void GatherPurgeMessages(struct ctdlroom *qrbuf, void *data) {
128         struct ExpirePolicy epbuf;
129         long delnum;
130         time_t xtime, now;
131         struct CtdlMessage *msg = NULL;
132         int a;
133         struct cdbdata *cdbfr;
134         long *msglist = NULL;
135         int num_msgs = 0;
136         FILE *purgelist;
137
138         purgelist = (FILE *)data;
139         fprintf(purgelist, "r=%s\n", qrbuf->QRname);
140
141         time(&now);
142         GetExpirePolicy(&epbuf, qrbuf);
143
144         /* If the room is set to never expire messages ... do nothing */
145         if (epbuf.expire_mode == EXPIRE_NEXTLEVEL) return;
146         if (epbuf.expire_mode == EXPIRE_MANUAL) return;
147
148         cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf->QRnumber, sizeof(long));
149
150         if (cdbfr != NULL) {
151                 msglist = malloc(cdbfr->len);
152                 memcpy(msglist, cdbfr->ptr, cdbfr->len);
153                 num_msgs = cdbfr->len / sizeof(long);
154                 cdb_free(cdbfr);
155         }
156
157         /* Nothing to do if there aren't any messages */
158         if (num_msgs == 0) {
159                 if (msglist != NULL) free(msglist);
160                 return;
161         }
162
163         /* If the room is set to expire by count, do that */
164         if (epbuf.expire_mode == EXPIRE_NUMMSGS) {
165                 if (num_msgs > epbuf.expire_value) {
166                         for (a=0; a<(num_msgs - epbuf.expire_value); ++a) {
167                                 fprintf(purgelist, "m=%ld\n", msglist[a]);
168                                 ++messages_purged;
169                         }
170                 }
171         }
172
173         /* If the room is set to expire by age... */
174         if (epbuf.expire_mode == EXPIRE_AGE) {
175                 for (a=0; a<num_msgs; ++a) {
176                         delnum = msglist[a];
177
178                         msg = CtdlFetchMessage(delnum, 0); /* dont need body */
179                         if (msg != NULL) {
180                                 xtime = atol(msg->cm_fields['T']);
181                                 CtdlFreeMessage(msg);
182                         } else {
183                                 xtime = 0L;
184                         }
185
186                         if ((xtime > 0L)
187                            && (now - xtime > (time_t)(epbuf.expire_value * 86400L))) {
188                                 fprintf(purgelist, "m=%ld\n", delnum);
189                                 ++messages_purged;
190                         }
191                 }
192         }
193
194         if (msglist != NULL) free(msglist);
195 }
196
197
198 /*
199  * Second phase of message purge -- read list of msgs from temp file and
200  * delete them.
201  */
202 void DoPurgeMessages(FILE *purgelist) {
203         char roomname[ROOMNAMELEN];
204         long msgnum;
205         char buf[SIZ];
206
207         rewind(purgelist);
208         strcpy(roomname, "nonexistent room ___ ___");
209         while (fgets(buf, sizeof buf, purgelist) != NULL) {
210                 buf[strlen(buf)-1]=0;
211                 if (!strncasecmp(buf, "r=", 2)) {
212                         strcpy(roomname, &buf[2]);
213                 }
214                 if (!strncasecmp(buf, "m=", 2)) {
215                         msgnum = atol(&buf[2]);
216                         if (msgnum > 0L) {
217                                 CtdlDeleteMessages(roomname, &msgnum, 1, "");
218                         }
219                 }
220         }
221 }
222
223
224 void PurgeMessages(void) {
225         FILE *purgelist;
226
227         lprintf(CTDL_DEBUG, "PurgeMessages() called\n");
228         messages_purged = 0;
229
230         purgelist = tmpfile();
231         if (purgelist == NULL) {
232                 lprintf(CTDL_CRIT, "Can't create purgelist temp file: %s\n",
233                         strerror(errno));
234                 return;
235         }
236
237         ForEachRoom(GatherPurgeMessages, (void *)purgelist );
238         DoPurgeMessages(purgelist);
239         fclose(purgelist);
240 }
241
242
243 void AddValidUser(struct ctdluser *usbuf, void *data) {
244         struct ValidUser *vuptr;
245
246         vuptr = (struct ValidUser *)malloc(sizeof(struct ValidUser));
247         vuptr->next = ValidUserList;
248         vuptr->vu_usernum = usbuf->usernum;
249         ValidUserList = vuptr;
250 }
251
252 void AddValidRoom(struct ctdlroom *qrbuf, void *data) {
253         struct ValidRoom *vrptr;
254
255         vrptr = (struct ValidRoom *)malloc(sizeof(struct ValidRoom));
256         vrptr->next = ValidRoomList;
257         vrptr->vr_roomnum = qrbuf->QRnumber;
258         vrptr->vr_roomgen = qrbuf->QRgen;
259         ValidRoomList = vrptr;
260 }
261
262 void DoPurgeRooms(struct ctdlroom *qrbuf, void *data) {
263         time_t age, purge_secs;
264         struct PurgeList *pptr;
265         struct ValidUser *vuptr;
266         int do_purge = 0;
267
268         /* For mailbox rooms, there's only one purging rule: if the user who
269          * owns the room still exists, we keep the room; otherwise, we purge
270          * it.  Bypass any other rules.
271          */
272         if (qrbuf->QRflags & QR_MAILBOX) {
273                 /* if user not found, do_purge will be 1 */
274                 do_purge = 1;
275                 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
276                         if (vuptr->vu_usernum == atol(qrbuf->QRname)) {
277                                 do_purge = 0;
278                         }
279                 }
280         }
281         else {
282                 /* Any of these attributes render a room non-purgable */
283                 if (qrbuf->QRflags & QR_PERMANENT) return;
284                 if (qrbuf->QRflags & QR_DIRECTORY) return;
285                 if (qrbuf->QRflags & QR_NETWORK) return;
286                 if (!strcasecmp(qrbuf->QRname, SYSCONFIGROOM)) return;
287                 if (is_noneditable(qrbuf)) return;
288
289                 /* If we don't know the modification date, be safe and don't purge */
290                 if (qrbuf->QRmtime <= (time_t)0) return;
291
292                 /* If no room purge time is set, be safe and don't purge */
293                 if (config.c_roompurge < 0) return;
294
295                 /* Otherwise, check the date of last modification */
296                 age = time(NULL) - (qrbuf->QRmtime);
297                 purge_secs = (time_t)config.c_roompurge * (time_t)86400;
298                 if (purge_secs <= (time_t)0) return;
299                 lprintf(CTDL_DEBUG, "<%s> is <%ld> seconds old\n", qrbuf->QRname, (long)age);
300                 if (age > purge_secs) do_purge = 1;
301         } /* !QR_MAILBOX */
302
303         if (do_purge) {
304                 pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
305                 pptr->next = RoomPurgeList;
306                 strcpy(pptr->name, qrbuf->QRname);
307                 RoomPurgeList = pptr;
308         }
309
310 }
311
312
313
314 int PurgeRooms(void) {
315         struct PurgeList *pptr;
316         int num_rooms_purged = 0;
317         struct ctdlroom qrbuf;
318         struct ValidUser *vuptr;
319         char *transcript = NULL;
320
321         lprintf(CTDL_DEBUG, "PurgeRooms() called\n");
322
323
324         /* Load up a table full of valid user numbers so we can delete
325          * user-owned rooms for users who no longer exist */
326         ForEachUser(AddValidUser, NULL);
327
328         /* Then cycle through the room file */
329         ForEachRoom(DoPurgeRooms, NULL);
330
331         /* Free the valid user list */
332         while (ValidUserList != NULL) {
333                 vuptr = ValidUserList->next;
334                 free(ValidUserList);
335                 ValidUserList = vuptr;
336         }
337
338
339         transcript = malloc(SIZ);
340         strcpy(transcript, "The following rooms have been auto-purged:\n");
341
342         while (RoomPurgeList != NULL) {
343                 if (getroom(&qrbuf, RoomPurgeList->name) == 0) {
344                         transcript=realloc(transcript, strlen(transcript)+SIZ);
345                         snprintf(&transcript[strlen(transcript)], SIZ, " %s\n",
346                                 qrbuf.QRname);
347                         delete_room(&qrbuf);
348                 }
349                 pptr = RoomPurgeList->next;
350                 free(RoomPurgeList);
351                 RoomPurgeList = pptr;
352                 ++num_rooms_purged;
353         }
354
355         if (num_rooms_purged > 0) aide_message(transcript, "Room Autopurger Message");
356         free(transcript);
357
358         lprintf(CTDL_DEBUG, "Purged %d rooms.\n", num_rooms_purged);
359         return(num_rooms_purged);
360 }
361
362
363 /*
364  * Back end function to check user accounts for associated Unix accounts
365  * which no longer exist.  (Only relevant for host auth mode.)
366  */
367 void do_uid_user_purge(struct ctdluser *us, void *data) {
368         struct PurgeList *pptr;
369
370         if ((us->uid != (-1)) && (us->uid != CTDLUID)) {
371                 if (getpwuid(us->uid) == NULL) {
372                         pptr = (struct PurgeList *)
373                                 malloc(sizeof(struct PurgeList));
374                         pptr->next = UserPurgeList;
375                         strcpy(pptr->name, us->fullname);
376                         UserPurgeList = pptr;
377                 }
378         }
379         else {
380                 ++users_not_purged;
381         }
382 }
383
384
385
386 /*
387  * Back end function to check user accounts for expiration.
388  */
389 void do_user_purge(struct ctdluser *us, void *data) {
390         int purge;
391         time_t now;
392         time_t purge_time;
393         struct PurgeList *pptr;
394
395         /* Set purge time; if the user overrides the system default, use it */
396         if (us->USuserpurge > 0) {
397                 purge_time = ((time_t)us->USuserpurge) * 86400L;
398         }
399         else {
400                 purge_time = ((time_t)config.c_userpurge) * 86400L;
401         }
402
403         /* The default rule is to not purge. */
404         purge = 0;
405
406         /* If the user hasn't called in two months and expiring of accounts is turned on, his/her account
407          * has expired, so purge the record.
408          */
409         if (config.c_userpurge > 0)
410         {
411                 now = time(NULL);
412                 if ((now - us->lastcall) > purge_time) purge = 1;
413         }
414
415         /* If the record is marked as permanent, don't purge it.
416          */
417         if (us->flags & US_PERM) purge = 0;
418
419         /* If the user is an Aide, don't purge him/her/it.
420          */
421         if (us->axlevel == 6) purge = 0;
422
423         /* If the access level is 0, the record should already have been
424          * deleted, but maybe the user was logged in at the time or something.
425          * Delete the record now.
426          */
427         if (us->axlevel == 0) purge = 1;
428
429         /* If the user set his/her password to 'deleteme', he/she
430          * wishes to be deleted, so purge the record.
431          * Moved this lower down so that aides and permanent users get purged if they ask to be.
432          */
433         if (!strcasecmp(us->password, "deleteme")) purge = 1;
434         
435         /* 0 calls is impossible.  If there are 0 calls, it must
436          * be a corrupted record, so purge it.
437          */
438         if (us->timescalled == 0) purge = 1;
439
440         /* User number 0, as well as any negative user number, is
441          * also impossible.
442          */
443         if (us->usernum < 1L) purge = 1;
444
445         if (purge == 1) {
446                 pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
447                 pptr->next = UserPurgeList;
448                 strcpy(pptr->name, us->fullname);
449                 UserPurgeList = pptr;
450         }
451         else {
452                 ++users_not_purged;
453         }
454
455 }
456
457
458
459 int PurgeUsers(void) {
460         struct PurgeList *pptr;
461         int num_users_purged = 0;
462         char *transcript = NULL;
463
464         lprintf(CTDL_DEBUG, "PurgeUsers() called\n");
465         users_not_purged = 0;
466
467         switch(config.c_auth_mode) {
468                 case AUTHMODE_NATIVE:
469                         ForEachUser(do_user_purge, NULL);
470                         break;
471                 case AUTHMODE_HOST:
472                         ForEachUser(do_uid_user_purge, NULL);
473                         break;
474                 default:
475                         lprintf(CTDL_DEBUG, "Unknown authentication mode!\n");
476                         break;
477         }
478
479         transcript = malloc(SIZ);
480
481         if (users_not_purged == 0) {
482                 strcpy(transcript, "The auto-purger was told to purge every user.  It is\n"
483                                 "refusing to do this because it usually indicates a problem\n"
484                                 "such as an inability to communicate with a name service.\n"
485                 );
486                 while (UserPurgeList != NULL) {
487                         pptr = UserPurgeList->next;
488                         free(UserPurgeList);
489                         UserPurgeList = pptr;
490                         ++num_users_purged;
491                 }
492         }
493
494         else {
495                 strcpy(transcript, "The following users have been auto-purged:\n");
496                 while (UserPurgeList != NULL) {
497                         transcript=realloc(transcript, strlen(transcript)+SIZ);
498                         snprintf(&transcript[strlen(transcript)], SIZ, " %s\n",
499                                 UserPurgeList->name);
500                         purge_user(UserPurgeList->name);
501                         pptr = UserPurgeList->next;
502                         free(UserPurgeList);
503                         UserPurgeList = pptr;
504                         ++num_users_purged;
505                 }
506         }
507
508         if (num_users_purged > 0) aide_message(transcript, "User Purge Message");
509         free(transcript);
510
511         lprintf(CTDL_DEBUG, "Purged %d users.\n", num_users_purged);
512         return(num_users_purged);
513 }
514
515
516 /*
517  * Purge visits
518  *
519  * This is a really cumbersome "garbage collection" function.  We have to
520  * delete visits which refer to rooms and/or users which no longer exist.  In
521  * order to prevent endless traversals of the room and user files, we first
522  * build linked lists of rooms and users which _do_ exist on the system, then
523  * traverse the visit file, checking each record against those two lists and
524  * purging the ones that do not have a match on _both_ lists.  (Remember, if
525  * either the room or user being referred to is no longer on the system, the
526  * record is completely useless.)
527  */
528 int PurgeVisits(void) {
529         struct cdbdata *cdbvisit;
530         struct visit vbuf;
531         struct VPurgeList *VisitPurgeList = NULL;
532         struct VPurgeList *vptr;
533         int purged = 0;
534         char IndexBuf[32];
535         int IndexLen;
536         struct ValidRoom *vrptr;
537         struct ValidUser *vuptr;
538         int RoomIsValid, UserIsValid;
539
540         /* First, load up a table full of valid room/gen combinations */
541         ForEachRoom(AddValidRoom, NULL);
542
543         /* Then load up a table full of valid user numbers */
544         ForEachUser(AddValidUser, NULL);
545
546         /* Now traverse through the visits, purging irrelevant records... */
547         cdb_rewind(CDB_VISIT);
548         while(cdbvisit = cdb_next_item(CDB_VISIT), cdbvisit != NULL) {
549                 memset(&vbuf, 0, sizeof(struct visit));
550                 memcpy(&vbuf, cdbvisit->ptr,
551                         ( (cdbvisit->len > sizeof(struct visit)) ?
552                         sizeof(struct visit) : cdbvisit->len) );
553                 cdb_free(cdbvisit);
554
555                 RoomIsValid = 0;
556                 UserIsValid = 0;
557
558                 /* Check to see if the room exists */
559                 for (vrptr=ValidRoomList; vrptr!=NULL; vrptr=vrptr->next) {
560                         if ( (vrptr->vr_roomnum==vbuf.v_roomnum)
561                              && (vrptr->vr_roomgen==vbuf.v_roomgen))
562                                 RoomIsValid = 1;
563                 }
564
565                 /* Check to see if the user exists */
566                 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
567                         if (vuptr->vu_usernum == vbuf.v_usernum)
568                                 UserIsValid = 1;
569                 }
570
571                 /* Put the record on the purge list if it's dead */
572                 if ((RoomIsValid==0) || (UserIsValid==0)) {
573                         vptr = (struct VPurgeList *)
574                                 malloc(sizeof(struct VPurgeList));
575                         vptr->next = VisitPurgeList;
576                         vptr->vp_roomnum = vbuf.v_roomnum;
577                         vptr->vp_roomgen = vbuf.v_roomgen;
578                         vptr->vp_usernum = vbuf.v_usernum;
579                         VisitPurgeList = vptr;
580                 }
581
582         }
583
584         /* Free the valid room/gen combination list */
585         while (ValidRoomList != NULL) {
586                 vrptr = ValidRoomList->next;
587                 free(ValidRoomList);
588                 ValidRoomList = vrptr;
589         }
590
591         /* Free the valid user list */
592         while (ValidUserList != NULL) {
593                 vuptr = ValidUserList->next;
594                 free(ValidUserList);
595                 ValidUserList = vuptr;
596         }
597
598         /* Now delete every visit on the purged list */
599         while (VisitPurgeList != NULL) {
600                 IndexLen = GenerateRelationshipIndex(IndexBuf,
601                                 VisitPurgeList->vp_roomnum,
602                                 VisitPurgeList->vp_roomgen,
603                                 VisitPurgeList->vp_usernum);
604                 cdb_delete(CDB_VISIT, IndexBuf, IndexLen);
605                 vptr = VisitPurgeList->next;
606                 free(VisitPurgeList);
607                 VisitPurgeList = vptr;
608                 ++purged;
609         }
610
611         return(purged);
612 }
613
614 /*
615  * Purge the use table of old entries.
616  *
617  */
618 int PurgeUseTable(void) {
619         int purged = 0;
620         struct cdbdata *cdbut;
621         struct UseTable ut;
622         struct UPurgeList *ul = NULL;
623         struct UPurgeList *uptr; 
624
625         /* Phase 1: traverse through the table, discovering old records... */
626         lprintf(CTDL_DEBUG, "Purge use table: phase 1\n");
627         cdb_rewind(CDB_USETABLE);
628         while(cdbut = cdb_next_item(CDB_USETABLE), cdbut != NULL) {
629
630         /*
631          * TODODRW: change this to create a new function time_t cdb_get_timestamp( struct cdbdata *)
632          * this will release this file from the serv_network.h
633          * Maybe it could be a macro that extracts and casts the reult
634          */
635                 memcpy(&ut, cdbut->ptr,
636                        ((cdbut->len > sizeof(struct UseTable)) ?
637                         sizeof(struct UseTable) : cdbut->len));
638                 cdb_free(cdbut);
639
640                 if ( (time(NULL) - ut.ut_timestamp) > USETABLE_RETAIN ) {
641                         uptr = (struct UPurgeList *) malloc(sizeof(struct UPurgeList));
642                         if (uptr != NULL) {
643                                 uptr->next = ul;
644                                 safestrncpy(uptr->up_key, ut.ut_msgid, sizeof uptr->up_key);
645                                 ul = uptr;
646                         }
647                         ++purged;
648                 }
649
650         }
651
652         /* Phase 2: delete the records */
653         lprintf(CTDL_DEBUG, "Purge use table: phase 2\n");
654         while (ul != NULL) {
655                 cdb_delete(CDB_USETABLE, ul->up_key, strlen(ul->up_key));
656                 uptr = ul->next;
657                 free(ul);
658                 ul = uptr;
659         }
660
661         lprintf(CTDL_DEBUG, "Purge use table: finished (purged %d records)\n", purged);
662         return(purged);
663 }
664
665
666
667 /*
668  * Purge the EUID Index of old records.
669  *
670  */
671 int PurgeEuidIndexTable(void) {
672         int purged = 0;
673         struct cdbdata *cdbei;
674         struct EPurgeList *el = NULL;
675         struct EPurgeList *eptr; 
676         long msgnum;
677         struct CtdlMessage *msg = NULL;
678
679         /* Phase 1: traverse through the table, discovering old records... */
680         lprintf(CTDL_DEBUG, "Purge EUID index: phase 1\n");
681         cdb_rewind(CDB_EUIDINDEX);
682         while(cdbei = cdb_next_item(CDB_EUIDINDEX), cdbei != NULL) {
683
684                 memcpy(&msgnum, cdbei->ptr, sizeof(long));
685
686                 msg = CtdlFetchMessage(msgnum, 0);
687                 if (msg != NULL) {
688                         CtdlFreeMessage(msg);   /* it still exists, so do nothing */
689                 }
690                 else {
691                         eptr = (struct EPurgeList *) malloc(sizeof(struct EPurgeList));
692                         if (eptr != NULL) {
693                                 eptr->next = el;
694                                 eptr->ep_keylen = cdbei->len - sizeof(long);
695                                 eptr->ep_key = malloc(cdbei->len);
696                                 memcpy(eptr->ep_key, &cdbei->ptr[sizeof(long)], eptr->ep_keylen);
697                                 el = eptr;
698                         }
699                         ++purged;
700                 }
701
702                 cdb_free(cdbei);
703
704         }
705
706         /* Phase 2: delete the records */
707         lprintf(CTDL_DEBUG, "Purge euid index: phase 2\n");
708         while (el != NULL) {
709                 cdb_delete(CDB_EUIDINDEX, el->ep_key, el->ep_keylen);
710                 free(el->ep_key);
711                 eptr = el->next;
712                 free(el);
713                 el = eptr;
714         }
715
716         lprintf(CTDL_DEBUG, "Purge euid index: finished (purged %d records)\n", purged);
717         return(purged);
718 }
719
720
721 void *purge_databases(void *args)
722 {
723         int retval;
724         static time_t last_purge = 0;
725         time_t now;
726         struct tm tm;
727
728         while (!CtdlThreadCheckStop()) {
729                 /* Do the auto-purge if the current hour equals the purge hour,
730                  * but not if the operation has already been performed in the
731                  * last twelve hours.  This is usually enough granularity.
732                  */
733                 now = time(NULL);
734                 localtime_r(&now, &tm);
735                 if ((tm.tm_hour != config.c_purge_hour) || ((now - last_purge) < 43200)) {
736                         CtdlThreadSleep(60);
737                         continue;
738                 }
739
740
741                 lprintf(CTDL_INFO, "Auto-purger: starting.\n");
742
743                 if (!CtdlThreadCheckStop())
744                 {
745                         retval = PurgeUsers();
746                         lprintf(CTDL_NOTICE, "Purged %d users.\n", retval);
747                 }
748                 
749                 if (!CtdlThreadCheckStop())
750                 {
751                         PurgeMessages();
752                         lprintf(CTDL_NOTICE, "Expired %d messages.\n", messages_purged);
753                 }
754
755                 if (!CtdlThreadCheckStop())
756                 {
757                         retval = PurgeRooms();
758                         lprintf(CTDL_NOTICE, "Expired %d rooms.\n", retval);
759                 }
760
761                 if (!CtdlThreadCheckStop())
762                 {
763                         retval = PurgeVisits();
764                         lprintf(CTDL_NOTICE, "Purged %d visits.\n", retval);
765                 }
766
767                 if (!CtdlThreadCheckStop())
768                 {
769                         retval = PurgeUseTable();
770                         lprintf(CTDL_NOTICE, "Purged %d entries from the use table.\n", retval);
771                 }
772
773                 if (!CtdlThreadCheckStop())
774                 {
775                         retval = PurgeEuidIndexTable();
776                         lprintf(CTDL_NOTICE, "Purged %d entries from the EUID index.\n", retval);
777                 }
778
779                 if (!CtdlThreadCheckStop())
780                 {
781                         retval = TDAP_ProcessAdjRefCountQueue();
782                         lprintf(CTDL_NOTICE, "Processed %d message reference count adjustments.\n", retval);
783                 }
784
785                 if (!CtdlThreadCheckStop())
786                 {
787                         lprintf(CTDL_INFO, "Auto-purger: finished.\n");
788                         last_purge = now;       /* So we don't do it again soon */
789                 }
790                 else
791                         lprintf(CTDL_INFO, "Auto-purger: STOPPED.\n");
792
793         }
794         return NULL;
795 }
796 /*****************************************************************************/
797
798
799 void do_fsck_msg(long msgnum, void *userdata) {
800         struct ctdlroomref *ptr;
801
802         ptr = (struct ctdlroomref *)malloc(sizeof(struct ctdlroomref));
803         ptr->next = rr;
804         ptr->msgnum = msgnum;
805         rr = ptr;
806 }
807
808 void do_fsck_room(struct ctdlroom *qrbuf, void *data)
809 {
810         getroom(&CC->room, qrbuf->QRname);
811         CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL, do_fsck_msg, NULL);
812 }
813
814 /*
815  * Check message reference counts
816  */
817 void cmd_fsck(char *argbuf) {
818         long msgnum;
819         struct cdbdata *cdbmsg;
820         struct MetaData smi;
821         struct ctdlroomref *ptr;
822         int realcount;
823
824         if (CtdlAccessCheck(ac_aide)) return;
825
826         /* Lame way of checking whether anyone else is doing this now */
827         if (rr != NULL) {
828                 cprintf("%d Another FSCK is already running.\n", ERROR + RESOURCE_BUSY);
829                 return;
830         }
831
832         cprintf("%d Checking message reference counts\n", LISTING_FOLLOWS);
833
834         cprintf("\nThis could take a while.  Please be patient!\n\n");
835         cprintf("Gathering pointers...\n");
836         ForEachRoom(do_fsck_room, NULL);
837
838         get_control();
839         cprintf("Checking message base...\n");
840         for (msgnum = 0L; msgnum <= CitControl.MMhighest; ++msgnum) {
841
842                 cdbmsg = cdb_fetch(CDB_MSGMAIN, &msgnum, sizeof(long));
843                 if (cdbmsg != NULL) {
844                         cdb_free(cdbmsg);
845                         cprintf("Message %7ld    ", msgnum);
846
847                         GetMetaData(&smi, msgnum);
848                         cprintf("refcount=%-2d   ", smi.meta_refcount);
849
850                         realcount = 0;
851                         for (ptr = rr; ptr != NULL; ptr = ptr->next) {
852                                 if (ptr->msgnum == msgnum) ++realcount;
853                         }
854                         cprintf("realcount=%-2d\n", realcount);
855
856                         if ( (smi.meta_refcount != realcount)
857                            || (realcount == 0) ) {
858                                 AdjRefCount(msgnum, (smi.meta_refcount - realcount));
859                         }
860
861                 }
862
863         }
864
865         cprintf("Freeing memory...\n");
866         while (rr != NULL) {
867                 ptr = rr->next;
868                 free(rr);
869                 rr = ptr;
870         }
871
872         cprintf("Done!\n");
873         cprintf("000\n");
874
875 }
876
877
878
879
880 /*****************************************************************************/
881
882 CTDL_MODULE_INIT(expire)
883 {
884         if (!threading)
885         {
886                 CtdlRegisterProtoHook(cmd_fsck, "FSCK", "Check message ref counts");
887         }
888         else
889                 CtdlThreadCreate("Auto Purger", CTDLTHREAD_BIGSTACK, purge_databases, NULL);
890         /* return our Subversion id for the Log */
891         return "$Id$";
892 }