chiark / gitweb /
10ff89bb673b3021bcec2de832107ee568f1b663
[disorder] / server / disorderd.c
1 /*
2  * This file is part of DisOrder.
3  * Copyright (C) 2004-2008 Richard Kettlewell
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (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, see <http://www.gnu.org/licenses/>.
17  */
18 #include "disorder-server.h"
19
20 static ev_source *ev;
21
22 static const struct option options[] = {
23   { "help", no_argument, 0, 'h' },
24   { "version", no_argument, 0, 'V' },
25   { "config", required_argument, 0, 'c' },
26   { "debug", no_argument, 0, 'd' },
27   { "foreground", no_argument, 0, 'f' },
28   { "log", required_argument, 0, 'l' },
29   { "pidfile", required_argument, 0, 'P' },
30   { "wide-open", no_argument, 0, 'w' },
31   { "syslog", no_argument, 0, 's' },
32   { 0, 0, 0, 0 }
33 };
34
35 /* display usage message and terminate */
36 static void help(void) {
37   xprintf("Usage:\n"
38           "  disorderd [OPTIONS]\n"
39           "Options:\n"
40           "  --help, -h               Display usage message\n"
41           "  --version, -V            Display version number\n"
42           "  --config PATH, -c PATH   Set configuration file\n"
43           "  --debug, -d              Turn on debugging\n"
44           "  --foreground, -f         Do not become a daemon\n"
45           "  --syslog, -s             Log to syslog even with -f\n"
46           "  --pidfile PATH, -P PATH  Leave a pidfile\n");
47   xfclose(stdout);
48   exit(0);
49 }
50
51 /* signals ------------------------------------------------------------------ */
52
53 /* SIGHUP callback */
54 static int handle_sighup(ev_source attribute((unused)) *ev_,
55                          int attribute((unused)) sig,
56                          void attribute((unused)) *u) {
57   info("received SIGHUP");
58   reconfigure(ev, 1);
59   return 0;
60 }
61
62 /* fatal signals */
63
64 static int handle_sigint(ev_source attribute((unused)) *ev_,
65                          int attribute((unused)) sig,
66                          void attribute((unused)) *u) {
67   info("received SIGINT");
68   quit(ev);
69 }
70
71 static int handle_sigterm(ev_source attribute((unused)) *ev_,
72                           int attribute((unused)) sig,
73                           void attribute((unused)) *u) {
74   info("received SIGTERM");
75   quit(ev);
76 }
77
78 /* periodic actions --------------------------------------------------------- */
79
80 struct periodic_data {
81   void (*callback)(ev_source *);
82   int period;
83 };
84
85 static int periodic_callback(ev_source *ev_,
86                              const struct timeval attribute((unused)) *now,
87                              void *u) {
88   struct timeval w;
89   struct periodic_data *const pd = u;
90
91   pd->callback(ev_);
92   gettimeofday(&w, 0);
93   w.tv_sec += pd->period;
94   ev_timeout(ev, 0, &w, periodic_callback, pd);
95   return 0;
96 }
97
98 /** @brief Create a periodic action
99  * @param ev_ Event loop
100  * @param callback Callback function
101  * @param period Interval between calls in seconds
102  * @param immediate If true, call @p callback straight away
103  */
104 static void create_periodic(ev_source *ev_,
105                             void (*callback)(ev_source *),
106                             int period,
107                             int immediate) {
108   struct timeval w;
109   struct periodic_data *const pd = xmalloc(sizeof *pd);
110
111   pd->callback = callback;
112   pd->period = period;
113   if(immediate)
114     callback(ev_);
115   gettimeofday(&w, 0);
116   w.tv_sec += period;
117   ev_timeout(ev_, 0, &w, periodic_callback, pd);
118 }
119
120 static void periodic_rescan(ev_source *ev_) {
121   trackdb_rescan(ev_, 1/*check*/, 0, 0);
122 }
123
124 static void periodic_database_gc(ev_source attribute((unused)) *ev_) {
125   trackdb_gc();
126 }
127
128 static void periodic_volume_check(ev_source attribute((unused)) *ev_) {
129   int l, r;
130   char lb[32], rb[32];
131
132   if(!mixer_control(-1/*as configured*/, &l, &r, 0)) {
133     if(l != volume_left || r != volume_right) {
134       volume_left = l;
135       volume_right = r;
136       snprintf(lb, sizeof lb, "%d", l);
137       snprintf(rb, sizeof rb, "%d", r);
138       eventlog("volume", lb, rb, (char *)0);
139     }
140   }
141 }
142
143 static void periodic_play_check(ev_source *ev_) {
144   play(ev_);
145 }
146
147 static void periodic_add_random(ev_source *ev_) {
148   add_random_track(ev_);
149 }
150
151 /* We fix the path to include the bindir and sbindir we were installed into */
152 static void fix_path(void) {
153   char *path = getenv("PATH");
154   static char *newpath;
155   /* static or libgc collects it! */
156
157   if(!path)
158     error(0, "PATH is not set at all!");
159
160   if(*finkbindir && strcmp(finkbindir, "/"))
161     /* We appear to be a finkized mac; include fink on the path in case the
162      * tools we need are there. */
163     byte_xasprintf(&newpath, "PATH=%s:%s:%s:%s", 
164                    path, bindir, sbindir, finkbindir);
165   else
166     byte_xasprintf(&newpath, "PATH=%s:%s:%s", path, bindir, sbindir);
167   putenv(newpath);
168   info("%s", newpath); 
169 }
170
171 int main(int argc, char **argv) {
172   int n, background = 1, logsyslog = 0;
173   const char *pidfile = 0;
174
175   set_progname(argv);
176   mem_init();
177   if(!setlocale(LC_CTYPE, "")) fatal(errno, "error calling setlocale");
178   /* garbage-collect PCRE's memory */
179   pcre_malloc = xmalloc;
180   pcre_free = xfree;
181   while((n = getopt_long(argc, argv, "hVc:dfP:Ns", options, 0)) >= 0) {
182     switch(n) {
183     case 'h': help();
184     case 'V': version("disorderd");
185     case 'c': configfile = optarg; break;
186     case 'd': debugging = 1; break;
187     case 'f': background = 0; break;
188     case 'P': pidfile = optarg; break;
189     case 's': logsyslog = 1; break;
190     case 'w': wideopen = 1; break;
191     default: fatal(0, "invalid option");
192     }
193   }
194   /* go into background if necessary */
195   if(background)
196     daemonize(progname, LOG_DAEMON, pidfile);
197   else if(logsyslog) {
198     /* If we're running under some kind of daemon supervisor then we may want
199      * to log to syslog but not to go into background */
200     openlog(progname, LOG_PID, LOG_DAEMON);
201     log_default = &log_syslog;
202   }
203   info("process ID %lu", (unsigned long)getpid());
204   fix_path();
205   srand(time(0));                       /* don't start the same every time */
206   /* gcrypt initialization */
207   gcry_control(GCRYCTL_INIT_SECMEM, 1);
208   /* create event loop */
209   ev = ev_new();
210   if(ev_child_setup(ev)) fatal(0, "ev_child_setup failed");
211   /* read config */
212   if(config_read(1))
213     fatal(0, "cannot read configuration");
214   /* make sure the home directory exists and has suitable permissions */
215   make_home();
216   /* Start the speaker process (as root! - so it can choose its nice value) */
217   speaker_setup(ev);
218   /* set server nice value _after_ starting the speaker, so that they
219    * are independently niceable */
220   xnice(config->nice_server);
221   /* change user */
222   become_mortal();
223   /* make sure we're not root, whatever the config says */
224   if(getuid() == 0 || geteuid() == 0) fatal(0, "do not run as root");
225   /* open a lockfile - we only want one copy of the server to run at once. */
226   if(config->lock) {
227     const char *lockfile;
228     int lockfd;
229     struct flock lock;
230
231     lockfile = config_get_file("lock");
232     if((lockfd = open(lockfile, O_RDWR|O_CREAT, 0600)) < 0)
233       fatal(errno, "error opening %s", lockfile);
234     cloexec(lockfd);
235     memset(&lock, 0, sizeof lock);
236     lock.l_type = F_WRLCK;
237     lock.l_whence = SEEK_SET;
238     if(fcntl(lockfd, F_SETLK, &lock) < 0)
239       fatal(errno, "error locking %s", lockfile);
240   }
241   /* initialize database environment */
242   trackdb_init(TRACKDB_NORMAL_RECOVER|TRACKDB_MAY_CREATE);
243   trackdb_master(ev);
244   /* install new config (calls trackdb_open()) */
245   reconfigure(ev, 0);
246   /* pull in old users */
247   trackdb_old_users();
248   /* create a root login */
249   trackdb_create_root();
250   /* re-read config if we receive a SIGHUP */
251   if(ev_signal(ev, SIGHUP, handle_sighup, 0)) fatal(0, "ev_signal failed");
252   /* exit on SIGINT/SIGTERM */
253   if(ev_signal(ev, SIGINT, handle_sigint, 0)) fatal(0, "ev_signal failed");
254   if(ev_signal(ev, SIGTERM, handle_sigterm, 0)) fatal(0, "ev_signal failed");
255   /* ignore SIGPIPE */
256   signal(SIGPIPE, SIG_IGN);
257   /* Rescan immediately and then daily */
258   create_periodic(ev, periodic_rescan, 86400, 1/*immediate*/);
259   /* Tidy up the database once a minute */
260   create_periodic(ev, periodic_database_gc, 60, 0);
261   /* Check the volume immediately and then once a minute */
262   create_periodic(ev, periodic_volume_check, 60, 1);
263   /* Check for a playable track once a second */
264   create_periodic(ev, periodic_play_check, 1, 0);
265   /* Try adding a random track immediately and once every two seconds */
266   create_periodic(ev, periodic_add_random, 2, 1);
267   /* enter the event loop */
268   n = ev_run(ev);
269   /* if we exit the event loop, something must have gone wrong */
270   fatal(errno, "ev_run returned %d", n);
271 }
272
273 /*
274 Local Variables:
275 c-basic-offset:2
276 comment-column:40
277 fill-column:79
278 End:
279 */