879975496dc942626a31e90c2692c82e4afe71ce
[citadel.git] / citadel / modules / expire / serv_expire.c
1 /*
2  * This module handles the expiry of old messages and the purging of old users.
3  *
4  * You might also see this module affectionately referred to as the DAP (the Dreaded Auto-Purger).
5  *
6  * Copyright (c) 1988-2018 by citadel.org (Art Cancro, Wilifried Goesgens, and others)
7  *
8  * This program is open source software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License as published
10  * by the Free Software Foundation; either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * A brief technical discussion:
19  *
20  * Several of the purge operations found in this module operate in two
21  * stages: the first stage generates a linked list of objects to be deleted,
22  * then the second stage deletes all listed objects from the database.
23  *
24  * At first glance this may seem cumbersome and unnecessary.  The reason it is
25  * implemented in this way is because Berkeley DB, and possibly other backends
26  * we may hook into in the future, explicitly do _not_ support the deletion of
27  * records from a file while the file is being traversed.  The delete operation
28  * will succeed, but the traversal is not guaranteed to visit every object if
29  * this is done.  Therefore we utilize the two-stage purge.
30  *
31  * When using Berkeley DB, there's another reason for the two-phase purge: we
32  * don't want the entire thing being done as one huge transaction.
33  *
34  * You'll also notice that we build the in-memory list of records to be deleted
35  * sometimes with a linked list and sometimes with a hash table.  There is no
36  * reason for this aside from the fact that the linked list ones were written
37  * before we had the hash table library available.
38  */
39
40
41 #include "sysdep.h"
42 #include <stdlib.h>
43 #include <unistd.h>
44 #include <stdio.h>
45 #include <fcntl.h>
46 #include <signal.h>
47 #include <pwd.h>
48 #include <errno.h>
49 #include <sys/types.h>
50
51 #if TIME_WITH_SYS_TIME
52 # include <sys/time.h>
53 # include <time.h>
54 #else
55 # if HAVE_SYS_TIME_H
56 #  include <sys/time.h>
57 # else
58 #  include <time.h>
59 # endif
60 #endif
61
62 #include <sys/wait.h>
63 #include <string.h>
64 #include <limits.h>
65 #include <libcitadel.h>
66 #include "citadel.h"
67 #include "server.h"
68 #include "citserver.h"
69 #include "support.h"
70 #include "config.h"
71 #include "policy.h"
72 #include "database.h"
73 #include "msgbase.h"
74 #include "user_ops.h"
75 #include "control.h"
76 #include "threads.h"
77 #include "context.h"
78
79 #include "ctdl_module.h"
80
81
82 struct PurgeList {
83         struct PurgeList *next;
84         char name[ROOMNAMELEN]; /* use the larger of username or roomname */
85 };
86
87 struct VPurgeList {
88         struct VPurgeList *next;
89         long vp_roomnum;
90         long vp_roomgen;
91         long vp_usernum;
92 };
93
94 struct ValidRoom {
95         struct ValidRoom *next;
96         long vr_roomnum;
97         long vr_roomgen;
98 };
99
100 struct ValidUser {
101         struct ValidUser *next;
102         long vu_usernum;
103 };
104
105 struct ctdlroomref {
106         struct ctdlroomref *next;
107         long msgnum;
108 };
109
110 struct UPurgeList {
111         struct UPurgeList *next;
112         char up_key[256];
113 };
114
115 struct EPurgeList {
116         struct EPurgeList *next;
117         int ep_keylen;
118         char *ep_key;
119 };
120
121
122 struct PurgeList *UserPurgeList = NULL;
123 struct PurgeList *RoomPurgeList = NULL;
124 struct ValidRoom *ValidRoomList = NULL;
125 struct ValidUser *ValidUserList = NULL;
126 int messages_purged;
127 int users_not_purged;
128 char *users_corrupt_msg = NULL;
129 char *users_zero_msg = NULL;
130 struct ctdlroomref *rr = NULL;
131 int force_purge_now = 0;                        /* set to nonzero to force a run right now */
132
133
134 /*
135  * First phase of message purge -- gather the locations of messages which
136  * qualify for purging and write them to a temp file.
137  */
138 void GatherPurgeMessages(struct ctdlroom *qrbuf, void *data) {
139         struct ExpirePolicy epbuf;
140         long delnum;
141         time_t xtime, now;
142         struct CtdlMessage *msg = NULL;
143         int a;
144         struct cdbdata *cdbfr;
145         long *msglist = NULL;
146         int num_msgs = 0;
147         FILE *purgelist;
148
149         purgelist = (FILE *)data;
150         fprintf(purgelist, "r=%s\n", qrbuf->QRname);
151
152         time(&now);
153         GetExpirePolicy(&epbuf, qrbuf);
154
155         /* If the room is set to never expire messages ... do nothing */
156         if (epbuf.expire_mode == EXPIRE_NEXTLEVEL) return;
157         if (epbuf.expire_mode == EXPIRE_MANUAL) return;
158
159         /* Don't purge messages containing system configuration, dumbass. */
160         if (!strcasecmp(qrbuf->QRname, SYSCONFIGROOM)) return;
161
162         /* Ok, we got this far ... now let's see what's in the room */
163         cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf->QRnumber, sizeof(long));
164
165         if (cdbfr != NULL) {
166                 msglist = malloc(cdbfr->len);
167                 memcpy(msglist, cdbfr->ptr, cdbfr->len);
168                 num_msgs = cdbfr->len / sizeof(long);
169                 cdb_free(cdbfr);
170         }
171
172         /* Nothing to do if there aren't any messages */
173         if (num_msgs == 0) {
174                 if (msglist != NULL) free(msglist);
175                 return;
176         }
177
178         /* If the room is set to expire by count, do that */
179         if (epbuf.expire_mode == EXPIRE_NUMMSGS) {
180                 if (num_msgs > epbuf.expire_value) {
181                         for (a=0; a<(num_msgs - epbuf.expire_value); ++a) {
182                                 fprintf(purgelist, "m=%ld\n", msglist[a]);
183                                 ++messages_purged;
184                         }
185                 }
186         }
187
188         /* If the room is set to expire by age... */
189         if (epbuf.expire_mode == EXPIRE_AGE) {
190                 for (a=0; a<num_msgs; ++a) {
191                         delnum = msglist[a];
192
193                         msg = CtdlFetchMessage(delnum, 0, 1); /* dont need body */
194                         if (msg != NULL) {
195                                 xtime = atol(msg->cm_fields[eTimestamp]);
196                                 CM_Free(msg);
197                         } else {
198                                 xtime = 0L;
199                         }
200
201                         if ((xtime > 0L)
202                            && (now - xtime > (time_t)(epbuf.expire_value * 86400L))) {
203                                 fprintf(purgelist, "m=%ld\n", delnum);
204                                 ++messages_purged;
205                         }
206                 }
207         }
208
209         if (msglist != NULL) free(msglist);
210 }
211
212
213 /*
214  * Second phase of message purge -- read list of msgs from temp file and
215  * delete them.
216  */
217 void DoPurgeMessages(FILE *purgelist) {
218         char roomname[ROOMNAMELEN];
219         long msgnum;
220         char buf[SIZ];
221
222         rewind(purgelist);
223         strcpy(roomname, "nonexistent room ___ ___");
224         while (fgets(buf, sizeof buf, purgelist) != NULL) {
225                 buf[strlen(buf)-1]=0;
226                 if (!strncasecmp(buf, "r=", 2)) {
227                         strcpy(roomname, &buf[2]);
228                 }
229                 if (!strncasecmp(buf, "m=", 2)) {
230                         msgnum = atol(&buf[2]);
231                         if (msgnum > 0L) {
232                                 CtdlDeleteMessages(roomname, &msgnum, 1, "");
233                         }
234                 }
235         }
236 }
237
238
239 void PurgeMessages(void) {
240         FILE *purgelist;
241
242         syslog(LOG_DEBUG, "PurgeMessages() called");
243         messages_purged = 0;
244
245         purgelist = tmpfile();
246         if (purgelist == NULL) {
247                 syslog(LOG_CRIT, "Can't create purgelist temp file: %s", strerror(errno));
248                 return;
249         }
250
251         CtdlForEachRoom(GatherPurgeMessages, (void *)purgelist );
252         DoPurgeMessages(purgelist);
253         fclose(purgelist);
254 }
255
256
257 void AddValidUser(struct ctdluser *usbuf, void *data) {
258         struct ValidUser *vuptr;
259
260         vuptr = (struct ValidUser *)malloc(sizeof(struct ValidUser));
261         vuptr->next = ValidUserList;
262         vuptr->vu_usernum = usbuf->usernum;
263         ValidUserList = vuptr;
264 }
265
266 void AddValidRoom(struct ctdlroom *qrbuf, void *data) {
267         struct ValidRoom *vrptr;
268
269         vrptr = (struct ValidRoom *)malloc(sizeof(struct ValidRoom));
270         vrptr->next = ValidRoomList;
271         vrptr->vr_roomnum = qrbuf->QRnumber;
272         vrptr->vr_roomgen = qrbuf->QRgen;
273         ValidRoomList = vrptr;
274 }
275
276 void DoPurgeRooms(struct ctdlroom *qrbuf, void *data) {
277         time_t age, purge_secs;
278         struct PurgeList *pptr;
279         struct ValidUser *vuptr;
280         int do_purge = 0;
281
282         /* For mailbox rooms, there's only one purging rule: if the user who
283          * owns the room still exists, we keep the room; otherwise, we purge
284          * it.  Bypass any other rules.
285          */
286         if (qrbuf->QRflags & QR_MAILBOX) {
287                 /* if user not found, do_purge will be 1 */
288                 do_purge = 1;
289                 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
290                         if (vuptr->vu_usernum == atol(qrbuf->QRname)) {
291                                 do_purge = 0;
292                         }
293                 }
294         }
295         else {
296                 /* Any of these attributes render a room non-purgable */
297                 if (qrbuf->QRflags & QR_PERMANENT) return;
298                 if (qrbuf->QRflags & QR_DIRECTORY) return;
299                 if (qrbuf->QRflags & QR_NETWORK) return;
300                 if (qrbuf->QRflags2 & QR2_SYSTEM) return;
301                 if (!strcasecmp(qrbuf->QRname, SYSCONFIGROOM)) return;
302                 if (CtdlIsNonEditable(qrbuf)) return;
303
304                 /* If we don't know the modification date, be safe and don't purge */
305                 if (qrbuf->QRmtime <= (time_t)0) return;
306
307                 /* If no room purge time is set, be safe and don't purge */
308                 if (CtdlGetConfigLong("c_roompurge") < 0) return;
309
310                 /* Otherwise, check the date of last modification */
311                 age = time(NULL) - (qrbuf->QRmtime);
312                 purge_secs = CtdlGetConfigLong("c_roompurge") * 86400;
313                 if (purge_secs <= (time_t)0) return;
314                 syslog(LOG_DEBUG, "<%s> is <%ld> seconds old", qrbuf->QRname, (long)age);
315                 if (age > purge_secs) do_purge = 1;
316         } /* !QR_MAILBOX */
317
318         if (do_purge) {
319                 pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
320                 pptr->next = RoomPurgeList;
321                 strcpy(pptr->name, qrbuf->QRname);
322                 RoomPurgeList = pptr;
323         }
324
325 }
326
327
328 int PurgeRooms(void) {
329         struct PurgeList *pptr;
330         int num_rooms_purged = 0;
331         struct ctdlroom qrbuf;
332         struct ValidUser *vuptr;
333         char *transcript = NULL;
334
335         syslog(LOG_DEBUG, "PurgeRooms() called");
336
337         /* Load up a table full of valid user numbers so we can delete
338          * user-owned rooms for users who no longer exist */
339         ForEachUser(AddValidUser, NULL);
340
341         /* Then cycle through the room file */
342         CtdlForEachRoom(DoPurgeRooms, NULL);
343
344         /* Free the valid user list */
345         while (ValidUserList != NULL) {
346                 vuptr = ValidUserList->next;
347                 free(ValidUserList);
348                 ValidUserList = vuptr;
349         }
350
351         transcript = malloc(SIZ);
352         strcpy(transcript, "The following rooms have been auto-purged:\n");
353
354         while (RoomPurgeList != NULL) {
355                 if (CtdlGetRoom(&qrbuf, RoomPurgeList->name) == 0) {
356                         transcript=realloc(transcript, strlen(transcript)+SIZ);
357                         snprintf(&transcript[strlen(transcript)], SIZ, " %s\n",
358                                 qrbuf.QRname);
359                         CtdlDeleteRoom(&qrbuf);
360                 }
361                 pptr = RoomPurgeList->next;
362                 free(RoomPurgeList);
363                 RoomPurgeList = pptr;
364                 ++num_rooms_purged;
365         }
366
367         if (num_rooms_purged > 0) CtdlAideMessage(transcript, "Room Autopurger Message");
368         free(transcript);
369
370         syslog(LOG_DEBUG, "Purged %d rooms.", num_rooms_purged);
371         return(num_rooms_purged);
372 }
373
374
375 /*
376  * Back end function to check user accounts for associated Unix accounts
377  * which no longer exist.  (Only relevant for host auth mode.)
378  */
379 void do_uid_user_purge(struct ctdluser *us, void *data) {
380         struct PurgeList *pptr;
381
382         if ((us->uid != (-1)) && (us->uid != CTDLUID)) {
383                 if (getpwuid(us->uid) == NULL) {
384                         pptr = (struct PurgeList *)
385                                 malloc(sizeof(struct PurgeList));
386                         pptr->next = UserPurgeList;
387                         strcpy(pptr->name, us->fullname);
388                         UserPurgeList = pptr;
389                 }
390         }
391         else {
392                 ++users_not_purged;
393         }
394 }
395
396
397 /*
398  * Back end function to check user accounts for expiration.
399  */
400 void do_user_purge(struct ctdluser *us, void *data) {
401         int purge;
402         time_t now;
403         time_t purge_time;
404         struct PurgeList *pptr;
405
406         /* Set purge time; if the user overrides the system default, use it */
407         if (us->USuserpurge > 0) {
408                 purge_time = ((time_t)us->USuserpurge) * 86400;
409         }
410         else {
411                 purge_time = CtdlGetConfigLong("c_userpurge") * 86400;
412         }
413
414         /* The default rule is to not purge. */
415         purge = 0;
416         
417         /* If the user hasn't called in two months and expiring of accounts is turned on, his/her account
418          * has expired, so purge the record.
419          */
420         if (CtdlGetConfigLong("c_userpurge") > 0)
421         {
422                 now = time(NULL);
423                 if ((now - us->lastcall) > purge_time) purge = 1;
424         }
425
426         /* If the record is marked as permanent, don't purge it.
427          */
428         if (us->flags & US_PERM) purge = 0;
429
430         /* If the user is an Aide, don't purge him/her/it.
431          */
432         if (us->axlevel == 6) purge = 0;
433
434         /* If the access level is 0, the record should already have been
435          * deleted, but maybe the user was logged in at the time or something.
436          * Delete the record now.
437          */
438         if (us->axlevel == 0) purge = 1;
439
440         /* If the user set his/her password to 'deleteme', he/she
441          * wishes to be deleted, so purge the record.
442          * Moved this lower down so that aides and permanent users get purged if they ask to be.
443          */
444         if (!strcasecmp(us->password, "deleteme")) purge = 1;
445         
446         /* 0 calls is impossible.  If there are 0 calls, it must
447          * be a corrupted record, so purge it.
448          * Actually it is possible if an Aide created the user so now we check for less than 0 (DRW)
449          */
450         if (us->timescalled < 0) purge = 1;
451
452         /* any negative user number, is
453          * also impossible.
454          */
455         if (us->usernum < 0L) purge = 1;
456         
457         /* Don't purge user 0. That user is there for the system */
458         if (us->usernum == 0L)
459         {
460                 /* FIXME: Temporary log message. Until we do unauth access with user 0 we should
461                  * try to get rid of all user 0 occurences. Many will be remnants from old code so
462                  * we will need to try and purge them from users data bases.Some will not have names but
463                  * those with names should be purged.
464                  */
465                 syslog(LOG_DEBUG, "Auto purger found a user 0 with name <%s>", us->fullname);
466                 // purge = 0;
467         }
468         
469         /* If the user has no full name entry then we can't purge them
470          * since the actual purge can't find them.
471          * This shouldn't happen but does somehow.
472          */
473         if (IsEmptyStr(us->fullname))
474         {
475                 purge = 0;
476                 
477                 if (us->usernum > 0L)
478                 {
479                         purge=0;
480                         if (users_corrupt_msg == NULL)
481                         {
482                                 users_corrupt_msg = malloc(SIZ);
483                                 strcpy(users_corrupt_msg,
484                                         "The auto-purger found the following user numbers with no name.\n"
485                                         "The system has no way to purge a user with no name,"
486                                         " and should not be able to create them either.\n"
487                                         "This indicates corruption of the user DB or possibly a bug.\n"
488                                         "It may be a good idea to restore your DB from a backup.\n"
489                                 );
490                         }
491                 
492                         users_corrupt_msg=realloc(users_corrupt_msg, strlen(users_corrupt_msg)+30);
493                         snprintf(&users_corrupt_msg[strlen(users_corrupt_msg)], 29, " %ld\n", us->usernum);
494                 }
495         }
496
497         if (purge == 1) {
498                 pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
499                 pptr->next = UserPurgeList;
500                 strcpy(pptr->name, us->fullname);
501                 UserPurgeList = pptr;
502         }
503         else {
504                 ++users_not_purged;
505         }
506
507 }
508
509
510 int PurgeUsers(void) {
511         struct PurgeList *pptr;
512         int num_users_purged = 0;
513         char *transcript = NULL;
514
515         syslog(LOG_DEBUG, "PurgeUsers() called");
516         users_not_purged = 0;
517
518         switch(CtdlGetConfigInt("c_auth_mode")) {
519                 case AUTHMODE_NATIVE:
520                         ForEachUser(do_user_purge, NULL);
521                         break;
522                 case AUTHMODE_HOST:
523                         ForEachUser(do_uid_user_purge, NULL);
524                         break;
525                 default:
526                         syslog(LOG_DEBUG, "User purge for auth mode %d is not implemented.", CtdlGetConfigInt("c_auth_mode"));
527                         break;
528         }
529
530         transcript = malloc(SIZ);
531
532         if (users_not_purged == 0) {
533                 strcpy(transcript, "The auto-purger was told to purge every user.  It is\n"
534                                 "refusing to do this because it usually indicates a problem\n"
535                                 "such as an inability to communicate with a name service.\n"
536                 );
537                 while (UserPurgeList != NULL) {
538                         pptr = UserPurgeList->next;
539                         free(UserPurgeList);
540                         UserPurgeList = pptr;
541                         ++num_users_purged;
542                 }
543         }
544
545         else {
546                 strcpy(transcript, "The following users have been auto-purged:\n");
547                 while (UserPurgeList != NULL) {
548                         transcript=realloc(transcript, strlen(transcript)+SIZ);
549                         snprintf(&transcript[strlen(transcript)], SIZ, " %s\n",
550                                 UserPurgeList->name);
551                         purge_user(UserPurgeList->name);
552                         pptr = UserPurgeList->next;
553                         free(UserPurgeList);
554                         UserPurgeList = pptr;
555                         ++num_users_purged;
556                 }
557         }
558
559         if (num_users_purged > 0) CtdlAideMessage(transcript, "User Purge Message");
560         free(transcript);
561
562         if(users_corrupt_msg)
563         {
564                 CtdlAideMessage(users_corrupt_msg, "User Corruption Message");
565                 free (users_corrupt_msg);
566                 users_corrupt_msg = NULL;
567         }
568         
569         if(users_zero_msg)
570         {
571                 CtdlAideMessage(users_zero_msg, "User Zero Message");
572                 free (users_zero_msg);
573                 users_zero_msg = NULL;
574         }
575                 
576         syslog(LOG_DEBUG, "Purged %d users.", num_users_purged);
577         return(num_users_purged);
578 }
579
580
581 /*
582  * Purge visits
583  *
584  * This is a really cumbersome "garbage collection" function.  We have to
585  * delete visits which refer to rooms and/or users which no longer exist.  In
586  * order to prevent endless traversals of the room and user files, we first
587  * build linked lists of rooms and users which _do_ exist on the system, then
588  * traverse the visit file, checking each record against those two lists and
589  * purging the ones that do not have a match on _both_ lists.  (Remember, if
590  * either the room or user being referred to is no longer on the system, the
591  * record is completely useless.)
592  */
593 int PurgeVisits(void) {
594         struct cdbdata *cdbvisit;
595         visit vbuf;
596         struct VPurgeList *VisitPurgeList = NULL;
597         struct VPurgeList *vptr;
598         int purged = 0;
599         char IndexBuf[32];
600         int IndexLen;
601         struct ValidRoom *vrptr;
602         struct ValidUser *vuptr;
603         int RoomIsValid, UserIsValid;
604
605         /* First, load up a table full of valid room/gen combinations */
606         CtdlForEachRoom(AddValidRoom, NULL);
607
608         /* Then load up a table full of valid user numbers */
609         ForEachUser(AddValidUser, NULL);
610
611         /* Now traverse through the visits, purging irrelevant records... */
612         cdb_rewind(CDB_VISIT);
613         while(cdbvisit = cdb_next_item(CDB_VISIT), cdbvisit != NULL) {
614                 memset(&vbuf, 0, sizeof(visit));
615                 memcpy(&vbuf, cdbvisit->ptr,
616                         ( (cdbvisit->len > sizeof(visit)) ?
617                           sizeof(visit) : cdbvisit->len) );
618                 cdb_free(cdbvisit);
619
620                 RoomIsValid = 0;
621                 UserIsValid = 0;
622
623                 /* Check to see if the room exists */
624                 for (vrptr=ValidRoomList; vrptr!=NULL; vrptr=vrptr->next) {
625                         if ( (vrptr->vr_roomnum==vbuf.v_roomnum)
626                              && (vrptr->vr_roomgen==vbuf.v_roomgen))
627                                 RoomIsValid = 1;
628                 }
629
630                 /* Check to see if the user exists */
631                 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
632                         if (vuptr->vu_usernum == vbuf.v_usernum)
633                                 UserIsValid = 1;
634                 }
635
636                 /* Put the record on the purge list if it's dead */
637                 if ((RoomIsValid==0) || (UserIsValid==0)) {
638                         vptr = (struct VPurgeList *)
639                                 malloc(sizeof(struct VPurgeList));
640                         vptr->next = VisitPurgeList;
641                         vptr->vp_roomnum = vbuf.v_roomnum;
642                         vptr->vp_roomgen = vbuf.v_roomgen;
643                         vptr->vp_usernum = vbuf.v_usernum;
644                         VisitPurgeList = vptr;
645                 }
646
647         }
648
649         /* Free the valid room/gen combination list */
650         while (ValidRoomList != NULL) {
651                 vrptr = ValidRoomList->next;
652                 free(ValidRoomList);
653                 ValidRoomList = vrptr;
654         }
655
656         /* Free the valid user list */
657         while (ValidUserList != NULL) {
658                 vuptr = ValidUserList->next;
659                 free(ValidUserList);
660                 ValidUserList = vuptr;
661         }
662
663         /* Now delete every visit on the purged list */
664         while (VisitPurgeList != NULL) {
665                 IndexLen = GenerateRelationshipIndex(IndexBuf,
666                                 VisitPurgeList->vp_roomnum,
667                                 VisitPurgeList->vp_roomgen,
668                                 VisitPurgeList->vp_usernum);
669                 cdb_delete(CDB_VISIT, IndexBuf, IndexLen);
670                 vptr = VisitPurgeList->next;
671                 free(VisitPurgeList);
672                 VisitPurgeList = vptr;
673                 ++purged;
674         }
675
676         return(purged);
677 }
678
679
680 /*
681  * Purge the use table of old entries.
682  *
683  */
684 int PurgeUseTable(StrBuf *ErrMsg) {
685         int purged = 0;
686         struct cdbdata *cdbut;
687         struct UseTable ut;
688         struct UPurgeList *ul = NULL;
689         struct UPurgeList *uptr; 
690
691         /* Phase 1: traverse through the table, discovering old records... */
692
693         syslog(LOG_DEBUG, "Purge use table: phase 1");
694         cdb_rewind(CDB_USETABLE);
695         while(cdbut = cdb_next_item(CDB_USETABLE), cdbut != NULL)
696         {
697                 if (cdbut->len > sizeof(struct UseTable))
698                         memcpy(&ut, cdbut->ptr, sizeof(struct UseTable));
699                 else
700                 {
701                         memset(&ut, 0, sizeof(struct UseTable));
702                         memcpy(&ut, cdbut->ptr, cdbut->len);
703                 }
704                 cdb_free(cdbut);
705
706                 if ( (time(NULL) - ut.ut_timestamp) > USETABLE_RETAIN )
707                 {
708                         uptr = (struct UPurgeList *) malloc(sizeof(struct UPurgeList));
709                         if (uptr != NULL)
710                         {
711                                 uptr->next = ul;
712                                 safestrncpy(uptr->up_key, ut.ut_msgid, sizeof uptr->up_key);
713                                 ul = uptr;
714                         }
715                         ++purged;
716                 }
717
718         }
719
720         /* Phase 2: delete the records */
721         syslog(LOG_DEBUG, "Purge use table: phase 2");
722         while (ul != NULL) {
723                 cdb_delete(CDB_USETABLE, ul->up_key, strlen(ul->up_key));
724                 uptr = ul->next;
725                 free(ul);
726                 ul = uptr;
727         }
728
729         syslog(LOG_DEBUG, "Purge use table: finished (purged %d records)", purged);
730         return(purged);
731 }
732
733
734 /*
735  * Purge the EUID Index of old records.
736  *
737  */
738 int PurgeEuidIndexTable(void) {
739         int purged = 0;
740         struct cdbdata *cdbei;
741         struct EPurgeList *el = NULL;
742         struct EPurgeList *eptr; 
743         long msgnum;
744         struct CtdlMessage *msg = NULL;
745
746         /* Phase 1: traverse through the table, discovering old records... */
747         syslog(LOG_DEBUG, "Purge EUID index: phase 1");
748         cdb_rewind(CDB_EUIDINDEX);
749         while(cdbei = cdb_next_item(CDB_EUIDINDEX), cdbei != NULL) {
750
751                 memcpy(&msgnum, cdbei->ptr, sizeof(long));
752
753                 msg = CtdlFetchMessage(msgnum, 0, 1);
754                 if (msg != NULL) {
755                         CM_Free(msg);   /* it still exists, so do nothing */
756                 }
757                 else {
758                         eptr = (struct EPurgeList *) malloc(sizeof(struct EPurgeList));
759                         if (eptr != NULL) {
760                                 eptr->next = el;
761                                 eptr->ep_keylen = cdbei->len - sizeof(long);
762                                 eptr->ep_key = malloc(cdbei->len);
763                                 memcpy(eptr->ep_key, &cdbei->ptr[sizeof(long)], eptr->ep_keylen);
764                                 el = eptr;
765                         }
766                         ++purged;
767                 }
768
769                cdb_free(cdbei);
770
771         }
772
773         /* Phase 2: delete the records */
774         syslog(LOG_DEBUG, "Purge euid index: phase 2");
775         while (el != NULL) {
776                 cdb_delete(CDB_EUIDINDEX, el->ep_key, el->ep_keylen);
777                 free(el->ep_key);
778                 eptr = el->next;
779                 free(el);
780                 el = eptr;
781         }
782
783         syslog(LOG_DEBUG, "Purge euid index: finished (purged %d records)", purged);
784         return(purged);
785 }
786
787
788 /*
789  * Purge external auth assocations for missing users (theoretically this will never delete anything)
790  */
791 int PurgeStaleExtAuthAssociations(void) {
792         struct cdbdata *cdboi;
793         struct ctdluser usbuf;
794         HashList *keys = NULL;
795         HashPos *HashPos;
796         char *deleteme = NULL;
797         long len;
798         void *Value;
799         const char *Key;
800         int num_deleted = 0;
801         long usernum = 0L;
802
803         keys = NewHash(1, NULL);
804         if (!keys) return(0);
805
806
807         cdb_rewind(CDB_EXTAUTH);
808         while (cdboi = cdb_next_item(CDB_EXTAUTH), cdboi != NULL) {
809                 if (cdboi->len > sizeof(long)) {
810                         memcpy(&usernum, cdboi->ptr, sizeof(long));
811                         if (CtdlGetUserByNumber(&usbuf, usernum) != 0) {
812                                 deleteme = strdup(cdboi->ptr + sizeof(long)),
813                                 Put(keys, deleteme, strlen(deleteme), deleteme, NULL);
814                         }
815                 }
816                 cdb_free(cdboi);
817         }
818
819         /* Go through the hash list, deleting keys we stored in it */
820
821         HashPos = GetNewHashPos(keys, 0);
822         while (GetNextHashPos(keys, HashPos, &len, &Key, &Value)!=0)
823         {
824                 syslog(LOG_DEBUG, "Deleting associated external authenticator <%s>",  (char*)Value);
825                 cdb_delete(CDB_EXTAUTH, Value, strlen(Value));
826                 /* note: don't free(Value) -- deleting the hash list will handle this for us */
827                 ++num_deleted;
828         }
829         DeleteHashPos(&HashPos);
830         DeleteHash(&keys);
831         return num_deleted;
832 }
833
834
835 void purge_databases(void)
836 {
837         int retval;
838         static time_t last_purge = 0;
839         time_t now;
840         struct tm tm;
841
842         /* Do the auto-purge if the current hour equals the purge hour,
843          * but not if the operation has already been performed in the
844          * last twelve hours.  This is usually enough granularity.
845          */
846         now = time(NULL);
847         localtime_r(&now, &tm);
848         if (((tm.tm_hour != CtdlGetConfigInt("c_purge_hour")) || ((now - last_purge) < 43200)) && (force_purge_now == 0))
849         {
850                         return;
851         }
852
853         syslog(LOG_INFO, "Auto-purger: starting.");
854
855         if (!server_shutting_down)
856         {
857                 retval = PurgeUsers();
858                 syslog(LOG_NOTICE, "Purged %d users.", retval);
859         }
860                 
861         if (!server_shutting_down)
862         {
863                 PurgeMessages();
864                 syslog(LOG_NOTICE, "Expired %d messages.", messages_purged);
865         }
866
867         if (!server_shutting_down)
868         {
869                 retval = PurgeRooms();
870                 syslog(LOG_NOTICE, "Expired %d rooms.", retval);
871         }
872
873         if (!server_shutting_down)
874         {
875                 retval = PurgeVisits();
876                 syslog(LOG_NOTICE, "Purged %d visits.", retval);
877         }
878
879         if (!server_shutting_down)
880         {
881                 StrBuf *ErrMsg;
882
883                 ErrMsg = NewStrBuf ();
884                 retval = PurgeUseTable(ErrMsg);
885                 syslog(LOG_NOTICE, "Purged %d entries from the use table.", retval);
886                 FreeStrBuf(&ErrMsg);
887         }
888
889         if (!server_shutting_down)
890         {
891         retval = PurgeEuidIndexTable();
892         syslog(LOG_NOTICE, "Purged %d entries from the EUID index.", retval);
893         }
894
895         if (!server_shutting_down)
896         {
897                 retval = PurgeStaleExtAuthAssociations();
898                 syslog(LOG_NOTICE, "Purged %d stale external auth associations.", retval);
899         }
900
901         //if (!server_shutting_down)
902         //{
903         //      FIXME this is where we could do a non-interactive delete of zero-refcount messages
904         //}
905
906         if ( (!server_shutting_down) && (CtdlGetConfigInt("c_shrink_db_files") != 0) )
907         {
908                 cdb_compact();                                  // Shrink the DB files on disk
909         }
910
911         if (!server_shutting_down)
912         {
913                 syslog(LOG_INFO, "Auto-purger: finished.");
914                 last_purge = now;                               // So we don't do it again soon
915                 force_purge_now = 0;
916         }
917         else {
918                 syslog(LOG_INFO, "Auto-purger: STOPPED.");
919         }
920 }
921
922
923 /*
924  * Manually initiate a run of The Dreaded Auto-Purger (tm)
925  */
926 void cmd_tdap(char *argbuf) {
927         if (CtdlAccessCheck(ac_aide)) return;
928         force_purge_now = 1;
929         cprintf("%d Manually initiating a purger run now.\n", CIT_OK);
930 }
931
932
933 CTDL_MODULE_INIT(expire)
934 {
935         if (!threading)
936         {
937                 CtdlRegisterProtoHook(cmd_tdap, "TDAP", "Manually initiate auto-purger");
938                 CtdlRegisterProtoHook(cmd_gpex, "GPEX", "Get expire policy");
939                 CtdlRegisterProtoHook(cmd_spex, "SPEX", "Set expire policy");
940                 CtdlRegisterSessionHook(purge_databases, EVT_TIMER, PRIO_CLEANUP + 20);
941         }
942
943         /* return our module name for the log */
944         return "expire";
945 }