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