Example #1
0
File: rea.c Project: eavgerinos/rea
void setup_and_listen(char *port)
{
	int status, fd;
	struct addrinfo hints;
	struct addrinfo *ai;

	server = (struct Server *)malloc(sizeof(struct Server));
	if (!server) {
		fprintf(stderr, "Couldn't allocate memory for starting the server\n");
		exit(EXIT_FAILURE);
	}

	memset(&hints, 0, sizeof(hints));
	hints.ai_family = AF_INET; /* Only IPv4 for now */
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags = AI_PASSIVE; /* Listen on all network addresses */

	if ((status = getaddrinfo(NULL, port, &hints, &ai)) != 0) {
		fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
		exit(EXIT_FAILURE);
	}

	/*
	 * Normally only a single protocol exists to support a particular
	 * socket [type, protocol family] combination, so we can skip specifying it
	 */
	fd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
	if (fd < 0) {
		err(EXIT_FAILURE, "Socket creation error");
	}

	status = bind(fd, ai->ai_addr, ai->ai_addrlen);
	if (status != 0) {
		err(EXIT_FAILURE, "Socket bind error");
	}

	status = listen(fd, RECV_BACKLOG);
	if (status != 0) {
		err(EXIT_FAILURE, "Socket listen error");
	}

	server->fd = fd;
	server->addr = ai;

	setup_sighandlers();

	printf("Listening on 0.0.0.0:%s ...\n", port);
}
Example #2
0
int main(int argc, char **argv)
{
	int i;
   setvbuf(stdout, NULL, _IOLBF, 0);

	setup_sighandlers();

    // check wiringPi setup
    if (wiringPiSetup() == -1)
    {
        printf("wiringPi-Error\n");
        exit(1);
    }

    // init and clear lcd
    pinMode(_bk, OUTPUT);
    digitalWrite(_bk, HIGH);

	unlink(DEVFILE);
	if (mkfifo(DEVFILE, 0666) < 0)
		fatal("dispd: Failed to create %s: %m\n", DEVFILE);
	if (chmod(DEVFILE, 0666) < 0)
		fatal("didpd: Failed to set permissions on %s: %m\n", DEVFILE);

	//if (daemon(0,1) < 0)
	//	fatal("dispd: Failed to daemonize process: %m\n");

    LCDInit(_sclk, _din, _dc, _cs, _rst, contrast);
    LCDclear();
    LCDshowLogo();
    delay(2000);

	go_go_go();

	return 0;
}
Example #3
0
File: when.c Project: ca98am79/when
int
main(int argc, char **argv)
{
  char ch;

  if (argc > 1) {
    while ((ch = getopt(argc, argv, "hn:tvz")) != -1) {
      switch (ch) {
      case 'h':
        usage(argc, argv);
        _exit(EXIT_SUCCESS);
      case 'n':
        alarm_time = atoi(optarg);
        break;
      case 't':
        success_when_timebomb = 1;
        break;
      case 'v':
        printf("%s\n", VERSION);
        _exit(EXIT_SUCCESS);
      case 'V':
        verbose = 1;
        break;
      case 'z':
        success_when_zero = 1;
        break;
      default:
        usage(argc, argv);
        _exit(EXIT_FAILURE);
      }
    }

    if (success_when_timebomb && success_when_zero) {
      fprintf(stderr, "ERROR: can't use both timebomb and zero mode\n");
      usage(argc, argv);
      return 1;
    }

    setup_sighandlers();

    if ((argc - optind) == 2) {
      argv += optind;

      execargs[2] = strdup(argv[0]);
      if (success_when_timebomb) {
        run_timebomb();
      }
      else {
        run_zero();
      }

      if (current_state == FINISHED || current_state == ALARM) {
        execargs[2] = strdup(argv[1]);
        finish();
        _exit(EXIT_SUCCESS);
      }
    }
  }

  usage(argc, argv);
  return 0;
}
Example #4
0
int
main(int argc, char **argv)
{
	parseargs(argc, argv);
	mbox.handle = mbox_open();
	if (mbox.handle < 0)
		fatal("Failed to open mailbox\n");
	unsigned mbox_board_rev = get_board_revision(mbox.handle);
	printf("MBox Board Revision: %#x\n", mbox_board_rev);
	get_model(mbox_board_rev);
	unsigned mbox_dma_channels = get_dma_channels(mbox.handle);
	printf("DMA Channels Info: %#x, using DMA Channel: %d\n", mbox_dma_channels, DMA_CHAN_NUM);

	printf("Using hardware:                 %5s\n", delay_hw == DELAY_VIA_PWM ? "PWM" : "PCM");
	printf("Number of channels:             %5d\n", (int)num_channels);
	printf("PWM frequency:               %5d Hz\n", 1000000/CYCLE_TIME_US);
	printf("PWM steps:                      %5d\n", NUM_SAMPLES);
	printf("Maximum period (100  %%):      %5dus\n", CYCLE_TIME_US);
	printf("Minimum period (%1.3f%%):      %5dus\n", 100.0*SAMPLE_US / CYCLE_TIME_US, SAMPLE_US);
	printf("DMA Base:                  %#010x\n", DMA_BASE);

	setup_sighandlers();

	/* map the registers for all DMA Channels */
	dma_virt_base = map_peripheral(DMA_BASE, (DMA_CHAN_SIZE * (DMA_CHAN_MAX + 1)));
	/* set dma_reg to point to the DMA Channel we are using */
	dma_reg = dma_virt_base + DMA_CHAN_NUM * (DMA_CHAN_SIZE / sizeof(dma_reg));
	pwm_reg = map_peripheral(PWM_BASE, PWM_LEN);
	pcm_reg = map_peripheral(PCM_BASE, PCM_LEN);
	clk_reg = map_peripheral(CLK_BASE, CLK_LEN);
	gpio_reg = map_peripheral(GPIO_BASE, GPIO_LEN);

	/* Use the mailbox interface to the VC to ask for physical memory */
	mbox.mem_ref = mem_alloc(mbox.handle, NUM_PAGES * PAGE_SIZE, PAGE_SIZE, mem_flag);
	/* TODO: How do we know that succeeded? */
	dprintf("mem_ref %u\n", mbox.mem_ref);
	mbox.bus_addr = mem_lock(mbox.handle, mbox.mem_ref);
	dprintf("bus_addr = %#x\n", mbox.bus_addr);
	mbox.virt_addr = mapmem(BUS_TO_PHYS(mbox.bus_addr), NUM_PAGES * PAGE_SIZE);
	dprintf("virt_addr %p\n", mbox.virt_addr);

	if ((unsigned long)mbox.virt_addr & (PAGE_SIZE-1))
		fatal("pi-blaster: Virtual address is not page aligned\n");

	/* we are done with the mbox */
	mbox_close(mbox.handle);
	mbox.handle = -1;
	
	//fatal("TempFatal\n");

	init_ctrl_data();
	init_hardware();
	init_channel_pwm();
	// Init pin2gpio array with 0/false values to avoid locking all of them as PWM.
	init_pin2gpio();
	// Only calls update_pwm after ctrl_data calculates the pin mask to unlock all pins on start.
	init_pwm();
	unlink(DEVFILE);
	if (mkfifo(DEVFILE, 0666) < 0)
		fatal("pi-blaster: Failed to create %s: %m\n", DEVFILE);
	if (chmod(DEVFILE, 0666) < 0)
		fatal("pi-blaster: Failed to set permissions on %s: %m\n", DEVFILE);

	printf("Initialised, ");
	if (daemonize) {
		if (daemon(0,1) < 0) 
			fatal("pi-blaster: Failed to daemonize process: %m\n");
		else
			printf("Daemonized, ");
	}
	printf("Reading %s.\n", DEVFILE);

	go_go_go();

	return 0;
}
Example #5
0
int connect_daemon(int argc, char *argv[], int ppid) {
    int uid = getuid();
    int ptmx = -1;
    char pts_slave[PATH_MAX];

    struct sockaddr_un sun;

    // Open a socket to the daemon
    int socketfd = socket(AF_LOCAL, SOCK_STREAM, 0);
    if (socketfd < 0) {
        PLOGE("socket");
        exit(-1);
    }
    if (fcntl(socketfd, F_SETFD, FD_CLOEXEC)) {
        PLOGE("fcntl FD_CLOEXEC");
        exit(-1);
    }

    memset(&sun, 0, sizeof(sun));
    sun.sun_family = AF_LOCAL;
    sprintf(sun.sun_path, "%s/server", REQUESTOR_DAEMON_PATH);

    memset(sun.sun_path, 0, sizeof(sun.sun_path));
    memcpy(sun.sun_path, "\0" "SUPERUSER", strlen("SUPERUSER") + 1);

    if (0 != connect(socketfd, (struct sockaddr*)&sun, sizeof(sun))) {
        PLOGE("connect");
        exit(-1);
    }

    LOGD("connecting client %d", getpid());

    int mount_storage = getenv("MOUNT_EMULATED_STORAGE") != NULL;

    // Determine which one of our streams are attached to a TTY
    int atty = 0;

    // Send TTYs directly (instead of proxying with a PTY) if
    // the SUPERUSER_SEND_TTY environment variable is set.
    if (getenv("SUPERUSER_SEND_TTY") == NULL) {
        if (isatty(STDIN_FILENO))  atty |= ATTY_IN;
        if (isatty(STDOUT_FILENO)) atty |= ATTY_OUT;
        if (isatty(STDERR_FILENO)) atty |= ATTY_ERR;
    }

    if (atty) {
        // We need a PTY. Get one.
        ptmx = pts_open(pts_slave, sizeof(pts_slave));
        if (ptmx < 0) {
            PLOGE("pts_open");
            exit(-1);
        }
    } else {
        pts_slave[0] = '\0';
    }

    // Send some info to the daemon, starting with our PID
    write_int(socketfd, getpid());
    // Send the slave path to the daemon
    // (This is "" if we're not using PTYs)
    write_string(socketfd, pts_slave);
    // User ID
    write_int(socketfd, uid);
    // Parent PID
    write_int(socketfd, ppid);
    write_int(socketfd, mount_storage);

    // Send stdin
    if (atty & ATTY_IN) {
        // Using PTY
        send_fd(socketfd, -1);
    } else {
        send_fd(socketfd, STDIN_FILENO);
    }

    // Send stdout
    if (atty & ATTY_OUT) {
        // Forward SIGWINCH
        watch_sigwinch_async(STDOUT_FILENO, ptmx);

        // Using PTY
        send_fd(socketfd, -1);
    } else {
        send_fd(socketfd, STDOUT_FILENO);
    }

    // Send stderr
    if (atty & ATTY_ERR) {
        // Using PTY
        send_fd(socketfd, -1);
    } else {
        send_fd(socketfd, STDERR_FILENO);
    }

    // Number of command line arguments
    write_int(socketfd, mount_storage ? argc - 1 : argc);

    // Command line arguments
    int i;
    for (i = 0; i < argc; i++) {
        if (i == 1 && mount_storage) {
            continue;
        }
        write_string(socketfd, argv[i]);
    }

    // Wait for acknowledgement from daemon
    read_int(socketfd);

    if (atty & ATTY_IN) {
        setup_sighandlers();
        pump_stdin_async(ptmx);
    }
    if (atty & ATTY_OUT) {
        pump_stdout_blocking(ptmx);
    }

    // Get the exit code
    int code = read_int(socketfd);
    close(socketfd);
    LOGD("client exited %d", code);

    return code;
}
Example #6
0
int run_watchdog (int pids[], int num_pids, char* port, char* email_address, char* mail_server) {
	signal (SIGPIPE, SIG_IGN);

	pid_t pid = fork();
	if (pid < 0) {
		PERR ("fork");
		exit (EXIT_FAILURE);
	}

	if (pid == 0) {

		umask(0);

		openlog ("SPROCKETS_WATCHDOG", LOG_CONS, LOG_DAEMON);

		pid_t sid = setsid();
		if (sid < 0) {
			PMSG ("Sprockets watchdog failed to setsid. Exiting now.\n");
			exit (EXIT_FAILURE);
		}

		if ((chdir("/")) < 0) {
			PMSG ("Sprockets watchdog failed to chdir. Exiting now.\n");
			exit (EXIT_FAILURE);
		}

		int sigs[] = { SIGINT, SIGQUIT, SIGHUP, SIGCHLD };
		int sfd = setup_sighandlers (sigs, 3);
		if (sfd == 0) {
			PMSG ("Sprockets watchdog failed to set sighandlers. Exiting now.\n");
			exit (EXIT_FAILURE);
		}

		int epfd = init_epoll (sfd);
		if (epfd == 0) {
			PMSG ("Sprockets watchdog failed to initialize epoll. Exiting now.\n");
			exit (EXIT_FAILURE);
		}

		int server_fd = NULL;
		if (port != NULL) {
			server_fd = sprocket_tcp_server (port, NULL);
			if (server_fd == 0) {
				PMSG ("Couldn't start watchdog server\n");
			       	exit (EXIT_FAILURE);	
			}

			if (add_fd_to_epoll (epfd, server_fd) == 0) {
				PERR ("Couldn't add watchdog server to epoll\n");
			       	exit (EXIT_FAILURE);	
			}
		}

		close(STDIN_FILENO);
		close(STDOUT_FILENO);
		close(STDERR_FILENO);

		syslog (LOG_NOTICE, "Sprockets watchdog successfully started\n");



				
		int paused_for_signal = 0;
		char* stats = NULL;
		auto_string* stat_buffer = NULL;
		pthread_mutex_t stats_mutex;
		pthread_mutex_init(&stats_mutex, NULL);

		auto_array* thread_array = auto_array_create (10);
		if (thread_array == NULL) {
			syslog (LOG_CRIT, "Unable to create thread array - out of memory");
			exit (EXIT_FAILURE);
		}


		while (1) {
			struct epoll_event events[MAX_EPOLL_EVENTS];
			int num_fd = epoll_wait(epfd, events, MAX_EPOLL_EVENTS, 500);

			if (num_fd == -1) {
				if (errno == EINTR) {
					syslog (LOG_NOTICE, "epoll_wait interrupted. Continuing\n");
					continue;
				}

				syslog (LOG_CRIT, "epoll_wait error: %s\n", strerror (errno)); 
				exit (EXIT_FAILURE);
			}

			if (num_fd != 0) { // no fds  timeout occurred
				for (int i = 0; i < num_fd; ++i) {
					if (events[i].data.fd == sfd) { // caught signal
						struct signalfd_siginfo fdsi;

 						int s = read (sfd, &fdsi, sizeof fdsi);
               					if (s != sizeof fdsi) {
							syslog (LOG_CRIT, "Read signal error: %s\n", strerror (errno));
							continue;
						}

						switch (fdsi.ssi_signo) {
							case SIGINT:
								syslog (LOG_NOTICE, "Caught SIGINT - pausing\n");
								paused_for_signal = 1;
								break;	
							case SIGQUIT:
								syslog (LOG_NOTICE, "Caught SIGQUIT - exiting\n");
								for (int ii = 0; ii < num_pids; ++ii) {
									if (pids[ii] != 0) { 
										kill (pids[ii], SIGTERM);
									}
								}

								for (int ii = 0; ii < thread_array->count; ++ii) {
									watchdog_thread* wt = auto_array_get (thread_array, ii);
									char ex[2] = "EX";
									write (wt->pipe_write, ex, 2);

								       	auto_array_delete (thread_array, free);	
								}

								exit (EXIT_SUCCESS);
							case SIGHUP:
								syslog (LOG_NOTICE, "Caught SIGHUP\n");
								paused_for_signal = 0;
								break;
							case SIGCHLD:
								syslog (LOG_NOTICE, "Caught SIGCHLD\n");
								break;
							default:
								syslog (LOG_NOTICE, "Caught unknown signal\n");
								break;
						}
	       				} else if (events[i].data.fd == server_fd) {
						struct sockaddr_in addr;
						socklen_t addr_sz = 0;
						int client_fd = accept (server_fd, (struct sockaddr*) &addr, &addr_sz);
						
						watchdog_thread_args* thread_args = malloc (sizeof thread_args);
						if (thread_args == NULL) {
							syslog (LOG_CRIT, "Malloc returned NULL: %s", strerror (errno));
							exit (EXIT_FAILURE);
						}

						watchdog_thread* dog_thread = malloc (sizeof dog_thread);
						if (dog_thread == NULL) {
							syslog (LOG_CRIT, "Malloc returned NULL: %s", strerror (errno));
							exit (EXIT_FAILURE);
						}

						int pipefd[2];
						if (pipe (pipefd) < 0) {
							syslog (LOG_CRIT, "watchdog pipe error: %s", strerror (errno));
							continue;
						}
						
						dog_thread->pipe_write = pipefd[1];

						thread_args->pipe_read = pipefd[0];
						thread_args->client_fd = client_fd;
						thread_args->stats = &stats;
						thread_args->stats_mutex = &stats_mutex;

						pthread_attr_t attr;
						int trv = 0;
						if ((trv = pthread_attr_init (&attr)) != 0) {
							syslog (LOG_CRIT, "pthread_attr_init: %s\n", strerror (trv));
						       	continue;	
						}

						if ((trv = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)) != 0) {
							syslog (LOG_CRIT, "pthread_attr_setdetachstate: %s\n", strerror (trv));
						       	continue;	
						}

						if ((trv = pthread_create(&dog_thread->th_id, &attr, client_thread, thread_args)) != 0) {
							syslog (LOG_CRIT, "pthread_create: %s\n", strerror (trv));
						       	continue;	
						}

						auto_array_add (thread_array, dog_thread);

						pthread_attr_destroy(&attr);
					}
				}

			}

			if (paused_for_signal) {
				syslog (LOG_NOTICE, "Paused for signal\n");
			} else {
				auto_array* stat_files = auto_array_create (num_pids);
				for (int i = 0; i < num_pids; ++i) {
					if (pids[i] == 0) {
						continue;
					}

					char pid[32];
					sprintf (pid, "%d", pids[i]);
					
					FILE* p = get_stat_filep (pid);
					if (p == NULL) {
						syslog (LOG_CRIT, "Process with pid %s has halted", pid);
						if (email_address != NULL && mail_server != NULL) {
							char msg[2048];
							snprintf (msg, 2048, email_alert_msg_format, email_address, email_address, pid);
							send_email (mail_server, email_address, email_address, msg);
									
							pids[i] = 0; 
						}

						continue;
					}

					auto_array_add (stat_files, p);
				}

				pthread_mutex_lock(&stats_mutex);

				if (stat_buffer != NULL) {
					auto_string_delete (stat_buffer);
				}
				
				stat_buffer = auto_string_create (1024);
				if (stat_buffer == NULL) {
					syslog (LOG_CRIT, "Unable to create stat buffer - out of memory");
					exit (EXIT_FAILURE);
				}

				for (int i = 0; i < stat_files->count; ++i) {
					FILE* f = auto_array_get (stat_files, i);
					
					char* tmp = get_proc_string (f);
					
					if (tmp != NULL) {
						auto_string_append (stat_buffer, tmp);
						free (tmp);	
					}
				}

				stats = stat_buffer->buf;

				pthread_mutex_unlock (&stats_mutex);

				for (int i = 0; i < thread_array->count; ++i) {
					watchdog_thread* wt = auto_array_get (thread_array, i);
					char ok[2] = "OK";
					if (write (wt->pipe_write, ok, 2) <= 0) {
						syslog (LOG_CRIT, "watchdog write client thread: %s", strerror (errno));
						auto_array_remove (thread_array, i);
						close (wt->pipe_write);
						free (wt);
					}
				}
				
				auto_array_delete (stat_files, close_file);
			}	
		}

	}

	return pid;
}
Example #7
0
int main(int argc, char *argv[])
{
  int i;
  char configname[PATH_MAX] = "";
  char playername[PATH_MAX] = "";
  char scorename[PATH_MAX] = "";
  int playernamegiven = 0;
  char tmpstr[PATH_MAX + 256];
  long subsong = -1;
  FILE *listfile = NULL;
  int have_modules = 0;
  int ret;
  char *endptr;
  int uadeconf_loaded, songconf_loaded;
  char songconfname[PATH_MAX] = "";
  char uadeconfname[PATH_MAX];
  struct uade_config uc_cmdline;
  char songoptions[256] = "";
  int have_song_options = 0;
  int plistdir;
  int scanmode = 0;

  struct uade_state state = {};
  char *basedir;

  enum {
    OPT_FIRST = 0x1FFF,
    OPT_BASEDIR,
    OPT_REPEAT,
    OPT_SCAN,
    OPT_SCOPE,
    OPT_SET,
    OPT_STDERR,
    OPT_VERSION
  };

  struct option long_options[] = {
    {"ao-option",        1, NULL, UC_AO_OPTION},
    {"basedir",          1, NULL, OPT_BASEDIR},
    {"buffer-time",      1, NULL, UC_BUFFER_TIME},
    {"cygwin",           0, NULL, UC_CYGWIN_DRIVE_WORKAROUND},
    {"debug",            0, NULL, 'd'},
    {"detect-format-by-content", 0, NULL, UC_CONTENT_DETECTION},
    {"disable-timeouts", 0, NULL, UC_DISABLE_TIMEOUTS},
    {"enable-timeouts",  0, NULL, UC_ENABLE_TIMEOUTS},
    {"ep-option",        1, NULL, 'x'},
    {"filter",           2, NULL, UC_FILTER_TYPE},
    {"force-led",        1, NULL, UC_FORCE_LED},
    {"frequency",        1, NULL, UC_FREQUENCY},
    {"gain",             1, NULL, 'G'},
    {"get-info",         0, NULL, 'g'},
    {"headphones",       0, NULL, UC_HEADPHONES},
    {"headphones2",      0, NULL, UC_HEADPHONES2},
    {"help",             0, NULL, 'h'},
    {"ignore",           0, NULL, 'i'},
    {"interpolator",     1, NULL, UC_RESAMPLER},
    {"jump",             1, NULL, 'j'},
    {"keys",             1, NULL, 'k'},
    {"list",             1, NULL, '@'},
    {"magic",            0, NULL, UC_CONTENT_DETECTION},
    {"no-ep-end-detect", 0, NULL, 'n'},
    {"no-song-end",      0, NULL, 'n'},
    {"normalise",        2, NULL, UC_NORMALISE},
    {"ntsc",             0, NULL, UC_NTSC},
    {"one",              0, NULL, '1'},
    {"pal",              0, NULL, UC_PAL},
    {"panning",          1, NULL, 'p'},
    {"recursive",        0, NULL, 'r'},
    {"repeat",           0, NULL, OPT_REPEAT},
    {"resampler",        1, NULL, UC_RESAMPLER},
    {"scan",             0, NULL, OPT_SCAN},
    {"scope",            0, NULL, OPT_SCOPE},
    {"shuffle",          0, NULL, 'z'},
    {"set",              1, NULL, OPT_SET},
    {"silence-timeout",  1, NULL, 'y'},
    {"speed-hack",       0, NULL, UC_SPEED_HACK},
    {"stderr",           0, NULL, OPT_STDERR},
    {"stdout",           0, NULL, 'c'},
    {"subsong",          1, NULL, 's'},
    {"subsong-timeout",  1, NULL, 'w'},
    {"timeout",          1, NULL, 't'},
    {"verbose",          0, NULL, 'v'},
    {"version",          0, NULL, OPT_VERSION},
    {NULL,               0, NULL, 0}
  };

  uade_config_set_defaults(&uc_cmdline);

  if (!playlist_init(&uade_playlist))
    die("Can not initialize playlist.\n");

#define GET_OPT_STRING(x) if (strlcpy((x), optarg, sizeof(x)) >= sizeof(x)) { die("Too long a string for option %c.\n", ret); }

  while ((ret = getopt_long(argc, argv, "@:1cde:f:gG:hij:k:np:P:rs:S:t:u:vw:x:y:z", long_options, 0)) != -1) {
    switch (ret) {

    case '@':
      listfile = fopen(optarg, "r");
      if (listfile == NULL)
    die("Can not open list file: %s\n", optarg);
      break;

    case '1':
      uade_set_config_option(&uc_cmdline, UC_ONE_SUBSONG, NULL);
      break;

    case 'c':
      strlcpy(uade_output_file_name, "/dev/stdout", sizeof uade_output_file_name);
      /* Output sample data to stdout so do not print anything on stdout */
      uade_terminal_file = stderr;
      break;

    case 'd':
      debug_mode = 1;
      uade_debug_trigger = 1;
      break;
    case 'e':
      GET_OPT_STRING(uade_output_file_format);
      break;

    case 'f':
      GET_OPT_STRING(uade_output_file_name);
      break;

    case 'g':
      uade_info_mode = 1;
      uade_no_audio_output = 1;
      uade_no_text_output = 1;
      uade_set_config_option(&uc_cmdline, UC_ACTION_KEYS, "off");
      break;

    case 'G':
      uade_set_config_option(&uc_cmdline, UC_GAIN, optarg);
      break;

    case 'h':
      print_help();
      exit(0);

    case 'i':
      uade_set_config_option(&uc_cmdline, UC_IGNORE_PLAYER_CHECK, NULL);
      break;

    case 'j':
      uade_jump_pos = strtod(optarg, &endptr);
      if (*endptr != 0 || uade_jump_pos < 0.0)
    die("Invalid jump position: %s\n", optarg);
      break;

    case 'k':
      uade_set_config_option(&uc_cmdline, UC_ACTION_KEYS, optarg);
      break;

    case 'n':
      uade_set_config_option(&uc_cmdline, UC_NO_EP_END, NULL);
      break;

    case 'p':
      uade_set_config_option(&uc_cmdline, UC_PANNING_VALUE, optarg);
      break;

    case 'P':
      GET_OPT_STRING(playername);
      playernamegiven = 1;
      have_modules = 1;
      break;

    case 'r':
      uade_set_config_option(&uc_cmdline, UC_RECURSIVE_MODE, NULL);
      break;

    case 's':
      subsong = strtol(optarg, &endptr, 10);
      if (*endptr != 0 || subsong < 0 || subsong > 255)
    die("Invalid subsong string: %s\n", optarg);
      break;

    case 'S':
      GET_OPT_STRING(scorename);
      break;

    case 't':
      uade_set_config_option(&uc_cmdline, UC_TIMEOUT_VALUE, optarg);
      break;

    case 'u':
      GET_OPT_STRING(uadename);
      break;

    case 'v':
      uade_set_config_option(&uc_cmdline, UC_VERBOSE, NULL);
      break;

    case 'w':
      uade_set_config_option(&uc_cmdline, UC_SUBSONG_TIMEOUT_VALUE, optarg);
      break;

    case 'x':
      uade_set_config_option(&uc_cmdline, UC_EAGLEPLAYER_OPTION, optarg);
      break;

    case 'y':
      uade_set_config_option(&uc_cmdline, UC_SILENCE_TIMEOUT_VALUE, optarg);
      break;

    case 'z':
      uade_set_config_option(&uc_cmdline, UC_RANDOM_PLAY, NULL);
      break;

    case '?':
    case ':':
      exit(1);

    case OPT_BASEDIR:
      uade_set_config_option(&uc_cmdline, UC_BASE_DIR, optarg);
      break;

    case OPT_REPEAT:
      playlist_repeat(&uade_playlist);
      break;

    case OPT_SCAN:
      scanmode = 1;
      /* Set recursive mode in scan mode */
      uade_set_config_option(&uc_cmdline, UC_RECURSIVE_MODE, NULL);
      break;

    case OPT_SCOPE:
      uade_no_text_output = 1;
      uade_set_config_option(&uc_cmdline, UC_USE_TEXT_SCOPE, NULL);
      break;

    case OPT_SET:
      have_song_options = 1;
      strlcpy(songoptions, optarg, sizeof songoptions);
      break;

    case OPT_STDERR:
      uade_terminal_file = stderr;
      break;

    case OPT_VERSION:
      printf("uade123 %s\n", UADE_VERSION);
      exit(0);
      break;

    case UC_AO_OPTION:
    case UC_BUFFER_TIME:
    case UC_FILTER_TYPE:
    case UC_FORCE_LED:
    case UC_FREQUENCY:
    case UC_NORMALISE:
    case UC_RESAMPLER:
      uade_set_config_option(&uc_cmdline, ret, optarg);
      break;

    case UC_CONTENT_DETECTION:
    case UC_CYGWIN_DRIVE_WORKAROUND:
    case UC_DISABLE_TIMEOUTS:
    case UC_ENABLE_TIMEOUTS:
    case UC_HEADPHONES:
    case UC_HEADPHONES2:
    case UC_NTSC:
    case UC_PAL:
    case UC_SPEED_HACK:
      uade_set_config_option(&uc_cmdline, ret, NULL);
      break;

    default:
      die("Impossible option.\n");
    }
  }

  basedir = NULL;
  if (uc_cmdline.basedir_set) {
      basedir = uc_cmdline.basedir.name;
  }
  
  uadeconf_loaded = uade_load_initial_config(&state, uadeconfname, sizeof uadeconfname, basedir);

  /* Merge loaded configurations and command line options */
  uade_merge_configs(&state.config, &uc_cmdline);

  if (uadeconf_loaded == 0) {
    debug(state.config.verbose, "Not able to load uade.conf from ~/.uade2/ or %s/.\n", state.config.basedir.name);
  } else {
    debug(state.config.verbose, "Loaded configuration: %s\n", uadeconfname);
  }

  songconf_loaded = uade_load_initial_song_conf(songconfname, sizeof songconfname, &state.permconfig, &uc_cmdline, &state);

  if (songconf_loaded == 0) {
    debug(state.config.verbose, "Not able to load song.conf from ~/.uade2/ or %s/.\n", state.config.basedir.name);
  } else {
    debug(state.config.verbose, "Loaded song.conf: %s\n", songconfname);
  }

  /* Read play list from file */
  if (listfile != NULL) {
    while (xfgets(tmpstr, sizeof(tmpstr), listfile) != NULL) {
      if (tmpstr[0] == '#')
    continue;
      if (tmpstr[strlen(tmpstr) - 1] == '\n')
    tmpstr[strlen(tmpstr) - 1] = 0;
      playlist_add(&uade_playlist, tmpstr, state.config.recursive_mode, state.config.cygwin_drive_workaround);
    }
    fclose(listfile);
    listfile = NULL;
    have_modules = 1;
  }

  /* Read play list from command line parameters */
  for (i = optind; i < argc; i++) {
    /* Play files */
    playlist_add(&uade_playlist, argv[i], uc_eff.recursive_mode, uc_eff.cygwin_drive_workaround);
    have_modules = 1;
  }

  if (scanmode) {
    scan_playlist(&state.config);
    exit(0);
  }

  if (have_song_options) {
    set_song_options(&songconf_loaded, songoptions, songconfname, sizeof songconfname);
    exit(0);
  }

  load_content_db(&state.config, &state);

  if (state.config.random_play)
    playlist_randomize(&uade_playlist);

  if (have_modules == 0) {
    print_help();
    exit(0);
  }

  /* we want to control terminal differently in debug mode */
  if (debug_mode)
    state.config.action_keys = 0;

  if (state.config.action_keys)
    setup_terminal();

  do {
    DIR *bd = opendir(state.config.basedir.name);
    if (bd == NULL)
      dieerror("Could not access dir %s", state.config.basedir.name);

    closedir(bd);

    snprintf(configname, sizeof configname, "%s/uaerc", state.config.basedir.name);

    if (scorename[0] == 0)
      snprintf(scorename, sizeof scorename, "%s/score", state.config.basedir.name);

    if (uadename[0] == 0)
      strlcpy(uadename, UADE_CONFIG_UADE_CORE, sizeof uadename);

    if (access(configname, R_OK))
      dieerror("Could not read %s", configname);

    if (access(scorename, R_OK))
      dieerror("Could not read %s", scorename);

    if (access(uadename, X_OK))
      dieerror("Could not execute %s", uadename);

  } while (0);

  setup_sighandlers();

  uade_spawn(&state, uadename, configname);

  if (!audio_init(&state.config))
    goto cleanup;

  plistdir = UADE_PLAY_CURRENT;

  while (1) {

    ssize_t filesize;

    /* modulename and songname are a bit different. modulename is the name
       of the song from uadecore's point of view and songname is the
       name of the song from user point of view. Sound core considers all
       custom songs to be players (instead of modules) and therefore modulename
       will become a zero-string with custom songs. */
    char modulename[PATH_MAX];
    char songname[PATH_MAX];

    if (!playlist_get(modulename, sizeof modulename, &uade_playlist, plistdir))
      break;

    plistdir = UADE_PLAY_NEXT;

    state.config = state.permconfig;
    state.song = NULL;
    state.ep = NULL;

    if (uc_cmdline.verbose)
      state.config.verbose = 1;

    if (playernamegiven == 0) {
      debug(state.config.verbose, "\n");

      if (!uade_is_our_file(modulename, 0, &state)) {
    __android_log_print(ANDROID_LOG_VERBOSE, "UADE", "Unknown format: %s\n", modulename);
    continue;
      }

      debug(state.config.verbose, "Player candidate: %s\n", state.ep->playername);

      if (strcmp(state.ep->playername, "custom") == 0) {
    strlcpy(playername, modulename, sizeof playername);
    modulename[0] = 0;
      } else {
    snprintf(playername, sizeof playername, "%s/players/%s", uc_cmdline.basedir.name, state.ep->playername);
      }
    }

    if (strlen(playername) == 0) {
      __android_log_print(ANDROID_LOG_VERBOSE, "UADE", "Error: an empty player name given\n");
      goto cleanup;
    }

    /* If no modulename given, try the playername as it can be a custom song */
    strlcpy(songname, modulename[0] ? modulename : playername, sizeof songname);

    if (!uade_alloc_song(&state, songname)) {
      __android_log_print(ANDROID_LOG_VERBOSE, "UADE", "Can not read %s: %s\n", songname, strerror(errno));
      continue;
    }

    /* The order of parameter processing is important:
     * 0. set uade.conf options (done before this)
     * 1. set eagleplayer attributes
     * 2. set song attributes
     * 3. set command line options
     */

    if (state.ep != NULL)
      uade_set_ep_attributes(&state);

    if (uade_set_song_attributes(&state, playername, sizeof playername)) {
      debug(state.config.verbose, "Song rejected based on attributes: %s\n",
        state.song->module_filename);
      uade_unalloc_song(&state);
      continue;
    }

    uade_merge_configs(&state.config, &uc_cmdline);

    /* Now we have the final configuration in "uc". */

    uade_set_effects(&state);

    if ((filesize = stat_file_size(playername)) < 0) {
      __android_log_print(ANDROID_LOG_VERBOSE, "UADE", "Can not find player: %s (%s)\n", playername, strerror(errno));
      uade_unalloc_song(&state);
      continue;
    }

    debug(state.config.verbose, "Player: %s (%zd bytes)\n", playername, filesize);

    __android_log_print(ANDROID_LOG_VERBOSE, "UADE", "Song: %s (%zd bytes)\n", state.song->module_filename, state.song->bufsize);

    ret = uade_song_initialization(scorename, playername, modulename, &state);
    switch (ret) {
    case UADECORE_INIT_OK:
      break;

    case UADECORE_INIT_ERROR:
      uade_unalloc_song(&state);
      goto cleanup;

    case UADECORE_CANT_PLAY:
    debug(state.config.verbose, "Uadecore refuses to play the song.\n");
    uade_unalloc_song(&state);
    continue; /* jump to the beginning of playlist loop */

    default:
      die("Unknown error from uade_song_initialization()\n");
    }

    if (subsong >= 0)
      uade_set_subsong(subsong, &state.ipc);

    plistdir = play_loop(&state);

    uade_unalloc_song(&state);

    if (plistdir == UADE_PLAY_FAILURE)
      goto cleanup;
    else if (plistdir == UADE_PLAY_EXIT)
      break;
  }

  debug(uc_cmdline.verbose || state.permconfig.verbose, "Killing child (%d).\n", uadepid);
  cleanup(&state);
  return 0;

 cleanup:
  cleanup(&state);
  return 1;
}