* The size constant "256" which shows up everywhere as a buffer size has now
[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);
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_rewind(CDB_VISIT);
440         while(cdbvisit = cdb_next_item(CDB_VISIT), cdbvisit != NULL) {
441                 memset(&vbuf, 0, sizeof(struct visit));
442                 memcpy(&vbuf, cdbvisit->ptr,
443                         ( (cdbvisit->len > sizeof(struct visit)) ?
444                         sizeof(struct visit) : cdbvisit->len) );
445                 cdb_free(cdbvisit);
446
447                 RoomIsValid = 0;
448                 UserIsValid = 0;
449
450                 /* Check to see if the room exists */
451                 for (vrptr=ValidRoomList; vrptr!=NULL; vrptr=vrptr->next) {
452                         if ( (vrptr->vr_roomnum==vbuf.v_roomnum)
453                              && (vrptr->vr_roomgen==vbuf.v_roomgen))
454                                 RoomIsValid = 1;
455                 }
456
457                 /* Check to see if the user exists */
458                 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
459                         if (vuptr->vu_usernum == vbuf.v_usernum)
460                                 UserIsValid = 1;
461                 }
462
463                 /* Put the record on the purge list if it's dead */
464                 if ((RoomIsValid==0) || (UserIsValid==0)) {
465                         vptr = (struct VPurgeList *)
466                                 mallok(sizeof(struct VPurgeList));
467                         vptr->next = VisitPurgeList;
468                         vptr->vp_roomnum = vbuf.v_roomnum;
469                         vptr->vp_roomgen = vbuf.v_roomgen;
470                         vptr->vp_usernum = vbuf.v_usernum;
471                         VisitPurgeList = vptr;
472                 }
473
474         }
475
476         /* Free the valid room/gen combination list */
477         while (ValidRoomList != NULL) {
478                 vrptr = ValidRoomList->next;
479                 phree(ValidRoomList);
480                 ValidRoomList = vrptr;
481         }
482
483         /* Free the valid user list */
484         while (ValidUserList != NULL) {
485                 vuptr = ValidUserList->next;
486                 phree(ValidUserList);
487                 ValidUserList = vuptr;
488         }
489
490         /* Now delete every visit on the purged list */
491         while (VisitPurgeList != NULL) {
492                 IndexLen = GenerateRelationshipIndex(IndexBuf,
493                                 VisitPurgeList->vp_roomnum,
494                                 VisitPurgeList->vp_roomgen,
495                                 VisitPurgeList->vp_usernum);
496                 cdb_delete(CDB_VISIT, IndexBuf, IndexLen);
497                 vptr = VisitPurgeList->next;
498                 phree(VisitPurgeList);
499                 VisitPurgeList = vptr;
500                 ++purged;
501         }
502
503         return(purged);
504 }
505
506
507 void cmd_expi(char *argbuf) {
508         char cmd[SIZ];
509         int retval;
510
511         if (CtdlAccessCheck(ac_aide)) return;
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, void *userdata) {
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, (-127), NULL, NULL,
559                 do_fsck_msg, NULL);
560 }
561
562 /*
563  * Check message reference counts
564  */
565 void cmd_fsck(char *argbuf) {
566         long msgnum;
567         struct cdbdata *cdbmsg;
568         struct SuppMsgInfo smi;
569         struct roomref *ptr;
570         int realcount;
571
572         if (CtdlAccessCheck(ac_aide)) return;
573
574         /* Lame way of checking whether anyone else is doing this now */
575         if (rr != NULL) {
576                 cprintf("%d Another FSCK is already running.\n", ERROR);
577                 return;
578         }
579
580         cprintf("%d Checking message reference counts\n", LISTING_FOLLOWS);
581
582         cprintf("\nThis could take a while.  Please be patient!\n\n");
583         cprintf("Gathering pointers...\n");
584         ForEachRoom(do_fsck_room, NULL);
585
586         get_control();
587         cprintf("Checking message base...\n");
588         for (msgnum = 0L; msgnum <= CitControl.MMhighest; ++msgnum) {
589
590                 cdbmsg = cdb_fetch(CDB_MSGMAIN, &msgnum, sizeof(long));
591                 if (cdbmsg != NULL) {
592                         cdb_free(cdbmsg);
593                         cprintf("Message %7ld    ", msgnum);
594
595                         GetSuppMsgInfo(&smi, msgnum);
596                         cprintf("refcount=%-2d   ", smi.smi_refcount);
597
598                         realcount = 0;
599                         for (ptr = rr; ptr != NULL; ptr = ptr->next) {
600                                 if (ptr->msgnum == msgnum) ++realcount;
601                         }
602                         cprintf("realcount=%-2d\n", realcount);
603
604                         if ( (smi.smi_refcount != realcount)
605                            || (realcount == 0) ) {
606                                 smi.smi_refcount = realcount;
607                                 PutSuppMsgInfo(&smi);
608                                 AdjRefCount(msgnum, 0); /* deletes if needed */
609                         }
610
611                 }
612
613         }
614
615         cprintf("Freeing memory...\n");
616         while (rr != NULL) {
617                 ptr = rr->next;
618                 phree(rr);
619                 rr = ptr;
620         }
621
622         cprintf("Done!\n");
623         cprintf("000\n");
624
625 }
626
627
628
629
630 /*****************************************************************************/
631
632 char *Dynamic_Module_Init(void)
633 {
634         CtdlRegisterProtoHook(cmd_expi, "EXPI", "Expire old system objects");
635         CtdlRegisterProtoHook(cmd_fsck, "FSCK", "Check message ref counts");
636         return "$Id$";
637 }