]> code.citadel.org Git - citadel.git/blob - citadel/serv_expire.c
* Wrote the expire/purge routine for the new use table
[citadel.git] / citadel / serv_expire.c
1 /*
2  * $Id$
3  *
4  * This module handles the expiry of old messages and the purging of old users.
5  *
6  */
7
8
9 /*
10  * A brief technical discussion:
11  *
12  * Several of the purge operations found in this module operate in two
13  * stages: the first stage generates a linked list of objects to be deleted,
14  * then the second stage deletes all listed objects from the database.
15  *
16  * At first glance this may seem cumbersome and unnecessary.  The reason it is
17  * implemented in this way is because GDBM (and perhaps some other backends we
18  * may hook into in the future) explicitly do _not_ support the deletion of
19  * records from a file while the file is being traversed.  The delete operation
20  * will succeed, but the traversal is not guaranteed to visit every object if
21  * this is done.  Therefore we utilize the two-stage purge.
22  *
23  * When using Berkeley DB, there's another reason for the two-phase purge: we
24  * don't want the entire thing being done as one huge transaction.
25  */
26
27
28 #include "sysdep.h"
29 #include <stdlib.h>
30 #include <unistd.h>
31 #include <stdio.h>
32 #include <fcntl.h>
33 #include <signal.h>
34 #include <pwd.h>
35 #include <errno.h>
36 #include <sys/types.h>
37
38 #if TIME_WITH_SYS_TIME
39 # include <sys/time.h>
40 # include <time.h>
41 #else
42 # if HAVE_SYS_TIME_H
43 #  include <sys/time.h>
44 # else
45 #  include <time.h>
46 # endif
47 #endif
48
49 #include <sys/wait.h>
50 #include <string.h>
51 #include <limits.h>
52 #include "citadel.h"
53 #include "server.h"
54 #include <syslog.h>
55 #include "sysdep_decls.h"
56 #include "citserver.h"
57 #include "support.h"
58 #include "config.h"
59 #include "dynloader.h"
60 #include "room_ops.h"
61 #include "policy.h"
62 #include "database.h"
63 #include "msgbase.h"
64 #include "user_ops.h"
65 #include "control.h"
66 #include "serv_network.h"
67 #include "tools.h"
68
69
70 struct PurgeList {
71         struct PurgeList *next;
72         char name[ROOMNAMELEN]; /* use the larger of username or roomname */
73 };
74
75 struct VPurgeList {
76         struct VPurgeList *next;
77         long vp_roomnum;
78         long vp_roomgen;
79         long vp_usernum;
80 };
81
82 struct ValidRoom {
83         struct ValidRoom *next;
84         long vr_roomnum;
85         long vr_roomgen;
86 };
87
88 struct ValidUser {
89         struct ValidUser *next;
90         long vu_usernum;
91 };
92
93
94 struct roomref {
95         struct roomref *next;
96         long msgnum;
97 };
98
99
100 struct PurgeList *UserPurgeList = NULL;
101 struct PurgeList *RoomPurgeList = NULL;
102 struct ValidRoom *ValidRoomList = NULL;
103 struct ValidUser *ValidUserList = NULL;
104 int messages_purged;
105
106 struct roomref *rr = NULL;
107
108 extern struct CitContext *ContextList;
109
110
111 /*
112  * First phase of message purge -- gather the locations of messages which
113  * qualify for purging and write them to a temp file.
114  */
115 void GatherPurgeMessages(struct quickroom *qrbuf, void *data) {
116         struct ExpirePolicy epbuf;
117         long delnum;
118         time_t xtime, now;
119         struct CtdlMessage *msg;
120         int a;
121         struct cdbdata *cdbfr;
122         long *msglist = NULL;
123         int num_msgs = 0;
124         FILE *purgelist;
125
126         purgelist = (FILE *)data;
127         fprintf(purgelist, "r=%s\n", qrbuf->QRname);
128
129         time(&now);
130         GetExpirePolicy(&epbuf, qrbuf);
131
132         /* If the room is set to never expire messages ... do nothing */
133         if (epbuf.expire_mode == EXPIRE_NEXTLEVEL) return;
134         if (epbuf.expire_mode == EXPIRE_MANUAL) return;
135
136         cdbfr = cdb_fetch(CDB_MSGLISTS, &qrbuf->QRnumber, sizeof(long));
137
138         if (cdbfr != NULL) {
139                 msglist = mallok(cdbfr->len);
140                 memcpy(msglist, cdbfr->ptr, cdbfr->len);
141                 num_msgs = cdbfr->len / sizeof(long);
142                 cdb_free(cdbfr);
143         }
144
145         /* Nothing to do if there aren't any messages */
146         if (num_msgs == 0) {
147                 if (msglist != NULL) phree(msglist);
148                 return;
149         }
150
151         /* If the room is set to expire by count, do that */
152         if (epbuf.expire_mode == EXPIRE_NUMMSGS) {
153                 if (num_msgs > epbuf.expire_value) {
154                         for (a=0; a<(num_msgs - epbuf.expire_value); ++a) {
155                                 fprintf(purgelist, "m=%ld\n", msglist[a]);
156                                 ++messages_purged;
157                         }
158                 }
159         }
160
161         /* If the room is set to expire by age... */
162         if (epbuf.expire_mode == EXPIRE_AGE) {
163                 for (a=0; a<num_msgs; ++a) {
164                         delnum = msglist[a];
165
166                         msg = CtdlFetchMessage(delnum);
167                         if (msg != NULL) {
168                                 xtime = atol(msg->cm_fields['T']);
169                                 CtdlFreeMessage(msg);
170                         } else {
171                                 xtime = 0L;
172                         }
173
174                         if ((xtime > 0L)
175                            && (now - xtime > (time_t)(epbuf.expire_value * 86400L))) {
176                                 fprintf(purgelist, "m=%ld\n", delnum);
177                                 ++messages_purged;
178                         }
179                 }
180         }
181
182         if (msglist != NULL) phree(msglist);
183 }
184
185
186 /*
187  * Second phase of message purge -- read list of msgs from temp file and
188  * delete them.
189  */
190 void DoPurgeMessages(FILE *purgelist) {
191         char roomname[ROOMNAMELEN];
192         long msgnum;
193         char buf[SIZ];
194
195         rewind(purgelist);
196         strcpy(roomname, "nonexistent room ___ ___");
197         while (fgets(buf, sizeof buf, purgelist) != NULL) {
198                 buf[strlen(buf)-1]=0;
199                 if (!strncasecmp(buf, "r=", 2)) {
200                         strcpy(roomname, &buf[2]);
201                 }
202                 if (!strncasecmp(buf, "m=", 2)) {
203                         msgnum = atol(&buf[2]);
204                         if (msgnum > 0L) {
205                                 CtdlDeleteMessages(roomname, msgnum, "");
206                         }
207                 }
208         }
209 }
210
211
212 void PurgeMessages(void) {
213         FILE *purgelist;
214
215         lprintf(5, "PurgeMessages() called\n");
216         messages_purged = 0;
217
218         purgelist = tmpfile();
219         if (purgelist == NULL) {
220                 lprintf(3, "Can't create purgelist temp file: %s\n",
221                         strerror(errno));
222                 return;
223         }
224
225         ForEachRoom(GatherPurgeMessages, (void *)purgelist );
226         DoPurgeMessages(purgelist);
227         fclose(purgelist);
228 }
229
230
231 void AddValidUser(struct usersupp *usbuf, void *data) {
232         struct ValidUser *vuptr;
233
234         vuptr = (struct ValidUser *)mallok(sizeof(struct ValidUser));
235         vuptr->next = ValidUserList;
236         vuptr->vu_usernum = usbuf->usernum;
237         ValidUserList = vuptr;
238 }
239
240 void AddValidRoom(struct quickroom *qrbuf, void *data) {
241         struct ValidRoom *vrptr;
242
243         vrptr = (struct ValidRoom *)mallok(sizeof(struct ValidRoom));
244         vrptr->next = ValidRoomList;
245         vrptr->vr_roomnum = qrbuf->QRnumber;
246         vrptr->vr_roomgen = qrbuf->QRgen;
247         ValidRoomList = vrptr;
248 }
249
250 void DoPurgeRooms(struct quickroom *qrbuf, void *data) {
251         time_t age, purge_secs;
252         struct PurgeList *pptr;
253         struct ValidUser *vuptr;
254         int do_purge = 0;
255
256         /* For mailbox rooms, there's only one purging rule: if the user who
257          * owns the room still exists, we keep the room; otherwise, we purge
258          * it.  Bypass any other rules.
259          */
260         if (qrbuf->QRflags & QR_MAILBOX) {
261                 /* if user not found, do_purge will be 1 */
262                 do_purge = 1;
263                 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
264                         if (vuptr->vu_usernum == atol(qrbuf->QRname)) {
265                                 do_purge = 0;
266                         }
267                 }
268         }
269         else {
270                 /* Any of these attributes render a room non-purgable */
271                 if (qrbuf->QRflags & QR_PERMANENT) return;
272                 if (qrbuf->QRflags & QR_DIRECTORY) return;
273                 if (qrbuf->QRflags & QR_NETWORK) return;
274                 if (!strcasecmp(qrbuf->QRname, SYSCONFIGROOM)) return;
275                 if (is_noneditable(qrbuf)) return;
276
277                 /* If we don't know the modification date, be safe and don't purge */
278                 if (qrbuf->QRmtime <= (time_t)0) return;
279
280                 /* If no room purge time is set, be safe and don't purge */
281                 if (config.c_roompurge < 0) return;
282
283                 /* Otherwise, check the date of last modification */
284                 age = time(NULL) - (qrbuf->QRmtime);
285                 purge_secs = (time_t)config.c_roompurge * (time_t)86400;
286                 if (purge_secs <= (time_t)0) return;
287                 lprintf(9, "<%s> is <%ld> seconds old\n", qrbuf->QRname, (long)age);
288                 if (age > purge_secs) do_purge = 1;
289         } /* !QR_MAILBOX */
290
291         if (do_purge) {
292                 pptr = (struct PurgeList *) mallok(sizeof(struct PurgeList));
293                 pptr->next = RoomPurgeList;
294                 strcpy(pptr->name, qrbuf->QRname);
295                 RoomPurgeList = pptr;
296         }
297
298 }
299
300
301
302 int PurgeRooms(void) {
303         struct PurgeList *pptr;
304         int num_rooms_purged = 0;
305         struct quickroom qrbuf;
306         struct ValidUser *vuptr;
307         char *transcript = NULL;
308
309         lprintf(5, "PurgeRooms() called\n");
310
311
312         /* Load up a table full of valid user numbers so we can delete
313          * user-owned rooms for users who no longer exist */
314         ForEachUser(AddValidUser, NULL);
315
316         /* Then cycle through the room file */
317         ForEachRoom(DoPurgeRooms, NULL);
318
319         /* Free the valid user list */
320         while (ValidUserList != NULL) {
321                 vuptr = ValidUserList->next;
322                 phree(ValidUserList);
323                 ValidUserList = vuptr;
324         }
325
326
327         transcript = mallok(SIZ);
328         strcpy(transcript, "The following rooms have been auto-purged:\n");
329
330         while (RoomPurgeList != NULL) {
331                 if (getroom(&qrbuf, RoomPurgeList->name) == 0) {
332                         transcript=reallok(transcript, strlen(transcript)+SIZ);
333                         sprintf(&transcript[strlen(transcript)], " %s\n",
334                                 qrbuf.QRname);
335                         delete_room(&qrbuf);
336                 }
337                 pptr = RoomPurgeList->next;
338                 phree(RoomPurgeList);
339                 RoomPurgeList = pptr;
340                 ++num_rooms_purged;
341         }
342
343         if (num_rooms_purged > 0) aide_message(transcript);
344         phree(transcript);
345
346         lprintf(5, "Purged %d rooms.\n", num_rooms_purged);
347         return(num_rooms_purged);
348 }
349
350
351 void do_user_purge(struct usersupp *us, void *data) {
352         int purge;
353         time_t now;
354         time_t purge_time;
355         struct PurgeList *pptr;
356
357         /* stupid recovery routine to re-create missing mailboxen.
358          * don't enable this.
359         struct quickroom qrbuf;
360         char mailboxname[ROOMNAMELEN];
361         MailboxName(mailboxname, us, MAILROOM);
362         create_room(mailboxname, 4, "", 0, 1);
363         if (getroom(&qrbuf, mailboxname) != 0) return;
364         lprintf(9, "Got %s\n", qrbuf.QRname);
365          */
366
367
368         /* Set purge time; if the user overrides the system default, use it */
369         if (us->USuserpurge > 0) {
370                 purge_time = ((time_t)us->USuserpurge) * 86400L;
371         }
372         else {
373                 purge_time = ((time_t)config.c_userpurge) * 86400L;
374         }
375
376         /* The default rule is to not purge. */
377         purge = 0;
378
379         /* If the user hasn't called in two months, his/her account
380          * has expired, so purge the record.
381          */
382         now = time(NULL);
383         if ((now - us->lastcall) > purge_time) purge = 1;
384
385         /* If the user set his/her password to 'deleteme', he/she
386          * wishes to be deleted, so purge the record.
387          */
388         if (!strcasecmp(us->password, "deleteme")) purge = 1;
389
390         /* If the record is marked as permanent, don't purge it.
391          */
392         if (us->flags & US_PERM) purge = 0;
393
394         /* If the access level is 0, the record should already have been
395          * deleted, but maybe the user was logged in at the time or something.
396          * Delete the record now.
397          */
398         if (us->axlevel == 0) purge = 1;
399
400         /* 0 calls is impossible.  If there are 0 calls, it must
401          * be a corrupted record, so purge it.
402          */
403         if (us->timescalled == 0) purge = 1;
404
405         if (purge == 1) {
406                 pptr = (struct PurgeList *) mallok(sizeof(struct PurgeList));
407                 pptr->next = UserPurgeList;
408                 strcpy(pptr->name, us->fullname);
409                 UserPurgeList = pptr;
410         }
411
412 }
413
414
415
416 int PurgeUsers(void) {
417         struct PurgeList *pptr;
418         int num_users_purged = 0;
419         char *transcript = NULL;
420
421         lprintf(5, "PurgeUsers() called\n");
422         if (config.c_userpurge > 0) {
423                 ForEachUser(do_user_purge, NULL);
424         }
425
426         transcript = mallok(SIZ);
427         strcpy(transcript, "The following users have been auto-purged:\n");
428
429         while (UserPurgeList != NULL) {
430                 transcript=reallok(transcript, strlen(transcript)+SIZ);
431                 sprintf(&transcript[strlen(transcript)], " %s\n",
432                         UserPurgeList->name);
433                 purge_user(UserPurgeList->name);
434                 pptr = UserPurgeList->next;
435                 phree(UserPurgeList);
436                 UserPurgeList = pptr;
437                 ++num_users_purged;
438         }
439
440         if (num_users_purged > 0) aide_message(transcript);
441         phree(transcript);
442
443         lprintf(5, "Purged %d users.\n", num_users_purged);
444         return(num_users_purged);
445 }
446
447
448 /*
449  * Purge visits
450  *
451  * This is a really cumbersome "garbage collection" function.  We have to
452  * delete visits which refer to rooms and/or users which no longer exist.  In
453  * order to prevent endless traversals of the room and user files, we first
454  * build linked lists of rooms and users which _do_ exist on the system, then
455  * traverse the visit file, checking each record against those two lists and
456  * purging the ones that do not have a match on _both_ lists.  (Remember, if
457  * either the room or user being referred to is no longer on the system, the
458  * record is completely useless.)
459  */
460 int PurgeVisits(void) {
461         struct cdbdata *cdbvisit;
462         struct visit vbuf;
463         struct VPurgeList *VisitPurgeList = NULL;
464         struct VPurgeList *vptr;
465         int purged = 0;
466         char IndexBuf[32];
467         int IndexLen;
468         struct ValidRoom *vrptr;
469         struct ValidUser *vuptr;
470         int RoomIsValid, UserIsValid;
471
472         /* First, load up a table full of valid room/gen combinations */
473         ForEachRoom(AddValidRoom, NULL);
474
475         /* Then load up a table full of valid user numbers */
476         ForEachUser(AddValidUser, NULL);
477
478         /* Now traverse through the visits, purging irrelevant records... */
479         cdb_rewind(CDB_VISIT);
480         while(cdbvisit = cdb_next_item(CDB_VISIT), cdbvisit != NULL) {
481                 memset(&vbuf, 0, sizeof(struct visit));
482                 memcpy(&vbuf, cdbvisit->ptr,
483                         ( (cdbvisit->len > sizeof(struct visit)) ?
484                         sizeof(struct visit) : cdbvisit->len) );
485                 cdb_free(cdbvisit);
486
487                 RoomIsValid = 0;
488                 UserIsValid = 0;
489
490                 /* Check to see if the room exists */
491                 for (vrptr=ValidRoomList; vrptr!=NULL; vrptr=vrptr->next) {
492                         if ( (vrptr->vr_roomnum==vbuf.v_roomnum)
493                              && (vrptr->vr_roomgen==vbuf.v_roomgen))
494                                 RoomIsValid = 1;
495                 }
496
497                 /* Check to see if the user exists */
498                 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
499                         if (vuptr->vu_usernum == vbuf.v_usernum)
500                                 UserIsValid = 1;
501                 }
502
503                 /* Put the record on the purge list if it's dead */
504                 if ((RoomIsValid==0) || (UserIsValid==0)) {
505                         vptr = (struct VPurgeList *)
506                                 mallok(sizeof(struct VPurgeList));
507                         vptr->next = VisitPurgeList;
508                         vptr->vp_roomnum = vbuf.v_roomnum;
509                         vptr->vp_roomgen = vbuf.v_roomgen;
510                         vptr->vp_usernum = vbuf.v_usernum;
511                         VisitPurgeList = vptr;
512                 }
513
514         }
515
516         /* Free the valid room/gen combination list */
517         while (ValidRoomList != NULL) {
518                 vrptr = ValidRoomList->next;
519                 phree(ValidRoomList);
520                 ValidRoomList = vrptr;
521         }
522
523         /* Free the valid user list */
524         while (ValidUserList != NULL) {
525                 vuptr = ValidUserList->next;
526                 phree(ValidUserList);
527                 ValidUserList = vuptr;
528         }
529
530         /* Now delete every visit on the purged list */
531         while (VisitPurgeList != NULL) {
532                 IndexLen = GenerateRelationshipIndex(IndexBuf,
533                                 VisitPurgeList->vp_roomnum,
534                                 VisitPurgeList->vp_roomgen,
535                                 VisitPurgeList->vp_usernum);
536                 cdb_delete(CDB_VISIT, IndexBuf, IndexLen);
537                 vptr = VisitPurgeList->next;
538                 phree(VisitPurgeList);
539                 VisitPurgeList = vptr;
540                 ++purged;
541         }
542
543         return(purged);
544 }
545
546 /*
547  * Purge the use table of old entries.
548  *
549  */
550 int PurgeUseTable(void) {
551         int purged = 0;
552         struct cdbdata *cdbut;
553         struct UseTable ut;
554
555         /* Traverse through the table, purging old records... */
556         cdb_rewind(CDB_USETABLE);
557         while(cdbut = cdb_next_item(CDB_USETABLE), cdbut != NULL) {
558
559                 memcpy(&ut, cdbut->ptr,
560                        ((cdbut->len > sizeof(struct UseTable)) ?
561                         sizeof(struct UseTable) : cdbut->len));
562                 cdb_free(cdbut);
563
564                 if ( (time(NULL) - ut.ut_timestamp) > USETABLE_RETAIN ) {
565                         cdb_delete(CDB_USETABLE, ut.ut_msgid,
566                                                 strlen(ut.ut_msgid) );
567                         ++purged;
568                 }
569
570         }
571
572         return(purged);
573 }
574
575
576 void cmd_expi(char *argbuf) {
577         char cmd[SIZ];
578         int retval;
579
580         if (CtdlAccessCheck(ac_aide)) return;
581
582         extract(cmd, argbuf, 0);
583         if (!strcasecmp(cmd, "users")) {
584                 retval = PurgeUsers();
585                 cprintf("%d Purged %d users.\n", OK, retval);
586                 return;
587         }
588         else if (!strcasecmp(cmd, "messages")) {
589                 PurgeMessages();
590                 cprintf("%d Expired %d messages.\n", OK, messages_purged);
591                 return;
592         }
593         else if (!strcasecmp(cmd, "rooms")) {
594                 retval = PurgeRooms();
595                 cprintf("%d Expired %d rooms.\n", OK, retval);
596                 return;
597         }
598         else if (!strcasecmp(cmd, "visits")) {
599                 retval = PurgeVisits();
600                 cprintf("%d Purged %d visits.\n", OK, retval);
601         }
602         else if (!strcasecmp(cmd, "usetable")) {
603                 retval = PurgeUseTable();
604                 cprintf("%d Purged %d entries from the use table.\n",
605                         OK, retval);
606         }
607         else if (!strcasecmp(cmd, "defrag")) {
608                 defrag_databases();
609                 cprintf("%d Defragmented the databases.\n", OK);
610         }
611         else {
612                 cprintf("%d Invalid command.\n", ERROR+ILLEGAL_VALUE);
613                 return;
614         }
615 }
616
617 /*****************************************************************************/
618
619
620 void do_fsck_msg(long msgnum, void *userdata) {
621         struct roomref *ptr;
622
623         ptr = (struct roomref *)mallok(sizeof(struct roomref));
624         ptr->next = rr;
625         ptr->msgnum = msgnum;
626         rr = ptr;
627 }
628
629 void do_fsck_room(struct quickroom *qrbuf, void *data)
630 {
631         getroom(&CC->quickroom, qrbuf->QRname);
632         CtdlForEachMessage(MSGS_ALL, 0L, (-127), NULL, NULL,
633                 do_fsck_msg, NULL);
634 }
635
636 /*
637  * Check message reference counts
638  */
639 void cmd_fsck(char *argbuf) {
640         long msgnum;
641         struct cdbdata *cdbmsg;
642         struct MetaData smi;
643         struct roomref *ptr;
644         int realcount;
645
646         if (CtdlAccessCheck(ac_aide)) return;
647
648         /* Lame way of checking whether anyone else is doing this now */
649         if (rr != NULL) {
650                 cprintf("%d Another FSCK is already running.\n", ERROR);
651                 return;
652         }
653
654         cprintf("%d Checking message reference counts\n", LISTING_FOLLOWS);
655
656         cprintf("\nThis could take a while.  Please be patient!\n\n");
657         cprintf("Gathering pointers...\n");
658         ForEachRoom(do_fsck_room, NULL);
659
660         get_control();
661         cprintf("Checking message base...\n");
662         for (msgnum = 0L; msgnum <= CitControl.MMhighest; ++msgnum) {
663
664                 cdbmsg = cdb_fetch(CDB_MSGMAIN, &msgnum, sizeof(long));
665                 if (cdbmsg != NULL) {
666                         cdb_free(cdbmsg);
667                         cprintf("Message %7ld    ", msgnum);
668
669                         GetMetaData(&smi, msgnum);
670                         cprintf("refcount=%-2d   ", smi.meta_refcount);
671
672                         realcount = 0;
673                         for (ptr = rr; ptr != NULL; ptr = ptr->next) {
674                                 if (ptr->msgnum == msgnum) ++realcount;
675                         }
676                         cprintf("realcount=%-2d\n", realcount);
677
678                         if ( (smi.meta_refcount != realcount)
679                            || (realcount == 0) ) {
680                                 smi.meta_refcount = realcount;
681                                 PutMetaData(&smi);
682                                 AdjRefCount(msgnum, 0); /* deletes if needed */
683                         }
684
685                 }
686
687         }
688
689         cprintf("Freeing memory...\n");
690         while (rr != NULL) {
691                 ptr = rr->next;
692                 phree(rr);
693                 rr = ptr;
694         }
695
696         cprintf("Done!\n");
697         cprintf("000\n");
698
699 }
700
701
702
703
704 /*****************************************************************************/
705
706 char *Dynamic_Module_Init(void)
707 {
708         CtdlRegisterProtoHook(cmd_expi, "EXPI", "Expire old system objects");
709         CtdlRegisterProtoHook(cmd_fsck, "FSCK", "Check message ref counts");
710         return "$Id$";
711 }