Debian Codegraph @

w4/session.c

raw
1 /* File: session.c
2 * Author: Jean Thierry-Mieg ([email protected])
3 * Copyright (C) J Thierry-Mieg and R Durbin, 1992
4 * -------------------------------------------------------------------
5 * Acedb is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18 * or see the on-line version at http://www.gnu.org/copyleft/gpl.txt
19 * -------------------------------------------------------------------
20 * This file is part of the ACEDB genome database package, written by
21 * Richard Durbin (MRC LMB, UK) [email protected], and
22 * Jean Thierry-Mieg (CRBM du CNR, France) [email protected]
23 *
24 * Description:
25 * Session control, passwords, write access, locks etc.
26 * Exported functions:
27 * HISTORY:
28 * Last edited: Mar 30 14:39 2007 (edgrif)
29 * * Jun 20 10:54 2001 (edgrif): Add extra check of blockN.wrm file read/write
30 * access to check for write access permission.
31 * * Jul 20 14:46 2000 (edgrif): Change logfile format for intial record for
32 * new user, add standard prefix of time, network_id and PID.
33 * * Dec 16 11:23 1999 (edgrif): Added callbacks for server, made models.wrm
34 * test fatal if models.wrm not found.
35 * * Sep 29 11:30 1999 (edgrif): Move sync write & nolock options from passwd.wrm
36 * to database.wrm, required moving getOtherDatabaseConfigs() call.
37 * * Sep 21 11:54 1999 (edgrif): Added code to read/set sync write option
38 * from passwd.wrm.
39 * * Apr 19 12:06 1999 (fw): added // for messages written to stdout
40 * * Apr 19 12:06 1999 (fw): set the readlock for (thisSession_num - 1)
41 * * Jan 25 16:01 1999 (edgrif): Remove getLogin, now in w1/utils.c
42 * * Dec 3 14:43 1998 (edgrif): Change calls to new interface to aceversion.
43 * * Nov 26 11:21 1998 (fw): removed waction stuff
44 * * Oct 22 11:54 1998 (edgrif): Add action.h for init/close_action()
45 * THERE IS A PROBLEM WITH CLASHES WITH disk.h for BP..sigh.
46 * * Oct 21 14:01 1998 (edgrif): Remove use of isGraphics to make graphOut
47 * do a printf, not needed now.
48 * * Sep 11 09:56 1998 (rbsk) need strnew for filGetFullPath assigned to ACEDIR
49 * * Sep 11 09:56 1998 (edgrif): Replace calls to messcrash with messExit
50 * where the problem is a user error.
51 * * Sep 11 09:43 1998 (edgrif): Replace messcrash calls with messExit
52 * where this is appropriate. Remove from messages any mention
53 * of "setenv ACEDB" as this is now deprecated.
54 * * Sep 3 11:14 1998 (edgrif): Remove "ACEDB" from fprintf string in
55 * acedbCrash, this is provided by uMessCrash now.
56 * * Aug 21 14:49 1998 (rd): moved ruid/euid back here, along with getLogin
57 * and dump/crash handlers
58 * * missing date/name
59 * - Moved the write access messages to the locking subroutines to cover
60 * - all uses. And removed time etc which is now automatically done.
61 * * Sep 5 10:44 1997 (rd)
62 * - WIN32 runs sessionFilName() like UNIX when defined(NON_GRAPHIC)
63 * WinTace user should specify ACEDB directory on the commandline?
64 * * Jun 9 14:50 1996 (rd)
65 * - extern uid_t euid, ruid moved to session.h
66 * * Jun 6 17:41 1996 (rd)
67 * * Jun 3 19:00 1996 (rd)
68 * * Feb 2 11:46 1992 (mieg): interactive session control
69 * * Jan 24 11:20 1992 (mieg): session fusion.
70 * Created: Fri Jan 24 11:19:27 1992 (mieg)
71 * CVS info: $Id: session.c,v 1.270 2007/04/02 09:43:27 edgrif Exp $
72 *-------------------------------------------------------------------
73 */
74
75 /* $Id: session.c,v 1.270 2007/04/02 09:43:27 edgrif Exp $ */
76 /* #define CHRONO define it to get global chrono on whole session */
77
78 #define DEF_BP /* avoid typedefing it as void* in disk.h */
79 typedef struct block *BLOCKP ;
80 typedef BLOCKP BP ;
81
82 #include <wh/acedb.h>
83
84 #if defined(__CYGWIN__)
85 #include <windows.h>
86 #endif
87
88 #include <wh/mytime.h>
89 #include <signal.h> /* for autosave */
90
91 #include <wh/aceio.h>
92 #include <wh/bindex.h>
93 #include <wh/lex.h>
94 #include <wh/freeout.h> /* for freeOutInit */
95 #include <whooks/systags.h>
96 #include <whooks/sysclass.h>
97 #include <wh/byteswap.h> /* for calls in swapSuperBlock() */
98 #include <wh/block.h>
99 #include <wh/session.h>
100 #include <wh/a.h>
101 #include <wh/bs.h>
102 #include <wh/disk.h>
103 #include <wh/disk_.h> /* defines BLOCKHEADER */
104 #include <wh/session_.h> /* uses BLOCKHEADER */
105 #include <wh/lex_sess_.h> /* lexSessionStart etc.. */
106 #include <wh/pick.h>
107 #include <wh/pref.h> /* prefReadDBPrefs() */
108 #include <wh/model.h> /* for readModels() */
109 #include <wh/status.h> /* for tStatus */
110 #include <wh/help.h> /* for helpSetDir during initilisation */
111 #include <wh/dbpath.h>
112 #include <wh/log.h>
113 #include <wh/chrono.h>
114
115
116 /* Stub functions for user ID's in non-multiuser systems
117 Note: A WIN32 implementation for Windows NT may be possible */
118 #if defined(MACINTOSH)
119
120 void seteuid(uid_t uid) { return ; }
121 uid_t getuid() { return 1 ; }
122 uid_t geteuid() { return 1 ; }
123 int gethostname(char *b, int l) { *b = 0; }
124 typedef int pid_t;
125 pid_t getpid (void) { return 0; }
126
127 #endif /* not MAC */
128
129
130 #if defined(FreeBSD)
131 #define O_SYNC O_FSYNC /* O_SYNC may be XOPEN thing +gg */
132 #endif /* FreeBSD */
133
134
135 static void closeSession(BOOL doSave) ;
136
137
138 /* One day this should hold all of the below globals....and should be passed into
139 * session calls as context. */
140 static SessionContext session_context_G = NULL ;
141
142
143 /************************************************************/
144 /* globals declared in session.h */
145
146
147 SESSION thisSession ;
148 BOOL swapData = FALSE ;
149
150
151 VoidRoutine messcrashroutine = simpleCrashRoutine;
152 /* The meaning of this function has changed now.
153 it is now only used for acedb code, where acedbCrash()
154 is messCrashRegister'd with the message package.
155 keep using this name for now because used frequently in code */
156
157 /* By default (simpleCrashRoutine) will be close down in style,
158 but not save the database.
159 A user defined routine may check write access and save
160 if required.. (Should always release locks). */
161
162 /************************************************************/
163 /* local globals */
164
165
166 /* A section of database configuration variables that can be overridden from */
167 /* wspec/database.wrm */
168
169 /* number of sessions to keep living before a session expires
170 (if non-permanent and not readlocked) Default is 2, must be > 1 */
171 enum {SESSKEEPALIVE_MIN = 2, SESSKEEPALIVE_DEF = 2} ;
172 static int sessionKeepAlive = SESSKEEPALIVE_DEF ; /* init'd in sessionInit */
173
174
175 enum {RDLCKTIMEOUT_MIN = 1, RDLCKTIMEOUT_DEF = 8} ;
176 static int readlockTimeout = RDLCKTIMEOUT_DEF ; /* readlock files older than that
177 * are removed and ignored */
178
179 /* suppressLock - indicates whether the file-locking system lockf(3)
180 * should be avoided or not.
181 * The default depends on OS type, but it can be
182 * set per-database by inserting the word NOLOCK
183 * in wspec/database.wrm */
184 #if defined(MACINTOSH) || defined(__CYGWIN__)
185
186 #define F_ULOCK 0
187 #define F_TLOCK 0
188
189 static BOOL suppressLock = TRUE ;
190 /* don't use the lockf system, This fine on win & mac even without
191 NOLOCK for this database, because it is unlikely for a Unix program
192 (which uses lockf) to access a database on a PC or Mac */
193
194 /* stub.. */
195 BOOL lockf ( int lockFD, int mode1, int mode2 ) { return 0 ; }
196
197 #else /* UNIX */
198
199 static BOOL suppressLock = FALSE ; /* do use lockf */
200
201 #endif /* not MAC */
202
203 /* If TRUE then all acedb writes to the database will be with O_SYNC which */
204 /* guarantees the data has been written to disk before returning, BUT is */
205 /* VERY slow. (n.b. this need not be a global static but is placed here so */
206 /* all the database configuration variables are together.) */
207 static BOOL syncWrite = FALSE ;
208
209 /* If TRUE then we stop old, non-object-timestamp-aware code from accessing
210 the database. This ensures that an object cannot be updated without its
211 timestamp being updated also. This is a hack, we should really increment
212 the major release number, but it is only required for a small number of
213 databases, so we don't want to obsolete all of them.
214 */
215 static BOOL enforceTimestamps = FALSE;
216
217
218 /* The string to use as the "name" of this session user. */
219 static char *userSessionUser = NULL ;
220
221
222 /* This is a title that can be given to the database and will override that */
223 /* given in wspec/displays.wrm for the main window. Really the main window */
224 /* title should be disabled. */
225 static char *db_title_G = NULL ;
226
227 /* If this is TRUE then any users who are in the unix group that owns the */
228 /* wspec/models.wrm will be allowed to initialise the database. Uncomment */
229 /* the GROUP_ADMIN option in wspec/database.wrm to activate this. */
230 static BOOL group_admin_G = FALSE ;
231
232
233 /* end of database configuration variables. */
234
235
236 /* some write access and save behaviour controlling variables, they may
237 * need rationalising..... */
238 static BOOL dropWriteAccess = FALSE ; /* once TRUE, write access
239 is forbidden and can't be regained
240 this is an odd behaviour */
241
242 static int saveMagic = 0 ; /* read/write verification seems
243 always to be zero currently ??? */
244
245 static BOOL writeAccess = FALSE ; /* Does process have write access
246 currently ? */
247
248 static BOOL saveDB_G = TRUE ; /* Even if the process can get write
249 access this flag if FALSE prevents
250 any saving. */
251
252
253 static BLOCK theSuperBlock ;
254
255 static BOOL debug = FALSE; /* more log-file output */
256
257 static char *messcrashbuf; /* a memory buffer that is
258 allocated at initialization time
259 and free'd when acedb crashes, to
260 gain some extra memory for the crash
261 recovery procedures */
262
263
264 /* Logfile state, sometimes we run without being able to log, this is */
265 /* allowed for databases where we don't have write permission in the */
266 /* database directory. */
267 static ACEOUT logfile_out = NULL;
268 static BOOL logfile_possible = FALSE;
269 static BOOL logfile_request_new_G = FALSE ;
270
271
272 /* graphical versions of acedb may need to have special routines called at */
273 /* various points during session handling. */
274 static GraphSessionCB graphCBs_G = NULL ;
275
276 /* Boolean forceInit_G indicates, if TRUE, that the database
277 ** is to be initialised without further prompting
278 */
279 static BOOL forceInit_G = FALSE;
280
281 /************************************************************/
282 /* The server needs to perform some special actions on initialisation/ */
283 /* termination and does so through callbacks. */
284 static ServerSessionCB serverCBs_G = NULL ;
285
286
287 /************************************************************/
288
289
290 /* if set, externalServer will be called once on every new object, and
291 always in query(0,..) and in grep
292 Registration of this pointer done via xCientInit
293 */
294
295 KEYSET (*externalServer) (KEY key, char *query, char *grep, BOOL getNeighbours) ;
296 void (*externalSaver) (KEY key, int action) ;
297 void (*externalAlias) (KEY key, char *oldname, BOOL keepOldName) ;
298
299 void (*externalCommit) (void) ;
300 BOOL (*externalServerState) (int nn) ;
301 char* (*externalServerName) (void) ;
302
303 /************************************************************/
304
305
306 static char *getConfiguredDatabaseName (void) ;
307 static void getOtherDatabaseConfigs(int *keepAlive, int *timeOut,
308 BOOL *suppressLock, BOOL *syncWrite,
309 BOOL *enforceTimestamps, char **db_title,
310 BOOL *group_admin) ;
311 static BOOL blocksWriteable(BOOL report_errors) ;
312
313 static void sessionDoInit (void) ; /* session.c's own initialisation */
314 static int sessionFindSon (Array sessionTree, KEY father, KEY *sonp) ;
315 static BOOL sessionDatabaseWritable (BOOL doTalk);
316 static BOOL sessionCheckUserName (BOOL doTalk);
317
318 static BOOL readlockCreateDir (void);
319 static BOOL readlockCreateFile (void);
320 static BOOL readlockUpdateFile (void); /* increase thisSession.session before calling */
321 static Array readlockGetSessionNumbers (BOOL isReport);
322
323 static BOOL acedbStartNewLogFile(BOOL just_reopen, char *old_log_name, char *log_msg,
324 BOOL new_session) ;
325 static void acedbLog (char *text, void *user_pointer);
326 static void acedbCloseLog(aceLogExitType exit_type) ;
327
328 static void acedbExit (char *mesg_buf, void *user_pointer);
329 static void acedbCrash (char *mesg_buf, void *user_pointer);
330
331 static BOOL checkFileGroupPerm(struct stat *passwd_stat) ;
332
333 /************************************************************/
334
335 static VoidRoutine writeAccessChangeRoutine = 0;
336
337 /************************************************************/
338
339 /* this mechanism is used to register a function that redraws the
340 window layout or changes menus etc. when the write access changes */
341
342
343 VoidRoutine writeAccessChangeRegister (VoidRoutine func)
344 /* call with NULL to enquire function */
345 {
346 VoidRoutine old = writeAccessChangeRoutine ;
347 if (func)
348 writeAccessChangeRoutine = func ;
349 return old ;
350 } /* writeAccessChangeRegister */
351
352 void writeAccessChangeUnRegister (void)
353 {
354 writeAccessChangeRoutine = NULL ;
355 return;
356 } /* writeAccessChangeUnRegister */
357
358 /*************************************************************/
359
360 /* this mechanism is used to reflect changes in the session structure
361 in a graphical representation of session objects */
362
363 static VoidRoutine sessionChangeRoutine = 0;
364
365 VoidRoutine sessionChangeRegister (VoidRoutine func)
366 {
367 VoidRoutine old = sessionChangeRoutine ;
368 sessionChangeRoutine = func ;
369 return old ;
370 } /* sessionChangeRegister */
371
372 /*************************************************************/
373
374 #ifndef ACEDB5
375 #ifdef ACEDB4
376 void swapSuperBlock(BLOCKP bp) /* used also by disknew.c */
377 { bp->h.disk = swapDISK(bp->h.disk);
378 bp->h.nextdisk = swapDISK(bp->h.nextdisk);
379 bp->h.session = swapInt(bp->h.session);
380 bp->h.key = swapKEY(bp->h.key);
381 bp->gAddress = swapDISK(bp->gAddress);
382 bp->mainRelease = swapInt(bp->mainRelease);
383 bp->subDataRelease = swapInt(bp->subDataRelease);
384 bp->subCodeRelease = swapInt(bp->subCodeRelease);
385 bp->alternateMainRelease = swapInt(bp->alternateMainRelease);
386 } /* swapSuperBlock */
387 #endif
388 #endif
389
390
391 /*************************************************************/
392
393 /* user-defined routine for messExit -
394 * perform acedb-specific tasks when we have to exit
395 * because of some error.
396 * NOTE, that this exit is not as severe as acedbCrash
397 * it merely means that acedb is unable to continue. */
398 static void acedbExit (char *mesg_buf, void *user_pointer)
399 {
400 /* make copy of message to prevent mesg_buf tangle */
401 char *text_copy = strnew(mesg_buf, 0);
402
403 /* output the exit-message to the user
404 * uuugggghhh, unfortunately this call to messout subverts the principle
405 * that exit messages should _not_ go to the scrolled message window.
406 * So before doing them I make sure we switch back to popup windows. In
407 * the giface version this call does nothing. */
408 if (graphCBs_G)
409 graphCBs_G->exit_msg_cb(FALSE) ;
410 messout(text_copy); /* See server code below. */
411
412 messdump (text_copy);
413
414 /* the messcrashroutine should call aceQuit, to clean up,
415 it may give the user a chance to save their work so far */
416 if (messcrashroutine)
417 {
418 VoidRoutine the_routine = messcrashroutine ;
419 messcrashroutine = 0; /* avoids blind recursion */
420 (*the_routine)(); /* call user cleanup routine */
421 }
422
423 acedbCloseLog(ACELOG_ABNORMAL_EXIT) ;
424
425 /* Give the server a chance to clean up/set lock files before we exit.
426 * Note that we do not pass the exit message as the second parameter because
427 * the messout() above has already dumped the message, if you remove the messout()
428 * above you should pass the message in here instead. */
429 if (serverCBs_G)
430 serverCBs_G->exit.funcs.mesgfunc(serverCBs_G->exit.data, NULL) ;
431
432 messfree(text_copy) ;
433
434 return; /* give control back to messExit to
435 * terminate the program */
436 } /* acedbExit */
437
438 /************************************************************/
439
440 static void acedbCrash (char *mesg_buf, void *user_pointer)
441 /* user-defined routine for messcrash -
442 * perform acedb-specific tasks when we have to crash out
443 * in a ball of flames because of a FATAL ERROR.
444 * This is traditionally used to crash out for failed
445 * assertions, as the crash location in the code will be reported.
446 */
447 {
448 char *text_copy;
449
450 if (messcrashbuf)
451 free (messcrashbuf) ; /* frees up space that might be useful */
452
453 /* copy message-text for messout to avoid mesg_buf tangle */
454 /* NOTE, don't use messalloc & Co, to avoid using more code
455 * that could potentially fail */
456 text_copy = malloc(strlen(mesg_buf) + 1);
457 if (!text_copy)
458 {
459 /* we're in big trouble */
460 fprintf (stderr, "fatal memory allocation error in acedbCrash() termination routine, abort");
461
462 /* Hopefully will write a core file. */
463 abort() ;
464 }
465 strcpy (text_copy, mesg_buf);
466
467
468 /***** output crash-message to user and to log-file ****/
469
470 /* uuugggghhh, unfortunately these calls to messout subvert the principle */
471 /* that crash messages should _not_ go to the scrolled message window. */
472 /* So before doing them I make sure we switch back to popup windows. In */
473 /* the giface version this call does nothing. */
474 if (graphCBs_G)
475 graphCBs_G->exit_msg_cb(FALSE) ;
476 messout (text_copy);
477 messout ("Sorry for the crash, please report it, "
478 "if it is reproducible\n") ;
479
480 messdump (text_copy);
481
482
483 /********* if memory failure report usage info **************/
484
485 if (strstr (text_copy, HANDLE_ALLOC_FAILED_STR) != NULL)
486 {
487 if (logfile_out)
488 {
489 tStatus (logfile_out);
490 aceOutFlush (logfile_out);
491 }
492 else
493 /* e.g. if can't write database/ directory */
494 {
495 ACEOUT status_out = aceOutCreateToStderr (0);
496 tStatus (status_out) ;
497 aceOutDestroy (status_out);
498 }
499 }
500
501
502 /* the messcrashroutine should call aceQuit, to clean up,
503 it may give the user a chance to save their work so far */
504 if (messcrashroutine)
505 {
506 VoidRoutine the_routine = messcrashroutine ;
507 messcrashroutine = 0; /* avoids blind recursion */
508 (*the_routine)(); /* call user cleanup routine */
509 }
510
511 acedbCloseLog(ACELOG_CRASH_EXIT) ;
512
513 /* Give the server a chance to clean up/set lock files before we exit. */
514 if (serverCBs_G)
515 serverCBs_G->crash.funcs.mesgfunc(serverCBs_G->crash.data, text_copy) ;
516
517 free(text_copy) ;
518
519 return;
520 } /* acedbCrash */
521
522
523 /************************************************************/
524 /* */
525 /* acedb log file routines, used for the general acedb log file (log.wrm). */
526 /* */
527
528
529 /* Start a new log file at request of user, probably because old one is */
530 /* getting too big. */
531 /* if log_file_name is NULL then old log is called "log.<ace-time>.wrm" */
532 /* */
533 BOOL sessionNewLogFile(char *old_log_name)
534 {
535 BOOL result = FALSE ;
536
537 result = acedbStartNewLogFile(FALSE, old_log_name, NULL, FALSE) ;
538
539 return result ;
540 }
541
542 /* Request that new log file be started next time a logging entry is made, */
543 /* this routine can be called from a signal handler so that an ace server */
544 /* for instance can be sent a signal to start a new log. */
545 /* */
546 void sessionRequestNewLogFile(void)
547 {
548 logfile_request_new_G = TRUE ;
549
550 return ;
551 }
552
553 /* Do a straight close/reopen of the logfile, can be used in conjunction */
554 /* with the "rotatelogs" script found on some unix versions (e.g. linux). */
555 /* */
556 BOOL sessionReopenLogFile(void)
557 {
558 BOOL result = FALSE ;
559
560 result = acedbStartNewLogFile(TRUE, NULL, NULL, FALSE) ;
561
562 return result ;
563 }
564
565
566
567 /* Rename the existing log file and start a new one. Gets called either when */
568 /* requested by user or when database is bootstrapped (start new log because */
569 /* old one is really only applicable to previous incarnation of database. */
570 /* */
571 /*************************************************************
572 * The messages in logfiles only really apply to the database
573 * in its current state, if the database is being rebuilt the
574 * previous log becomes inappropriate.
575 * The previous log is therefore moved to a backup location,
576 * and a new logfile is started at this point (SANgc02773) */
577 /* if log_file_name is NULL then old log is called "log.<ace-time>.wrm" */
578 /* if log_msg is non-NULL then its written to end of old log. */
579 /* */
580 static BOOL acedbStartNewLogFile(BOOL just_reopen, char *old_log_name, char *log_msg, BOOL new_session)
581 {
582 BOOL result = FALSE ;
583
584 if (logfile_possible)
585 {
586 if (just_reopen)
587 {
588 result = reopenAceLogFile(&logfile_out) ;
589 }
590 else
591 {
592 BOOL timestamp = FALSE ;
593 char *log_name = "log" ;
594 ACEOUT new_logfile = NULL ;
595
596 if (old_log_name)
597 {
598 log_name = old_log_name ;
599 }
600 else
601 timestamp = TRUE ;
602
603 logfile_possible = FALSE; /* Prevent logging by below calls. */
604 if (logfile_out)
605 {
606 if ((new_logfile = startNewAceLogFile(logfile_out, log_name, timestamp,
607 log_msg, new_session)))
608 result = TRUE ;
609 }
610 else
611 {
612 result = openAceLogFile("log", &new_logfile, new_session) ;
613 }
614
615 if (result)
616 logfile_out = new_logfile ;
617 }
618
619 if (result)
620 {
621 logfile_possible = TRUE ;
622 }
623 }
624
625 return result ;
626 }
627
628
629 /* registered to be the messDumpRoutine for messdump
630 * PARAMETERS:
631 * text : the message to be logged
632 * may be NULL, if we just want to init the logfile
633 * but not actually log a message
634 * user_pointer : unused */
635 static void acedbLog (char *text, void *user_pointer_unused)
636 {
637
638 if (!logfile_possible)
639 return ;
640
641 /* open the file - establish status */
642 if (!logfile_out)
643 {
644 if (!(openAceLogFile("log", &logfile_out, TRUE)))
645 logfile_possible = FALSE;
646 else
647 logfile_possible = TRUE;
648 }
649
650 /* A signal handler may have asked for a new log to be started... */
651 if (logfile_request_new_G && logfile_out)
652 {
653 logfile_request_new_G = FALSE ; /* Must come first to prevent possible
654 recursion between any messXXX and
655 here. */
656 if (!acedbStartNewLogFile(FALSE, NULL, NULL, FALSE))
657 {
658 messdump("Could not honour requested switch to new log file.") ;
659 }
660 }
661
662
663 /* Log the message if ... */
664 if (text != NULL && /* if we're not initialising */
665 logfile_out != NULL) /* if we have a log-file */
666 {
667 appendAceLogFile(logfile_out, text) ;
668 }
669
670 return;
671 } /* acedbLog */
672
673
674 /* Close the log file and put in a closing message for the session. */
675 /* */
676 static void acedbCloseLog(aceLogExitType exit_type)
677 {
678 if (logfile_out)
679 {
680 closeAceLogFile(logfile_out, exit_type) ;
681
682 logfile_out = NULL ;
683 logfile_possible = FALSE;
684 }
685
686 return ;
687 }
688
689
690 /************************************************************/
691 /* */
692 /* session callback routine registration, needed for allowing other bits of */
693 /* acedb to take special actions on initialisation etc., e.g. both graph and */
694 /* the server code need to do special things. */
695 /* */
696
697
698 /* Register the graph callbacks, this routine is expected to be called */
699 /* before sessionInit(). This is _not_ some generalised interface, it is */
700 /* simply a way to allow the server to take some graph-specific actions */
701 /* at various points. Note that all functions must be provided. */
702 /* NOTE that we expect the caller to keep their struct around and allocated, */
703 /* we do not take a copy so that the caller can change dynamically the */
704 /* routines/data that we point at. */
705 /* */
706 /* This routine is not thread safe, but we shouldn't be threading here */
707 /* anyway. */
708 void sessionRegisterGraphCB(GraphSessionCB callbacks)
709 {
710 if (callbacks == NULL
711 || callbacks->exit_msg_cb == NULL
712 || callbacks->crash_msg_cb == NULL)
713 messcrash("Registering of graph callbacks failed, "
714 "a NULL callback struct or NULL callback routine was passed.") ;
715 else
716 graphCBs_G = callbacks ;
717
718 return ;
719 }
720
721
722 /************************************************************/
723
724 /* Register the server callbacks, this routine is expected to be called */
725 /* before sessionInit(). This is _not_ some generalised interface, it is */
726 /* simply a way to allow the server to take some server-specific actions */
727 /* on intialisation and termination of acedb. Note that all functions must */
728 /* be provided. */
729 /* NOTE that we expect the caller to keep their struct around and allocated, */
730 /* we do not take a copy so that the caller can change dynamically the */
731 /* routines/data that we point at. */
732 /* */
733 /* This routine is not thread safe, but we shouldn't be threading here */
734 /* anyway. */
735 void sessionRegisterServerCB(ServerSessionCB callbacks)
736 {
737 if (callbacks == NULL
738 || callbacks->init.funcs.func == NULL
739 || callbacks->checkFiles.funcs.func == NULL
740 || callbacks->mess_out.user_func == NULL
741 || callbacks->mess_err.user_func == NULL
742 || callbacks->exit.funcs.mesgfunc == NULL
743 || callbacks->crash.funcs.mesgfunc == NULL
744 || callbacks->sighup.funcs.mesgfunc == NULL
745 || callbacks->sigterm.funcs.mesgfunc == NULL)
746 messcrash("Registering of server callbacks failed, "
747 "a NULL callback struct or NULL callback routine was passed.") ;
748 else
749 serverCBs_G = callbacks ;
750
751 return ;
752 }
753
754 /* Get a pointer to the serverCBs struct, needed by some routines outside */
755 /* of session.c (e.g. sigsubs.c) to find out whether to call server */
756 /* routines. */
757 /* */
758 ServerSessionCB sessionGetServerCB(void)
759 {
760 return serverCBs_G ;
761 }
762
763
764 /************************************************************/
765
766 /* Allocate and get hold of a global session control block, intent is to move
767 * all session stuff over to a context one day. */
768 static SessionContext createContext(void)
769 {
770 SessionContext context ;
771
772 context = messalloc(sizeof(SessionContextStruct)) ;
773
774 context->unused = NULL ;
775
776 session_context_G = context ;
777
778 return context ;
779 }
780
781 SessionContext getContext(void)
782 {
783 return session_context_G ;
784 }
785
786
787
788 /************************************************************/
789
790 void sessionInit (char* ace_path)
791 /* general public function */
792 {
793 /* NOTE: only ever called from aceInit() */
794 KEY lastSession = 0;
795 SessionContext context = NULL ;
796
797 #if !(defined(MACINTOSH))
798 euid = geteuid();
799 ruid = getuid();
800 seteuid(ruid);
801
802 if (euid != ruid && !getenv("ACEDB_NO_BANNER"))
803 { printf("// Acedb is running for user %s.\n", getLogin (TRUE));
804 printf("// Acedb is inheriting database write access from user %s.\n",
805 getLogin (FALSE));
806 }
807
808 if (getgid() != getegid())
809 messerror("WARNING. Your acedb executable has a permission "
810 "flag that inherits the group-id on execution (setgid). "
811 "This is pointless, and will stop acedb from spawning "
812 "external programs on systems with dynamic linking. "
813 "Use executables with a set-user-id flag instead.");
814
815 #endif
816
817 /* Macro KEYKEY relies on KEY beeing 4 bytes long */
818 /* Furthermore, it may be assumed implicitly elsewhere */
819
820 if (sizeof(KEY) != 4)
821 messcrash ("KEY size is %d - it must be 4 - rethink and recompile!",
822 sizeof(KEY)) ;
823
824 if (__Global_Bat != KEYMAKE(1,1)) /* something is really wrong */
825 messcrash
826 ("Hand edit systags.h because KEYMAKE(1,1) = %d != __Global_Bat",
827 KEYMAKE(1,1)) ;
828
829
830 /* init these freeXXX first, they belong to the utilities-library,
831 do all the acedb specific inits after that */
832 freeinit () ;
833 freeOutInit () ;
834 utilsInit () ; /* makes later calls to getLogin effectivelly threadSafe */
835
836 if (!dbPathInit (ace_path))
837 messExit ("Home database directory not found - you must give a "
838 "parent directory with subdirectories database/ and wspec/ "
839 "as a command line argument.") ;
840
841 /* Check that the database directory has /database and /wspec
842 sub directories and that the models.wrm file is in /spec.
843 */
844 {
845 char *tmp;
846 if ((tmp = dbPathStrictFilName("wspec", 0, 0, "rd", 0)) != NULL)
847 messfree(tmp);
848 else
849 messExit ("wspec directory not found - you must give a "
850 "parent directory with subdirectories database/ and wspec/ "
851 "as a command line argument.") ;
852
853 if ((tmp = dbPathStrictFilName("database", 0, 0, "rd", 0)) != NULL)
854 messfree(tmp);
855 else
856 messExit ("database directory not found - you must give a "
857 "parent directory with subdirectories database/ and wspec/ "
858 "as a command line argument.") ;
859
860 if ((tmp = dbPathStrictFilName("wspec", "models", "wrm", "r", 0)) != NULL)
861 messfree(tmp);
862 else
863 messExit("The file \"wspec/models.wrm\" could not be found "
864 "in the parent database directory, the database must have "
865 "this file to be usable.") ;
866
867 if ((tmp = dbPathStrictFilName("wspec", "database", "wrm", "r", 0)) != NULL)
868 messfree(tmp);
869 else
870 messExit("The file \"wspec/database.wrm\" could not be found "
871 "in the parent database directory, the database must have "
872 "this file to be usable.") ;
873 }
874
875 /* Locate a whelp directory if we can. Note that we use the contents of
876 ${ACEDB}/whelp if we can, otherwise ${ACEDB_COMMON}/whelp, but we never
877 mix the contents of the two. */
878 {
879 char *helpDir = dbPathFilName("whelp", "", "", "rd", 0);
880 if (helpDir)
881 {
882 helpSetDir(helpDir);
883 messfree(helpDir);
884 }
885 }
886
887
888 /* Set up the session context, in the end this should be returned by sessionInit()
889 * to the application. */
890 context = createContext() ;
891
892
893 /* Initialise the server call backs, must come after sessionSetPath but */
894 /* before crash routine registration. */
895 if (serverCBs_G)
896 serverCBs_G->init.funcs.func(serverCBs_G->init.data) ;
897
898
899 /* this is panic-memory, we claim some memory here which
900 we'll never use. In case the program messcrash'es we free this
901 chunk of storage, so hopefully we can exit gracefully and
902 save our work before we have to exit */
903 messcrashbuf = malloc (12*1024) ;
904
905 /* now register all the acedb specific crash/recovery routines */
906 /* NOTE, if you add an outContext or ErrorContext you should revue the */
907 /* code for these functions which is registered by the server below. */
908 {
909 static struct messContextStruct exitContext = {acedbExit, NULL};
910 static struct messContextStruct crashContext = {acedbCrash, NULL};
911 static struct messContextStruct dumpContext = {acedbLog, NULL};
912
913 messExitRegister (exitContext);
914 messCrashRegister (crashContext);
915
916 logfile_possible = TRUE; /* make sure we try to open log */
917 acedbLog (NULL, NULL); /* open logfile - establish status
918 * before we register it as the
919 * dumpRoutine to use for messubs */
920 messDumpRegister (dumpContext);
921
922 /* Server needs normal or error messages to go to special places. */
923 if (serverCBs_G)
924 {
925 messOutRegister(serverCBs_G->mess_out) ;
926 messErrorRegister(serverCBs_G->mess_err) ;
927 }
928 }
929
930
931 /* Call server routine so server can check for config. or lock files. */
932 /* NOTE, this call must come before the database is truly opened and */
933 /* intialised because it may exit if a database lock file is found. It will*/
934 /* exit directly, not via messcrash, because of interactions with inetd. */
935 /* Needs to be after crash routine registration so we can log errors. */
936 if (serverCBs_G)
937 serverCBs_G->checkFiles.funcs.func(serverCBs_G->checkFiles.data) ;
938
939
940 #ifdef CHRONO
941 chronoStart () ;
942 #endif
943 /* The order of the initialisations is crucial */
944 chrono ("preInit") ;
945 blockInit() ; /* Initialisation du cache */
946 lexInit() ; /* Initialisation du lexique */
947 pickPreInit() ; /* Enough SysClass definitions
948 to read the session voc */
949
950 getOtherDatabaseConfigs(&sessionKeepAlive, &readlockTimeout,
951 &suppressLock, &syncWrite,
952 &enforceTimestamps, &db_title_G, &group_admin_G) ;
953
954 if (syncWrite) /* Synchronous writing to disk, slow */
955 diskSetSyncWrite() ; /* but reliable. */
956 sessionDoInit() ; /* Checks ACEDB.wrm
957 (and boostraps if neces.)
958 Sets the number thisSession.session
959 sets readlock for thisSession
960 Reads in the lexiques etc, */
961
962 lastSession = lexLastKey(_VSession);
963 if (lastSession == 0)
964 messcrash("The session class is empty, Reconstruct, sorry") ;
965 sessionStart(lastSession) ;
966
967
968 chronoReturn () ;
969 chrono ("realInit") ;
970
971 pickInit() ; /* Class definitions */
972
973 prefInit () ;
974 prefReadDBPrefs() ; /* Preferences */
975
976 pickCheckConsistency() ; /* Check tag values and class hierarchy */
977 lexAlphaClear () ; /* Prevents pointless savings */
978 sessionInitialize () ; /* must come after pickInit */
979 parseArrayInit() ; /* in quovadis.c */
980 bIndexInit(BINDEX_AUTO) ; /* will do only from disk */
981
982 {
983 /* purge the readlocks directory of timed-out readlocks
984 and report the readlocks still active
985 (unless ACEDB_NO_BANNER is set) */
986 Array tmp = readlockGetSessionNumbers
987 (getenv("ACEDB_NO_BANNER") ? FALSE : TRUE);
988 arrayDestroy (tmp);
989 }
990
991 chronoReturn () ;
992 return;
993 } /* sessionInit */
994
995 /*************************************************************/
996 /* definitelly release all memories before exit */
997
998 void sessionShutDown (void)
999 {
1000
1001 #ifdef CHRONO
1002 chronoStop () ;
1003 chronoReport () ;
1004 #endif
1005
1006 #if 0
1007 /* called funct not yet folded in from ncbi (mieg, june 03 */
1008 int n0, n1 ;
1009 BOOL debug = FALSE ;
1010
1011 messAllocStatus (&n1) ;
1012
1013 if (debug) freeOutf ("%18s%8s%8s\n","// Layer","Freed","Used") ;
1014 if (debug) freeOutf ("%18s%8d%8d kb\n","// Shutdown start", 0, n1 >> 10) ; n0 = n1 ;
1015
1016 lexAlphaShutDown () ;
1017 messAllocStatus (&n1) ;
1018 if (debug) freeOutf ("%18s%8d%8d kb\n","// LexAlpha", (n0 - n1) >> 10, n1 >> 10) ;
1019 n0 = n1 ;
1020
1021 lexShutDown () ;
1022 messAllocStatus (&n1) ;
1023 if (debug) freeOutf ("%18s%8d%8d kb\n","// Lex", (n0 - n1) >> 10, n1 >> 10) ;
1024 n0 = n1 ;
1025
1026 bIndexShutDown () ;
1027 messAllocStatus (&n1) ;
1028 if (debug) freeOutf ("%18s%8d%8d kb\n","// Bindex", (n0 - n1) >> 10, n1 >> 10) ;
1029 n0 = n1 ;
1030
1031 bsMakePathShutDown () ;
1032 messAllocStatus (&n1) ;
1033 if (debug) freeOutf ("%18s%8d%8d kb\n","// MakePaths", (n0 - n1) >> 10, n1 >> 10) ;
1034 n0 = n1 ;
1035
1036 cacheShutDown () ;
1037 messAllocStatus (&n1) ;
1038 if (debug) freeOutf ("%18s%8d%8d kb\n","// Cache2", (n0 - n1) >> 10, n1 >> 10) ;
1039 n0 = n1 ;
1040
1041 blockShutDown () ;
1042 messAllocStatus (&n1) ;
1043 if (debug) freeOutf ("%18s%8d%8d kb\n","// Blocks", (n0 - n1) >> 10, n1 >> 10) ;
1044 n0 = n1 ;
1045
1046 BSshutdown () ;
1047 messAllocStatus (&n1) ;
1048 if (debug) freeOutf ("%18s%8d%8d kb\n","// BS", (n0 - n1) >> 10, n1 >> 10) ;
1049 n0 = n1 ;
1050
1051 BTshutdown () ;
1052 messAllocStatus (&n1) ;
1053 if (debug) freeOutf ("%18s%8d%8d kb\n","// BT", (n0 - n1) >> 10, n1 >> 10) ;
1054 n0 = n1 ;
1055
1056 OBJShutDown () ;
1057 messAllocStatus (&n1) ;
1058 if (debug) freeOutf ("%18s%8d%8d kb\n","// OBJ", (n0 - n1) >> 10, n1 >> 10) ;
1059 n0 = n1 ;
1060
1061 diskShutDown () ;
1062 messAllocStatus (&n1) ;
1063 if (debug) freeOutf ("%18s%8d%8d kb\n","// OBJ", (n0 - n1) >> 10, n1 >> 10) ;
1064 n0 = n1 ;
1065
1066 /*
1067 prefShutDown () ;
1068 */
1069
1070 messfree (messcrashbuf) ;
1071 if (debug) freeOutf ("\n") ;
1072 freeOutShutDown () ; /* cannot use freeout after freeshutdown, which anyway uses very little */
1073 freeshutdown () ;
1074 messAllocShutdown () ;
1075 n0 = n1 ;
1076 #endif
1077 }
1078
1079 /*************************************************************/
1080
1081 /* External interface to I_own_the_passwd() function. */
1082 BOOL sessionAdminUser(char *err_msg)
1083 {
1084 BOOL result = FALSE ;
1085
1086 result = I_own_the_passwd(err_msg) ;
1087
1088 return result ;
1089 }
1090
1091 /* Check ownership of wspec/passwd.wrm file which is used to decide which */
1092 /* users are allowed to reinitialise the database. */
1093 /* */
1094 /* for_what is a string like */
1095 /* "initialize the database" or "change something important" */
1096 /* or "enable write access" */
1097 /* */
1098 /* 1) following must be true: ruid == euid and rgid == egid */
1099 /* 2) wspec/passwd.wrm must be readable */
1100 /* 3) by default we check that ruid == uid of wspec/passwd.wrm */
1101 /* 4) but if GROUP_ADMIN is specified in wspec/database.wrm then in addition */
1102 /* we check whether rgid or users supplementary groups match the gid of */
1103 /* wspec/passwd.wrm. */
1104 /* */
1105 /* */
1106 BOOL I_own_the_passwd(char *for_what)
1107 {
1108 #if defined(MACINTOSH)
1109
1110 return TRUE;
1111
1112 #elif defined (__CYGWIN__)
1113
1114 /* For windows 95, 98, always return TRUE, since it has no security */
1115 if ( GetVersion() & 0x80000000)
1116
1117 return TRUE ;
1118
1119 #else /* normal Unixes */
1120
1121 struct stat status ;
1122 char *passwd_filename = 0;
1123 STORE_HANDLE handle;
1124 BOOL result = FALSE ;
1125
1126 handle = handleCreate();
1127 passwd_filename = dbPathStrictFilName("wspec", "passwd", "wrm", "r", handle);
1128
1129 if (passwd_filename && stat(passwd_filename, &status) == 0)
1130 {
1131 if (ruid == status.st_uid)
1132 {
1133 result = TRUE;
1134 }
1135 else if (group_admin_G)
1136 {
1137 /* Group permissions check allowed. */
1138 if (checkFileGroupPerm(&status))
1139 result = TRUE ;
1140 else
1141 {
1142 messout ("Sorry, to %s, you must be in the unix group for the "
1143 "password file. Check %s !",
1144 for_what, passwd_filename);
1145 result = FALSE;
1146 }
1147 }
1148 else
1149 {
1150 messout ("Sorry, to %s, you must be the owner of the "
1151 "password file. Check %s !",
1152 for_what, passwd_filename);
1153 result = FALSE;
1154 }
1155 }
1156 else
1157 {
1158 messout ("Sorry, the database has no password file. "
1159 "To %s, the usernames of trusted administrators "
1160 "have to be listed in the file : %s/passwd.wrm",
1161 for_what, dbPathStrictFilName("wspec", "", "", "rd", handle));
1162 result = FALSE;
1163 }
1164
1165 handleDestroy(handle) ;
1166
1167 return result ;
1168 #endif
1169 }
1170
1171 /* This could be made into a general utility with a little work. */
1172 /* */
1173 /* Strict check of whether a users rgid or supplementary gids match a files */
1174 /* gid. */
1175 /* */
1176 /* Note that some Unixes do not support supplementary groups, we test */
1177 /* NGROUPS_MAX to look for this. */
1178 /* */
1179 static BOOL checkFileGroupPerm(struct stat *file_stat)
1180 {
1181 BOOL result = FALSE ;
1182 gid_t rgroup, egroup ;
1183
1184 rgroup = getgid() ;
1185 egroup = getegid() ;
1186
1187 if (rgroup == egroup)
1188 {
1189 if (file_stat->st_gid == rgroup)
1190 result = TRUE ;
1191 #ifdef NGROUPS_MAX
1192 else
1193 {
1194 int ngroups ;
1195
1196 /* This looks a little arcane, basically you have to find out how */
1197 /* many supplementary groups there are before you can find what */
1198 /* they are...sigh... */
1199 ngroups = getgroups(0, NULL) ;
1200 if (ngroups == -1)
1201 messcrash("Internal coding error in checkFileGroupPerm() "
1202 "the getgroups() call to find the number of supplementary "
1203 "groups failed.") ;
1204 else if (ngroups == 0)
1205 result = FALSE ;
1206 else
1207 {
1208 gid_t *groups ;
1209
1210 groups = messalloc(sizeof(gid_t) * ngroups) ;
1211
1212 if (getgroups(ngroups, groups) <= 0)
1213 messcrash("Internal coding error in checkFileGroupPerm() "
1214 "the getgroups() call to retrieve the supplementary "
1215 "groups failed.") ;
1216 else
1217 {
1218 int i ;
1219 gid_t gid ;
1220 gid_t *grpptr = groups ;
1221
1222 for (i = 0 ; i < ngroups ; i++)
1223 {
1224 gid = *grpptr++ ;
1225
1226 if (gid == file_stat->st_gid)
1227 {
1228 result = TRUE ;
1229 break ;
1230 }
1231 }
1232 }
1233
1234 messfree(groups) ;
1235 }
1236 }
1237 #endif /* NGROUPS_MAX */
1238 }
1239
1240 return result ;
1241 }
1242
1243
1244 /*************************************************************/
1245 /************** Disk Lock System *****************************/
1246 /*************************************************************/
1247
1248 static BOOL showWriteLock (void)
1249 {
1250 static char* logName = "Don't-know-who" ;
1251 int n = 0;
1252 ACEIN lock_io = 0 ;
1253 char *filename;
1254
1255 filename = dbPathMakeFilName("database", "lock", "wrm", 0);
1256 lock_io = aceInCreateFromFile (filename, "r", "", 0);
1257 messfree(filename);
1258
1259 if (lock_io)
1260 {
1261 if (aceInCard(lock_io))
1262 {
1263 aceInNext(lock_io) ;
1264 if (aceInInt(lock_io,&n))
1265 {
1266 char *name ;
1267
1268 aceInNext(lock_io) ;
1269 name = aceInWord(lock_io) ;
1270 if (name != NULL)
1271 logName = name ;
1272 }
1273 }
1274 aceInDestroy (lock_io) ;
1275 messout ("%s (session %d) already has write access", logName, n) ;
1276 return TRUE ;
1277 }
1278
1279 return FALSE;
1280 } /* showWriteLock */
1281
1282 /**************************/
1283
1284 static int lockFd = -1 ; /* lock file descriptor */
1285
1286 static void releaseWriteLock (void)
1287 {
1288 char *filename = NULL;
1289
1290 seteuid(euid);
1291 if (lockFd == -1)
1292 messcrash ("Unbalanced call to releaseWriteLock") ;
1293
1294 if (!suppressLock)
1295 if (lockf (lockFd, F_ULOCK, 0)) /* non-blocking */
1296 messcrash ("releaseWriteLock cannot unlock the lock file");
1297
1298 close (lockFd) ;
1299
1300 filename = dbPathStrictFilName("database", "lock", "wrm", "w", 0);
1301 if ((!filename) || (!filremove(filename, "")))
1302 messerror ("Cannot unlock database "
1303 "by removing database/lock.wrm (%s)",
1304 messSysErrorText()) ;
1305
1306 if (filename)
1307 messfree(filename);
1308
1309 lockFd = -1 ;
1310 seteuid(ruid);
1311
1312 messdump ("Write access dropped") ;
1313 } /* releaseWriteLock */
1314
1315 /**************************/
1316
1317 static BOOL setWriteLock (void)
1318 {
1319 unsigned int size ;
1320 char *cp ;
1321 /* should never fail */
1322 char *filename = dbPathMakeFilName("database", "lock", "wrm", 0);
1323
1324 if (lockFd != -1)
1325 messcrash ("Unbalanced call to setWriteLock") ;
1326
1327 if (suppressLock)
1328 {
1329 /* check for existence of unlocked lock.wrm file
1330 if it exists, then the database is considered locked
1331 */
1332 lockFd = open(filename, O_RDONLY);
1333 if(lockFd != -1) /* open was successful
1334 * the lock-file exists */
1335 {
1336 showWriteLock(); /* show the owner of the lock */
1337 close(lockFd);
1338 lockFd = -1;
1339 messfree(filename);
1340 return FALSE; /* can't get lock */
1341 }
1342 /* OK so we don't have a lock-file .... */
1343 }
1344
1345 /* open the file regardless whether the file is there,
1346 * create it if it's not there and open in readwrite mode */
1347
1348 seteuid(euid);
1349 lockFd = open (filename, O_RDWR | O_CREAT | O_SYNC, 0644) ;
1350
1351 if (lockFd == -1)
1352 {
1353 /* is there a permissions problem ? */
1354 /* shouldn't have happened, if
1355 * sessionDatabaseWritable() succeeded... */
1356 messerror ("I can't open or create the lock file %s. (%s)",
1357 filename, messSysErrorText()) ;
1358 seteuid(ruid);
1359 messfree(filename);
1360 return FALSE ;
1361 }
1362
1363 if (!suppressLock)
1364 {
1365 /* on systems that permit file-locking we make use of lockf(3)
1366 * on the actual lockfile. Its advantage is that the kernel-lock
1367 * will be cleaned up even when the program dies and
1368 * leaves the file hanging around.
1369 */
1370 /* THERE IS A BIG PROBLEM HERE WITH NFS, IF THE FILE EXISTS ON A */
1371 /* REMOTE FILE SYSTEM AND THE LOCK DAEMON IS NOT WORKING PROPERLY, */
1372 /* THE CODE WILL HANG ON THIS TEST AND NOT RETURN. There is nothing we */
1373 /* can do about this because our NFS mounts at sanger are "hard" mounts*/
1374 if (lockf (lockFd, F_TLOCK, 0)) /* non-blocking test for lock */
1375 {
1376 if (errno == EACCES)
1377 {
1378 /* "Permission denied" - standard case
1379 * can't lock file - show who has locked locked it */
1380 showWriteLock();
1381 }
1382 else
1383 {
1384 /* other error */
1385 /* could be the errno ENOLCK - "No locks available"
1386 hints to a possible misconfiguration
1387 of the lockdaemon, see man-page lockf(3) */
1388 messout ("Sorry, I am unable to establish a lock "
1389 "on file database/lock.wrm\n"
1390 "(%s)\n"
1391 "There may be a problem with the lock daemon "
1392 "on this machine, esp. if running NFS.\n"
1393 "To avoid the use of the lock daemon, "
1394 "insert the word NOLOCK\n"
1395 "in the file wspec/database.wrm",
1396 messSysErrorText());
1397 }
1398
1399 close(lockFd);
1400 lockFd = -1 ;
1401
1402 seteuid(ruid);
1403 messfree(filename);
1404 return FALSE ;
1405 }
1406 }
1407
1408 /* write lock-owner info into the lock-file */
1409 cp = messprintf ("%d %s\n\n", thisSession.session, getLogin(TRUE)) ;
1410 size = strlen(cp) + 1 ;
1411 write (lockFd, cp, size) ;
1412
1413 seteuid(ruid);
1414
1415 messdump ("Write access");
1416 messfree(filename);
1417 return TRUE;
1418 } /* setWriteLock */
1419
1420 /****************************************************************/
1421 /****************************************************************/
1422
1423 /* If thisSessionStartTime == 0 then no session has currently been started
1424 we set the start time here but only create the userSession key in
1425 sessionUserKey in case it is never needed. */
1426
1427 static mytime_t thisSessionStartTime = 0 ;
1428
1429
1430 /* set start time of session and init userKey */
1431 void sessionInitialize (void)
1432 {
1433 thisSessionStartTime = timeNow() ;
1434 thisSession.userKey = 0 ;
1435 lexSessionStart () ;
1436
1437 return ;
1438 } /* sessionInitialize */
1439
1440 /************************************************************/
1441
1442 void sessionStart (KEY fromSession)
1443 /* private function in session module */
1444 {
1445 OBJ Session ;
1446 int a3 = 0, b3 = 0, c3 = 0, h3 = 0,
1447 parent_index_version = 0 ;
1448
1449 Session = bsCreate(fromSession) ;
1450 if(!Session )
1451 { messout("Sorry, I cannot find %s", name(fromSession)) ;
1452 return ;
1453 }
1454 if(!bsGetData(Session,_VocLex,_Int,&a3) ||
1455 !bsGetData(Session,_bsRight,_Int,&b3) ||
1456 !bsGetData(Session,_bsRight,_Int,&c3) ||
1457 /* Hasher only introduced in release 1.4 !bsGetData(Session,_bsRight,_Int,&h0) || */
1458 !bsGetData(Session,_CodeRelease,
1459 _Int,&thisSession.mainCodeRelease) ||
1460 !bsGetData(Session,_bsRight,
1461 _Int,&thisSession.subCodeRelease) ||
1462 !bsGetData(Session,_DataRelease,
1463 _Int,&thisSession.mainDataRelease) ||
1464 !bsGetData(Session,_bsRight,
1465 _Int,&thisSession.subDataRelease) )
1466 { messout("No address in this session") ;
1467 bsDestroy(Session) ;
1468 return ;
1469 }
1470 bsGetData(Session,_IndexVersion,
1471 _Int,&parent_index_version) ;
1472
1473 bsDestroy(Session) ;
1474
1475 thisSession.from = fromSession ;
1476 thisSession.upLink = fromSession ;
1477 thisSession.index_version = bIndexVersion(parent_index_version) ;
1478
1479 lexOverLoad(__lexi3,(DISK)a3) ;
1480 lexOverLoad(__voc3,(DISK)c3) ;
1481 lexOverLoad(__lexh3,(DISK)h3) ;
1482
1483 lexRead() ;
1484
1485 return;
1486 } /* sessionStart */
1487
1488 /*************************************************************/
1489
1490 static BOOL sessionOedipe (void) /* Kill the father of the present session */
1491 { KEY father = thisSession.upLink, grandFather, fPlus, fMinus ;
1492 OBJ Father ;
1493 Array fPlusArray, fMinusArray ;
1494
1495 if(!father || !(Father = bsUpdate(father)))
1496 return FALSE ;
1497 if(!bsGetKey(Father,_BatPlus,&fPlus) ||
1498 !bsGetKey(Father,_BatMinus,&fMinus) )
1499 { messout("No address in this father") ;
1500 bsDestroy(Father) ;
1501 return FALSE ;
1502 }
1503
1504 if(!bsFindTag(Father,_Permanent_session))
1505 { messout("The previous session being delared permanent, I keep it") ;
1506 bsDestroy(Father) ;
1507 return FALSE ;
1508 }
1509
1510 if (bsGetKey(Father, _Up_linked_to, &grandFather))
1511 { thisSession.upLink = grandFather ;
1512 bsAddData(Father, _Destroyed_by_session, _Int, &thisSession.session) ;
1513 bsSave(Father) ;
1514 }
1515 else
1516 { thisSession.upLink = 0 ;
1517 bsDestroy(Father) ;
1518 }
1519
1520 fPlusArray = arrayGet(fPlus,unsigned char,"c") ;
1521 fMinusArray = arrayGet(fMinus,unsigned char,"c") ;
1522
1523 diskFuseOedipeBats(fPlusArray, fMinusArray) ;
1524
1525 arrayDestroy(fPlusArray) ;
1526 arrayDestroy(fMinusArray) ;
1527 /* Kill the father bats */
1528 arrayKill(fPlus) ;
1529 arrayKill(fMinus) ;
1530
1531 saveAll() ;
1532 return TRUE ;
1533 } /* sessionOedipe */
1534
1535 /******************/
1536
1537 static BOOL sessionFuse (KEY father, KEY son)
1538 {
1539 KEY fPlus, fMinus, sPlus, sMinus, grandFather ;
1540 OBJ Father = 0 , Son = 0 ;
1541 int nPlus = 0, nMinus = 0 ;
1542
1543 Father = bsUpdate(father) ;
1544 Son = bsUpdate(son) ;
1545 if(!Father || !Son ||
1546 !bsGetKey(Father,_BatPlus,&fPlus) ||
1547 !bsGetKey(Father,_BatMinus,&fMinus) ||
1548 bsFindTag(Father, _Destroyed_by_session) ||
1549 !bsGetKey(Son,_BatPlus,&sPlus) ||
1550 !bsGetKey(Son,_BatMinus,&sMinus)
1551 )
1552 goto abort ;
1553
1554 if (!diskFuseBats(fPlus, fMinus, sPlus, sMinus, &nPlus, &nMinus))
1555 goto abort ;
1556
1557 /* Store the sons bat sizes */
1558 bsAddKey(Son, _BatPlus, sPlus) ; /* to reposition */
1559 bsAddData(Son, _bsRight, _Int, &nPlus) ;
1560 bsAddKey(Son, _BatMinus, sMinus) ;
1561 bsAddData(Son, _bsRight, _Int, &nMinus) ;
1562
1563 bsAddData(Father, _Destroyed_by_session, _Int, &thisSession.session) ;
1564 if (bsGetKey(Father, _Up_linked_to,&grandFather))
1565 bsAddKey(Son , _Up_linked_to, grandFather) ;
1566
1567 bsSave(Father) ;
1568 bsSave(Son) ;
1569 saveAll() ;
1570 return TRUE ;
1571
1572 abort:
1573 bsSave(Son) ;
1574 bsSave(Father) ;
1575 return FALSE ;
1576 } /* sessionFuse */
1577
1578 /************************************************************/
1579
1580 Array sessionTreeCreate(BOOL showDeads)
1581 /* private function in session module */
1582 {
1583 KEY key = 0 , kk ;
1584 int treeArrayMax ;
1585 char *cp ;
1586 OBJ obj ;
1587 ST *st , *st1 ;
1588 int gen, i, j;
1589 BOOL found ;
1590 Array sessionTree;
1591
1592 messStatus ("Reading sessions");
1593
1594 sessionTree = arrayCreate(50, ST) ;
1595
1596 /* Add all Session objects to the session tree */
1597 treeArrayMax = 0;
1598 while (lexNext(_VSession, &key))
1599 if ((obj = bsCreate(key)))
1600 {
1601 st = arrayp(sessionTree, treeArrayMax++, ST) ;
1602 st->key = key ;
1603 bsGetData(obj,_Session, _Int, &st->number);
1604
1605 if (bsGetKey(obj,_Created_from, &kk))
1606 st->father = st->ancester = kk ;
1607 if (bsGetKey(obj,_Up_linked_to, &kk))
1608 st->ancester = kk ;
1609 else if (st->key != KEYMAKE(_VSession, 2))
1610 st->isDestroyed = TRUE ; /* i.e. to old a release */
1611 if (bsFindTag(obj,_Destroyed_by_session))
1612 st->isDestroyed = TRUE ;
1613 if (bsFindTag(obj,_Permanent_session))
1614 st->isPermanent = TRUE ;
1615
1616 if (bsGetData(obj,_User, _Text, &cp))
1617 st->user = strnew(cp, 0);
1618
1619 if (bsGetData(obj,_Date, _Text, &cp))
1620 st->date = strnew(cp, 0);
1621
1622 if (bsGetData(obj,_Session_Title, _Text, &cp) && strlen(cp) > 0)
1623 st->title = strnew(cp, 0);
1624 else
1625 st->title = strnew(name(st->key), 0);
1626
1627 st->len = strlen(st->title);
1628
1629 bsDestroy(obj) ;
1630 }
1631
1632 /* Add thisSession to the session tree
1633 (the object for the current session is not a finalized object
1634 yet and therfore won't show up in the lexer up) */
1635 st = arrayp(sessionTree, treeArrayMax++, ST) ;
1636 st->key = _This_session ;
1637 st->father = st->ancester = thisSession.from ;
1638 st->title = strnew(name(st->key), 0);
1639 st->len = strlen(st->title);
1640
1641 /* links the st */
1642 for (i = 0, st = arrp(sessionTree,0,ST) ; i < arrayMax(sessionTree) ; st++, i++)
1643 for (j = 0, st1 = arrp(sessionTree,0,ST) ; j < arrayMax(sessionTree) ; st1++, j++)
1644 if(st->key == st1->ancester)
1645 st1->sta = st ;
1646
1647 /* Count generations */
1648 if (showDeads)
1649 {
1650 for (i = 0, st = arrp(sessionTree,0,ST); i < arrayMax(sessionTree) ; st++, i++)
1651 if (!st->ancester)
1652 st->generation = 1 ;
1653 }
1654 else
1655 {
1656 for (i = 0, st = arrp(sessionTree,0,ST) ; i < arrayMax(sessionTree) ; st++, i++)
1657 if ((!st->isDestroyed || st->isReadlocked) && ( !st->ancester || (st->sta && st->sta->isDestroyed)) )
1658 st->generation = 1 ;
1659 }
1660 gen = 1 ;
1661 found = TRUE ;
1662 while (found)
1663 { found = FALSE ;
1664 if (showDeads)
1665 {
1666 for (i = 0, st = arrp(sessionTree,0,ST) ; i < arrayMax(sessionTree) ; st++, i++)
1667 if (st->sta && st->sta->generation == gen)
1668 { st->generation = gen + 1 ;
1669 found = TRUE ;
1670 }
1671 }
1672 else
1673 {
1674 for (i = 0, st = arrp(sessionTree,0,ST) ; i < arrayMax(sessionTree) ; st++, i++)
1675 if ((!st->isDestroyed || st->isReadlocked) && st->sta && st->sta->generation == gen)
1676 { st->generation = gen + 1 ;
1677 found = TRUE ;
1678 }
1679 }
1680 gen++ ;
1681 }
1682
1683 /* mark readlocked sessions, they won't get destroyed, because
1684 other processes still have that data cached */
1685 {
1686 Array readlockedSessions;
1687 int n, locked_num;
1688
1689 if ((readlockedSessions = readlockGetSessionNumbers(FALSE)))
1690 {
1691 for (n = 0; n < arrayMax(readlockedSessions); n++)
1692 {
1693 locked_num = arr (readlockedSessions, n, int);
1694
1695 for (i = 0, st = arrp(sessionTree,0,ST) ;
1696 i < arrayMax(sessionTree) ; st++, i++)
1697 /* locked_num - 1 is the session that the process
1698 (that keeps the readlock) was initialised from -
1699 that is the number that needs to be protected. */
1700 if (st->number == locked_num - 1)
1701 st->isReadlocked = TRUE;
1702 }
1703 arrayDestroy (readlockedSessions);
1704 }
1705 }
1706
1707 return sessionTree;
1708 } /* sessionTreeConstruct */
1709
1710 /************************************************************/
1711
1712 void sessionTreeDestroy(Array sessionTree)
1713 /* private function in session module */
1714 {
1715 ST *st ;
1716 int i;
1717
1718 if (!arrayExists(sessionTree))
1719 messcrash("sessionTreeDestroy() - called with invalid sessionTree");
1720
1721 for (i = 0, st = arrp(sessionTree, 0, ST);
1722 i < arrayMax(sessionTree); st++, i++)
1723 {
1724 if (st->user) messfree (st->user);
1725 if (st->date) messfree (st->date);
1726 if (st->title) messfree (st->title);
1727 }
1728
1729 arrayDestroy (sessionTree);
1730
1731 return;
1732 } /* sessionTreeDestroy */
1733
1734 /************************************************************/
1735
1736 static int sessionFindSon(Array sessionTree, KEY father, KEY *sonp)
1737 {
1738 int i, n = 0;
1739 ST *st, *sta ;
1740
1741 *sonp = 0 ; /* Suicide */
1742 if (father == _This_session)
1743 return -2 ;
1744 if (!father) /* Trivial */
1745 return -3 ;
1746 if (father <= KEYMAKE(_VSession, 2))
1747 return -6 ;
1748
1749 for (i = 0, sta = arrp(sessionTree,0,ST) ; i < arrayMax(sessionTree) ; sta++, i++)
1750 if (sta->key == father)
1751 break ;
1752
1753 if (sta->key != father) /* not found error */
1754 return -5 ;
1755
1756 if (sta->isDestroyed) /* dead */
1757 return -3 ;
1758
1759 for (i = 0, st = arrp(sessionTree,0,ST) ; i < arrayMax(sessionTree) ; st++, i++)
1760 if(!st->isDestroyed && st->sta == sta)
1761 { *sonp = st->key ;
1762 n++ ;
1763 }
1764
1765 if (n == 1) /* is st1 in my direct ancestors */
1766 { for (i = 0, st = arrp(sessionTree,0,ST) ; i < arrayMax(sessionTree) ; st++, i++)
1767 if (st->key == thisSession.from)
1768 {
1769 while (st)
1770 { if (st == sta)
1771 return 1 ;
1772 st = st->sta ;
1773 }
1774 return -4 ;
1775 }
1776 return -4 ; /* not ancestor */
1777 }
1778
1779 return n ; /* number of sons */
1780 } /* sessionFindSon */
1781
1782 /************************************************************/
1783
1784 static BOOL sessionKillAncestors (Array sessionTree, int n)
1785 /* Kill all father over level n */
1786 {
1787 KEY father = thisSession.upLink, son ;
1788 ST *st ;
1789 int i ;
1790
1791 for (i = 0, st = arrp(sessionTree,0,ST);
1792 i < arrayMax(sessionTree); st++, i++)
1793 if (st->key == father)
1794 break ;
1795
1796 if (father && st->key != father)
1797 {
1798 messerror ("sessionKillAncestors() - "
1799 "could not find the father he wanted to murder.") ;
1800 return FALSE ;
1801 }
1802
1803 while (st && --n) /* Move up the ladder n times */
1804 st = st->sta ;
1805 if (!st || n) /* Not many ancesters alive */
1806 return FALSE ;
1807
1808 while (st && (st->isPermanent ||
1809 st->isReadlocked ||
1810 sessionFindSon(sessionTree, st->key, &son) != 1))
1811 st = st->sta ; /* Try higher up */
1812
1813 if (st && st->key && son)
1814 return sessionFuse(st->key, son) ;
1815
1816 return FALSE ;
1817 } /* sessionKillAncestors */
1818
1819 /*************************************************************/
1820
1821 static char* getConfiguredDatabaseName (void)
1822 {
1823 static char dbname[32] = "";
1824 char *word ;
1825 ACEIN db_io = 0 ;
1826 char *filename;
1827
1828 filename = dbPathMakeFilName("wspec", "database", "wrm", 0);
1829 db_io = aceInCreateFromFile (filename, "r", "", 0);
1830 messfree(filename);
1831
1832 if (db_io);
1833 {
1834 while (aceInCard(db_io))
1835 if ((word = aceInWord(db_io))
1836 && strcmp (word, "NAME") == 0
1837 && (word = aceInWord(db_io)))
1838 {
1839 if (strlen (word) > 31)
1840 messExit ("Error in wspec/database.wrm : "
1841 "the NAME is too long (31 characters max).") ;
1842 else
1843 strcpy (dbname, word) ;
1844 }
1845 aceInDestroy (db_io) ;
1846 }
1847
1848 return &dbname[0];
1849 } /* getConfiguredDatabaseName */
1850
1851 /*************************************************************/
1852
1853 /* Set any default value overrides from wspec/database.wrm */
1854 static void getOtherDatabaseConfigs(int *keepAlive, int *timeOut,
1855 BOOL *suppressLock, BOOL *syncWrite,
1856 BOOL *enforceTs, char **db_title,
1857 BOOL *group_admin)
1858 {
1859 char *word ;
1860 ACEIN db_io = 0 ;
1861 char *filename;
1862
1863 filename = dbPathMakeFilName("wspec", "database", "wrm", 0);
1864 db_io = aceInCreateFromFile (filename, "r", "", 0);
1865 messfree(filename);
1866
1867 if (db_io)
1868 {
1869 while (aceInCard(db_io))
1870 {
1871 if ((word = aceInWord(db_io)))
1872 {
1873 if (strcmp (word, "SESSION_KEEP_ALIVE") == 0)
1874 {
1875 BOOL rc ;
1876 rc = aceInInt(db_io,keepAlive) ;
1877 if (rc == FALSE || *keepAlive < SESSKEEPALIVE_MIN)
1878 messExit ("Error in wspec/database.wrm : "
1879 "smallest legal value for SESSION_KEEP_ALIVE is %d",
1880 SESSKEEPALIVE_MIN) ;
1881 }
1882 else if (strcmp (word, "READLOCK_TIMEOUT") == 0)
1883 {
1884 BOOL rc ;
1885 rc = aceInInt(db_io,timeOut) ;
1886 if (rc == FALSE || *timeOut < RDLCKTIMEOUT_MIN)
1887 messExit ("Error in wspec/database.wrm : "
1888 "smallest legal value for READLOCK_TIMEOUT is %d hours",
1889 RDLCKTIMEOUT_MIN) ;
1890 }
1891 else if (strcmp(word, "NOLOCK") == 0)
1892 {
1893 *suppressLock = TRUE ;
1894 }
1895 else if (strcmp(word, "SYNC_WRITE") == 0)
1896 {
1897 *syncWrite = TRUE ;
1898 }
1899 else if (strcmp(word, "ENFORCE_TIMESTAMPS") == 0)
1900 {
1901 *enforceTs = TRUE;
1902 }
1903 else if (strcmp(word, "TITLE") == 0)
1904 {
1905 word = aceInPos(db_io) ;
1906 if (word && *word)
1907 *db_title = strnew(word, 0) ;
1908 }
1909 else if (strcmp(word, "GROUP_ADMIN") == 0)
1910 {
1911 *group_admin = TRUE ;
1912 }
1913 }
1914 }
1915
1916 aceInDestroy (db_io) ;
1917 }
1918
1919 return;
1920 } /* getOtherDatabaseConfigs */
1921
1922
1923 static BOOL purgeDirectory (char *directoryPath)
1924 {
1925 BOOL isError = FALSE;
1926 int n;
1927 char fullFileName[MAXPATHLEN];
1928 FilDir dirList;
1929
1930 if (!directoryPath)
1931 return FALSE;
1932
1933
1934 dirList = filDirCreate (directoryPath, 0, "w");
1935 /* list all files that we can potentially delete */
1936
1937 for (n = 0; n < filDirMax(dirList); n++)
1938 {
1939 strcpy (fullFileName, directoryPath);
1940 strcat (fullFileName, SUBDIR_DELIMITER_STR);
1941 strcat (fullFileName, filDirEntry(dirList, n));
1942
1943 if (unlink(fullFileName) == -1)
1944 isError = TRUE;
1945 }
1946
1947 messfree (dirList);
1948
1949 return isError;
1950 } /* purgeDirectory */
1951
1952 /*************************************************************/
1953
1954 static void sessionDoInit(void)
1955 {
1956 FILE *f ;
1957 int mainRelease;
1958 char *filename;
1959 char *log_msg = NULL ;
1960
1961 if ((filename = dbPathStrictFilName ("database", "ACEDB","wrm","r", 0))
1962 != NULL)
1963 {
1964 messfree(filename);
1965 /* this doesn't swap the superblock (write does) */
1966 #ifndef ACEDB5
1967 dataBaseAccessInit();
1968 diskblockread (&theSuperBlock,1) ;
1969 if (theSuperBlock.byteSexIndicator != 1)
1970 { swapData = TRUE;
1971 swapSuperBlock(&theSuperBlock);
1972 if (!getenv("ACEDB_NO_BANNER"))
1973 printf("// Database has non-native byte-order: swapping\n");
1974 }
1975 else
1976 {
1977 swapData = FALSE;
1978 }
1979
1980
1981 /* In order to stop old database code running on databases which
1982 have timestamps, we zero the mainrelease value in the superblock.
1983 Hence old code will fail the test below.
1984 For code in the know, the real mainrelease value is held elsewhere
1985 in the superblock. Note that we only implement this if
1986 ENFORCE_TIMETSTAMPS is set in database.wrm */
1987 if (theSuperBlock.mainRelease)
1988 {
1989 mainRelease = theSuperBlock.mainRelease;
1990 if (enforceTimestamps)
1991 {
1992 theSuperBlock.alternateMainRelease = mainRelease;
1993 theSuperBlock.mainRelease = 0;
1994 }
1995 }
1996 else
1997 mainRelease = theSuperBlock.alternateMainRelease;
1998
1999 #else /* ACEDB5 */
2000 aDiskAccessInit(&theSuperBlock);
2001 mainRelease = theSuperBlock.mainRelease;
2002 #endif /* ACEDB5 */
2003
2004 if (mainRelease != aceGetVersion())
2005 {
2006 if (getenv ("ACEDB_CHANGE_MAIN_RELEASE")) /* override */
2007 {
2008 #ifdef ACEDB4
2009 if (theSuperBlock.mainRelease)
2010 theSuperBlock.mainRelease = aceGetVersion() ;
2011 else
2012 theSuperBlock.alternateMainRelease = aceGetVersion();
2013 #else
2014 theSuperBlock.mainRelease = aceGetVersion() ;
2015 #endif
2016 }
2017 else
2018 messExit
2019 ("You are running %s of the code.\n"
2020 "The database was created under release %d.\n"
2021 "Either use the correct binary or upgrade the database.\n",
2022 aceGetVersionString(), theSuperBlock.mainRelease) ;
2023 }
2024 #ifdef ACEDB5
2025 thisSession.session = ++theSuperBlock.session ;
2026 #else
2027 thisSession.session = ++theSuperBlock.h.session ;
2028 #endif
2029 thisSession.gAddress = theSuperBlock.gAddress ;
2030 lexOverLoad (__lexi1,theSuperBlock.gAddress) ;
2031 lexReadGlobalTables () ;
2032
2033 if (!readlockCreateFile())
2034 fprintf (stderr,
2035 "Unable to set readlock for session %d.\n"
2036 "The database owner should run an acedb program\n"
2037 "with this new version (%s) to prepare the\n"
2038 "database for readlocks.\n",
2039 thisSession.session, aceGetVersionString());
2040
2041 return ;
2042 }
2043 /* else reinitialise the system */
2044
2045 /* Boolean forceInit_G indicates that if the main program was called with -init
2046 ** then the database is to be initialised without further prompting.
2047 */
2048 if (forceInit_G == FALSE)
2049 {
2050 if (!messQuery ("The file database/ACEDB.wrm does not exist, \n"
2051 "indicating that the database is empty.\n"
2052 " Should I re-initialise the system?"))
2053 messExit ("Database will remain uninitialized. Bye!") ;
2054 }
2055
2056 /* make sure we start the new database with a fresh log-file, do that */
2057 /* before anything else writes to the current log-file. */
2058 log_msg = hprintf(0, "Database is being rebuilt by %s - End of this logfile",
2059 getLogin(TRUE)) ;
2060 if (!acedbStartNewLogFile(FALSE, NULL, log_msg, TRUE))
2061 messExit ("Cannot start new log file for new session ! Initialization failed !") ;
2062 messfree(log_msg) ;
2063
2064 /* Only the acedb administrator is entitled to proceed
2065 * I check this by (a) getuid == geteuid
2066 * (b) checking for a password file
2067 * (c) testing that the user owns the file or
2068 * if GROUP_ADMIN = TRUE that the user is
2069 * is in the group for the password file.
2070 * (d) testing that the user is listed in that file
2071 * In the install documentation, it is stated that
2072 * passwd.wrm should be set chmod 644, but 444 is OK,
2073 * once the file is set-up
2074 */
2075 if (!I_own_the_passwd ("initialise the database") ||
2076 !sessionCheckUserName (TRUE))
2077 messExit ("Not authorized to initialize the database.\n"
2078 "Check wspec/passwd.wrm");
2079
2080
2081 if (!setWriteLock())
2082 /* RARE occurence, but this can happen if another process is also
2083 in the middle of the initialization process at the same time */
2084 messExit ("Cannot set write lock! Initialization failed!") ;
2085
2086 /****************************************************************/
2087 /****** all permissions clear, boostrap an empty database *******/
2088 /****************************************************************/
2089
2090 {
2091 char *tmp;
2092 if ((tmp = dbPathStrictFilName("database", "new", 0, "wd", 0)) != NULL)
2093 {
2094 purgeDirectory(tmp);
2095 messfree(tmp);
2096 }
2097 if ((tmp = dbPathStrictFilName("database", "touched", 0, "wd", 0)) != NULL)
2098 {
2099 purgeDirectory(tmp);
2100 messfree(tmp);
2101 }
2102 if ((tmp = dbPathStrictFilName("database", "readlocks", 0, "wd", 0)) != NULL)
2103 {
2104 purgeDirectory(tmp);
2105 messfree(tmp);
2106 }
2107 }
2108
2109 thisSession.session = 0; /* special session number to be used
2110 for this first readlock
2111 will be updated by sessionDoClose()
2112 called at the end of this function */
2113 if (!readlockCreateFile())
2114 messExit ("Unable to set readlock in database/readlocks/");
2115
2116 /****************************************************************/
2117
2118 writeAccess = TRUE ; /* implied */
2119 swapData = FALSE ; /* The database file must be in our order */
2120 thisSession.session = 1 ;
2121 strcpy (thisSession.name, "Empty_db") ;
2122 thisSession.gAddress = 0 ; /* so far */
2123 thisSession.mainCodeRelease = aceGetVersion() ;
2124 thisSession.subCodeRelease = aceGetRelease() ;
2125 thisSession.mainDataRelease = aceGetVersion() ;
2126 thisSession.subDataRelease = 0 ;
2127 thisSession.from = 0 ;
2128 thisSession.upLink = 0 ;
2129
2130 #ifndef ACEDB5
2131 theSuperBlock.h.disk = 1 ;
2132 theSuperBlock.h.nextdisk = 0 ;
2133 theSuperBlock.h.type = 'S' ;
2134 theSuperBlock.h.key = 0 ;
2135 theSuperBlock.byteSexIndicator = 1;
2136
2137 if (enforceTimestamps)
2138 {
2139 theSuperBlock.mainRelease = 0;
2140 theSuperBlock.alternateMainRelease = aceGetVersion();
2141 }
2142 else
2143 theSuperBlock.mainRelease = aceGetVersion() ;
2144 #endif
2145
2146 strcpy (theSuperBlock.dbName, getConfiguredDatabaseName());
2147
2148 /* DataBase creation */
2149 if (!dataBaseCreate())
2150 messExit ("Database Creation failed, check write permissions etc.") ;
2151
2152
2153 messdump("**********************************************************");
2154 messdump("Making a new database file and starting at session 1 again");
2155
2156 readModels ();
2157
2158 /* application specific initialisations, in quovadis.wrm */
2159 diskPrepare ();
2160
2161 sessionInitialize (); /* do this last before saving */
2162
2163 filename = dbPathMakeFilName("database", "ACEDB", "wrm", 0);
2164 if (!(f = filopen (filename, 0 , "w")))
2165 messExit ("Sorry, the operating system won't let me create %s", filename) ;
2166 fprintf (f, "Destroy this file to reinitialize the database\n") ;
2167 filclose (f) ;
2168 messfree(filename);
2169
2170 filename = dbPathStrictFilName("database", "lock", "wrm", "w", 0);
2171 f = filopen (filename, 0, "w") ;
2172 fprintf (f, "The lock file\n") ;
2173 filclose (f) ;
2174 messfree(filename);
2175
2176 readModels () ; /* second read needed to register the _VModel obj */
2177
2178 bIndexInit(BINDEX_AUTO) ;
2179 sessionDoClose () ; /* real save without sessionInitialize
2180 will also update readlock-file */
2181 } /* sessionDoInit */
2182
2183 /************************************************************/
2184
2185
2186 /* Used by status.c and display.c to get users title for the database. */
2187 /* */
2188 char *sessionDBTitle(void)
2189 {
2190 return db_title_G ;
2191 }
2192
2193
2194 char *sessionDbName (void)
2195 /* general public function */
2196 {
2197 #ifdef ACEDB4
2198 int mainRelease = theSuperBlock.mainRelease ?
2199 theSuperBlock.mainRelease : theSuperBlock.alternateMainRelease;
2200 #else
2201 int mainRelease = theSuperBlock.mainRelease;
2202 #endif
2203 /* returns the name of the database as gathered from the superblock,
2204 used for the window title and messages in data updates */
2205 if (mainRelease < 4 || theSuperBlock.subCodeRelease < 3)
2206 return 0 ; /* not implemented before 4.3 */
2207 else if (*theSuperBlock.dbName)
2208 return theSuperBlock.dbName ;
2209 else
2210 return 0 ;
2211 } /* sessionDbName */
2212
2213
2214
2215 /* Return last time/date the database was saved. */
2216 char *sessionLastSaveTime(void)
2217 {
2218 char *save_time = NULL, *cp ;
2219 KEY last_session ;
2220 OBJ obj ;
2221
2222 last_session = thisSession.upLink ;
2223
2224 if (!(obj = bsCreate(last_session)))
2225 messcrash("Unable to open last session object from its key: \"%s\"", name(last_session)) ;
2226
2227 if (!(bsGetData(obj,_Date, _Text, &cp)))
2228 messcrash("Unable to get \"Date\" from last session object: \"%s\"", name(last_session)) ;
2229 save_time = strnew(cp, 0);
2230
2231 bsDestroy(obj) ;
2232
2233 return save_time ;
2234 }
2235
2236
2237
2238 /************************************************************/
2239
2240 static void sessionSaveSessionObject(void)
2241 {
2242 /* store the Session Object */
2243 /* update the BAT block access table for thisSession */
2244 DISK d ;
2245 OBJ Session ;
2246 KEY kPlus, kMinus ;
2247 int free2, plus, minus, used, ndread,ndwrite ;
2248
2249
2250 Session = bsUpdate (thisSession.key) ;
2251 if(!Session)
2252 messcrash("Session register fails to create the session object") ;
2253
2254 if (thisSession.session == 1)
2255 bsAddTag(Session,_Permanent_session) ;
2256
2257 bsAddData(Session,_User,_Text,&thisSession.name) ;
2258
2259 if (!bsFindTag (Session, _Date)) /* don't add date twice - it changes => save loop */
2260 {
2261 bsAddTag (Session, _Date) ;
2262
2263 if (bsType (Session, _bsRight) == _Text)
2264 /* dates used to be _Text, we have to account for that */
2265 bsAddData (Session, _Date, _Text, timeShow(timeNow())) ;
2266 else
2267 /* with recent versions, the date is _DateType */
2268 /* ERRRRRMMMMM, this seems not to be true...see definition in whooks/sysclass.c */
2269 {
2270 mytime_t session_date = timeNow() ;
2271 bsAddData (Session, _Date, _DateType, &session_date) ;
2272 }
2273 }
2274
2275 if (*thisSession.title)
2276 bsAddData(Session,_Session_Title,_Text,thisSession.title) ;
2277 bsAddData(Session,_Session,_Int,&thisSession.session) ;
2278 if(thisSession.from)
2279 bsAddKey(Session,_Created_from,thisSession.from) ;
2280 if(thisSession.upLink)
2281 bsAddKey(Session,_Up_linked_to,thisSession.upLink) ;
2282
2283 thisSession.mainCodeRelease = aceGetVersion() ;
2284 thisSession.subCodeRelease = aceGetRelease() ;
2285 bsAddData(Session,_CodeRelease,
2286 _Int,&thisSession.mainCodeRelease) ;
2287 bsAddData(Session,_bsRight,
2288 _Int,&thisSession.subCodeRelease) ;
2289 bsAddData(Session,_DataRelease,
2290 _Int,&thisSession.mainDataRelease) ;
2291 bsAddData(Session,_bsRight,
2292 _Int,&thisSession.subDataRelease) ;
2293 { int v = bIndexVersion(-1) ;
2294 if (v)
2295 bsAddData(Session,_IndexVersion,
2296 _Int,&v) ;
2297 }
2298
2299 diskavail(&free2,&used,&plus,&minus,&ndread,&ndwrite) ;
2300
2301 d = lexDisk(__Global_Bat) ;
2302 bsAddData(Session,_GlobalBat,_Int,&d) ;
2303 bsAddData(Session,_bsRight,_Int,&used) ;
2304
2305 d = lexDisk(__lexi1) ;
2306 bsAddData(Session,_GlobalLex,_Int,&d) ;
2307
2308 d = lexDisk(__lexi2) ;
2309 bsAddData(Session,_SessionLex,_Int,&d) ;
2310 d = lexDisk(__lexa2) ;
2311 bsAddData(Session,_bsRight,_Int,&d) ;
2312 d = lexDisk(__voc2) ;
2313 bsAddData(Session,_bsRight,_Int,&d) ;
2314 d = lexDisk(__lexh2) ;
2315 bsAddData(Session,_bsRight,_Int,&d) ;
2316
2317 d = lexDisk(__lexi3) ;
2318 bsAddData(Session,_VocLex,_Int,&d) ;
2319 d = lexDisk(__lexa3) ;
2320 bsAddData(Session,_bsRight,_Int,&d) ;
2321 d = lexDisk(__voc3) ;
2322 bsAddData(Session,_bsRight,_Int,&d) ;
2323 d = lexDisk(__lexh3) ;
2324 bsAddData(Session,_bsRight,_Int,&d) ;
2325
2326 lexaddkey(messprintf("p-%d",thisSession.session),&kPlus,_VBat) ;
2327 lexaddkey(messprintf("m-%d",thisSession.session),&kMinus,_VBat) ;
2328 bsAddKey(Session,_BatPlus,kPlus) ;
2329 bsAddData(Session,_bsRight,_Int,&plus) ;
2330
2331 bsAddKey(Session,_BatMinus,kMinus) ;
2332 bsAddData(Session,_bsRight,_Int,&minus) ;
2333
2334 bsSave(Session) ;
2335 } /* sessionSaveSessionObject */
2336
2337 /************************************************************/
2338
2339 static void sessionSaveUserSessionObject (void)
2340 {
2341 /* complete the UserSession object */
2342 /* this might be called several times over
2343 in the process of saveAll() */
2344 OBJ obj ;
2345 KEY key, tag ;
2346 mytime_t timEnd = timeNow() ;
2347
2348 lexSessionEnd () ; /* writes new and touched keysets */
2349
2350 sessionUserKey () ;
2351 obj = bsUpdate (thisSession.userKey) ;
2352
2353 bsAddKey (obj, _Session, thisSession.key) ;
2354 bsAddData (obj, _User, _Text, thisSession.name) ;
2355
2356 /* don't change dates again, once set, to avoid causing
2357 saveAll() to think that modifications have happened
2358 in the multiple saving loop */
2359 if (!bsFindTag (obj, _Start))
2360 {
2361 if (!thisSessionStartTime)
2362 messcrash ("Can't save UserSession object "
2363 "with unititialized StartTime");
2364 bsAddData (obj, _Start, _DateType, &thisSessionStartTime) ;
2365 }
2366 if (!bsFindTag (obj, _Finish))
2367 bsAddData (obj, _Finish, _DateType, &timEnd) ;
2368
2369 if (lexword2key (messprintf ("new-%s", name(thisSession.userKey)),
2370 &key, _VKeySet))
2371 {
2372 lexaddkey ("New", &tag, 0) ;
2373 bsAddKey (obj, tag, key) ;
2374 }
2375
2376 if (lexword2key (messprintf ("touched-%s", name(thisSession.userKey)),
2377 &key, _VKeySet))
2378 {
2379 lexaddkey ("Touched", &tag, 0) ;
2380 bsAddKey (obj, tag, key) ;
2381 }
2382
2383 bsSave (obj) ;
2384 } /* sessionSaveUserSessionObject */
2385
2386 /**************************************************/
2387
2388 mytime_t sessionUserSession2Time(KEY userSession)
2389 {
2390 OBJ obj;
2391 static Associator key2time = NULL;
2392 void *v;
2393 mytime_t time;
2394
2395 if (!key2time)
2396 key2time = assCreate();
2397
2398 if (!userSession)
2399 return 0;
2400
2401 /* If the timestamp is for th current session, the data will not
2402 be in the object yet */
2403 if (userSession == sessionUserKey())
2404 return sessionStartTime();
2405
2406 if (assFind(key2time, assVoid(userSession), &v))
2407 return (mytime_t) assInt(v);
2408
2409 time = 0;
2410 if ((obj = bsCreate(userSession)))
2411 {
2412 bsGetData(obj, str2tag("Start"), _DateType, &time);
2413 bsDestroy(obj);
2414 }
2415
2416 assInsert(key2time, assVoid(userSession), assVoid(time));
2417
2418 return time;
2419 }
2420
2421 /************************************************************/
2422
2423 void sessionRegister(void)
2424 /* general public function */
2425 {
2426 /* this is called several times over during saveAll() */
2427 OBJ ModelObj ;
2428
2429 if (!isWriteAccess())
2430 return ;
2431
2432 #ifdef ACEDB4
2433 {
2434 OBJ obj1 = bsCreate (KEYMAKE (_VUserSession,0)) ;
2435 if (!obj1)
2436 {
2437 messout ("You are missing the model for UserSession. "
2438 "To bring your database up to date please Read Models. "
2439 "You will not be able to save until you do this.") ;
2440 return ;
2441 }
2442 bsDestroy (obj1) ;
2443 }
2444 #endif
2445
2446
2447 strncpy (thisSession.name, getLogin(TRUE), 78) ;
2448 lexaddkey (messprintf ("s-%d-%s",
2449 thisSession.session, thisSession.name),
2450 &thisSession.key, _VSession) ;
2451
2452 #ifdef ACEDB4
2453 ModelObj = bsCreate(KEYMAKE(_VSession,0)) ;
2454 #else
2455 { KEY ModelKey ;
2456 lexaddkey ("#Session", &ModelKey, _VModel) ;
2457 ModelObj = bsCreate(ModelKey) ;
2458 }
2459 #endif
2460
2461 if(!ModelObj || !bsFindTag(ModelObj,_Up_linked_to))
2462 /* Always check on latest tag added to ?Session */
2463 { messerror("%s\n%s\n%s\n%s\n%s\n",
2464 "FATAL, an eror occured in sessionRegister",
2465 "Probably, your model for the session class is not correct",
2466 "and corresponds to an earlier release.",
2467 "Look for the latest version of the wspec/models.wrm file,",
2468 "read the model file and try again.") ;
2469 exit(1) ;
2470 }
2471 bsDestroy(ModelObj) ;
2472
2473
2474 sessionSaveSessionObject() ;
2475
2476 sessionSaveUserSessionObject() ;
2477
2478 /* will be reset for next new session (in sessionInitialize) */
2479 thisSessionStartTime = 0 ;
2480 } /* sessionRegister */
2481
2482
2483 /*************************************************************/
2484
2485 /* returns TRUE if modifications had been saved */
2486 BOOL sessionDoClose (void)
2487 {
2488 BOOL savedSomething = FALSE ;
2489 KEY son ;
2490
2491 if (!isWriteAccess())
2492 return FALSE ;
2493
2494 /* Try to save all caches - return TRUE, if there
2495 had been modifications that were saved to disk*/
2496 if (saveAll())
2497 {
2498 /* Yes we saved modifications - adjust the session structure*/
2499
2500 /* I keep only a certain number of session alive
2501 (the sessionKeepAlive static int) */
2502 if (thisSession.session != 1)
2503 {
2504 Array sessionTree;
2505
2506 sessionTree = sessionTreeCreate (FALSE); /* exclude dead sessions */
2507
2508 if (sessionKeepAlive != 1)
2509 while (sessionKillAncestors(sessionTree, sessionKeepAlive))
2510 {
2511 sessionTreeDestroy(sessionTree);
2512 sessionTree = sessionTreeCreate (FALSE);
2513 }
2514 else if (sessionFindSon(sessionTree, thisSession.upLink, &son) == 1)
2515 sessionOedipe () ;
2516
2517 sessionTreeDestroy (sessionTree);
2518 }
2519
2520 /****************************/
2521 /* increment session number */
2522 /****************************/
2523
2524 /* if you edit this code, edit also readsuperblock
2525 and sessionDestroy */
2526 theSuperBlock.gAddress = thisSession.gAddress = lexDisk(__lexi1) ;
2527 #ifdef ACEDB4
2528 if (!theSuperBlock.mainRelease)
2529 theSuperBlock.alternateMainRelease = aceGetVersion() ;
2530 else
2531 #endif
2532 theSuperBlock.mainRelease = aceGetVersion() ;
2533 theSuperBlock.subCodeRelease = aceGetRelease() ;
2534 theSuperBlock.magic = saveMagic ;
2535 thisSession.from = thisSession.key ;
2536 thisSession.upLink = thisSession.key ;
2537 #ifdef ACEDB5
2538 theSuperBlock.session = thisSession.session ;
2539 #else
2540 theSuperBlock.h.session = thisSession.session ;
2541 #endif
2542 diskWriteSuperBlock(&theSuperBlock); /* writes and zeros the BATS*/
2543
2544 messdump ("Save session %d", thisSession.session) ;
2545
2546 thisSession.session++; /* increase current session number */
2547
2548 readlockUpdateFile (); /* update readlock
2549 for next session */
2550
2551 savedSomething = TRUE ;
2552
2553 if (sessionChangeRoutine)
2554 (*sessionChangeRoutine)();
2555 }
2556 /* else savedSomething is still FALSE */
2557
2558 sessionReleaseWriteAccess() ;
2559
2560 if (externalCommit) externalCommit() ;
2561
2562 return savedSomething ;
2563 } /* sessionDoClose */
2564
2565 /*************************************************************/
2566
2567 BOOL isWriteAccess(void)
2568 /* general public function */
2569 { return writeAccess ? TRUE : FALSE ;
2570 } /* isWriteAccess */
2571
2572 /*************************************************************/
2573
2574 /* gains write access for the user, if possible */
2575 BOOL sessionGainWriteAccess(void)
2576 {
2577 BOOL write_lock = FALSE ;
2578
2579 if (writeAccess) /* already has write access */
2580 return TRUE;
2581
2582 /* We don't have write access, but can we grab it ?? */
2583 /* The tests made are: */
2584 /* dropWriteAccess => cannot re-gain write access once permanently dropped.*/
2585 /* sessionCheckUserName() => checks wspec/passwd.wrm for user. */
2586 /* setWriteLock() => fails if we can't set a write lock, MUST do this */
2587 /* before doing sessionDatabaseWritable() otherwise */
2588 /* there is a window where another user can screw up */
2589 /* file permissions and we don't see this. */
2590 /* sessionDatabaseWritable() => check we can write files into database */
2591 /* subdir and that blockN.wrm files are R/W */
2592 if (dropWriteAccess
2593 || !sessionCheckUserName(TRUE)
2594 || !(write_lock = setWriteLock()) /* Remember if we got a lock. */
2595 || !sessionDatabaseWritable(TRUE))
2596 {
2597 if (debug)
2598 {
2599 messdump ("gainWriteAccess Failed") ;
2600 if (dropWriteAccess) messdump ("dropWriteAcces=TRUE") ;
2601 if (!sessionDatabaseWritable(TRUE)) messdump ("sessionDatabaseWritable=FALSE") ;
2602 if (!sessionCheckUserName(TRUE)) messdump ("sessionCheckUserName=FALSE") ;
2603 }
2604
2605 if (write_lock)
2606 releaseWriteLock() ;
2607
2608 return FALSE;
2609 }
2610
2611
2612 /* Cannot gain write access in an older session */
2613 if (!sessionCheckSuperBlock())
2614 {
2615 messout ("Sorry, while you where reading the database, "
2616 "another process updated it.\n"
2617 "// You can go on reading, but to write, you must "
2618 "quit and rerun.") ;
2619
2620 if (write_lock)
2621 releaseWriteLock();
2622
2623 return FALSE;
2624 }
2625
2626 /* all checks passed */
2627 writeAccess = TRUE ; /* was false before */
2628
2629 /* therefore calls the routine that gets notified of the change,
2630 this is usually to re-draw buttons or change the menus, etc */
2631 if (writeAccessChangeRoutine)
2632 (*writeAccessChangeRoutine)();
2633
2634 return TRUE;
2635 } /* sessionGainWriteAccess */
2636
2637 /*************************************************************/
2638
2639 void sessionReleaseWriteAccess (void)
2640 /* general public function */
2641 {
2642 if (isWriteAccess())
2643 {
2644 releaseWriteLock () ;
2645 writeAccess = FALSE ;
2646
2647 if (writeAccessChangeRoutine)
2648 (*writeAccessChangeRoutine)();
2649 }
2650
2651 return;
2652 } /* sessionReleaseWriteAccess */
2653
2654 /*************************************************************/
2655
2656 static BOOL sessionCheckUserName (BOOL doTalk)
2657 {
2658 #if defined(MACINTOSH)
2659
2660 extern BOOL passPrompt ( void ) ;
2661
2662 if(!passPrompt()) {
2663 messout ("Sorry, your name was not found in the password file") ;
2664 return FALSE ;
2665 }
2666 else
2667 return TRUE ;
2668
2669 #else /* !MACINTOSH */
2670 static int result = 0 ;
2671 register char *cp, *name ;
2672 Stack uStack ;
2673 ACEIN passwd_io = 0 ;
2674 char *passwd_filename;
2675
2676 /* check only once, since the userid of the process cannot change */
2677 switch (result)
2678 {
2679 case 0: result = 1 ; break ;
2680 case 1: return FALSE ;
2681 case 2: return TRUE ;
2682 }
2683
2684 #if defined (__CYGWIN__)
2685 if ( GetVersion() & 0x80000000)
2686 /* For windows 95, 98, always return TRUE, since it has no security */
2687 {
2688 result = 2;
2689 return TRUE;
2690 }
2691 #endif
2692
2693 /* Only users listed in wspec/passwd.wrm can get write access */
2694
2695 /* I cannot use cuserid, because I want the real userid and,
2696 depending on systems, cuserid may return either the real or
2697 the effective userid which is probably reset by setuid().
2698
2699 On the other hand, Unix getlogin() is replaced by local
2700 getLogin() because getlogin() returns NULL if the process
2701 is not attached to a terminal */
2702
2703 name = getLogin(TRUE) ;
2704 if (debug)
2705 {
2706 char *fname = dbPathMakeFilName("wspec","passwd","wrm",0);
2707 messdump ("getLogin=%s",name?name:"name=0") ;
2708 messdump ("wspec=%s",fname) ;
2709 messfree(fname);
2710 }
2711
2712 passwd_filename = dbPathMakeFilName("wspec", "passwd", "wrm", 0);
2713 passwd_io = aceInCreateFromFile(passwd_filename, "r", "", 0);
2714
2715 if (!passwd_io)
2716 {
2717 messout ("The database has no file wspec/passwd.wrm. To enable "
2718 "write access to the database, the usernames "
2719 "of trusted administrators have to be listed in the "
2720 "file : %s",
2721 passwd_filename);
2722 messfree(passwd_filename);
2723 return FALSE ;
2724 }
2725
2726 messfree(passwd_filename);
2727 uStack = stackCreate(32);
2728
2729 while (aceInCard (passwd_io))
2730 {
2731 aceInNext (passwd_io) ;
2732 if (!aceInStep(passwd_io,'#')) /* skip # lines */
2733 if ((cp = aceInWord(passwd_io))) /* read user name */
2734 pushText(uStack,cp) ;
2735 }
2736
2737
2738 /* Warn user that NOLOCK is no longer valid in wspec/passwd.wrm */
2739 #ifdef ACEDB5_forget_taht_mess
2740 /* within acedb4, this creates incompatibility with acedb.4_7 code */
2741 stackCursor(uStack, 0) ;
2742 while (!stackAtEnd (uStack))
2743 if (strcmp ("NOLOCK", stackNextText(uStack)) == 0)
2744 {
2745 messExit("The \"NOLOCK\" option has been found in wspec/passwd.wrm, "
2746 "this option must now be set in wspec/database.wrm. "
2747 "You should ask your database administrator to move this option "
2748 "from wspec/passwd.wrm to wspec/database.wrm and then you will "
2749 "be able to use the database. (This session will now terminate "
2750 "because running with \"NOLOCK\" set incorrectly may cause "
2751 "database integrity problems.)") ;
2752 }
2753 #endif
2754
2755 /* find our user-name amongst names in passwd.wrm */
2756 stackCursor(uStack, 0) ;
2757 while (!stackAtEnd (uStack))
2758 if (strcmp (name, stackNextText(uStack)) == 0)
2759 {
2760 stackDestroy (uStack) ;
2761 aceInDestroy (passwd_io) ;
2762 result = 2 ;
2763
2764 return TRUE ; /* found it */
2765 }
2766
2767 /* failed to find the name */
2768 if (doTalk)
2769 {
2770 if (strcmp (name, "getLoginFailed") == 0)
2771 messout ("On your particular machine, the operating system call "
2772 "\"getlogin\" failed. To circumvent this problem, you "
2773 "may uncomment the user name \"getLoginFailed\" in "
2774 "the file wspec/passwd.wrm.\n"
2775 "But from then on, everybody will have write access "
2776 "unless you set up other security measures using "
2777 "write permissions.") ;
2778 else
2779 messout ("%s is not a registered user. "
2780 "To register a user for write access add their "
2781 "login name to the file wspec/passwd.wrm", name) ;
2782 }
2783
2784 stackDestroy(uStack) ;
2785 aceInDestroy (passwd_io) ;
2786
2787 return FALSE ;
2788 #endif /* !MACINTOSH */
2789 }
2790
2791 /*************************************************************/
2792
2793 static BOOL sessionDatabaseWritable(BOOL doTalk)
2794 {
2795 BOOL result = FALSE ;
2796 FILE *f;
2797 char *name = NULL ;
2798
2799 /* first see if we can create a file in the database directory. */
2800 name = dbPathMakeFilName("database", "test", 0, 0);
2801 seteuid(euid);
2802 unlink(name);
2803 f = fopen (name, "a");
2804 if (f)
2805 fclose(f);
2806 unlink(name);
2807 seteuid(ruid);
2808 messfree(name);
2809
2810 if (!f)
2811 {
2812 if (doTalk)
2813 {
2814 name = dbPathMakeFilName("database", 0, 0, 0);
2815 messout ("Sorry, the program does not have permission to write "
2816 "files in %s", name) ;
2817 messfree(name);
2818 }
2819 result = FALSE ;
2820 }
2821 else
2822 {
2823 /* OK, now check the blockN.wrm files. */
2824 result = blocksWriteable(doTalk) ;
2825 }
2826
2827 return result ;
2828 } /* sessionDatabaseWritable */
2829
2830
2831 /* This code checks that all the blockN.wrm files specified in */
2832 /* wspec/database.wrm that actually exist in database/ are readable and */
2833 /* writeable. This check was introduced because previously users could get */
2834 /* write access without actually having write access to some block files. */
2835 /* Then when they tried to save, the database would get corrupted if they */
2836 /* needed to write to those files. */
2837 /* If report_errors is TRUE, errors are logged and an error message output, */
2838 /* otherwise the errors are just logged. */
2839 /* */
2840 static BOOL blocksWriteable(BOOL report_errors)
2841 {
2842 BOOL result ;
2843 char *config_file ;
2844 ACEIN config_in;
2845 char *cp ;
2846
2847 seteuid(euid);
2848
2849 /* If we can't find wspec/database.wrm then something is very wrong. */
2850 if (!(config_file = dbPathStrictFilName("wspec", "database", "wrm", "r", 0)))
2851 messcrash("Cannot find database configuration file wspec/database.wrm") ;
2852
2853 config_in = aceInCreateFromFile (config_file, "r", "", 0);
2854 messfree(config_file);
2855
2856 /* Look for all the block records which have the format: */
2857 /* PART : 1 local ACEDB block1.wrm 1000 0 */
2858 result = TRUE ;
2859 while (aceInCard (config_in))
2860 {
2861 char *block_name = NULL ;
2862
2863 if (!(cp = aceInWord(config_in)))
2864 continue ; /* skip empty lines and comments */
2865
2866 if (strcmp(cp, "PART") != 0) /* only do lines with PART keyword */
2867 continue ;
2868
2869 /* Fourth word is blocks file name. */
2870 aceInStep (config_in, ':') ;
2871 if (!(cp = aceInWord (config_in))
2872 || !(cp = aceInWord (config_in))
2873 || !(cp = aceInWord (config_in))
2874 || !(cp = aceInWord (config_in)))
2875 messExit("Parse error in database definition file %s at line %d",
2876 dbPathMakeFilName("wspec", "database", "wrm", 0),
2877 (aceInStreamLine(config_in) - 1)) ;
2878
2879 /* If the file exists, check to see if it is readable/writeable. */
2880 block_name = dbPathMakeFilName("database", cp, NULL, 0) ;
2881 if (access(block_name, F_OK) == 0) /* No equivalent in filsubs.c ? */
2882 {
2883 BOOL error = FALSE ;
2884 char *access = NULL ;
2885
2886 if (!filCheckName(block_name, NULL, "r"))
2887 {
2888 result = FALSE ;
2889 error = TRUE ;
2890 access = "read" ;
2891 }
2892 else if (!filCheckName(block_name, NULL, "w"))
2893 {
2894 result = FALSE ;
2895 error = TRUE ;
2896 access = "write" ;
2897 }
2898
2899 if (error)
2900 {
2901 if (report_errors)
2902 messerror("Cannot get %s access to database block file %s",
2903 access, block_name) ;
2904 else
2905 messdump("Cannot get %s access to database block file %s",
2906 access, block_name) ;
2907 }
2908
2909 }
2910 messfree(block_name) ;
2911 }
2912
2913 aceInDestroy (config_in);
2914
2915 seteuid(ruid);
2916
2917 return result ;
2918 }
2919
2920
2921 /*************************************************************/
2922
2923 /* If another process has written since I started
2924 either he has grabed the lock, and I can't write,
2925 or he may have released it but then he may have updated
2926 the disk.
2927 In this case, the session number on block 1 will be
2928 modified and I will know that my BAT is out of date
2929 */
2930
2931 BOOL sessionCheckSuperBlock(void)
2932 {
2933 int nn = 0 ;
2934 #ifndef ACEDB5
2935 BLOCK newSuperBlock ;
2936 #endif
2937
2938 /* The call to diskFlushLocalCache forces the latest version of the
2939 superblock to be read from the NFS server (for remote disks).
2940 This closes a concurrency hole which can see this function
2941 succeed because it is checking a stale, client side cached
2942 copy of the superblock. */
2943
2944 diskFlushLocalCache();
2945
2946 #ifdef ACEDB5
2947 nn = aDiskGetGlobalAdress() ;
2948 #else /* !ACEDB5 */
2949 diskblockread (&newSuperBlock,1) ;
2950
2951 if (swapData)
2952 swapSuperBlock(&newSuperBlock);
2953 nn = newSuperBlock.gAddress ;
2954 if (thisSession.gAddress != nn)
2955 {
2956 int ourSession = theSuperBlock.h.session, diskSession = newSuperBlock.h.session;
2957
2958 /* keep a record of this occurence in the logfile */
2959 messdump("FATAL ERROR cached superblock inconstistent "
2960 "with disk : ourSession=%d diskSession=%d",
2961 ourSession, diskSession);
2962 return FALSE ;
2963 }
2964 #endif
2965 return TRUE ;
2966 } /* sessionCheckSuperBlock */
2967
2968 /*************************************************************/
2969
2970 /* general public function */
2971 void sessionForbidWriteAccess (void)
2972 {
2973 /* definitive, can't re-gain write access ever again,
2974 Should we have a AllowWriteAccess function to match it ?? */
2975
2976 readlockDeleteFile(); /* read locks no longer needed */
2977 dropWriteAccess = TRUE ; /* make it permanent */
2978
2979 /* the permanent loss of write access will change the
2980 behaviour of writeAccessPosibble(), and therefor may
2981 change buttons or menus */
2982 if (writeAccessChangeRoutine)
2983 (*writeAccessChangeRoutine)();
2984
2985 return;
2986 } /* sessionForbidWriteAccess */
2987
2988 /*************************************************************/
2989
2990 BOOL writeAccessPossible(void)
2991 /* general public function */
2992 {
2993 /* return TRUE if it would be possible to gain write access */
2994 static int status = 0;
2995
2996 if (dropWriteAccess)
2997 return FALSE ;
2998 if (status)
2999 return status == 1 ? TRUE : FALSE ;
3000
3001 if (sessionDatabaseWritable(FALSE) && sessionCheckUserName(FALSE))
3002 { status = 1;
3003 return TRUE;
3004 }
3005 else
3006 { status = 2;
3007 return FALSE;
3008 }
3009 } /* writeAccessPossible */
3010
3011
3012 /**************************************************************/
3013
3014 /* Used to turn on/off saving globally, i.e. if you want to completely disable
3015 * saving, perhaps for testing purposes, you can use this call to prevent any
3016 * database saving. */
3017 void sessionSetSaveStatus(BOOL save)
3018 {
3019 saveDB_G = save ;
3020
3021 return ;
3022 }
3023
3024
3025 /**************************************************************/
3026
3027 /* Used largely in command.c by commands that need to save a session
3028 * after some operation that updates the database. */
3029 /* used also in aceserver.c */
3030 void sessionMark (BOOL doIt, int newTimeOut)
3031 {
3032 static mytime_t t = 0 , t0 = 0 ;
3033 static int dt, timeOut = -1 ;
3034
3035 t = timeNow () ;
3036 if (!t0)
3037 t0 = t ;
3038 if (newTimeOut > 0)
3039 timeOut = newTimeOut ;
3040
3041 if (isWriteAccess())
3042 {
3043 if (doIt || (timeDiffSecs (t, t0, &dt) && dt > timeOut))
3044 {
3045 messdump("Saving Session %d at %s",
3046 thisSession.session, timeShow(timeParse("now"))) ;
3047
3048 closeSession(TRUE) ;
3049
3050 messdump("Saving done %s", timeShow(timeParse("now"))) ;
3051 }
3052 }
3053 t0 = timeNow () ;
3054
3055 return;
3056 } /* sessionMark */
3057
3058
3059 /**************************************************************/
3060
3061 /* Close a database session, with or without saving current changes.
3062 *
3063 * This routine has come to be used just prior to calling exit() by acedb
3064 * applications so it closes the log. It should only be used
3065 * for "normal" exits, not for crashes.
3066 *
3067 * This is only here becaue sessionClose() calls are in a lot of places.
3068 * If they were all replaced with sessionCloseExit() it could be
3069 * removed.
3070 */
3071 void sessionClose (BOOL doSave)
3072 {
3073 sessionCloseExit(doSave, ACELOG_NORMAL_EXIT) ;
3074
3075 return ;
3076 }
3077
3078
3079 /* Close a database session, with or without saving current changes and
3080 * closes log with the given exit_type.
3081 */
3082 void sessionCloseExit(BOOL doSave, aceLogExitType exit_type)
3083 {
3084 closeSession(doSave) ;
3085
3086 acedbCloseLog(exit_type) ;
3087
3088 return ;
3089 }
3090
3091
3092 /* close and reinitialise a session, used for instance to save the database
3093 * periodically while an application is making updates.
3094 * Note that saving can be completely turned off, good for testing but
3095 * not for the faint hearted. */
3096 static void closeSession(BOOL doSave)
3097 {
3098
3099 /* Only save if the user has not turned off saving altogether. */
3100 if (saveDB_G)
3101 {
3102 sessionAutoSave(-3, 0) ; /* synchronizes autosave, without
3103 activating it */
3104 if (doSave == FALSE)
3105 {
3106 sessionReleaseWriteAccess() ;
3107 }
3108 else
3109 {
3110 if (sessionDoClose ()) /* returns TRUE if something was saved */
3111 sessionInitialize () ; /* only init if we had saved */
3112 }
3113
3114 sessionAutoSave (-4, 0) ; /* synchronizes autosave, without activating it */
3115 }
3116 else
3117 {
3118 /* Some tidying up to do even we are not saving. */
3119 sessionReleaseWriteAccess() ;
3120 }
3121
3122 return ;
3123 }
3124
3125
3126
3127 /*****************************************************************/
3128 /*****************************************************************/
3129 /******* AutoSaving package, mieg: march 2000 ********************/
3130 /*****************************************************************/
3131 /* Saves if more than timeLapse seconds elapsed since last save
3132 * or since timeZero if set
3133 * returns time since last save
3134 */
3135
3136 unsigned int sessionTimeSave (unsigned int timeLapse, int mode)
3137 {
3138 int dt = 0 ;
3139 mytime_t now = timeNow () ;
3140 BOOL debug = FALSE ;
3141 static mytime_t timeZero = 0 ;
3142
3143 switch (mode)
3144 {
3145 case 2:
3146 timeZero = now ;
3147 break ;
3148
3149 case 1:
3150 timeZero = 0 ;
3151 break ;
3152
3153 case 0:
3154 if (timeZero)
3155 timeDiffSecs (timeZero, now, &dt) ;
3156 else
3157 timeDiffSecs (thisSessionStartTime, now, &dt) ;
3158 if (isWriteAccess() &&
3159 (dt + 10 > timeLapse)) /* avoid rounding problems, and never substract on unsigned int */
3160 {
3161 messStatus ("Saving");
3162 messdump("Autosaving if %d s elapsed done, last save was %d s ago", timeLapse, dt) ;
3163 timeZero = 0 ;
3164 sessionClose (TRUE) ;
3165 sessionGainWriteAccess () ; /* grab again */
3166
3167 now = timeNow () ;
3168 messdump("Autosaving done") ;
3169 timeDiffSecs (thisSessionStartTime, now, &dt) ;
3170 }
3171 else if (debug)
3172 messdump("Autosaving if %d s elapsed not needed, last %d s ago ",
3173 timeLapse, dt) ;
3174 break ;
3175
3176 default:
3177 messcrash ("Wrong call to sessionTimeSave, mode = %d", mode) ;
3178 break ;
3179 }
3180 return dt ;
3181 }
3182
3183 /*************************************************************/
3184 /* alarm routine */
3185 static void sessionAutoSaveAlarm (int dummy)
3186 {
3187 unsigned int
3188 dt = 0, /* time since last save */
3189 dtAlarm = 0, /* delay till next alarm */
3190 s1 = sessionAutoSave (-1, 0) , /* in seconds */
3191 s2 = 0 ; /* ask value after saving */
3192 BOOL debug = FALSE ; ;
3193
3194 alarm ((unsigned int) 0) ; /* disables autosaving */
3195 if (s1 > 0)
3196 {
3197 if (debug) messdump("AutoSaveAlarm calling sessionTimeSave (%d,0)", s1, 0) ;
3198 dt = sessionTimeSave (s1, 0) ; /* save if necessary */
3199 s2 = sessionAutoSave (-2, 0) ;
3200 if (s2 > 0)
3201 {
3202 dtAlarm = s2 > dt ? s2 - dt : s2 ;
3203 if (dtAlarm < 10) dtAlarm = 10 ;
3204 signal (SIGALRM, sessionAutoSaveAlarm) ; /* self register */
3205 alarm (dtAlarm) ; /* raise alarm */
3206 if (debug)
3207 messdump ("Autosaving alarm expected in %d s", dtAlarm) ;
3208 }
3209 else if (debug)
3210 messdump ("Autosaving alarm cancelled", dtAlarm) ;
3211 }
3212 else if (debug)
3213 messdump ("Autosaving alarm cancelled", dtAlarm) ;
3214 return ;
3215 }
3216
3217 /*************************************************************/
3218 /*
3219 * sessionAutoSave (int saveInterval, int inactivityInterval)
3220 *
3221 * Example
3222 * From anywhere in the code call
3223 * sessionAutoSave (1800, 300)
3224 * As a result the system will autosave every half hour
3225 * or at the end of the first 5 minutes of innactivity
3226 * or of course on explicit user request
3227 *
3228 ************** Public calls
3229 * saveInterval > 0 : The maximal delay before a save
3230 * saveInterval = 0 : cancels
3231 * inactivityInterval : The maximal inactivity delay before a save
3232 * Activity is raised by the acedb kernel calls to bsCreate
3233 ************** Kernel calls
3234 * negative values are private to sessionAutoSave/acedb-kernel
3235 *** saveInterval = -1 : returns maximal saveTime interval
3236 *** saveInterval = -2 : returns delay till next alarm
3237 *** saveInterval = -3 : ace kernel starts saving
3238 *** saveInterval = -4 : ace kernel finished saving
3239 *** saveInterval = -8 : signals modif, called by bsUpdate
3240 *** saveInterval = -9 : signals activity, called by bsCreate
3241 ************** State
3242 *** 0: unset
3243 *** 1: saving while unset
3244 *** 2: saving while set
3245 *** 3: dead
3246 *** 4: inactif
3247 *** 5: actif
3248 ************* Algorithm
3249 * This routine is just a finite state machine, actual job done by
3250 * sessionAutoSaveAlarm which self registers in alarm() and calls
3251 * sessionTimeSave which saves if last save too old
3252 */
3253
3254 unsigned int sessionAutoSave (int saveInterval, int inactivityInterval)
3255 {
3256 static int
3257 state = 0,
3258 longDelay = 0 ,
3259 shortDelay = 0 ;
3260 int noDelay = 1 ;
3261 BOOL debug = FALSE ;
3262
3263 if (getenv ("ACEDB_NO_AUTOSAVE")) return 0 ;
3264 if (saveInterval == -9) /* record activity, called by all bsCreate */
3265 switch (state)
3266 {
3267 case 0: /* autoSave not set, ignore */
3268 case 2: /* saving while set , ignore */
3269 case 1: /* saving while unset, ignore */
3270 return 0 ;
3271 case 3: /* dead, ignore */
3272 return 3 ;
3273 case 4: /* inactif */
3274 state = 5 ; /* new activity occured */
3275 case 5: /* actif */
3276 return 5 ; /* return actif */
3277 default:
3278 messcrash ("sessionAutoSave in wrong state %d", state) ;
3279 return state ;
3280 }
3281
3282 if (saveInterval == -8) /* record modif, called by all bsUpdate */
3283 switch (state)
3284 {
3285 case 0: /* autoSave not set, ignore */
3286 case 2: /* saving while set , ignore */
3287 case 1: /* saving while unset, ignore */
3288 return 0 ;
3289 case 3: /* raise from dead */
3290 if (debug) messdump("sessionAutoSave(-8) calling sessionTimeSave (0,2)") ;
3291 sessionTimeSave (0, 2) ; /* synchronize */
3292 sessionAutoSaveAlarm (0) ;
3293 case 4: /* inactif */
3294 state = 5 ; /* new activity occured */
3295 case 5: /* actif */
3296 return 5 ; /* return actif */
3297 default:
3298 messcrash ("sessionAutoSave in wrong state %d", state) ;
3299 return state ;
3300 }
3301
3302 if (saveInterval == -1) /* gives maximal delay since previous save */
3303 switch (state)
3304 {
3305 case 0: /* autoSave not set */
3306 case 1: /* saving while unset, ignore */
3307 case 2: /* saving while set, ignore */
3308 case 3: /* dead, goto sleep */
3309 return 0 ;
3310 case 4: /* inactif, save immediately */
3311 return noDelay ;
3312 case 5: /* actif */
3313 state = 4 ; /* sets to inactif, crucial switch of whole system */
3314 return longDelay ;
3315 default:
3316 messcrash ("sessionAutoSave in wrong state %d", state) ;
3317 return state ;
3318 }
3319
3320 if (saveInterval == -2) /* gives delay till next alarm */
3321 switch (state)
3322 {
3323 case 0: /* autoSave not set */
3324 case 1: /* saving while unset, ignore */
3325 case 2: /* saving while set, ignore */
3326 case 3: /* dead, go to sleep */
3327 return 0 ;
3328 case 4: /* inactif */
3329 case 5: /* actif */
3330 return shortDelay ;
3331 default:
3332 messcrash ("sessionAutoSave in wrong state %d", state) ;
3333 return state ;
3334 }
3335
3336 if (saveInterval == -3) /* saving starts */
3337 switch (state)
3338 {
3339 case 0: /* autoSave not set */
3340 state = 1 ; /* set saving while unset */
3341 case 1: /* saving while unset, ignore */
3342 return 1 ;
3343 case 2: /* saving while set, ignore */
3344 case 3: /* dead */
3345 case 4: /* inactif */
3346 case 5: /* actif */
3347 state = 2 ;
3348 return 2 ;
3349 default:
3350 messcrash ("sessionAutoSave in wrong state %d", state) ;
3351 return state ;
3352 }
3353
3354 if (saveInterval == -4) /* saving ends */
3355 switch (state)
3356 {
3357 case 0: /* autoSave not set */
3358 return 0 ;
3359 case 1: /* saving while unset, revert to unset */
3360 state = 0 ;
3361 if (debug) messdump("sessionAutoSave(-4) calling sessionTimeSave (0,2)") ;
3362 sessionTimeSave (0, 2) ; /* synchronize */
3363 return 0 ;
3364 case 2: /* saving while set, revert to dead */
3365 case 3: /* dead */
3366 case 4: /* inactif */
3367 state = 3 ;
3368 return 3 ;
3369 case 5: /* actif */
3370 state = 3 ;
3371 if (debug) messdump("sessionAutoSave(-5) calling sessionTimeSave (0,2)") ;
3372 sessionTimeSave (0, 2) ; /* synchronize */
3373 sessionAutoSaveAlarm (0) ;
3374 return 3 ;
3375 default:
3376 messcrash ("sessionAutoSave in wrong state %d", state) ;
3377 return state ;
3378 }
3379
3380 if (saveInterval <= 0) /* zero or silly values, disables autosave */
3381 switch (state)
3382 {
3383 case 0: /* autoSave not set, ignore */
3384 case 1: /* saving while unset ignore */
3385 return 0 ;
3386 case 2: /* saving while set, unset with delay */
3387 state = 1 ;
3388 longDelay = shortDelay = 0 ;
3389 return 1 ;
3390 case 3: /* autosave set, unset */
3391 case 4:
3392 case 5:
3393 state = 0 ;
3394 longDelay = shortDelay = 0 ;
3395 sessionAutoSaveAlarm (0) ;
3396 return 1 ;
3397 default:
3398 messcrash ("sessionAutoSave in wrong state %d", state) ;
3399 return state ;
3400 }
3401
3402 /* verify parameters are reasonable */
3403 if (saveInterval <= 3 * 60)
3404 saveInterval = 180 ; /* 300 ; */
3405 if (inactivityInterval < 60)
3406 inactivityInterval = 60 ;
3407
3408 if (shortDelay != inactivityInterval ||
3409 longDelay != saveInterval)
3410 state = 0 ; /* reregistering needed */
3411
3412 if (state != 5)
3413 {
3414 state = 5 ; /* short wait needed */
3415 shortDelay = inactivityInterval ;
3416 longDelay = saveInterval ;
3417 sessionAutoSaveAlarm (0) ; /* register */
3418 }
3419
3420 return state ;
3421 }
3422
3423 /*****************************************************************/
3424 /********** AutoSaving package end *******************************/
3425 /*****************************************************************/
3426
3427 void sessionDoSave (BOOL reGainWriteAccess)
3428 /* general public function */
3429 {
3430 /* saves even if i had forgotten to take write access before,
3431 there can be no conflict, because if another user has written
3432 i won't be able to grab the write access */
3433
3434 messStatus ("Saving") ;
3435
3436 if (!isWriteAccess())
3437 sessionGainWriteAccess () ; /* try to grab it */
3438 if (isWriteAccess())
3439 {
3440 sessionClose (TRUE) ;
3441 if (reGainWriteAccess)
3442 sessionGainWriteAccess () ; /* grab again */
3443 }
3444 }
3445
3446 /*************************************************************/
3447
3448
3449 BOOL sessionSetUserSessionUser(char *user)
3450 {
3451 BOOL result ;
3452 int i ;
3453
3454 if (userSessionUser)
3455 messcrash("User session user set twice");
3456
3457 for (i = 0, result = TRUE ; (user[i]) ; i++)
3458 {
3459 if (!isalnum((int)(user[i])) && user[i] != '_')
3460 {
3461 result = FALSE ;
3462 break ;
3463 }
3464 }
3465
3466 if (result)
3467 userSessionUser = strnew(user, 0);
3468
3469 return result ;
3470 }
3471
3472 KEY sessionUserKey (void)
3473 {
3474 mytime_t savedTime;
3475
3476 /* Return zero when thisSessionStartTime is zero. This is important in two
3477 cases. a) Before a userSession has started, when eg timestamps get put
3478 on objects in some system classes. b) To avoid infinite recursion when
3479 trying to timestamp timestamps. These get zero timestamps because
3480 thisSessionStartTime is temporarily set to zero before calling lexaddkey
3481 which recursively calls sessionUserKey */
3482
3483 if (!thisSessionStartTime)
3484 return 0;
3485
3486 if (!thisSession.userKey)
3487 {
3488 /* This avoids inifinite recursion. The timestamps for the system objects
3489 created in recusive calls to sessionUserKey during the lexaddkey below
3490 will be zero. (because sessionUserKey always returns zero when
3491 thisSessionSTartTime is zero. This is OK. */
3492 savedTime = thisSessionStartTime;
3493 thisSessionStartTime = 0;
3494
3495 if (!userSessionUser)
3496 sessionSetUserSessionUser(getLogin(TRUE));
3497
3498 if (!lexaddkey (messprintf ("%s_%s",
3499 timeShow(savedTime),
3500 userSessionUser),
3501 &thisSession.userKey, _VUserSession))
3502 { /* we've had that key already, now make a unique one */
3503 int i = 0 ;
3504 while (!lexaddkey (messprintf ("%s.%d_%s",
3505 timeShow (savedTime),
3506 ++i,
3507 userSessionUser),
3508 &thisSession.userKey, _VUserSession)) ;
3509 }
3510 thisSessionStartTime = savedTime;
3511 }
3512
3513 return thisSession.userKey ;
3514 }
3515
3516 mytime_t sessionStartTime(void)
3517 {
3518 return thisSessionStartTime;
3519 }
3520 /*************************************************************/
3521 /********************* Readlock manager **********************/
3522 /*************************************************************/
3523
3524 static char readlock_filename[MAXPATHLEN] = "";
3525
3526
3527 void sessionCheckReadlock (void)
3528 /* public function called periodically to make sure that
3529 nobody else has destroyed our readlock. This
3530 may happen if a process is legitimately running for a long
3531 time (longer than readlockTimeout) and the readlocks
3532 was killed due to timeout by another process */
3533 {
3534 struct stat status ;
3535
3536 if (strlen(readlock_filename) == 0) /* don't use readlocks */
3537 return;
3538
3539 if (stat (readlock_filename, &status) != 0)
3540 /* failed to probe the file */
3541 readlockCreateFile();
3542
3543 return;
3544 } /* sessionCheckReadlock */
3545
3546
3547 /*************************************************************/
3548 /* creates the directory database/readlocks/ and gives
3549 everybody write access to it. This directory will contain
3550 lock files, that specify which sessions are being looked at,
3551 so they aren't destroyed under an old process' feet */
3552 /*************************************************************/
3553
3554 static BOOL readlockCreateDir (void)
3555 {
3556 static int readlock_status = 0; /* 0 : not tried before
3557 1 : everything OK
3558 2 : had problems, don't try again */
3559 char *readlock_dir;
3560 STORE_HANDLE handle = handleCreate();;
3561
3562 if (readlock_status != 0)
3563 return (readlock_status == 1 ? TRUE : FALSE);
3564
3565 if (dbPathStrictFilName("database", "readlocks", 0, "wd", handle))
3566 {
3567 /* a writable directory already exists */
3568 readlock_status = 1; /* no need to check again next time */
3569 handleDestroy(handle);
3570 return TRUE;
3571 }
3572
3573 readlock_dir = dbPathMakeFilName("database", "readlocks", 0, handle);
3574
3575 /* make the readlocks directory with rwxrwxrwx permissions,
3576 so that any other user can create and remove files from there */
3577 if (mkdir (readlock_dir, 0000777) == -1)
3578 {
3579 /* unsuccessful completion of command */
3580 /* This will happen, if we us this code on a database, which
3581 the administrator (the one with all the permissions) hasn't
3582 initialised yet - that would have created the directory
3583 correctly, even for users to use, that normally only have
3584 read-only permissions. */
3585
3586 /* no big error-message, we'll have to silently accept it */
3587 readlock_status = 2; /* don't try (and fail) again */
3588
3589 handleDestroy (handle);
3590 return FALSE;
3591 }
3592
3593 /* I noticed that the mkdir(2) won't assign the right permissions
3594 at all times. That may have to do with different umask(2)
3595 settings. So we explicitly change the permissions again.
3596 The chmod fails for very mysterious reasons under windows, so
3597 we skip this on that platfrom.
3598 */
3599 #ifndef __CYGWIN__
3600 if (chmod (readlock_dir, 0777) == -1)
3601 {
3602 readlock_status = 2; /* don't try (and fail) again */
3603
3604 handleDestroy (handle);
3605 return FALSE;
3606 }
3607 #endif
3608
3609 readlock_status = 1; /* everything went OK */
3610
3611 messdump ("Readlock manager : created readlocks directory %s",
3612 readlock_dir);
3613
3614
3615 handleDestroy (handle);
3616 return TRUE; /* managed to create directory alright */
3617 } /* readLockCreateDir */
3618
3619
3620
3621 /*************************************************************/
3622 /* for the given session, create the readlock file
3623 the file-name has the format <session>.<host>.<pid>
3624 and the file is in the directory database/readlocks/... */
3625 /*************************************************************/
3626 static BOOL readlockCreateFile (void)
3627 {
3628 char host_name[100];
3629 int pid;
3630 int fd;
3631 char *buffer;
3632 STORE_HANDLE handle = handleCreate();
3633
3634 if (dropWriteAccess) return TRUE;
3635
3636 if (!(readlockCreateDir()))
3637 return FALSE;
3638
3639 gethostname (host_name, 100) ;
3640 pid = getpid () ;
3641
3642 sprintf(readlock_filename, "%s/%d.%s.%d",
3643 dbPathStrictFilName("database", "readlocks", 0, "wd", handle),
3644 thisSession.session, host_name, pid);
3645 /* create the readlockfile with rw-rw-rw- permission. */
3646 /* That makes it possible for other processes to
3647 remove expired readlock files that this proces may leave behind */
3648
3649 fd = open(readlock_filename, O_RDWR | O_CREAT | O_SYNC, 0666);
3650
3651 if (fd == -1)
3652 {
3653 fprintf (stderr, "Cannot create readlock file %s (%s)",
3654 readlock_filename, messSysErrorText());
3655
3656 strcpy (readlock_filename, "");
3657 handleDestroy(handle);
3658 return FALSE;
3659 }
3660
3661 buffer = messprintf
3662 ("Readlock file to prevent destruction of "
3663 "sessions still in use by other processes\n"
3664 "Created: %s\n"
3665 "User: %s\n"
3666 "Program: %s\n"
3667 "Version: %s\n"
3668 "Linkdate: %s\n",
3669 timeShow(timeNow()),
3670 getLogin(TRUE),
3671 messGetErrorProgram(),
3672 aceGetVersionString(),
3673 aceGetLinkDateString());
3674
3675 write (fd, buffer, strlen(buffer));
3676 close (fd);
3677
3678 /* I noticed that the open(2) won't assign the right permissions
3679 at all times. That may have to do with different umask(2)
3680 settings. So we explicitly change the permissions again. */
3681 if (chmod (readlock_filename, 0666) == -1)
3682 {
3683 fprintf (stderr, "Cannot chmod readlock file %s (%s)",
3684 readlock_filename, messSysErrorText());
3685
3686 strcpy (readlock_filename, "");
3687 return FALSE;
3688 }
3689
3690 if (debug)
3691 messdump ("Readlock manager : start readlock for session %d by %s",
3692 thisSession.session, getLogin(TRUE));
3693
3694 handleDestroy(handle);
3695 return TRUE;
3696 } /* readLockCreateFile */
3697
3698 /* The window is is not known when the readlock file is created, so we
3699 append it here */
3700 void sessionReadlockAppendFileWinID(unsigned long id)
3701 {
3702
3703 FILE *f = fopen(readlock_filename, "a");
3704 if (f)
3705 {
3706 fprintf(f, "WindowID: 0x%lx\n", id);
3707 fclose(f);
3708 }
3709 }
3710 /*************************************************************/
3711 /* when you save a session, we get a new session number
3712 (in thisSession.session)
3713 so we rename the current readlock-file to contain
3714 the new session-number in the file name */
3715 /*************************************************************/
3716 static BOOL readlockUpdateFile (void)
3717 {
3718 char host_name[100];
3719 int pid;
3720 char new_filename[MAXPATHLEN] = "";
3721 STORE_HANDLE handle = handleCreate();
3722
3723 if (dropWriteAccess) return TRUE;
3724
3725 if (strlen(readlock_filename) == 0)
3726 return FALSE;
3727
3728 gethostname (host_name, 100) ;
3729 pid = getpid () ;
3730
3731 sprintf(new_filename, "%s/%d.%s.%d",
3732 dbPathStrictFilName("database", "readlocks", 0, "rd", handle),
3733 thisSession.session, host_name, pid);
3734
3735 if (rename (readlock_filename, new_filename) == -1)
3736 {
3737 if (debug)
3738 messerror ("failed to rename readlock file %s to %s (%s)",
3739 readlock_filename,
3740 new_filename,
3741 messSysErrorText());
3742
3743 /* don't know how we lost it, but we must have a new readlock */
3744 handleDestroy(handle);
3745 return readlockCreateFile();
3746 }
3747
3748 strcpy (readlock_filename, new_filename);
3749
3750 if (debug)
3751 messdump ("Readlock manager : update readlock from session %d to %d",
3752 thisSession.session-1, thisSession.session);
3753
3754 handleDestroy(handle);
3755 return TRUE;
3756 } /* readlockUpdateFile */
3757
3758 /*************************************************************/
3759 /* called when the process exists */
3760 /*************************************************************/
3761 BOOL readlockDeleteFile (void)
3762 {
3763 if (dropWriteAccess) return TRUE;
3764
3765 if (strlen(readlock_filename) == 0)
3766 return TRUE; /* OK if we haven't got a file */
3767
3768 if (unlink(readlock_filename) == -1)
3769 {
3770 if (debug)
3771 messerror ("failed to remove readlock file %s (%s)",
3772 readlock_filename,
3773 messSysErrorText());
3774 strcpy (readlock_filename, "");
3775 return FALSE;
3776 }
3777 strcpy (readlock_filename, "");
3778
3779 if (debug)
3780 messdump ("Readlock manager : end readlock for session %d",
3781 thisSession.session);
3782
3783 return TRUE;
3784 } /* readlockDeleteFile */
3785
3786
3787 /*************************************************************/
3788 /* We will create an array of session numbers that still have
3789 a valid readlock. Sessions with those numbers will then be
3790 treated with caution, because other processes are still
3791 looking at that data of those older sessions. */
3792 /*************************************************************/
3793 static Array readlockGetSessionNumbers (BOOL isReport)
3794 /* isReport == TRUE, output report about readlocked sessions
3795 * on parent window
3796 * isReport == FALSE, do output
3797 */
3798 {
3799 Array readlockedSessions;
3800 FilDir dirList = 0;
3801 char lockfile_name[MAXPATHLEN];
3802 char *cp1, *cp2, *cp3;
3803 char *dirEntry;
3804 int file_session_num;
3805 char file_host_name[100];
3806 int file_pid;
3807 int n, hourAge;
3808 char *dir_name;
3809 STORE_HANDLE handle = handleCreate();
3810
3811 if (!(readlockCreateDir()))
3812 {
3813 handleDestroy(handle);
3814 return 0; /* no readlocks being used */
3815 }
3816
3817 dir_name = dbPathStrictFilName("database", "readlocks", 0, "rd", handle);
3818
3819 if (dir_name)
3820 dirList = filDirCreate (dir_name, 0, "r");
3821
3822 if (!dirList)
3823 {
3824 /* this shouldn't really go wrong, because we've managed to
3825 open or create the directory already */
3826 messerror ("failed to open directory database/readlocks/ (%s)",
3827 messSysErrorText());
3828
3829 return 0;
3830 }
3831
3832 if (filDirMax(dirList) == 0) /* nothing is readlocked */
3833 return 0;
3834
3835 readlockedSessions = arrayCreate (filDirMax(dirList), int);
3836
3837 for (n = 0; n < filDirMax(dirList); n++)
3838 /* start at 1 to skip . entry */
3839 {
3840 dirEntry = filDirEntry(dirList, n);
3841
3842 sprintf(lockfile_name, "%s/%s",
3843 dbPathStrictFilName("database", "readlocks", 0, "rd", handle),
3844 dirEntry);
3845
3846 /* don't consider the readlock file of this process */
3847 if (strcmp (lockfile_name, readlock_filename) == 0)
3848 continue;
3849
3850 /* extract the <sessionnum>.<hostname>.<pid> parts from filename */
3851
3852 cp1 = dirEntry;
3853 /* find the first dot in the name */
3854 if (!(cp2 = strstr(cp1, "."))) continue;
3855
3856 *cp2 = 0; /* cp1 now ends at the dot */
3857 ++cp2; /* cp2 starts just after it */
3858
3859 /* find the first dot from the end */
3860 cp3 = cp2 + strlen(cp2);
3861 while (cp3 > cp2 && *cp3 != '.') --cp3;
3862
3863 if (cp3 == cp2) continue;
3864
3865 *cp3 = 0; /* cp2 now ends at the 2nd dot */
3866 ++cp3; /* cp3 starts just after */
3867
3868 if (!*cp1 || !*cp2 || !*cp3) continue;
3869
3870 if (sscanf (cp1, "%d", &file_session_num) != 1) continue;
3871 if (sscanf (cp2, "%s", file_host_name) != 1) continue;
3872 if (sscanf (cp3, "%d", &file_pid) != 1) continue;
3873
3874 hourAge = 0;
3875
3876 if (!(filAge (lockfile_name, "", 0, 0, 0, &hourAge, 0, 0)))
3877 continue; /* couldn't get age, don't consider
3878 it a valid readlock then */
3879
3880 if (hourAge < readlockTimeout) /* still locked then */
3881 {
3882 int max = arrayMax(readlockedSessions);
3883 /* get session-number from file-name */
3884 /* terminate the filename at the position of the dot
3885 then read a number from that first part of the string */
3886 array(readlockedSessions, max, int) = file_session_num;
3887
3888 if (isReport)
3889 {
3890 ACEIN readlock_io;
3891 char *readlockCreateTime = "(unknown time)";
3892 char *readlockOwner = "(unknown user)";
3893 char *readlockProgram = "(unknown program)";
3894 char *word;
3895
3896 readlock_io = aceInCreateFromFile (lockfile_name, "r", "", handle);
3897 if (readlock_io)
3898 {
3899 while (aceInCard (readlock_io))
3900 {
3901 if ((word = aceInWord(readlock_io)))
3902 {
3903 if (strcmp (word, "Created:") == 0
3904 && (word = aceInWord(readlock_io)))
3905 readlockCreateTime = strnew (word, handle);
3906 else if (strcmp (word, "User:") == 0
3907 && (word = aceInWord(readlock_io)))
3908 readlockOwner = strnew (word, handle);
3909 else if (strcmp (word, "Program:") == 0
3910 && (word = aceInWord(readlock_io)))
3911 readlockProgram = strnew (word, handle);
3912 }
3913 }
3914 }
3915
3916 /* NOTE, the session number that is actually protected
3917 * is file_session_num-1, because that's the session
3918 * the process was initialised from. */
3919 printf ("// Session %d is "
3920 "readlocked by %s since %s using %s "
3921 "(process %d on machine %s)\n",
3922 file_session_num-1,
3923 readlockOwner, readlockCreateTime,
3924 readlockProgram, file_pid, file_host_name);
3925
3926 }
3927 }
3928 else /* lock has expired */
3929 {
3930 if (unlink (lockfile_name) == 0)
3931 {
3932 /* successfully removed */
3933 if (debug)
3934 messdump
3935 ("Readlock manager : kill readlock for session %d, "
3936 " process %d on %s is older than %d hours",
3937 file_session_num, file_pid, file_host_name,
3938 readlockTimeout);
3939 }
3940 }
3941 }
3942
3943 messfree(dirList);
3944 handleDestroy(handle);
3945
3946 return readlockedSessions;
3947 } /* readlockGetSessionNumbers */
3948
3949
3950 /******************************************************************/
3951 void sessionSetforceInit(BOOL value)
3952 {
3953 forceInit_G = value;
3954 return;
3955 }
3956 /******************************************************************/
3957 /*********************** eof **************************************/