#include #include #include #include extern const char *__progname; #include "system.h" #include "context.h" #include "profile.h" static int ctxfd = -1; const char context_always_flag; static void get_ctxfd(void) { if (ctxfd < 0) { const char *ctxname; ctxname = profile_relative_to(system_get_profile(),"statefile","state",system_mmdir()); ctxfd = open(ctxname,O_RDWR|O_CREAT,0600); if (ctxfd < 0) { fprintf(stderr,"%s: can't open context file %s: %s\n",__progname,ctxname,strerror(errno)); exit(1); } fcntl(ctxfd,F_SETFD,1); } } char *context_lookup(const char *tag) { PROFILE *p; const char *v; char *rv; get_ctxfd(); flock(ctxfd,LOCK_SH); lseek(ctxfd,0,SEEK_SET); p = profile_read_fd(ctxfd); flock(ctxfd,LOCK_UN); v = profile_lookup(p,tag); rv = v ? strdup(v) : 0; profile_free(p); return(rv); } int context_set(const char *tag, const char *newval, const char *oldval) { PROFILE *p; get_ctxfd(); flock(ctxfd,LOCK_EX); lseek(ctxfd,0,SEEK_SET); p = profile_read_fd(ctxfd); if (oldval != CONTEXT_ALWAYS) { const char *ov; ov = profile_lookup(p,tag); if ( (ov && !oldval) || (oldval && !ov) || (ov && oldval && strcmp(ov,oldval)) ) { profile_free(p); flock(ctxfd,LOCK_UN); return(0); } } profile_set(p,tag,newval); lseek(ctxfd,0,SEEK_SET); if ( (profile_write_fd(p,ctxfd) < 0) || (ftruncate(ctxfd,lseek(ctxfd,0,SEEK_CUR)) < 0) ) { fprintf(stderr,"%s: can't save context: %s\n",__progname,strerror(errno)); } profile_free(p); return(1); }