* Replaced most of the very repetitive and very redundant access level checks
[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 (!strcasecmp(qrbuf->QRname, SYSCONFIGROOM)) return;
238         if (is_noneditable(qrbuf)) return;
239
240         /* If we don't know the modification date, be safe and don't purge */
241         if (qrbuf->QRmtime <= (time_t)0) return;
242
243         /* If no room purge time is set, be safe and don't purge */
244         if (config.c_roompurge < 0) return;
245
246         /* Otherwise, check the date of last modification */
247         age = time(NULL) - (qrbuf->QRmtime);
248         purge_secs = (time_t)config.c_roompurge * (time_t)86400;
249         if (purge_secs <= (time_t)0) return;
250         lprintf(9, "<%s> is <%ld> seconds old\n", qrbuf->QRname, age);
251         if (age > purge_secs) do_purge = 1;
252
253 BYPASS: if (do_purge) {
254                 pptr = (struct PurgeList *) mallok(sizeof(struct PurgeList));
255                 pptr->next = RoomPurgeList;
256                 strcpy(pptr->name, qrbuf->QRname);
257                 RoomPurgeList = pptr;
258         }
259
260 }
261         
262
263
264 int PurgeRooms(void) {
265         struct PurgeList *pptr;
266         int num_rooms_purged = 0;
267         struct quickroom qrbuf;
268         struct ValidUser *vuptr;
269         char *transcript = NULL;
270
271         lprintf(5, "PurgeRooms() called\n");
272
273
274         /* Load up a table full of valid user numbers so we can delete
275          * user-owned rooms for users who no longer exist */
276         ForEachUser(AddValidUser, NULL);
277
278         /* Then cycle through the room file */
279         ForEachRoom(DoPurgeRooms, NULL);
280
281         /* Free the valid user list */
282         while (ValidUserList != NULL) {
283                 vuptr = ValidUserList->next;
284                 phree(ValidUserList);
285                 ValidUserList = vuptr;
286         }
287
288
289         transcript = mallok(256);
290         strcpy(transcript, "The following rooms have been auto-purged:\n");
291
292         while (RoomPurgeList != NULL) {
293                 if (getroom(&qrbuf, RoomPurgeList->name) == 0) {
294                         transcript=reallok(transcript, strlen(transcript)+256);
295                         sprintf(&transcript[strlen(transcript)], " %s\n",
296                                 qrbuf.QRname);
297                         delete_room(&qrbuf);
298                 }
299                 pptr = RoomPurgeList->next;
300                 phree(RoomPurgeList);
301                 RoomPurgeList = pptr;
302                 ++num_rooms_purged;
303         }
304
305         if (num_rooms_purged > 0) aide_message(transcript);
306         phree(transcript);
307
308         lprintf(5, "Purged %d rooms.\n", num_rooms_purged);
309         return(num_rooms_purged);
310 }
311
312
313 void do_user_purge(struct usersupp *us, void *data) {
314         int purge;
315         time_t now;
316         time_t purge_time;
317         struct PurgeList *pptr;
318
319         /* Set purge time; if the user overrides the system default, use it */
320         if (us->USuserpurge > 0) {
321                 purge_time = ((time_t)us->USuserpurge) * 86400L;
322         }
323         else {
324                 purge_time = ((time_t)config.c_userpurge) * 86400L;
325         }
326
327         /* The default rule is to not purge. */
328         purge = 0;
329
330         /* If the user hasn't called in two months, his/her account
331          * has expired, so purge the record.
332          */
333         now = time(NULL);
334         if ((now - us->lastcall) > purge_time) purge = 1;
335
336         /* If the user set his/her password to 'deleteme', he/she
337          * wishes to be deleted, so purge the record.
338          */
339         if (!strcasecmp(us->password, "deleteme")) purge = 1;
340
341         /* If the record is marked as permanent, don't purge it.
342          */
343         if (us->flags & US_PERM) purge = 0;
344
345         /* If the access level is 0, the record should already have been
346          * deleted, but maybe the user was logged in at the time or something.
347          * Delete the record now.
348          */
349         if (us->axlevel == 0) purge = 1;
350
351         /* 0 calls is impossible.  If there are 0 calls, it must
352          * be a corrupted record, so purge it.
353          */
354         if (us->timescalled == 0) purge = 1;
355
356         if (purge == 1) {
357                 pptr = (struct PurgeList *) mallok(sizeof(struct PurgeList));
358                 pptr->next = UserPurgeList;
359                 strcpy(pptr->name, us->fullname);
360                 UserPurgeList = pptr;
361         }
362
363 }
364
365
366
367 int PurgeUsers(void) {
368         struct PurgeList *pptr;
369         int num_users_purged = 0;
370         char *transcript = NULL;
371
372         lprintf(5, "PurgeUsers() called\n");
373         if (config.c_userpurge > 0) {
374                 ForEachUser(do_user_purge, NULL);
375         }
376
377         transcript = mallok(256);
378         strcpy(transcript, "The following users have been auto-purged:\n");
379
380         while (UserPurgeList != NULL) {
381                 transcript=reallok(transcript, strlen(transcript)+256);
382                 sprintf(&transcript[strlen(transcript)], " %s\n",
383                         UserPurgeList->name);
384                 purge_user(UserPurgeList->name);
385                 pptr = UserPurgeList->next;
386                 phree(UserPurgeList);
387                 UserPurgeList = pptr;
388                 ++num_users_purged;
389         }
390
391         if (num_users_purged > 0) aide_message(transcript);
392         phree(transcript);
393
394         lprintf(5, "Purged %d users.\n", num_users_purged);
395         return(num_users_purged);
396 }
397
398
399 /*
400  * Purge visits
401  *
402  * This is a really cumbersome "garbage collection" function.  We have to
403  * delete visits which refer to rooms and/or users which no longer exist.  In
404  * order to prevent endless traversals of the room and user files, we first
405  * build linked lists of rooms and users which _do_ exist on the system, then
406  * traverse the visit file, checking each record against those two lists and
407  * purging the ones that do not have a match on _both_ lists.  (Remember, if
408  * either the room or user being referred to is no longer on the system, the
409  * record is completely useless.)
410  */
411 int PurgeVisits(void) {
412         struct cdbdata *cdbvisit;
413         struct visit vbuf;
414         struct VPurgeList *VisitPurgeList = NULL;
415         struct VPurgeList *vptr;
416         int purged = 0;
417         char IndexBuf[32];
418         int IndexLen;
419         struct ValidRoom *vrptr;
420         struct ValidUser *vuptr;
421         int RoomIsValid, UserIsValid;
422
423         /* First, load up a table full of valid room/gen combinations */
424         ForEachRoom(AddValidRoom, NULL);
425
426         /* Then load up a table full of valid user numbers */
427         ForEachUser(AddValidUser, NULL);
428
429         /* Now traverse through the visits, purging irrelevant records... */
430         cdb_rewind(CDB_VISIT);
431         while(cdbvisit = cdb_next_item(CDB_VISIT), cdbvisit != NULL) {
432                 memset(&vbuf, 0, sizeof(struct visit));
433                 memcpy(&vbuf, cdbvisit->ptr,
434                         ( (cdbvisit->len > sizeof(struct visit)) ?
435                         sizeof(struct visit) : cdbvisit->len) );
436                 cdb_free(cdbvisit);
437
438                 RoomIsValid = 0;
439                 UserIsValid = 0;
440
441                 /* Check to see if the room exists */
442                 for (vrptr=ValidRoomList; vrptr!=NULL; vrptr=vrptr->next) {
443                         if ( (vrptr->vr_roomnum==vbuf.v_roomnum)
444                              && (vrptr->vr_roomgen==vbuf.v_roomgen))
445                                 RoomIsValid = 1;
446                 }
447
448                 /* Check to see if the user exists */
449                 for (vuptr=ValidUserList; vuptr!=NULL; vuptr=vuptr->next) {
450                         if (vuptr->vu_usernum == vbuf.v_usernum)
451                                 UserIsValid = 1;
452                 }
453
454                 /* Put the record on the purge list if it's dead */
455                 if ((RoomIsValid==0) || (UserIsValid==0)) {
456                         vptr = (struct VPurgeList *)
457                                 mallok(sizeof(struct VPurgeList));
458                         vptr->next = VisitPurgeList;
459                         vptr->vp_roomnum = vbuf.v_roomnum;
460                         vptr->vp_roomgen = vbuf.v_roomgen;
461                         vptr->vp_usernum = vbuf.v_usernum;
462                         VisitPurgeList = vptr;
463                 }
464
465         }
466
467         /* Free the valid room/gen combination list */
468         while (ValidRoomList != NULL) {
469                 vrptr = ValidRoomList->next;
470                 phree(ValidRoomList);
471                 ValidRoomList = vrptr;
472         }
473
474         /* Free the valid user list */
475         while (ValidUserList != NULL) {
476                 vuptr = ValidUserList->next;
477                 phree(ValidUserList);
478                 ValidUserList = vuptr;
479         }
480
481         /* Now delete every visit on the purged list */
482         while (VisitPurgeList != NULL) {
483                 IndexLen = GenerateRelationshipIndex(IndexBuf,
484                                 VisitPurgeList->vp_roomnum,
485                                 VisitPurgeList->vp_roomgen,
486                                 VisitPurgeList->vp_usernum);
487                 cdb_delete(CDB_VISIT, IndexBuf, IndexLen);
488                 vptr = VisitPurgeList->next;
489                 phree(VisitPurgeList);
490                 VisitPurgeList = vptr;
491                 ++purged;
492         }
493         
494         return(purged);
495 }
496
497
498 void cmd_expi(char *argbuf) {
499         char cmd[256];
500         int retval;
501
502         if (CtdlAccessCheck(ac_aide)) return;
503
504         extract(cmd, argbuf, 0);
505         if (!strcasecmp(cmd, "users")) {
506                 retval = PurgeUsers();
507                 cprintf("%d Purged %d users.\n", OK, retval);
508                 return;
509         }
510         else if (!strcasecmp(cmd, "messages")) {
511                 PurgeMessages();
512                 cprintf("%d Expired %d messages.\n", OK, messages_purged);
513                 return;
514         }
515         else if (!strcasecmp(cmd, "rooms")) {
516                 retval = PurgeRooms();
517                 cprintf("%d Expired %d rooms.\n", OK, retval);
518                 return;
519         }
520         else if (!strcasecmp(cmd, "visits")) {
521                 retval = PurgeVisits();
522                 cprintf("%d Purged %d visits.\n", OK, retval);
523         }
524         else if (!strcasecmp(cmd, "defrag")) {
525                 defrag_databases();
526                 cprintf("%d Defragmented the databases.\n", OK);
527         }
528         else {
529                 cprintf("%d Invalid command.\n", ERROR+ILLEGAL_VALUE);
530                 return;
531         }
532 }
533
534 /*****************************************************************************/
535
536
537 void do_fsck_msg(long msgnum) {
538         struct roomref *ptr;
539
540         ptr = (struct roomref *)mallok(sizeof(struct roomref));
541         ptr->next = rr;
542         ptr->msgnum = msgnum;
543         rr = ptr;
544 }
545
546 void do_fsck_room(struct quickroom *qrbuf, void *data)
547 {
548         getroom(&CC->quickroom, qrbuf->QRname);
549         CtdlForEachMessage(MSGS_ALL, 0L, (-127), NULL, NULL, do_fsck_msg);
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 }