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