* Added [idle] to client wholist display for sessions idle >15 minutes
[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                 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
222                         if (vuptr->vu_usernum == atol(qrbuf->QRname)) {
223                                 do_purge = 0;
224                                 goto BYPASS;
225                         }
226                 }
227                 /* user not found */
228                 do_purge = 1;
229                 goto BYPASS;
230         }
231
232         /* Any of these attributes render a room non-purgable */
233         if (qrbuf->QRflags & QR_PERMANENT) return;
234         if (qrbuf->QRflags & QR_DIRECTORY) return;
235         if (qrbuf->QRflags & QR_NETWORK) return;
236         if (!strcasecmp(qrbuf->QRname, SYSCONFIGROOM)) 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         if (CtdlAccessCheck(ac_aide)) return;
502
503         extract(cmd, argbuf, 0);
504         if (!strcasecmp(cmd, "users")) {
505                 retval = PurgeUsers();
506                 cprintf("%d Purged %d users.\n", OK, retval);
507                 return;
508         }
509         else if (!strcasecmp(cmd, "messages")) {
510                 PurgeMessages();
511                 cprintf("%d Expired %d messages.\n", OK, messages_purged);
512                 return;
513         }
514         else if (!strcasecmp(cmd, "rooms")) {
515                 retval = PurgeRooms();
516                 cprintf("%d Expired %d rooms.\n", OK, retval);
517                 return;
518         }
519         else if (!strcasecmp(cmd, "visits")) {
520                 retval = PurgeVisits();
521                 cprintf("%d Purged %d visits.\n", OK, retval);
522         }
523         else if (!strcasecmp(cmd, "defrag")) {
524                 defrag_databases();
525                 cprintf("%d Defragmented the databases.\n", OK);
526         }
527         else {
528                 cprintf("%d Invalid command.\n", ERROR+ILLEGAL_VALUE);
529                 return;
530         }
531 }
532
533 /*****************************************************************************/
534
535
536 void do_fsck_msg(long msgnum, void *userdata) {
537         struct roomref *ptr;
538
539         ptr = (struct roomref *)mallok(sizeof(struct roomref));
540         ptr->next = rr;
541         ptr->msgnum = msgnum;
542         rr = ptr;
543 }
544
545 void do_fsck_room(struct quickroom *qrbuf, void *data)
546 {
547         getroom(&CC->quickroom, qrbuf->QRname);
548         CtdlForEachMessage(MSGS_ALL, 0L, (-127), NULL, NULL,
549                 do_fsck_msg, NULL);
550 }
551
552 /*
553  * Check message reference counts
554  */
555 void cmd_fsck(char *argbuf) {
556         long msgnum;
557         struct cdbdata *cdbmsg;
558         struct SuppMsgInfo smi;
559         struct roomref *ptr;
560         int realcount;
561
562         if (CtdlAccessCheck(ac_aide)) return;
563
564         /* Lame way of checking whether anyone else is doing this now */
565         if (rr != NULL) {
566                 cprintf("%d Another FSCK is already running.\n", ERROR);
567                 return;
568         }
569
570         cprintf("%d Checking message reference counts\n", LISTING_FOLLOWS);
571
572         cprintf("\nThis could take a while.  Please be patient!\n\n");
573         cprintf("Gathering pointers...\n");
574         ForEachRoom(do_fsck_room, NULL);
575
576         get_control();
577         cprintf("Checking message base...\n");
578         for (msgnum = 0L; msgnum <= CitControl.MMhighest; ++msgnum) {
579
580                 cdbmsg = cdb_fetch(CDB_MSGMAIN, &msgnum, sizeof(long));
581                 if (cdbmsg != NULL) {
582                         cdb_free(cdbmsg);
583                         cprintf("Message %7ld    ", msgnum);
584
585                         GetSuppMsgInfo(&smi, msgnum);
586                         cprintf("refcount=%-2d   ", smi.smi_refcount);
587
588                         realcount = 0;
589                         for (ptr = rr; ptr != NULL; ptr = ptr->next) {
590                                 if (ptr->msgnum == msgnum) ++realcount;
591                         }
592                         cprintf("realcount=%-2d\n", realcount);
593
594                         if ( (smi.smi_refcount != realcount)
595                            || (realcount == 0) ) {
596                                 smi.smi_refcount = realcount;
597                                 PutSuppMsgInfo(&smi);
598                                 AdjRefCount(msgnum, 0); /* deletes if needed */
599                         }
600
601                 }
602
603         }
604
605         cprintf("Freeing memory...\n");
606         while (rr != NULL) {
607                 ptr = rr->next;
608                 phree(rr);
609                 rr = ptr;
610         }
611
612         cprintf("Done!\n");
613         cprintf("000\n");
614
615 }
616
617
618
619
620 /*****************************************************************************/
621
622 char *Dynamic_Module_Init(void)
623 {
624         CtdlRegisterProtoHook(cmd_expi, "EXPI", "Expire old system objects");
625         CtdlRegisterProtoHook(cmd_fsck, "FSCK", "Check message ref counts");
626         return "$Id$";
627 }