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