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