Give the user contained within masterCC a name.
[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 char *users_corrupt_msg = NULL;
118
119 struct ctdlroomref *rr = NULL;
120
121 extern struct CitContext *ContextList;
122
123
124 /*
125  * First phase of message purge -- gather the locations of messages which
126  * qualify for purging and write them to a temp file.
127  */
128 void GatherPurgeMessages(struct ctdlroom *qrbuf, void *data) {
129         struct ExpirePolicy epbuf;
130         long delnum;
131         time_t xtime, now;
132         struct CtdlMessage *msg = NULL;
133         int a;
134         struct cdbdata *cdbfr;
135         long *msglist = NULL;
136         int num_msgs = 0;
137         FILE *purgelist;
138
139         purgelist = (FILE *)data;
140         fprintf(purgelist, "r=%s\n", qrbuf->QRname);
141
142         time(&now);
143         GetExpirePolicy(&epbuf, qrbuf);
144
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;
148
149         cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf->QRnumber, sizeof(long));
150
151         if (cdbfr != NULL) {
152                 msglist = malloc(cdbfr->len);
153                 memcpy(msglist, cdbfr->ptr, cdbfr->len);
154                 num_msgs = cdbfr->len / sizeof(long);
155                 cdb_free(cdbfr);
156         }
157
158         /* Nothing to do if there aren't any messages */
159         if (num_msgs == 0) {
160                 if (msglist != NULL) free(msglist);
161                 return;
162         }
163
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]);
169                                 ++messages_purged;
170                         }
171                 }
172         }
173
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) {
177                         delnum = msglist[a];
178
179                         msg = CtdlFetchMessage(delnum, 0); /* dont need body */
180                         if (msg != NULL) {
181                                 xtime = atol(msg->cm_fields['T']);
182                                 CtdlFreeMessage(msg);
183                         } else {
184                                 xtime = 0L;
185                         }
186
187                         if ((xtime > 0L)
188                            && (now - xtime > (time_t)(epbuf.expire_value * 86400L))) {
189                                 fprintf(purgelist, "m=%ld\n", delnum);
190                                 ++messages_purged;
191                         }
192                 }
193         }
194
195         if (msglist != NULL) free(msglist);
196 }
197
198
199 /*
200  * Second phase of message purge -- read list of msgs from temp file and
201  * delete them.
202  */
203 void DoPurgeMessages(FILE *purgelist) {
204         char roomname[ROOMNAMELEN];
205         long msgnum;
206         char buf[SIZ];
207
208         rewind(purgelist);
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]);
214                 }
215                 if (!strncasecmp(buf, "m=", 2)) {
216                         msgnum = atol(&buf[2]);
217                         if (msgnum > 0L) {
218                                 CtdlDeleteMessages(roomname, &msgnum, 1, "");
219                         }
220                 }
221         }
222 }
223
224
225 void PurgeMessages(void) {
226         FILE *purgelist;
227
228         CtdlLogPrintf(CTDL_DEBUG, "PurgeMessages() called\n");
229         messages_purged = 0;
230
231         purgelist = tmpfile();
232         if (purgelist == NULL) {
233                 CtdlLogPrintf(CTDL_CRIT, "Can't create purgelist temp file: %s\n",
234                         strerror(errno));
235                 return;
236         }
237
238         ForEachRoom(GatherPurgeMessages, (void *)purgelist );
239         DoPurgeMessages(purgelist);
240         fclose(purgelist);
241 }
242
243
244 void AddValidUser(struct ctdluser *usbuf, void *data) {
245         struct ValidUser *vuptr;
246
247         vuptr = (struct ValidUser *)malloc(sizeof(struct ValidUser));
248         vuptr->next = ValidUserList;
249         vuptr->vu_usernum = usbuf->usernum;
250         ValidUserList = vuptr;
251 }
252
253 void AddValidRoom(struct ctdlroom *qrbuf, void *data) {
254         struct ValidRoom *vrptr;
255
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;
261 }
262
263 void DoPurgeRooms(struct ctdlroom *qrbuf, void *data) {
264         time_t age, purge_secs;
265         struct PurgeList *pptr;
266         struct ValidUser *vuptr;
267         int do_purge = 0;
268
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.
272          */
273         if (qrbuf->QRflags & QR_MAILBOX) {
274                 /* if user not found, do_purge will be 1 */
275                 do_purge = 1;
276                 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
277                         if (vuptr->vu_usernum == atol(qrbuf->QRname)) {
278                                 do_purge = 0;
279                         }
280                 }
281         }
282         else {
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;
289
290                 /* If we don't know the modification date, be safe and don't purge */
291                 if (qrbuf->QRmtime <= (time_t)0) return;
292
293                 /* If no room purge time is set, be safe and don't purge */
294                 if (config.c_roompurge < 0) return;
295
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;
302         } /* !QR_MAILBOX */
303
304         if (do_purge) {
305                 pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
306                 pptr->next = RoomPurgeList;
307                 strcpy(pptr->name, qrbuf->QRname);
308                 RoomPurgeList = pptr;
309         }
310
311 }
312
313
314
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;
321
322         CtdlLogPrintf(CTDL_DEBUG, "PurgeRooms() called\n");
323
324
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);
328
329         /* Then cycle through the room file */
330         ForEachRoom(DoPurgeRooms, NULL);
331
332         /* Free the valid user list */
333         while (ValidUserList != NULL) {
334                 vuptr = ValidUserList->next;
335                 free(ValidUserList);
336                 ValidUserList = vuptr;
337         }
338
339
340         transcript = malloc(SIZ);
341         strcpy(transcript, "The following rooms have been auto-purged:\n");
342
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",
347                                 qrbuf.QRname);
348                         delete_room(&qrbuf);
349                 }
350                 pptr = RoomPurgeList->next;
351                 free(RoomPurgeList);
352                 RoomPurgeList = pptr;
353                 ++num_rooms_purged;
354         }
355
356         if (num_rooms_purged > 0) aide_message(transcript, "Room Autopurger Message");
357         free(transcript);
358
359         CtdlLogPrintf(CTDL_DEBUG, "Purged %d rooms.\n", num_rooms_purged);
360         return(num_rooms_purged);
361 }
362
363
364 /*
365  * Back end function to check user accounts for associated Unix accounts
366  * which no longer exist.  (Only relevant for host auth mode.)
367  */
368 void do_uid_user_purge(struct ctdluser *us, void *data) {
369         struct PurgeList *pptr;
370
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;
378                 }
379         }
380         else {
381                 ++users_not_purged;
382         }
383 }
384
385
386
387
388 /*
389  * Back end function to check user accounts for expiration.
390  */
391 void do_user_purge(struct ctdluser *us, void *data) {
392         int purge;
393         time_t now;
394         time_t purge_time;
395         struct PurgeList *pptr;
396
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;
400         }
401         else {
402                 purge_time = ((time_t)config.c_userpurge) * 86400L;
403         }
404
405         /* The default rule is to not purge. */
406         purge = 0;
407
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.
410          */
411         if (config.c_userpurge > 0)
412         {
413                 now = time(NULL);
414                 if ((now - us->lastcall) > purge_time) purge = 1;
415         }
416
417         /* If the record is marked as permanent, don't purge it.
418          */
419         if (us->flags & US_PERM) purge = 0;
420
421         /* If the user is an Aide, don't purge him/her/it.
422          */
423         if (us->axlevel == 6) purge = 0;
424
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.
428          */
429         if (us->axlevel == 0) purge = 1;
430
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.
434          */
435         if (!strcasecmp(us->password, "deleteme")) purge = 1;
436         
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)
440          */
441         if (us->timescalled < 0) purge = 1;
442
443         /* User number 0, as well as any negative user number, is
444          * also impossible.
445          */
446         if (us->usernum < 0L) purge = 1;
447         
448         /** Don't purge user 0. That user is there for the system */
449         if (us->usernum == 0) purge = 0;
450         
451         /* If the user has no full name entry then we can't purge them
452          * since the actual purge can't find them.
453          * This shouldn't happen but does somehow.
454          * So we make an Aide message to alert to it but don't add it to the purge list
455          */
456         if (IsEmptyStr(us->fullname))
457         {
458                 if (us->usernum > 0L)
459                 {
460                         purge=0;
461                         if (users_corrupt_msg == NULL)
462                         {
463                                 users_corrupt_msg = malloc(SIZ);
464                                 strcpy(users_corrupt_msg, "The auto-purger found the following user numbers with no name.\n"
465                                 "Unfortunately the auto-purger is not yet able to fix this problem.\n"
466                                 "This problem is not considered serious since a user with no name can\n"
467                                 "not log in.\n");
468                         }
469                 
470                         users_corrupt_msg=realloc(users_corrupt_msg, strlen(users_corrupt_msg)+SIZ);
471                         snprintf(&users_corrupt_msg[strlen(users_corrupt_msg)], SIZ, " %ld\n", us->usernum);
472                 }
473         }
474
475
476         if (purge == 1) {
477                 pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
478                 pptr->next = UserPurgeList;
479                 strcpy(pptr->name, us->fullname);
480                 UserPurgeList = pptr;
481         }
482         else {
483                 ++users_not_purged;
484         }
485
486 }
487
488
489
490 int PurgeUsers(void) {
491         struct PurgeList *pptr;
492         int num_users_purged = 0;
493         char *transcript = NULL;
494
495         CtdlLogPrintf(CTDL_DEBUG, "PurgeUsers() called\n");
496         users_not_purged = 0;
497
498         switch(config.c_auth_mode) {
499                 case AUTHMODE_NATIVE:
500                         ForEachUser(do_user_purge, NULL);
501                         break;
502                 case AUTHMODE_HOST:
503                         ForEachUser(do_uid_user_purge, NULL);
504                         break;
505                 default:
506                         CtdlLogPrintf(CTDL_DEBUG, "Unknown authentication mode!\n");
507                         break;
508         }
509
510         transcript = malloc(SIZ);
511
512         if (users_not_purged == 0) {
513                 strcpy(transcript, "The auto-purger was told to purge every user.  It is\n"
514                                 "refusing to do this because it usually indicates a problem\n"
515                                 "such as an inability to communicate with a name service.\n"
516                 );
517                 while (UserPurgeList != NULL) {
518                         pptr = UserPurgeList->next;
519                         free(UserPurgeList);
520                         UserPurgeList = pptr;
521                         ++num_users_purged;
522                 }
523         }
524
525         else {
526                 strcpy(transcript, "The following users have been auto-purged:\n");
527                 while (UserPurgeList != NULL) {
528                         transcript=realloc(transcript, strlen(transcript)+SIZ);
529                         snprintf(&transcript[strlen(transcript)], SIZ, " %s\n",
530                                 UserPurgeList->name);
531                         purge_user(UserPurgeList->name);
532                         pptr = UserPurgeList->next;
533                         free(UserPurgeList);
534                         UserPurgeList = pptr;
535                         ++num_users_purged;
536                 }
537         }
538
539         if (num_users_purged > 0) aide_message(transcript, "User Purge Message");
540         free(transcript);
541
542         if(users_corrupt_msg)
543         {
544                 aide_message(users_corrupt_msg, "User Corruption Message");
545                 free (users_corrupt_msg);
546                 users_corrupt_msg = NULL;
547         }
548         
549                 
550         CtdlLogPrintf(CTDL_DEBUG, "Purged %d users.\n", num_users_purged);
551         return(num_users_purged);
552 }
553
554
555 /*
556  * Purge visits
557  *
558  * This is a really cumbersome "garbage collection" function.  We have to
559  * delete visits which refer to rooms and/or users which no longer exist.  In
560  * order to prevent endless traversals of the room and user files, we first
561  * build linked lists of rooms and users which _do_ exist on the system, then
562  * traverse the visit file, checking each record against those two lists and
563  * purging the ones that do not have a match on _both_ lists.  (Remember, if
564  * either the room or user being referred to is no longer on the system, the
565  * record is completely useless.)
566  */
567 int PurgeVisits(void) {
568         struct cdbdata *cdbvisit;
569         struct visit vbuf;
570         struct VPurgeList *VisitPurgeList = NULL;
571         struct VPurgeList *vptr;
572         int purged = 0;
573         char IndexBuf[32];
574         int IndexLen;
575         struct ValidRoom *vrptr;
576         struct ValidUser *vuptr;
577         int RoomIsValid, UserIsValid;
578
579         /* First, load up a table full of valid room/gen combinations */
580         ForEachRoom(AddValidRoom, NULL);
581
582         /* Then load up a table full of valid user numbers */
583         ForEachUser(AddValidUser, NULL);
584
585         /* Now traverse through the visits, purging irrelevant records... */
586         cdb_rewind(CDB_VISIT);
587         while(cdbvisit = cdb_next_item(CDB_VISIT), cdbvisit != NULL) {
588                 memset(&vbuf, 0, sizeof(struct visit));
589                 memcpy(&vbuf, cdbvisit->ptr,
590                         ( (cdbvisit->len > sizeof(struct visit)) ?
591                         sizeof(struct visit) : cdbvisit->len) );
592                 cdb_free(cdbvisit);
593
594                 RoomIsValid = 0;
595                 UserIsValid = 0;
596
597                 /* Check to see if the room exists */
598                 for (vrptr=ValidRoomList; vrptr!=NULL; vrptr=vrptr->next) {
599                         if ( (vrptr->vr_roomnum==vbuf.v_roomnum)
600                              && (vrptr->vr_roomgen==vbuf.v_roomgen))
601                                 RoomIsValid = 1;
602                 }
603
604                 /* Check to see if the user exists */
605                 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
606                         if (vuptr->vu_usernum == vbuf.v_usernum)
607                                 UserIsValid = 1;
608                 }
609
610                 /* Put the record on the purge list if it's dead */
611                 if ((RoomIsValid==0) || (UserIsValid==0)) {
612                         vptr = (struct VPurgeList *)
613                                 malloc(sizeof(struct VPurgeList));
614                         vptr->next = VisitPurgeList;
615                         vptr->vp_roomnum = vbuf.v_roomnum;
616                         vptr->vp_roomgen = vbuf.v_roomgen;
617                         vptr->vp_usernum = vbuf.v_usernum;
618                         VisitPurgeList = vptr;
619                 }
620
621         }
622
623         /* Free the valid room/gen combination list */
624         while (ValidRoomList != NULL) {
625                 vrptr = ValidRoomList->next;
626                 free(ValidRoomList);
627                 ValidRoomList = vrptr;
628         }
629
630         /* Free the valid user list */
631         while (ValidUserList != NULL) {
632                 vuptr = ValidUserList->next;
633                 free(ValidUserList);
634                 ValidUserList = vuptr;
635         }
636
637         /* Now delete every visit on the purged list */
638         while (VisitPurgeList != NULL) {
639                 IndexLen = GenerateRelationshipIndex(IndexBuf,
640                                 VisitPurgeList->vp_roomnum,
641                                 VisitPurgeList->vp_roomgen,
642                                 VisitPurgeList->vp_usernum);
643                 cdb_delete(CDB_VISIT, IndexBuf, IndexLen);
644                 vptr = VisitPurgeList->next;
645                 free(VisitPurgeList);
646                 VisitPurgeList = vptr;
647                 ++purged;
648         }
649
650         return(purged);
651 }
652
653 /*
654  * Purge the use table of old entries.
655  *
656  */
657 int PurgeUseTable(void) {
658         int purged = 0;
659         struct cdbdata *cdbut;
660         struct UseTable ut;
661         struct UPurgeList *ul = NULL;
662         struct UPurgeList *uptr; 
663
664         /* Phase 1: traverse through the table, discovering old records... */
665         CtdlLogPrintf(CTDL_DEBUG, "Purge use table: phase 1\n");
666         cdb_rewind(CDB_USETABLE);
667         while(cdbut = cdb_next_item(CDB_USETABLE), cdbut != NULL) {
668
669         /*
670          * TODODRW: change this to create a new function time_t cdb_get_timestamp( struct cdbdata *)
671          * this will release this file from the serv_network.h
672          * Maybe it could be a macro that extracts and casts the reult
673          */
674                 memcpy(&ut, cdbut->ptr,
675                        ((cdbut->len > sizeof(struct UseTable)) ?
676                         sizeof(struct UseTable) : cdbut->len));
677                 cdb_free(cdbut);
678
679                 if ( (time(NULL) - ut.ut_timestamp) > USETABLE_RETAIN ) {
680                         uptr = (struct UPurgeList *) malloc(sizeof(struct UPurgeList));
681                         if (uptr != NULL) {
682                                 uptr->next = ul;
683                                 safestrncpy(uptr->up_key, ut.ut_msgid, sizeof uptr->up_key);
684                                 ul = uptr;
685                         }
686                         ++purged;
687                 }
688
689         }
690
691         /* Phase 2: delete the records */
692         CtdlLogPrintf(CTDL_DEBUG, "Purge use table: phase 2\n");
693         while (ul != NULL) {
694                 cdb_delete(CDB_USETABLE, ul->up_key, strlen(ul->up_key));
695                 uptr = ul->next;
696                 free(ul);
697                 ul = uptr;
698         }
699
700         CtdlLogPrintf(CTDL_DEBUG, "Purge use table: finished (purged %d records)\n", purged);
701         return(purged);
702 }
703
704
705
706 /*
707  * Purge the EUID Index of old records.
708  *
709  */
710 int PurgeEuidIndexTable(void) {
711         int purged = 0;
712         struct cdbdata *cdbei;
713         struct EPurgeList *el = NULL;
714         struct EPurgeList *eptr; 
715         long msgnum;
716         struct CtdlMessage *msg = NULL;
717
718         /* Phase 1: traverse through the table, discovering old records... */
719         CtdlLogPrintf(CTDL_DEBUG, "Purge EUID index: phase 1\n");
720         cdb_rewind(CDB_EUIDINDEX);
721         while(cdbei = cdb_next_item(CDB_EUIDINDEX), cdbei != NULL) {
722
723                 memcpy(&msgnum, cdbei->ptr, sizeof(long));
724
725                 msg = CtdlFetchMessage(msgnum, 0);
726                 if (msg != NULL) {
727                         CtdlFreeMessage(msg);   /* it still exists, so do nothing */
728                 }
729                 else {
730                         eptr = (struct EPurgeList *) malloc(sizeof(struct EPurgeList));
731                         if (eptr != NULL) {
732                                 eptr->next = el;
733                                 eptr->ep_keylen = cdbei->len - sizeof(long);
734                                 eptr->ep_key = malloc(cdbei->len);
735                                 memcpy(eptr->ep_key, &cdbei->ptr[sizeof(long)], eptr->ep_keylen);
736                                 el = eptr;
737                         }
738                         ++purged;
739                 }
740
741                 cdb_free(cdbei);
742
743         }
744
745         /* Phase 2: delete the records */
746         CtdlLogPrintf(CTDL_DEBUG, "Purge euid index: phase 2\n");
747         while (el != NULL) {
748                 cdb_delete(CDB_EUIDINDEX, el->ep_key, el->ep_keylen);
749                 free(el->ep_key);
750                 eptr = el->next;
751                 free(el);
752                 el = eptr;
753         }
754
755         CtdlLogPrintf(CTDL_DEBUG, "Purge euid index: finished (purged %d records)\n", purged);
756         return(purged);
757 }
758
759
760 void *purge_databases(void *args)
761 {
762         int retval;
763         static time_t last_purge = 0;
764         time_t now;
765         struct tm tm;
766         struct CitContext purgerCC;
767
768         CtdlLogPrintf(CTDL_DEBUG, "Auto-purger_thread() initializing\n");
769
770         memset(&purgerCC, 0, sizeof(struct CitContext));
771         purgerCC.internal_pgm = 1;
772         purgerCC.cs_pid = 0;
773         pthread_setspecific(MyConKey, (void *)&purgerCC );
774
775         while (!CtdlThreadCheckStop()) {
776                 /* Do the auto-purge if the current hour equals the purge hour,
777                  * but not if the operation has already been performed in the
778                  * last twelve hours.  This is usually enough granularity.
779                  */
780                 now = time(NULL);
781                 localtime_r(&now, &tm);
782                 if ((tm.tm_hour != config.c_purge_hour) || ((now - last_purge) < 43200)) {
783                         CtdlThreadSleep(60);
784                         continue;
785                 }
786
787
788                 CtdlLogPrintf(CTDL_INFO, "Auto-purger: starting.\n");
789
790                 if (!CtdlThreadCheckStop())
791                 {
792                         retval = PurgeUsers();
793                         CtdlLogPrintf(CTDL_NOTICE, "Purged %d users.\n", retval);
794                 }
795                 
796                 if (!CtdlThreadCheckStop())
797                 {
798                         PurgeMessages();
799                         CtdlLogPrintf(CTDL_NOTICE, "Expired %d messages.\n", messages_purged);
800                 }
801
802                 if (!CtdlThreadCheckStop())
803                 {
804                         retval = PurgeRooms();
805                         CtdlLogPrintf(CTDL_NOTICE, "Expired %d rooms.\n", retval);
806                 }
807
808                 if (!CtdlThreadCheckStop())
809                 {
810                         retval = PurgeVisits();
811                         CtdlLogPrintf(CTDL_NOTICE, "Purged %d visits.\n", retval);
812                 }
813
814                 if (!CtdlThreadCheckStop())
815                 {
816                         retval = PurgeUseTable();
817                         CtdlLogPrintf(CTDL_NOTICE, "Purged %d entries from the use table.\n", retval);
818                 }
819
820                 if (!CtdlThreadCheckStop())
821                 {
822                         retval = PurgeEuidIndexTable();
823                         CtdlLogPrintf(CTDL_NOTICE, "Purged %d entries from the EUID index.\n", retval);
824                 }
825
826                 if (!CtdlThreadCheckStop())
827                 {
828                         retval = TDAP_ProcessAdjRefCountQueue();
829                         CtdlLogPrintf(CTDL_NOTICE, "Processed %d message reference count adjustments.\n", retval);
830                 }
831
832                 if (!CtdlThreadCheckStop())
833                 {
834                         CtdlLogPrintf(CTDL_INFO, "Auto-purger: finished.\n");
835                         last_purge = now;       /* So we don't do it again soon */
836                 }
837                 else
838                         CtdlLogPrintf(CTDL_INFO, "Auto-purger: STOPPED.\n");
839
840         }
841         return NULL;
842 }
843 /*****************************************************************************/
844
845
846 void do_fsck_msg(long msgnum, void *userdata) {
847         struct ctdlroomref *ptr;
848
849         ptr = (struct ctdlroomref *)malloc(sizeof(struct ctdlroomref));
850         ptr->next = rr;
851         ptr->msgnum = msgnum;
852         rr = ptr;
853 }
854
855 void do_fsck_room(struct ctdlroom *qrbuf, void *data)
856 {
857         getroom(&CC->room, qrbuf->QRname);
858         CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL, NULL, do_fsck_msg, NULL);
859 }
860
861 /*
862  * Check message reference counts
863  */
864 void cmd_fsck(char *argbuf) {
865         long msgnum;
866         struct cdbdata *cdbmsg;
867         struct MetaData smi;
868         struct ctdlroomref *ptr;
869         int realcount;
870
871         if (CtdlAccessCheck(ac_aide)) return;
872
873         /* Lame way of checking whether anyone else is doing this now */
874         if (rr != NULL) {
875                 cprintf("%d Another FSCK is already running.\n", ERROR + RESOURCE_BUSY);
876                 return;
877         }
878
879         cprintf("%d Checking message reference counts\n", LISTING_FOLLOWS);
880
881         cprintf("\nThis could take a while.  Please be patient!\n\n");
882         cprintf("Gathering pointers...\n");
883         ForEachRoom(do_fsck_room, NULL);
884
885         get_control();
886         cprintf("Checking message base...\n");
887         for (msgnum = 0L; msgnum <= CitControl.MMhighest; ++msgnum) {
888
889                 cdbmsg = cdb_fetch(CDB_MSGMAIN, &msgnum, sizeof(long));
890                 if (cdbmsg != NULL) {
891                         cdb_free(cdbmsg);
892                         cprintf("Message %7ld    ", msgnum);
893
894                         GetMetaData(&smi, msgnum);
895                         cprintf("refcount=%-2d   ", smi.meta_refcount);
896
897                         realcount = 0;
898                         for (ptr = rr; ptr != NULL; ptr = ptr->next) {
899                                 if (ptr->msgnum == msgnum) ++realcount;
900                         }
901                         cprintf("realcount=%-2d\n", realcount);
902
903                         if ( (smi.meta_refcount != realcount)
904                            || (realcount == 0) ) {
905                                 AdjRefCount(msgnum, (smi.meta_refcount - realcount));
906                         }
907
908                 }
909
910         }
911
912         cprintf("Freeing memory...\n");
913         while (rr != NULL) {
914                 ptr = rr->next;
915                 free(rr);
916                 rr = ptr;
917         }
918
919         cprintf("Done!\n");
920         cprintf("000\n");
921
922 }
923
924
925
926
927 /*****************************************************************************/
928
929 CTDL_MODULE_INIT(expire)
930 {
931         if (!threading)
932         {
933                 CtdlRegisterProtoHook(cmd_fsck, "FSCK", "Check message ref counts");
934         }
935         else
936                 CtdlThreadCreate("Auto Purger", CTDLTHREAD_BIGSTACK, purge_databases, NULL);
937         /* return our Subversion id for the Log */
938         return "$Id$";
939 }