Back to index

citadel  8.12
serv_expire.c
Go to the documentation of this file.
00001 /*
00002  * This module handles the expiry of old messages and the purging of old users.
00003  *
00004  * You might also see this module affectionately referred to as the DAP (the Dreaded Auto-Purger).
00005  *
00006  * Copyright (c) 1988-2011 by citadel.org (Art Cancro, Wilifried Goesgens, and others)
00007  *
00008  * This program is open source software; you can redistribute it and/or
00009  * modify it under the terms of the GNU General Public License as published
00010  * by the Free Software Foundation; either version 3 of the License, or
00011  * (at your option) any later version.
00012  *
00013  * This program is distributed in the hope that it will be useful,
00014  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00015  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00016  * GNU General Public License for more details.
00017  *
00018  * You should have received a copy of the GNU General Public License
00019  * along with this program; if not, write to the Free Software
00020  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
00021  *
00022  *
00023  * A brief technical discussion:
00024  *
00025  * Several of the purge operations found in this module operate in two
00026  * stages: the first stage generates a linked list of objects to be deleted,
00027  * then the second stage deletes all listed objects from the database.
00028  *
00029  * At first glance this may seem cumbersome and unnecessary.  The reason it is
00030  * implemented in this way is because Berkeley DB, and possibly other backends
00031  * we may hook into in the future, explicitly do _not_ support the deletion of
00032  * records from a file while the file is being traversed.  The delete operation
00033  * will succeed, but the traversal is not guaranteed to visit every object if
00034  * this is done.  Therefore we utilize the two-stage purge.
00035  *
00036  * When using Berkeley DB, there's another reason for the two-phase purge: we
00037  * don't want the entire thing being done as one huge transaction.
00038  *
00039  * You'll also notice that we build the in-memory list of records to be deleted
00040  * sometimes with a linked list and sometimes with a hash table.  There is no
00041  * reason for this aside from the fact that the linked list ones were written
00042  * before we had the hash table library available.
00043  */
00044 
00045 
00046 #include "sysdep.h"
00047 #include <stdlib.h>
00048 #include <unistd.h>
00049 #include <stdio.h>
00050 #include <fcntl.h>
00051 #include <signal.h>
00052 #include <pwd.h>
00053 #include <errno.h>
00054 #include <sys/types.h>
00055 
00056 #if TIME_WITH_SYS_TIME
00057 # include <sys/time.h>
00058 # include <time.h>
00059 #else
00060 # if HAVE_SYS_TIME_H
00061 #  include <sys/time.h>
00062 # else
00063 #  include <time.h>
00064 # endif
00065 #endif
00066 
00067 #include <sys/wait.h>
00068 #include <string.h>
00069 #include <limits.h>
00070 #include <libcitadel.h>
00071 #include "citadel.h"
00072 #include "server.h"
00073 #include "citserver.h"
00074 #include "support.h"
00075 #include "config.h"
00076 #include "policy.h"
00077 #include "database.h"
00078 #include "msgbase.h"
00079 #include "user_ops.h"
00080 #include "control.h"
00081 #include "threads.h"
00082 #include "context.h"
00083 
00084 #include "ctdl_module.h"
00085 
00086 
00087 struct PurgeList {
00088        struct PurgeList *next;
00089        char name[ROOMNAMELEN];     /* use the larger of username or roomname */
00090 };
00091 
00092 struct VPurgeList {
00093        struct VPurgeList *next;
00094        long vp_roomnum;
00095        long vp_roomgen;
00096        long vp_usernum;
00097 };
00098 
00099 struct ValidRoom {
00100        struct ValidRoom *next;
00101        long vr_roomnum;
00102        long vr_roomgen;
00103 };
00104 
00105 struct ValidUser {
00106        struct ValidUser *next;
00107        long vu_usernum;
00108 };
00109 
00110 
00111 struct ctdlroomref {
00112        struct ctdlroomref *next;
00113        long msgnum;
00114 };
00115 
00116 struct UPurgeList {
00117        struct UPurgeList *next;
00118        char up_key[256];
00119 };
00120 
00121 struct EPurgeList {
00122        struct EPurgeList *next;
00123        int ep_keylen;
00124        char *ep_key;
00125 };
00126 
00127 
00128 struct PurgeList *UserPurgeList = NULL;
00129 struct PurgeList *RoomPurgeList = NULL;
00130 struct ValidRoom *ValidRoomList = NULL;
00131 struct ValidUser *ValidUserList = NULL;
00132 int messages_purged;
00133 int users_not_purged;
00134 char *users_corrupt_msg = NULL;
00135 char *users_zero_msg = NULL;
00136 struct ctdlroomref *rr = NULL;
00137 int force_purge_now = 0;                  /* set to nonzero to force a run right now */
00138 
00139 
00140 /*
00141  * First phase of message purge -- gather the locations of messages which
00142  * qualify for purging and write them to a temp file.
00143  */
00144 void GatherPurgeMessages(struct ctdlroom *qrbuf, void *data) {
00145        struct ExpirePolicy epbuf;
00146        long delnum;
00147        time_t xtime, now;
00148        struct CtdlMessage *msg = NULL;
00149        int a;
00150        struct cdbdata *cdbfr;
00151        long *msglist = NULL;
00152        int num_msgs = 0;
00153        FILE *purgelist;
00154 
00155        purgelist = (FILE *)data;
00156        fprintf(purgelist, "r=%s\n", qrbuf->QRname);
00157 
00158        time(&now);
00159        GetExpirePolicy(&epbuf, qrbuf);
00160 
00161        /* If the room is set to never expire messages ... do nothing */
00162        if (epbuf.expire_mode == EXPIRE_NEXTLEVEL) return;
00163        if (epbuf.expire_mode == EXPIRE_MANUAL) return;
00164 
00165        /* Don't purge messages containing system configuration, dumbass. */
00166        if (!strcasecmp(qrbuf->QRname, SYSCONFIGROOM)) return;
00167 
00168        /* Ok, we got this far ... now let's see what's in the room */
00169        cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf->QRnumber, sizeof(long));
00170 
00171        if (cdbfr != NULL) {
00172               msglist = malloc(cdbfr->len);
00173               memcpy(msglist, cdbfr->ptr, cdbfr->len);
00174               num_msgs = cdbfr->len / sizeof(long);
00175               cdb_free(cdbfr);
00176        }
00177 
00178        /* Nothing to do if there aren't any messages */
00179        if (num_msgs == 0) {
00180               if (msglist != NULL) free(msglist);
00181               return;
00182        }
00183 
00184 
00185        /* If the room is set to expire by count, do that */
00186        if (epbuf.expire_mode == EXPIRE_NUMMSGS) {
00187               if (num_msgs > epbuf.expire_value) {
00188                      for (a=0; a<(num_msgs - epbuf.expire_value); ++a) {
00189                             fprintf(purgelist, "m=%ld\n", msglist[a]);
00190                             ++messages_purged;
00191                      }
00192               }
00193        }
00194 
00195        /* If the room is set to expire by age... */
00196        if (epbuf.expire_mode == EXPIRE_AGE) {
00197               for (a=0; a<num_msgs; ++a) {
00198                      delnum = msglist[a];
00199 
00200                      msg = CtdlFetchMessage(delnum, 0); /* dont need body */
00201                      if (msg != NULL) {
00202                             xtime = atol(msg->cm_fields['T']);
00203                             CtdlFreeMessage(msg);
00204                      } else {
00205                             xtime = 0L;
00206                      }
00207 
00208                      if ((xtime > 0L)
00209                         && (now - xtime > (time_t)(epbuf.expire_value * 86400L))) {
00210                             fprintf(purgelist, "m=%ld\n", delnum);
00211                             ++messages_purged;
00212                      }
00213               }
00214        }
00215 
00216        if (msglist != NULL) free(msglist);
00217 }
00218 
00219 
00220 /*
00221  * Second phase of message purge -- read list of msgs from temp file and
00222  * delete them.
00223  */
00224 void DoPurgeMessages(FILE *purgelist) {
00225        char roomname[ROOMNAMELEN];
00226        long msgnum;
00227        char buf[SIZ];
00228 
00229        rewind(purgelist);
00230        strcpy(roomname, "nonexistent room ___ ___");
00231        while (fgets(buf, sizeof buf, purgelist) != NULL) {
00232               buf[strlen(buf)-1]=0;
00233               if (!strncasecmp(buf, "r=", 2)) {
00234                      strcpy(roomname, &buf[2]);
00235               }
00236               if (!strncasecmp(buf, "m=", 2)) {
00237                      msgnum = atol(&buf[2]);
00238                      if (msgnum > 0L) {
00239                             CtdlDeleteMessages(roomname, &msgnum, 1, "");
00240                      }
00241               }
00242        }
00243 }
00244 
00245 
00246 void PurgeMessages(void) {
00247        FILE *purgelist;
00248 
00249        syslog(LOG_DEBUG, "PurgeMessages() called");
00250        messages_purged = 0;
00251 
00252        purgelist = tmpfile();
00253        if (purgelist == NULL) {
00254               syslog(LOG_CRIT, "Can't create purgelist temp file: %s", strerror(errno));
00255               return;
00256        }
00257 
00258        CtdlForEachRoom(GatherPurgeMessages, (void *)purgelist );
00259        DoPurgeMessages(purgelist);
00260        fclose(purgelist);
00261 }
00262 
00263 
00264 void AddValidUser(struct ctdluser *usbuf, void *data) {
00265        struct ValidUser *vuptr;
00266 
00267        vuptr = (struct ValidUser *)malloc(sizeof(struct ValidUser));
00268        vuptr->next = ValidUserList;
00269        vuptr->vu_usernum = usbuf->usernum;
00270        ValidUserList = vuptr;
00271 }
00272 
00273 void AddValidRoom(struct ctdlroom *qrbuf, void *data) {
00274        struct ValidRoom *vrptr;
00275 
00276        vrptr = (struct ValidRoom *)malloc(sizeof(struct ValidRoom));
00277        vrptr->next = ValidRoomList;
00278        vrptr->vr_roomnum = qrbuf->QRnumber;
00279        vrptr->vr_roomgen = qrbuf->QRgen;
00280        ValidRoomList = vrptr;
00281 }
00282 
00283 void DoPurgeRooms(struct ctdlroom *qrbuf, void *data) {
00284        time_t age, purge_secs;
00285        struct PurgeList *pptr;
00286        struct ValidUser *vuptr;
00287        int do_purge = 0;
00288 
00289        /* For mailbox rooms, there's only one purging rule: if the user who
00290         * owns the room still exists, we keep the room; otherwise, we purge
00291         * it.  Bypass any other rules.
00292         */
00293        if (qrbuf->QRflags & QR_MAILBOX) {
00294               /* if user not found, do_purge will be 1 */
00295               do_purge = 1;
00296               for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
00297                      if (vuptr->vu_usernum == atol(qrbuf->QRname)) {
00298                             do_purge = 0;
00299                      }
00300               }
00301        }
00302        else {
00303               /* Any of these attributes render a room non-purgable */
00304               if (qrbuf->QRflags & QR_PERMANENT) return;
00305               if (qrbuf->QRflags & QR_DIRECTORY) return;
00306               if (qrbuf->QRflags & QR_NETWORK) return;
00307               if (qrbuf->QRflags2 & QR2_SYSTEM) return;
00308               if (!strcasecmp(qrbuf->QRname, SYSCONFIGROOM)) return;
00309               if (CtdlIsNonEditable(qrbuf)) return;
00310 
00311               /* If we don't know the modification date, be safe and don't purge */
00312               if (qrbuf->QRmtime <= (time_t)0) return;
00313 
00314               /* If no room purge time is set, be safe and don't purge */
00315               if (config.c_roompurge < 0) return;
00316 
00317               /* Otherwise, check the date of last modification */
00318               age = time(NULL) - (qrbuf->QRmtime);
00319               purge_secs = (time_t)config.c_roompurge * (time_t)86400;
00320               if (purge_secs <= (time_t)0) return;
00321               syslog(LOG_DEBUG, "<%s> is <%ld> seconds old", qrbuf->QRname, (long)age);
00322               if (age > purge_secs) do_purge = 1;
00323        } /* !QR_MAILBOX */
00324 
00325        if (do_purge) {
00326               pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
00327               pptr->next = RoomPurgeList;
00328               strcpy(pptr->name, qrbuf->QRname);
00329               RoomPurgeList = pptr;
00330        }
00331 
00332 }
00333 
00334 
00335 
00336 int PurgeRooms(void) {
00337        struct PurgeList *pptr;
00338        int num_rooms_purged = 0;
00339        struct ctdlroom qrbuf;
00340        struct ValidUser *vuptr;
00341        char *transcript = NULL;
00342 
00343        syslog(LOG_DEBUG, "PurgeRooms() called");
00344 
00345 
00346        /* Load up a table full of valid user numbers so we can delete
00347         * user-owned rooms for users who no longer exist */
00348        ForEachUser(AddValidUser, NULL);
00349 
00350        /* Then cycle through the room file */
00351        CtdlForEachRoom(DoPurgeRooms, NULL);
00352 
00353        /* Free the valid user list */
00354        while (ValidUserList != NULL) {
00355               vuptr = ValidUserList->next;
00356               free(ValidUserList);
00357               ValidUserList = vuptr;
00358        }
00359 
00360 
00361        transcript = malloc(SIZ);
00362        strcpy(transcript, "The following rooms have been auto-purged:\n");
00363 
00364        while (RoomPurgeList != NULL) {
00365               if (CtdlGetRoom(&qrbuf, RoomPurgeList->name) == 0) {
00366                      transcript=realloc(transcript, strlen(transcript)+SIZ);
00367                      snprintf(&transcript[strlen(transcript)], SIZ, " %s\n",
00368                             qrbuf.QRname);
00369                      CtdlDeleteRoom(&qrbuf);
00370               }
00371               pptr = RoomPurgeList->next;
00372               free(RoomPurgeList);
00373               RoomPurgeList = pptr;
00374               ++num_rooms_purged;
00375        }
00376 
00377        if (num_rooms_purged > 0) CtdlAideMessage(transcript, "Room Autopurger Message");
00378        free(transcript);
00379 
00380        syslog(LOG_DEBUG, "Purged %d rooms.", num_rooms_purged);
00381        return(num_rooms_purged);
00382 }
00383 
00384 
00385 /*
00386  * Back end function to check user accounts for associated Unix accounts
00387  * which no longer exist.  (Only relevant for host auth mode.)
00388  */
00389 void do_uid_user_purge(struct ctdluser *us, void *data) {
00390        struct PurgeList *pptr;
00391 
00392        if ((us->uid != (-1)) && (us->uid != CTDLUID)) {
00393               if (getpwuid(us->uid) == NULL) {
00394                      pptr = (struct PurgeList *)
00395                             malloc(sizeof(struct PurgeList));
00396                      pptr->next = UserPurgeList;
00397                      strcpy(pptr->name, us->fullname);
00398                      UserPurgeList = pptr;
00399               }
00400        }
00401        else {
00402               ++users_not_purged;
00403        }
00404 }
00405 
00406 
00407 
00408 
00409 /*
00410  * Back end function to check user accounts for expiration.
00411  */
00412 void do_user_purge(struct ctdluser *us, void *data) {
00413        int purge;
00414        time_t now;
00415        time_t purge_time;
00416        struct PurgeList *pptr;
00417 
00418        /* Set purge time; if the user overrides the system default, use it */
00419        if (us->USuserpurge > 0) {
00420               purge_time = ((time_t)us->USuserpurge) * 86400L;
00421        }
00422        else {
00423               purge_time = ((time_t)config.c_userpurge) * 86400L;
00424        }
00425 
00426        /* The default rule is to not purge. */
00427        purge = 0;
00428        
00429        /* If the user hasn't called in two months and expiring of accounts is turned on, his/her account
00430         * has expired, so purge the record.
00431         */
00432        if (config.c_userpurge > 0)
00433        {
00434               now = time(NULL);
00435               if ((now - us->lastcall) > purge_time) purge = 1;
00436        }
00437 
00438        /* If the record is marked as permanent, don't purge it.
00439         */
00440        if (us->flags & US_PERM) purge = 0;
00441 
00442        /* If the user is an Aide, don't purge him/her/it.
00443         */
00444        if (us->axlevel == 6) purge = 0;
00445 
00446        /* If the access level is 0, the record should already have been
00447         * deleted, but maybe the user was logged in at the time or something.
00448         * Delete the record now.
00449         */
00450        if (us->axlevel == 0) purge = 1;
00451 
00452        /* If the user set his/her password to 'deleteme', he/she
00453         * wishes to be deleted, so purge the record.
00454         * Moved this lower down so that aides and permanent users get purged if they ask to be.
00455         */
00456        if (!strcasecmp(us->password, "deleteme")) purge = 1;
00457        
00458        /* 0 calls is impossible.  If there are 0 calls, it must
00459         * be a corrupted record, so purge it.
00460         * Actually it is possible if an Aide created the user so now we check for less than 0 (DRW)
00461         */
00462        if (us->timescalled < 0) purge = 1;
00463 
00464        /* any negative user number, is
00465         * also impossible.
00466         */
00467        if (us->usernum < 0L) purge = 1;
00468        
00469        /* Don't purge user 0. That user is there for the system */
00470        if (us->usernum == 0L)
00471        {
00472               /* FIXME: Temporary log message. Until we do unauth access with user 0 we should
00473                * try to get rid of all user 0 occurences. Many will be remnants from old code so
00474                * we will need to try and purge them from users data bases.Some will not have names but
00475                * those with names should be purged.
00476                */
00477               syslog(LOG_DEBUG, "Auto purger found a user 0 with name <%s>", us->fullname);
00478               // purge = 0;
00479        }
00480        
00481        /* If the user has no full name entry then we can't purge them
00482         * since the actual purge can't find them.
00483         * This shouldn't happen but does somehow.
00484         */
00485        if (IsEmptyStr(us->fullname))
00486        {
00487               purge = 0;
00488               
00489               if (us->usernum > 0L)
00490               {
00491                      purge=0;
00492                      if (users_corrupt_msg == NULL)
00493                      {
00494                             users_corrupt_msg = malloc(SIZ);
00495                             strcpy(users_corrupt_msg,
00496                                    "The auto-purger found the following user numbers with no name.\n"
00497                                    "The system has no way to purge a user with no name,"
00498                                    " and should not be able to create them either.\n"
00499                                    "This indicates corruption of the user DB or possibly a bug.\n"
00500                                    "It may be a good idea to restore your DB from a backup.\n"
00501                             );
00502                      }
00503               
00504                      users_corrupt_msg=realloc(users_corrupt_msg, strlen(users_corrupt_msg)+30);
00505                      snprintf(&users_corrupt_msg[strlen(users_corrupt_msg)], 29, " %ld\n", us->usernum);
00506               }
00507        }
00508 
00509        if (purge == 1) {
00510               pptr = (struct PurgeList *) malloc(sizeof(struct PurgeList));
00511               pptr->next = UserPurgeList;
00512               strcpy(pptr->name, us->fullname);
00513               UserPurgeList = pptr;
00514        }
00515        else {
00516               ++users_not_purged;
00517        }
00518 
00519 }
00520 
00521 
00522 
00523 int PurgeUsers(void) {
00524        struct PurgeList *pptr;
00525        int num_users_purged = 0;
00526        char *transcript = NULL;
00527 
00528        syslog(LOG_DEBUG, "PurgeUsers() called");
00529        users_not_purged = 0;
00530 
00531        switch(config.c_auth_mode) {
00532               case AUTHMODE_NATIVE:
00533                      ForEachUser(do_user_purge, NULL);
00534                      break;
00535               case AUTHMODE_HOST:
00536                      ForEachUser(do_uid_user_purge, NULL);
00537                      break;
00538               default:
00539                      syslog(LOG_DEBUG, "User purge for auth mode %d is not implemented.",
00540                             config.c_auth_mode);
00541                      break;
00542        }
00543 
00544        transcript = malloc(SIZ);
00545 
00546        if (users_not_purged == 0) {
00547               strcpy(transcript, "The auto-purger was told to purge every user.  It is\n"
00548                             "refusing to do this because it usually indicates a problem\n"
00549                             "such as an inability to communicate with a name service.\n"
00550               );
00551               while (UserPurgeList != NULL) {
00552                      pptr = UserPurgeList->next;
00553                      free(UserPurgeList);
00554                      UserPurgeList = pptr;
00555                      ++num_users_purged;
00556               }
00557        }
00558 
00559        else {
00560               strcpy(transcript, "The following users have been auto-purged:\n");
00561               while (UserPurgeList != NULL) {
00562                      transcript=realloc(transcript, strlen(transcript)+SIZ);
00563                      snprintf(&transcript[strlen(transcript)], SIZ, " %s\n",
00564                             UserPurgeList->name);
00565                      purge_user(UserPurgeList->name);
00566                      pptr = UserPurgeList->next;
00567                      free(UserPurgeList);
00568                      UserPurgeList = pptr;
00569                      ++num_users_purged;
00570               }
00571        }
00572 
00573        if (num_users_purged > 0) CtdlAideMessage(transcript, "User Purge Message");
00574        free(transcript);
00575 
00576        if(users_corrupt_msg)
00577        {
00578               CtdlAideMessage(users_corrupt_msg, "User Corruption Message");
00579               free (users_corrupt_msg);
00580               users_corrupt_msg = NULL;
00581        }
00582        
00583        if(users_zero_msg)
00584        {
00585               CtdlAideMessage(users_zero_msg, "User Zero Message");
00586               free (users_zero_msg);
00587               users_zero_msg = NULL;
00588        }
00589               
00590        syslog(LOG_DEBUG, "Purged %d users.", num_users_purged);
00591        return(num_users_purged);
00592 }
00593 
00594 
00595 /*
00596  * Purge visits
00597  *
00598  * This is a really cumbersome "garbage collection" function.  We have to
00599  * delete visits which refer to rooms and/or users which no longer exist.  In
00600  * order to prevent endless traversals of the room and user files, we first
00601  * build linked lists of rooms and users which _do_ exist on the system, then
00602  * traverse the visit file, checking each record against those two lists and
00603  * purging the ones that do not have a match on _both_ lists.  (Remember, if
00604  * either the room or user being referred to is no longer on the system, the
00605  * record is completely useless.)
00606  */
00607 int PurgeVisits(void) {
00608        struct cdbdata *cdbvisit;
00609        visit vbuf;
00610        struct VPurgeList *VisitPurgeList = NULL;
00611        struct VPurgeList *vptr;
00612        int purged = 0;
00613        char IndexBuf[32];
00614        int IndexLen;
00615        struct ValidRoom *vrptr;
00616        struct ValidUser *vuptr;
00617        int RoomIsValid, UserIsValid;
00618 
00619        /* First, load up a table full of valid room/gen combinations */
00620        CtdlForEachRoom(AddValidRoom, NULL);
00621 
00622        /* Then load up a table full of valid user numbers */
00623        ForEachUser(AddValidUser, NULL);
00624 
00625        /* Now traverse through the visits, purging irrelevant records... */
00626        cdb_rewind(CDB_VISIT);
00627        while(cdbvisit = cdb_next_item(CDB_VISIT), cdbvisit != NULL) {
00628               memset(&vbuf, 0, sizeof(visit));
00629               memcpy(&vbuf, cdbvisit->ptr,
00630                      ( (cdbvisit->len > sizeof(visit)) ?
00631                        sizeof(visit) : cdbvisit->len) );
00632               cdb_free(cdbvisit);
00633 
00634               RoomIsValid = 0;
00635               UserIsValid = 0;
00636 
00637               /* Check to see if the room exists */
00638               for (vrptr=ValidRoomList; vrptr!=NULL; vrptr=vrptr->next) {
00639                      if ( (vrptr->vr_roomnum==vbuf.v_roomnum)
00640                           && (vrptr->vr_roomgen==vbuf.v_roomgen))
00641                             RoomIsValid = 1;
00642               }
00643 
00644               /* Check to see if the user exists */
00645               for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
00646                      if (vuptr->vu_usernum == vbuf.v_usernum)
00647                             UserIsValid = 1;
00648               }
00649 
00650               /* Put the record on the purge list if it's dead */
00651               if ((RoomIsValid==0) || (UserIsValid==0)) {
00652                      vptr = (struct VPurgeList *)
00653                             malloc(sizeof(struct VPurgeList));
00654                      vptr->next = VisitPurgeList;
00655                      vptr->vp_roomnum = vbuf.v_roomnum;
00656                      vptr->vp_roomgen = vbuf.v_roomgen;
00657                      vptr->vp_usernum = vbuf.v_usernum;
00658                      VisitPurgeList = vptr;
00659               }
00660 
00661        }
00662 
00663        /* Free the valid room/gen combination list */
00664        while (ValidRoomList != NULL) {
00665               vrptr = ValidRoomList->next;
00666               free(ValidRoomList);
00667               ValidRoomList = vrptr;
00668        }
00669 
00670        /* Free the valid user list */
00671        while (ValidUserList != NULL) {
00672               vuptr = ValidUserList->next;
00673               free(ValidUserList);
00674               ValidUserList = vuptr;
00675        }
00676 
00677        /* Now delete every visit on the purged list */
00678        while (VisitPurgeList != NULL) {
00679               IndexLen = GenerateRelationshipIndex(IndexBuf,
00680                             VisitPurgeList->vp_roomnum,
00681                             VisitPurgeList->vp_roomgen,
00682                             VisitPurgeList->vp_usernum);
00683               cdb_delete(CDB_VISIT, IndexBuf, IndexLen);
00684               vptr = VisitPurgeList->next;
00685               free(VisitPurgeList);
00686               VisitPurgeList = vptr;
00687               ++purged;
00688        }
00689 
00690        return(purged);
00691 }
00692 
00693 /*
00694  * Purge the use table of old entries.
00695  *
00696  */
00697 int PurgeUseTable(void) {
00698        int purged = 0;
00699        struct cdbdata *cdbut;
00700        struct UseTable ut;
00701        struct UPurgeList *ul = NULL;
00702        struct UPurgeList *uptr; 
00703 
00704        /* Phase 1: traverse through the table, discovering old records... */
00705        syslog(LOG_DEBUG, "Purge use table: phase 1");
00706        cdb_rewind(CDB_USETABLE);
00707        while(cdbut = cdb_next_item(CDB_USETABLE), cdbut != NULL) {
00708 
00709               /*
00710                * TODODRW: change this to create a new function time_t cdb_get_timestamp( struct cdbdata *)
00711                * this will release this file from the serv_network.h
00712                * Maybe it could be a macro that extracts and casts the reult
00713                */
00714               if (cdbut->len > sizeof(struct UseTable))
00715                      memcpy(&ut, cdbut->ptr, sizeof(struct UseTable));
00716               else {
00717                      memset(&ut, 0, sizeof(struct UseTable));
00718                      memcpy(&ut, cdbut->ptr, cdbut->len);
00719               }
00720               cdb_free(cdbut);
00721 
00722               if ( (time(NULL) - ut.ut_timestamp) > USETABLE_RETAIN ) {
00723                      uptr = (struct UPurgeList *) malloc(sizeof(struct UPurgeList));
00724                      if (uptr != NULL) {
00725                             uptr->next = ul;
00726                             safestrncpy(uptr->up_key, ut.ut_msgid, sizeof uptr->up_key);
00727                             ul = uptr;
00728                      }
00729                      ++purged;
00730               }
00731 
00732        }
00733 
00734        /* Phase 2: delete the records */
00735        syslog(LOG_DEBUG, "Purge use table: phase 2");
00736        while (ul != NULL) {
00737               cdb_delete(CDB_USETABLE, ul->up_key, strlen(ul->up_key));
00738               uptr = ul->next;
00739               free(ul);
00740               ul = uptr;
00741        }
00742 
00743        syslog(LOG_DEBUG, "Purge use table: finished (purged %d records)", purged);
00744        return(purged);
00745 }
00746 
00747 
00748 
00749 /*
00750  * Purge the EUID Index of old records.
00751  *
00752  */
00753 int PurgeEuidIndexTable(void) {
00754        int purged = 0;
00755        struct cdbdata *cdbei;
00756        struct EPurgeList *el = NULL;
00757        struct EPurgeList *eptr; 
00758        long msgnum;
00759        struct CtdlMessage *msg = NULL;
00760 
00761        /* Phase 1: traverse through the table, discovering old records... */
00762        syslog(LOG_DEBUG, "Purge EUID index: phase 1");
00763        cdb_rewind(CDB_EUIDINDEX);
00764        while(cdbei = cdb_next_item(CDB_EUIDINDEX), cdbei != NULL) {
00765 
00766               memcpy(&msgnum, cdbei->ptr, sizeof(long));
00767 
00768               msg = CtdlFetchMessage(msgnum, 0);
00769               if (msg != NULL) {
00770                      CtdlFreeMessage(msg);       /* it still exists, so do nothing */
00771               }
00772               else {
00773                      eptr = (struct EPurgeList *) malloc(sizeof(struct EPurgeList));
00774                      if (eptr != NULL) {
00775                             eptr->next = el;
00776                             eptr->ep_keylen = cdbei->len - sizeof(long);
00777                             eptr->ep_key = malloc(cdbei->len);
00778                             memcpy(eptr->ep_key, &cdbei->ptr[sizeof(long)], eptr->ep_keylen);
00779                             el = eptr;
00780                      }
00781                      ++purged;
00782               }
00783 
00784               cdb_free(cdbei);
00785 
00786        }
00787 
00788        /* Phase 2: delete the records */
00789        syslog(LOG_DEBUG, "Purge euid index: phase 2");
00790        while (el != NULL) {
00791               cdb_delete(CDB_EUIDINDEX, el->ep_key, el->ep_keylen);
00792               free(el->ep_key);
00793               eptr = el->next;
00794               free(el);
00795               el = eptr;
00796        }
00797 
00798        syslog(LOG_DEBUG, "Purge euid index: finished (purged %d records)", purged);
00799        return(purged);
00800 }
00801 
00802 
00803 
00804 /*
00805  * Purge OpenID assocations for missing users (theoretically this will never delete anything)
00806  */
00807 int PurgeStaleOpenIDassociations(void) {
00808        struct cdbdata *cdboi;
00809        struct ctdluser usbuf;
00810        HashList *keys = NULL;
00811        HashPos *HashPos;
00812        char *deleteme = NULL;
00813        long len;
00814        void *Value;
00815        const char *Key;
00816        int num_deleted = 0;
00817        long usernum = 0L;
00818 
00819        keys = NewHash(1, NULL);
00820        if (!keys) return(0);
00821 
00822 
00823        cdb_rewind(CDB_OPENID);
00824        while (cdboi = cdb_next_item(CDB_OPENID), cdboi != NULL) {
00825               if (cdboi->len > sizeof(long)) {
00826                      memcpy(&usernum, cdboi->ptr, sizeof(long));
00827                      if (CtdlGetUserByNumber(&usbuf, usernum) != 0) {
00828                             deleteme = strdup(cdboi->ptr + sizeof(long)),
00829                             Put(keys, deleteme, strlen(deleteme), deleteme, NULL);
00830                      }
00831               }
00832               cdb_free(cdboi);
00833        }
00834 
00835        /* Go through the hash list, deleting keys we stored in it */
00836 
00837        HashPos = GetNewHashPos(keys, 0);
00838        while (GetNextHashPos(keys, HashPos, &len, &Key, &Value)!=0)
00839        {
00840               syslog(LOG_DEBUG, "Deleting associated OpenID <%s>",  (char*)Value);
00841               cdb_delete(CDB_OPENID, Value, strlen(Value));
00842               /* note: don't free(Value) -- deleting the hash list will handle this for us */
00843               ++num_deleted;
00844        }
00845        DeleteHashPos(&HashPos);
00846        DeleteHash(&keys);
00847        return num_deleted;
00848 }
00849 
00850 
00851 
00852 
00853 
00854 void purge_databases(void)
00855 {
00856        int retval;
00857        static time_t last_purge = 0;
00858        time_t now;
00859        struct tm tm;
00860 
00861        /* Do the auto-purge if the current hour equals the purge hour,
00862         * but not if the operation has already been performed in the
00863         * last twelve hours.  This is usually enough granularity.
00864         */
00865        now = time(NULL);
00866        localtime_r(&now, &tm);
00867        if (
00868               ((tm.tm_hour != config.c_purge_hour) || ((now - last_purge) < 43200))
00869               && (force_purge_now == 0)
00870        ) {
00871                      return;
00872        }
00873 
00874        syslog(LOG_INFO, "Auto-purger: starting.");
00875 
00876        if (!server_shutting_down)
00877        {
00878               retval = PurgeUsers();
00879               syslog(LOG_NOTICE, "Purged %d users.", retval);
00880        }
00881               
00882        if (!server_shutting_down)
00883        {
00884               PurgeMessages();
00885                      syslog(LOG_NOTICE, "Expired %d messages.", messages_purged);
00886        }
00887 
00888        if (!server_shutting_down)
00889        {
00890                      retval = PurgeRooms();
00891                      syslog(LOG_NOTICE, "Expired %d rooms.", retval);
00892        }
00893 
00894        if (!server_shutting_down)
00895        {
00896                      retval = PurgeVisits();
00897                      syslog(LOG_NOTICE, "Purged %d visits.", retval);
00898        }
00899 
00900        if (!server_shutting_down)
00901        {
00902               retval = PurgeUseTable();
00903                      syslog(LOG_NOTICE, "Purged %d entries from the use table.", retval);
00904        }
00905 
00906        if (!server_shutting_down)
00907        {
00908               retval = PurgeEuidIndexTable();
00909               syslog(LOG_NOTICE, "Purged %d entries from the EUID index.", retval);
00910        }
00911 
00912        if (!server_shutting_down)
00913        {
00914               retval = PurgeStaleOpenIDassociations();
00915                      syslog(LOG_NOTICE, "Purged %d stale OpenID associations.", retval);
00916        }
00917 
00918        if (!server_shutting_down)
00919        {
00920                      retval = TDAP_ProcessAdjRefCountQueue();
00921                      syslog(LOG_NOTICE, "Processed %d message reference count adjustments.", retval);
00922        }
00923 
00924        if (!server_shutting_down)
00925        {
00926                      syslog(LOG_INFO, "Auto-purger: finished.");
00927               last_purge = now;    /* So we don't do it again soon */
00928               force_purge_now = 0;
00929        }
00930        else {
00931                      syslog(LOG_INFO, "Auto-purger: STOPPED.");
00932        }
00933 }
00934 
00935 
00936 /*
00937  * Manually initiate a run of The Dreaded Auto-Purger (tm)
00938  */
00939 void cmd_tdap(char *argbuf) {
00940        if (CtdlAccessCheck(ac_aide)) return;
00941        force_purge_now = 1;
00942        cprintf("%d Manually initiating a purger run now.\n", CIT_OK);
00943 }
00944 
00945 
00946 
00947 CTDL_MODULE_INIT(expire)
00948 {
00949        if (!threading)
00950        {
00951               CtdlRegisterProtoHook(cmd_tdap, "TDAP", "Manually initiate auto-purger");
00952               CtdlRegisterProtoHook(cmd_gpex, "GPEX", "Get expire policy");
00953               CtdlRegisterProtoHook(cmd_spex, "SPEX", "Set expire policy");
00954               CtdlRegisterSessionHook(purge_databases, EVT_TIMER, PRIO_CLEANUP + 20);
00955        }
00956 
00957        /* return our module name for the log */
00958        return "expire";
00959 }