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