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