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