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