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