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