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