Initial revision 6759
[qball-mpd.git] / src / .svn / text-base / main.c.svn-base
blobddfe508b6d61ed1251ad2dd61c90b6397c8ebb95
1 /* the Music Player Daemon (MPD)
2  * Copyright (C) 2003-2007 by Warren Dukes (warren.dukes@gmail.com)
3  * This project's homepage is: http://www.musicpd.org
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 2 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  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17  */
19 #include "interface.h"
20 #include "command.h"
21 #include "playlist.h"
22 #include "directory.h"
23 #include "player.h"
24 #include "listen.h"
25 #include "conf.h"
26 #include "path.h"
27 #include "playerData.h"
28 #include "stats.h"
29 #include "sig_handlers.h"
30 #include "audio.h"
31 #include "volume.h"
32 #include "log.h"
33 #include "permission.h"
34 #include "replayGain.h"
35 #include "inputPlugin.h"
36 #include "audioOutput.h"
37 #include "inputStream.h"
38 #include "state_file.h"
39 #include "tag.h"
40 #include "tagTracker.h"
41 #include "dbUtils.h"
42 #include "../config.h"
43 #include "utils.h"
44 #include "normalize.h"
45 #include "zeroconf.h"
47 #include <stdio.h>
48 #include <sys/select.h>
49 #include <sys/types.h>
50 #include <sys/wait.h>
51 #include <sys/stat.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <errno.h>
55 #include <fcntl.h>
56 #include <pwd.h>
57 #include <grp.h>
58 #include <time.h>
59 #include <unistd.h>
61 #define SYSTEM_CONFIG_FILE_LOCATION     "/etc/mpd.conf"
62 #define USER_CONFIG_FILE_LOCATION       "/.mpdconf"
64 typedef struct _Options {
65         int kill;
66         int daemon;
67         int stdOutput;
68         int createDB;
69         int verbose;
70 } Options;
72 /* 
73  * from git-1.3.0, needed for solaris
74  */
75 #ifndef HAVE_SETENV
76 static int setenv(const char *name, const char *value, int replace)
78         int out;
79         size_t namelen, valuelen;
80         char *envstr;
82         if (!name || !value)
83                 return -1;
84         if (!replace) {
85                 char *oldval = NULL;
86                 oldval = getenv(name);
87                 if (oldval)
88                         return 0;
89         }
91         namelen = strlen(name);
92         valuelen = strlen(value);
93         envstr = xmalloc((namelen + valuelen + 2));
94         if (!envstr)
95                 return -1;
97         memcpy(envstr, name, namelen);
98         envstr[namelen] = '=';
99         memcpy(envstr + namelen + 1, value, valuelen);
100         envstr[namelen + valuelen + 1] = 0;
102         out = putenv(envstr);
103         /* putenv(3) makes the argument string part of the environment,
104          * and changing that string modifies the environment --- which
105          * means we do not own that storage anymore.  Do not free
106          * envstr.
107          */
109         return out;
111 #endif /* HAVE_SETENV */
113 static void usage(char *argv[])
115         ERROR("usage:\n");
116         ERROR("   %s [options] <conf file>\n", argv[0]);
117         ERROR("   %s [options]   (searches for ~%s then %s)\n",
118               argv[0], USER_CONFIG_FILE_LOCATION, SYSTEM_CONFIG_FILE_LOCATION);
119         ERROR("\n");
120         ERROR("options:\n");
121         ERROR("   --help             this usage statement\n");
122         ERROR("   --kill             kill the currently running mpd session\n");
123         ERROR
124             ("   --create-db        force (re)creation of database and exit\n");
125         ERROR
126             ("   --no-create-db     don't create database, even if it doesn't exist\n");
127         ERROR("   --no-daemon        don't detach from console\n");
128         ERROR("   --stdout           print messages to stdout and stderr\n");
129         ERROR("   --verbose          verbose logging\n");
130         ERROR("   --version          prints version information\n");
133 static void version(void)
135         LOG("mpd (MPD: Music Player Daemon) %s\n", VERSION);
136         LOG("\n");
137         LOG("Copyright (C) 2003-2007 Warren Dukes <warren.dukes@gmail.com>\n");
138         LOG("This is free software; see the source for copying conditions.  There is NO\n");
139         LOG("warranty; not even MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n");
140         LOG("\n");
141         LOG("Supported formats:\n");
143         initInputPlugins();
144         printAllInputPluginSuffixes(stdout);
146         LOG("\n");
147         LOG("Supported outputs:\n");
148         loadAudioDrivers();
149         printAllOutputPluginTypes(stdout);
152 static void parseOptions(int argc, char **argv, Options * options)
154         int argcLeft = argc;
156         options->verbose = 0;
157         options->daemon = 1;
158         options->stdOutput = 0;
159         options->createDB = 0;
160         options->kill = 0;
162         if (argc > 1) {
163                 int i = 1;
164                 while (i < argc) {
165                         if (strncmp(argv[i], "--", 2) == 0) {
166                                 if (strcmp(argv[i], "--help") == 0) {
167                                         usage(argv);
168                                         exit(EXIT_SUCCESS);
169                                 } else if (strcmp(argv[i], "--kill") == 0) {
170                                         options->kill++;
171                                         argcLeft--;
172                                 } else if (strcmp(argv[i], "--no-daemon") == 0) {
173                                         options->daemon = 0;
174                                         argcLeft--;
175                                 } else if (strcmp(argv[i], "--stdout") == 0) {
176                                         options->stdOutput = 1;
177                                         argcLeft--;
178                                 } else if (strcmp(argv[i], "--create-db") == 0) {
179                                         options->stdOutput = 1;
180                                         options->createDB = 1;
181                                         argcLeft--;
182                                 } else if (strcmp(argv[i], "--no-create-db") ==
183                                            0) {
184                                         options->createDB = -1;
185                                         argcLeft--;
186                                 } else if (strcmp(argv[i], "--verbose") == 0) {
187                                         options->verbose = 1;
188                                         argcLeft--;
189                                 } else if (strcmp(argv[i], "--version") == 0) {
190                                         version();
191                                         exit(EXIT_SUCCESS);
192                                 } else {
193                                         fprintf(stderr,
194                                                   "unknown command line option: %s\n",
195                                                   argv[i]);
196                                         exit(EXIT_FAILURE);
197                                 }
198                         } else
199                                 break;
200                         i++;
201                 }
202         }
204         if (argcLeft <= 2) {
205                 if (argcLeft == 2) {
206                         readConf(argv[argc - 1]);
207                         return;
208                 } else if (argcLeft == 1) {
209                         struct stat st;
210                         char *homedir = getenv("HOME");
211                         char userfile[MAXPATHLEN + 1] = "";
212                         if (homedir && (strlen(homedir) +
213                                         strlen(USER_CONFIG_FILE_LOCATION)) <
214                             MAXPATHLEN) {
215                                 strcpy(userfile, homedir);
216                                 strcat(userfile, USER_CONFIG_FILE_LOCATION);
217                         }
218                         if (strlen(userfile) && (0 == stat(userfile, &st))) {
219                                 readConf(userfile);
220                                 return;
221                         } else if (0 == stat(SYSTEM_CONFIG_FILE_LOCATION, &st)) {
222                                 readConf(SYSTEM_CONFIG_FILE_LOCATION);
223                                 return;
224                         }
225                 }
226         }
228         usage(argv);
229         exit(EXIT_FAILURE);
232 static void closeAllFDs(void)
234         int i;
235         int fds = getdtablesize();
237         for (i = 3; i < fds; i++)
238                 close(i);
241 static void changeToUser(void)
243         ConfigParam *param = getConfigParam(CONF_USER);
245         if (param && strlen(param->value)) {
246                 /* get uid */
247                 struct passwd *userpwd;
248                 if ((userpwd = getpwnam(param->value)) == NULL) {
249                         FATAL("no such user \"%s\" at line %i\n", param->value,
250                               param->line);
251                 }
253                 if (setgid(userpwd->pw_gid) == -1) {
254                         FATAL("cannot setgid for user \"%s\" at line %i: %s\n",
255                               param->value, param->line, strerror(errno));
256                 }
257 #ifdef _BSD_SOURCE
258                 /* init suplementary groups 
259                  * (must be done before we change our uid)
260                  */
261                 if (initgroups(param->value, userpwd->pw_gid) == -1) {
262                         WARNING("cannot init supplementary groups "
263                                 "of user \"%s\" at line %i: %s\n",
264                                 param->value, param->line, strerror(errno));
265                 }
266 #endif
268                 /* set uid */
269                 if (setuid(userpwd->pw_uid) == -1) {
270                         FATAL("cannot change to uid of user "
271                               "\"%s\" at line %i: %s\n",
272                               param->value, param->line, strerror(errno));
273                 }
275                 /* this is needed by libs such as arts */
276                 if (userpwd->pw_dir) {
277                         setenv("HOME", userpwd->pw_dir, 1);
278                 }
279         }
282 static void openDB(Options * options, char *argv0)
284         if (options->createDB > 0 || readDirectoryDB() < 0) {
285                 if (options->createDB < 0) {
286                         FATAL("can't open db file and using "
287                               "\"--no-create-db\" command line option\n"
288                               "try running \"%s --create-db\"\n", argv0);
289                 }
290                 flushWarningLog();
291                 if (checkDirectoryDB() < 0)
292                         exit(EXIT_FAILURE);
293                 initMp3Directory();
294                 if (writeDirectoryDB() < 0)
295                         exit(EXIT_FAILURE);
296                 if (options->createDB)
297                         exit(EXIT_SUCCESS);
298         }
301 static void daemonize(Options * options)
303         FILE *fp = NULL;
304         ConfigParam *pidFileParam = parseConfigFilePath(CONF_PID_FILE, 0);
306         if (pidFileParam) {
307                 /* do this before daemon'izing so we can fail gracefully if we can't
308                  * write to the pid file */
309                 DEBUG("opening pid file\n");
310                 fp = fopen(pidFileParam->value, "w+");
311                 if (!fp) {
312                         FATAL("could not open %s \"%s\" (at line %i) for writing: %s\n",
313                              CONF_PID_FILE, pidFileParam->value,
314                              pidFileParam->line, strerror(errno));
315                 }
316         }
318         if (options->daemon) {
319                 int pid;
321                 fflush(NULL);
322                 pid = fork();
323                 if (pid > 0)
324                         _exit(EXIT_SUCCESS);
325                 else if (pid < 0) {
326                         FATAL("problems fork'ing for daemon!\n");
327                 }
329                 if (chdir("/") < 0) {
330                         FATAL("problems changing to root directory\n");
331                 }
333                 if (setsid() < 0) {
334                         FATAL("problems setsid'ing\n");
335                 }
337                 fflush(NULL);
338                 pid = fork();
339                 if (pid > 0)
340                         _exit(EXIT_SUCCESS);
341                 else if (pid < 0) {
342                         FATAL("problems fork'ing for daemon!\n");
343                 }
345                 DEBUG("daemonized!\n");
346         }
348         if (pidFileParam) {
349                 DEBUG("writing pid file\n");
350                 fprintf(fp, "%lu\n", (unsigned long)getpid());
351                 fclose(fp);
352         }
355 static void cleanUpPidFile(void)
357         ConfigParam *pidFileParam = parseConfigFilePath(CONF_PID_FILE, 0);
359         if (!pidFileParam)
360                 return;
362         DEBUG("cleaning up pid file\n");
364         unlink(pidFileParam->value);
367 static void killFromPidFile(char *cmd, int killOption)
369         FILE *fp;
370         ConfigParam *pidFileParam = parseConfigFilePath(CONF_PID_FILE, 0);
371         int pid;
373         if (!pidFileParam) {
374                 FATAL("no pid_file specified in the config file\n");
375         }
377         fp = fopen(pidFileParam->value, "r");
378         if (!fp) {
379                 FATAL("unable to open %s \"%s\": %s\n",
380                       CONF_PID_FILE, pidFileParam->value, strerror(errno));
381         }
382         if (fscanf(fp, "%i", &pid) != 1) {
383                 FATAL("unable to read the pid from file \"%s\"\n",
384                       pidFileParam->value);
385         }
386         fclose(fp);
388         if (kill(pid, SIGTERM)) {
389                 FATAL("unable to kill proccess %i: %s\n", pid, strerror(errno));
390         }
391         exit(EXIT_SUCCESS);
394 int main(int argc, char *argv[])
396         Options options;
397         clock_t start;
399         closeAllFDs();
401         initConf();
403         parseOptions(argc, argv, &options);
405         if (options.kill)
406                 killFromPidFile(argv[0], options.kill);
408         initStats();
409         initTagConfig();
410         initLog(options.verbose);
412         if (options.createDB <= 0)
413                 listenOnPort();
415         changeToUser();
417         open_log_files(options.stdOutput);
419         initPaths();
420         initPermissions();
421         initPlaylist();
422         initInputPlugins();
424         openDB(&options, argv[0]);
426         initCommands();
427         initPlayerData();
428         initAudioConfig();
429         initAudioDriver();
430         initVolume();
431         initInterfaces();
432         initReplayGainState();
433         initNormalization();
434         initInputStream();
436         daemonize(&options);
438         setup_log_output(options.stdOutput);
440         initSigHandlers();
442         initZeroconf();
444         openVolumeDevice();
445         read_state_file();
447         while (COMMAND_RETURN_KILL != doIOForInterfaces()) {
448                 if (COMMAND_RETURN_KILL == handlePendingSignals())
449                         break;
450                 syncPlayerAndPlaylist();
451                 closeOldInterfaces();
452                 readDirectoryDBIfUpdateIsFinished();
453         }
455         write_state_file();
456         playerKill();
457         finishZeroconf();
458         freeAllInterfaces();
459         closeAllListenSockets();
460         finishPlaylist();
462         start = clock();
463         closeMp3Directory();
464         DEBUG("closeMp3Directory took %f seconds\n", 
465               ((float)(clock()-start))/CLOCKS_PER_SEC);
467         finishNormalization();
468         finishAudioDriver();
469         finishAudioConfig();
470         finishVolume();
471         finishPaths();
472         finishPermissions();
473         finishCommands();
474         finishInputPlugins();
475         cleanUpPidFile();
476         finishConf();
477         freePlayerData();
479         close_log_files();
480         return EXIT_SUCCESS;