Example #1
0
int srun(int ac, char **av)
{
	int debug_level;
	env_t *env = xmalloc(sizeof(env_t));
	log_options_t logopt = LOG_OPTS_STDERR_ONLY;
	bool got_alloc = false;
	slurm_step_io_fds_t cio_fds = SLURM_STEP_IO_FDS_INITIALIZER;
	slurm_step_launch_callbacks_t step_callbacks;

	env->stepid = -1;
	env->procid = -1;
	env->localid = -1;
	env->nodeid = -1;
	env->cli = NULL;
	env->env = NULL;
	env->ckpt_dir = NULL;

	slurm_conf_init(NULL);
	debug_level = _slurm_debug_env_val();
	logopt.stderr_level += debug_level;
	log_init(xbasename(av[0]), logopt, 0, NULL);
	_set_exit_code();

	if (slurm_select_init(1) != SLURM_SUCCESS )
		fatal( "failed to initialize node selection plugin" );

	if (switch_init(0) != SLURM_SUCCESS )
		fatal("failed to initialize switch plugins");

	_setup_env_working_cluster();

	init_srun(ac, av, &logopt, debug_level, 1);
	create_srun_job(&job, &got_alloc, 0, 1);

	/*
	 *  Enhance environment for job
	 */
	if (opt.bcast_flag)
		_file_bcast();
	if (opt.cpus_set)
		env->cpus_per_task = opt.cpus_per_task;
	if (opt.ntasks_per_node != NO_VAL)
		env->ntasks_per_node = opt.ntasks_per_node;
	if (opt.ntasks_per_socket != NO_VAL)
		env->ntasks_per_socket = opt.ntasks_per_socket;
	if (opt.ntasks_per_core != NO_VAL)
		env->ntasks_per_core = opt.ntasks_per_core;
	env->distribution = opt.distribution;
	if (opt.plane_size != NO_VAL)
		env->plane_size = opt.plane_size;
	env->cpu_bind_type = opt.cpu_bind_type;
	env->cpu_bind = opt.cpu_bind;

	env->cpu_freq_min = opt.cpu_freq_min;
	env->cpu_freq_max = opt.cpu_freq_max;
	env->cpu_freq_gov = opt.cpu_freq_gov;
	env->mem_bind_type = opt.mem_bind_type;
	env->mem_bind = opt.mem_bind;
	env->overcommit = opt.overcommit;
	env->slurmd_debug = opt.slurmd_debug;
	env->labelio = opt.labelio;
	env->comm_port = slurmctld_comm_addr.port;
	env->batch_flag = 0;
	if (opt.job_name)
		env->job_name = opt.job_name;
	if (job) {
		uint16_t *tasks = NULL;
		slurm_step_ctx_get(job->step_ctx, SLURM_STEP_CTX_TASKS,
				   &tasks);

		env->select_jobinfo = job->select_jobinfo;
		env->nodelist = job->nodelist;
		env->partition = job->partition;
		/* If we didn't get the allocation don't overwrite the
		 * previous info.
		 */
		if (got_alloc)
			env->nhosts = job->nhosts;
		env->ntasks = job->ntasks;
		env->task_count = _uint16_array_to_str(job->nhosts, tasks);
		env->jobid = job->jobid;
		env->stepid = job->stepid;
		env->account = job->account;
		env->qos = job->qos;
		env->resv_name = job->resv_name;
	}
	if (opt.pty && (set_winsize(job) < 0)) {
		error("Not using a pseudo-terminal, disregarding --pty option");
		opt.pty = false;
	}
	if (opt.pty) {
		struct termios term;
		int fd = STDIN_FILENO;

		/* Save terminal settings for restore */
		tcgetattr(fd, &termdefaults);
		tcgetattr(fd, &term);
		/* Set raw mode on local tty */
		cfmakeraw(&term);
		/* Re-enable output processing such that debug() and
		 * and error() work properly. */
		term.c_oflag |= OPOST;
		tcsetattr(fd, TCSANOW, &term);
		atexit(&_pty_restore);

		block_sigwinch();
		pty_thread_create(job);
		env->pty_port = job->pty_port;
		env->ws_col   = job->ws_col;
		env->ws_row   = job->ws_row;
	}
	setup_env(env, opt.preserve_env);
	xfree(env->task_count);
	xfree(env);
	_set_node_alias();

	memset(&step_callbacks, 0, sizeof(step_callbacks));
	step_callbacks.step_signal   = launch_g_fwd_signal;

	/* re_launch: */
relaunch:
	pre_launch_srun_job(job, 0, 1);

	launch_common_set_stdio_fds(job, &cio_fds);

	if (!launch_g_step_launch(job, &cio_fds, &global_rc, &step_callbacks)) {
		if (launch_g_step_wait(job, got_alloc) == -1)
			goto relaunch;
	}

	fini_srun(job, got_alloc, &global_rc, 0);

	return (int)global_rc;
}
Example #2
0
void cmd_parser(unsigned long data)
{
	char *curr_pos = &user_string[0];
	int ret;

	while(1) {

		while(cmd_in_progress)
			os_TaskDelay(10);
		DBG_P(( DBG_L0 "\r\n> "));
		cmd_parser_read_line();
	   
		if(strlen(user_string) == 0) {
			/* Do Nothing. */
		}
	   
		else if(!memcmp(user_string,"iwlist",6)){
			userif_prepare_scan_cmd(0);
		}     
		else if(!memcmp(user_string,"iwconf",6)){
			curr_pos = &user_string[get_next_word(user_string)];
			if(!memcmp(curr_pos,"essid",5)) {
				curr_pos = &curr_pos[get_next_word(curr_pos)];
				specificSSID.Len  = strlen(curr_pos);
				memcpy((void *)specificSSID.SsId, curr_pos, strlen(curr_pos));
				if(link_present) {
					if(currbss_type != BSS_INDEPENDENT)
						userif_prepare_deauth_cmd();
					else
						userif_prepare_adhoc_stop_cmd();
				} else {
					userif_prepare_scan_cmd(1);
				}
				link_present = 0;				
			} else if (!memcmp(curr_pos,"mode",4)) {
				curr_pos = &curr_pos[get_next_word(curr_pos)];
				if(!memcmp(curr_pos,"ad-hoc",6)) {
					bss_type = BSS_INDEPENDENT;
				} else if(!memcmp(curr_pos,"manage",6)) {
					bss_type = BSS_INFRASTRUCTURE;
				} else {
					bss_type = BSS_ANY;
				}
			} else if (!memcmp(curr_pos,"ap",2)) {
				curr_pos = &curr_pos[get_next_word(curr_pos)];
				get_macaddr(curr_pos,(char *)specificBSSID);
				if (FindBSSIDinList()) {
					userif_prepare_auth_cmd();			
				} else {
					if(link_present) {
						link_present = 0;
						userif_prepare_deauth_cmd();
					} else {
						userif_prepare_scan_cmd(2);
					}
				}
			}
		}
		else if(!memcmp(user_string,"econfi",6)){
			unsigned int ip;
			unsigned int nm;
			unsigned int gw;
			curr_pos = &user_string[get_next_word(user_string)];
			get_ipaddr(curr_pos, (char *)&ip);
			curr_pos = &curr_pos[get_next_word(curr_pos)];
			get_ipaddr(curr_pos, (char *)&nm);
			curr_pos = &curr_pos[get_next_word(curr_pos)];
			get_ipaddr(curr_pos, (char *)&gw);
			sys_tcpip_init(ip, nm);
		}
	   
		else if(!memcmp(user_string, "printip", 7)){
			DBG_P(( DBG_L0 "%d.%d.%d.%d,", ip_addr[0], ip_addr[1], ip_addr[2], 
				ip_addr[3] ));
			DBG_P(( DBG_L0 "%d.%d.%d.%d,", net_mask[0], net_mask[1], 
				net_mask[2], net_mask[3] ));
			DBG_P(( DBG_L0 "%d.%d.%d.%d\r\n", def_gtwy[0], def_gtwy[1], 
				def_gtwy[2], def_gtwy[3] ));
		}
	   
		else if(!memcmp(user_string, "printmac", 8)){
			char mac[6];
			GetMACAddr(NULL, mac);
			DBG_P(( DBG_L0 "%02x:%02x:%02x:%02x:%02x:%02x\r\n", \
					mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]));
		}
	   
		else if(!memcmp(user_string,"ping",4)){
			curr_pos = &user_string[get_next_word(user_string)];
			if(!memcmp(curr_pos,"stop",4)) {
				send_ping = 0;
			} else {
				get_ipaddr(curr_pos, ping_ipaddr);
#ifdef EMBEDDED_TCPIP
				userif_prepare_open_raw_socket();
#else
				userif_prepare_macaddr_get_cmd();
#endif
				send_ping = 1;
			}
		}

		/* Link-local address manager. */
		else if(!memcmp(user_string, "linklocal", 9)) {
			curr_pos = &user_string[get_next_word(user_string)];
			if(!memcmp(curr_pos, "start", 5)) {
				/* Launch the link local manager */
				ret = ll_init();
				if(ret)
					DBG_P(( DBG_L0 "Error launching link local: %d.\r\n", ret));
			} else if(!memcmp(curr_pos, "stop", 4)) {
				/* Kill the link local manager. */
				ret = ll_shutdown();
				if(ret)
					DBG_P(( DBG_L0 "Error killing link local: %d.\r\n", ret));
			}
		}

		/* mDNS responder */
		else if(!memcmp(user_string, "mdns", 4)) {
			curr_pos = &user_string[get_next_word(user_string)];
			if(!memcmp(curr_pos, "start", 5)) {
				/* launch the mDNS responder */
				ret = mdns_responder_init();
				if(ret)
					DBG_P(( DBG_L0 "Error launching mDNS responder: %d.\r\n",ret));
			}
			else if(!memcmp(curr_pos, "stop", 4)) {
				/* stop the mDNS responder */
				ret = mdns_responder_shutdown();
				if(ret)
					DBG_P(( DBG_L0 "Error stopping mDNS responder: %d.\r\n", ret));
			}
		}

	else if(!memcmp(user_string, "mcast", 5 )){
		curr_pos = &user_string[get_next_word(user_string)];
		if(!memcmp(curr_pos, "get", 3 )) {
			userif_prepare_mcast_cmd();
		}
		else if(!memcmp(curr_pos, "set", 3 )) {
			userif_prepare_mcast_add_cmd();
		}
	}

		/* httpd interface */
		else if(!memcmp(user_string, "httpd", 5)) {
			curr_pos = &user_string[get_next_word(user_string)];
			if(!memcmp(curr_pos, "start", 5)) {
				ret = httpd_init();
				if(ret)
					DBG_P(( DBG_L0 "Error launching httpd: %d.\r\n",ret));
			}
			else if(!memcmp(curr_pos, "stop", 4)) {
				ret = httpd_shutdown();
				if(ret)
					DBG_P(( DBG_L0 "Error stopping httpd: %d.\r\n", ret));
			}
			else {
				DBG_P(( DBG_L0 "No such httpd command: %s.\r\n", curr_pos));
			}
		}

		/* log interface */
		else if(!memcmp(user_string, "log", 3)) {
			curr_pos = &user_string[get_next_word(user_string)];
			if(!memcmp(curr_pos, "init", 5)) {
				ret = log_init();
				if(ret)
					DBG_P(( DBG_L0 "Error launching logger: %d.\r\n",ret));
			}
			else if(!memcmp(curr_pos, "shutdown", 8)) {
				ret = log_shutdown();
				if(ret)
					DBG_P(( DBG_L0 "Error stopping logger: %d.\r\n", ret));
			}
			else if(!memcmp(curr_pos, "dump", 4)) {
				ret = log_dump();
				if(ret)
					DBG_P(( DBG_L0 "Error dumping log: %d.\r\n", ret));
			}
			else if(!memcmp(curr_pos, "purge", 5)) {
				ret = log_purge();
				if(ret)
					DBG_P(( DBG_L0 "Error purging log: %d.\r\n", ret));
			}
			else if(!memcmp(curr_pos, "write", 5)) {
				curr_pos = &curr_pos[get_next_word(curr_pos)];
				ret = log(curr_pos);
				if(ret)
					DBG_P(( DBG_L0 "Failed to write log: %d.\r\n", ret));
			}
			else {
				DBG_P(( DBG_L0 "No such log command: %s.\r\n", curr_pos));
			}
		}

	 else if(!memcmp(user_string, "help", 4)) {
		 print_usage();
	 }

	else {
#ifdef UART_DRV
			DBG_P(( DBG_L0 "Unknown command.\r\n")); 
#endif		 
		}	   
	}
}
Example #3
0
int main()
{
	log_init();
	Log(LOG_INFO, "Starting in 5 seconds.\n");
	std::cout << "Starting in 5 seconds.\n";
	sleep(5000);
	Log(LOG_INFO, "Waiting until you are in the penalty box.\n"); 
	std::cout << "Waiting until you are in the penalty box.\n";
	
	while (1)
	{
		std::string resNetData;
		
		
		t1:
		try
		{
			resNetData = httpGetBasicAuth("http://ubcit.webi.it.ubc.ca/__shared/Pagelet5764.html","","",NULL);
		}
		catch (Exception e)
		{
			goto t1;
		}
		if (resNetData.find("not currently in the ResNet Penalty Box.") == std::string::npos)
		{
			Log(LOG_INFO, "You are in penalty box.\n");
			std::cout << "You are in penalty box.\n";
			t2:
			try
			{
				resNetData = httpGetBasicAuth("http://192.168.1.1/cgi/cgi_wanmac.js","","",NULL);
			}
			catch (Exception e)
			{
				goto t2;
			}
			//std::cout << resNetData;
			size_t start = resNetData.find("wan_mac") + strlen("wan_mac");
			size_t end = resNetData.find(";", start);
			std::string mac = resNetData.substr(end - 4 - 2*6 - 3, 17);
			std::cout << "Your current mac is " << mac << ".\n";
			unsigned int umac[6];
			sscanf(mac.c_str(), "%x:%x:%x:%x:%x:%x",&umac[0],&umac[1],&umac[2],&umac[3],&umac[4],&umac[5]);
			if (umac[5] == 255)
			{
				if (umac[4] == 255)
				{
					if (umac[3] == 255)
					{
						if (umac[2] == 255)
						{
							if (umac[1] == 255)
							{
								if (umac[0] == 255)
								{
									umac[0] = 0;
								}
								else
								{
									umac[0]++;
								}
								umac[1] = 0;
							}
							else
							{
								umac[1]++;
							}
							umac[2] = 0;
						}
						else
						{
							umac[2]++;
						}						
						umac[3] = 0;
					}
					else
					{
						umac[3]++;
					}
					umac[4] = 0;
				}
				else 
				{
					umac[4]++;
				}
				umac[5] = 0;
			}
			else 
			{
			umac[5]++;
			}
			char buf[30];
			Log(LOG_INFO, "Your current mac is %s.\n", mac.c_str());
			sprintf(buf, "%X:%X:%X:%X:%X:%X", umac[0],umac[1],umac[2],umac[3],umac[4],umac[5]);
			std::cout << "Setting your mac to " << buf << ".\n";
			Log(LOG_INFO, "Settings your mac to mac %s.\n", buf);
			sprintf(buf, "%X%%3A%X%%3A%X%%3A%X%%3A%X%%3A%X", umac[0],umac[1],umac[2],umac[3],umac[4],umac[5]);
			char buf2[500];
			sprintf(buf2, "CMD=ATM_MAC_CONF&SET0=50693120%%3D%s", buf);
			//std::cout << buf2 << "\n";
			//login
			
			t3:
			try
			{
				httpGetBasicAuth("http://192.168.1.1/login.cgi","","",(void *)"GO=wan_mac.htm&pws=d41d8cd98f00b204e9800998ecf8427e");
			}
			catch (Exception e)
			{
				goto t3;
			}
			
			t4:
			try
			{
				resNetData = httpGetBasicAuth("http://192.168.1.1/apply.cgi","","", (void *) &(buf2[0]));
			}
			catch (Exception e)
			{
				goto t4;
			}
			//std::cout << resNetData << "\n";
			sleep(30000);
		}
		else 
		{
			Log(LOG_INFO, "Not in penalty box.\n");
		}
				
		sleep(5000);
	}
	log_close();
	return 0;
}
Example #4
0
/* Entry point */
extern "C" int Menu_Main(void)
{
    //!*******************************************************************
    //!                   Initialize function pointers                   *
    //!*******************************************************************
    //! do OS (for acquire) and sockets first so we got logging
    InitOSFunctionPointers();
    InitSocketFunctionPointers();

    log_init(LOADIINE_LOGGER_IP);
    log_print("Starting Loadiine GX2 " LOADIINE_VERSION "\n");

    InitFSFunctionPointers();
    InitGX2FunctionPointers();
    InitSysFunctionPointers();
    InitVPadFunctionPointers();
    InitPadScoreFunctionPointers();
    InitAXFunctionPointers();
    InitCurlFunctionPointers();

    InitAocFunctionPointers();
    InitACPFunctionPointers();



    log_printf("Function exports loaded\n");

    //!*******************************************************************
    //!                Initialize our kernel variables                   *
    //!*******************************************************************
    log_printf("Setup kernel variables\n");
    SetupKernelCallback();
    //!*******************************************************************
    //!                    Initialize heap memory                        *
    //!*******************************************************************
    log_print("Initialize memory management\n");
    memoryInitialize();

    //!*******************************************************************
    //!                        Initialize FS                             *
    //!*******************************************************************
    log_printf("Mount SD partition\n");
    mount_sd_fat("sd");

    //!*******************************************************************
    //!                       Read Configs for HID support               *
    //!*******************************************************************
    if(gConfig_done == HID_INIT_DONE) {
        log_print("Reading config files from SD Card\n");
        ConfigReader::getInstance(); //doing the magic automatically
        ConfigReader::destroyInstance();
        log_print("Done with reading config files from SD Card\n");
        gConfig_done = HID_SDCARD_READ;
    }

    //!*******************************************************************
    //!                       Patch Functions                            *
    //!*******************************************************************
    log_printf("Patch FS and loader functions\n");
    ApplyPatches();
    PatchSDK();

    //!*******************************************************************
    //!                    Setup exception handler                       *
    //!*******************************************************************
    log_printf("Setup exception handler\n");
    setup_os_exceptions();

    //!*******************************************************************
    //!                    Enter main application                        *
    //!*******************************************************************
    log_printf("Start main application\n");
    Application::instance()->exec();
    log_printf("Main application stopped\n");

    Application::destroyInstance();

    log_printf("Unmount SD\n");
    unmount_sd_fat("sd");
    log_printf("Release memory\n");
    memoryRelease();
    log_printf("Loadiine peace out...\n");
    //log_deinit();

    return 0;
}
Example #5
0
int main(int argc, char **argv)
{
	int result;
	int file_index;
	int file_type;
	int file_size;
	char *conf_filename;
	char storage_ip[IP_ADDRESS_SIZE];
	struct timeval tv_start;
	struct timeval tv_end;
	int time_used;

	if (argc < 2)
	{
		printf("Usage: %s <process_index> [config_filename]\n", argv[0]);
		return EINVAL;
	}

	log_init();
	proccess_index = atoi(argv[1]);
	if (proccess_index < 0 || proccess_index >= PROCESS_COUNT)
	{
		printf("Invalid proccess index: %d\n", proccess_index);
		return EINVAL;
	}

	if (argc >= 3)
	{
		conf_filename = argv[2];
	}
	else
	{
		conf_filename = "/etc/fdfs/client.conf";
	}

	if ((result = load_file_ids()) != 0)
	{
		return result;
	}

	if ((result=test_init()) != 0)
	{
		return result;
	}

	if ((result=dfs_init(proccess_index, conf_filename)) != 0)
	{
		return result;
	}

#ifndef WIN32
	if (daemon(1, 1) != 0)
	{
		return errno != 0 ? errno : EFAULT;
	}
#endif

	/*
	printf("file_count = %d\n", file_count);
	printf("file_entries[0]=%s\n", file_entries[0].file_id);
	printf("file_entries[%d]=%s\n", file_count-1, file_entries[file_count-1].file_id);
	*/

	memset(&storages, 0, sizeof(storages));
	memset(storage_ip, 0, sizeof(storage_ip));

	start_time = time(NULL);
	srand(SRAND_SEED);
	result = 0;
	total_count = 0;
	success_count = 0;
	while (time(NULL) - start_time < TOTAL_SECONDS)
	{
		file_index = (int)(file_count * ((double)rand() / RAND_MAX));
		if (file_index >= file_count)
		{
			printf("file_index=%d!!!!\n", file_index);
			continue;
		}

		file_type = file_entries[file_index].file_type;
		files[file_type].download_count++;
		total_count++;

		gettimeofday(&tv_start, NULL);
		*storage_ip = '\0';
		result = download_file(file_entries[file_index].file_id, &file_size, storage_ip);
		gettimeofday(&tv_end, NULL);
		time_used = TIME_SUB_MS(tv_end, tv_start);
		files[file_type].time_used += time_used;

		add_to_storage_stat(storage_ip, result, time_used);
		if (result == 0) //success
		{
			if (file_size != files[file_type].bytes)
			{
				result = EINVAL;
			}
		}

		if (result == 0) //success
		{
			success_count++;
			files[file_type].success_count++;
		}
		else //fail
		{
			fprintf(fpFail, "%d %d %s %s %d %d\n", (int)tv_end.tv_sec, 
				files[file_type].bytes, file_entries[file_index].file_id, 
				storage_ip, result, time_used);
			fflush(fpFail);
		}

		if (total_count % 10000 == 0)
		{
			if ((result=save_stats_by_overall()) != 0)
			{
				break;
			}
			if ((result=save_stats_by_file_type()) != 0)
			{
				break;
			}

			if ((result=save_stats_by_storage_ip()) != 0)
			{
				break;
			}
		}
	}

	save_stats_by_overall();
	save_stats_by_file_type();
	save_stats_by_storage_ip();

	fclose(fpFail);

	dfs_destroy();

	printf("proccess %d, time used: %ds\n", proccess_index, (int)(time(NULL) - start_time));
	return result;
}
Example #6
0
int
main(int argc, char **argv)
{
	struct sshbuf *b;
	Options options;
#define NUM_KEYTYPES 4
	struct sshkey *keys[NUM_KEYTYPES], *key = NULL;
	struct passwd *pw;
	int r, key_fd[NUM_KEYTYPES], i, found, version = 2, fd;
	u_char *signature, *data, rver;
	char *host, *fp;
	size_t slen, dlen;
#ifdef WITH_OPENSSL
	u_int32_t rnd[256];
#endif

	/* Ensure that stdin and stdout are connected */
	if ((fd = open(_PATH_DEVNULL, O_RDWR)) < 2)
		exit(1);
	/* Leave /dev/null fd iff it is attached to stderr */
	if (fd > 2)
		close(fd);

	i = 0;
	/* XXX This really needs to read sshd_config for the paths */
	key_fd[i++] = open(_PATH_HOST_DSA_KEY_FILE, O_RDONLY);
	key_fd[i++] = open(_PATH_HOST_ECDSA_KEY_FILE, O_RDONLY);
	key_fd[i++] = open(_PATH_HOST_ED25519_KEY_FILE, O_RDONLY);
	key_fd[i++] = open(_PATH_HOST_RSA_KEY_FILE, O_RDONLY);

	original_real_uid = getuid();	/* XXX readconf.c needs this */
	if ((pw = getpwuid(original_real_uid)) == NULL)
		fatal("getpwuid failed");
	pw = pwcopy(pw);

	permanently_set_uid(pw);

	seed_rng();

#ifdef DEBUG_SSH_KEYSIGN
	log_init("ssh-keysign", SYSLOG_LEVEL_DEBUG3, SYSLOG_FACILITY_AUTH, 0);
#endif

	/* verify that ssh-keysign is enabled by the admin */
	initialize_options(&options);
	(void)read_config_file(_PATH_HOST_CONFIG_FILE, pw, "", "", &options, 0);

	#ifndef WIN32_FIXME
	fill_default_options(&options);
	#else
	fill_default_options(&options, pw);
	#endif

	if (options.enable_ssh_keysign != 1)
		fatal("ssh-keysign not enabled in %s",
		    _PATH_HOST_CONFIG_FILE);

	for (i = found = 0; i < NUM_KEYTYPES; i++) {
		if (key_fd[i] != -1)
			found = 1;
	}
	if (found == 0)
		fatal("could not open any host key");

#ifdef WITH_OPENSSL
	OpenSSL_add_all_algorithms();
	arc4random_buf(rnd, sizeof(rnd));
	RAND_seed(rnd, sizeof(rnd));
#endif

	found = 0;
	for (i = 0; i < NUM_KEYTYPES; i++) {
		keys[i] = NULL;
		if (key_fd[i] == -1)
			continue;
		r = sshkey_load_private_type_fd(key_fd[i], KEY_UNSPEC,
		    NULL, &key, NULL);
		close(key_fd[i]);
		if (r != 0)
			debug("parse key %d: %s", i, ssh_err(r));
		else if (key != NULL) {
			keys[i] = key;
			found = 1;
		}
	}
	if (!found)
		fatal("no hostkey found");

	if ((b = sshbuf_new()) == NULL)
		fatal("%s: sshbuf_new failed", __func__);
	if (ssh_msg_recv(STDIN_FILENO, b) < 0)
		fatal("ssh_msg_recv failed");
	if ((r = sshbuf_get_u8(b, &rver)) != 0)
		fatal("%s: buffer error: %s", __func__, ssh_err(r));
	if (rver != version)
		fatal("bad version: received %d, expected %d", rver, version);
	if ((r = sshbuf_get_u32(b, (u_int *)&fd)) != 0)
		fatal("%s: buffer error: %s", __func__, ssh_err(r));
	if (fd < 0 || fd == STDIN_FILENO || fd == STDOUT_FILENO)
		fatal("bad fd");
	if ((host = get_local_name(fd)) == NULL)
		fatal("cannot get local name for fd");

	if ((r = sshbuf_get_string(b, &data, &dlen)) != 0)
		fatal("%s: buffer error: %s", __func__, ssh_err(r));
	if (valid_request(pw, host, &key, data, dlen) < 0)
		fatal("not a valid request");
	free(host);

	found = 0;
	for (i = 0; i < NUM_KEYTYPES; i++) {
		if (keys[i] != NULL &&
		    sshkey_equal_public(key, keys[i])) {
			found = 1;
			break;
		}
	}
	if (!found) {
		if ((fp = sshkey_fingerprint(key, options.fingerprint_hash,
		    SSH_FP_DEFAULT)) == NULL)
			fatal("%s: sshkey_fingerprint failed", __func__);
		fatal("no matching hostkey found for key %s %s",
		    sshkey_type(key), fp ? fp : "");
	}

	if ((r = sshkey_sign(keys[i], &signature, &slen, data, dlen, 0)) != 0)
		fatal("sshkey_sign failed: %s", ssh_err(r));
	free(data);

	/* send reply */
	sshbuf_reset(b);
	if ((r = sshbuf_put_string(b, signature, slen)) != 0)
		fatal("%s: buffer error: %s", __func__, ssh_err(r));
	if (ssh_msg_send(STDOUT_FILENO, version, b) == -1)
		fatal("ssh_msg_send failed");

	return (0);
}
Example #7
0
File: salloc.c Project: edsw/slurm
int main(int argc, char *argv[])
{
	log_options_t logopt = LOG_OPTS_STDERR_ONLY;
	job_desc_msg_t desc;
	resource_allocation_response_msg_t *alloc;
	time_t before, after;
	allocation_msg_thread_t *msg_thr;
	char **env = NULL, *cluster_name;
	int status = 0;
	int retries = 0;
	pid_t pid  = getpid();
	pid_t tpgid = 0;
	pid_t rc_pid = 0;
	int i, rc = 0;
	static char *msg = "Slurm job queue full, sleeping and retrying.";
	slurm_allocation_callbacks_t callbacks;

	slurm_conf_init(NULL);
	log_init(xbasename(argv[0]), logopt, 0, NULL);
	_set_exit_code();

	if (spank_init_allocator() < 0) {
		error("Failed to initialize plugin stack");
		exit(error_exit);
	}

	/* Be sure to call spank_fini when salloc exits
	 */
	if (atexit((void (*) (void)) spank_fini) < 0)
		error("Failed to register atexit handler for plugins: %m");


	if (initialize_and_process_args(argc, argv) < 0) {
		error("salloc parameter parsing");
		exit(error_exit);
	}
	/* reinit log with new verbosity (if changed by command line) */
	if (opt.verbose || opt.quiet) {
		logopt.stderr_level += opt.verbose;
		logopt.stderr_level -= opt.quiet;
		logopt.prefix_level = 1;
		log_alter(logopt, 0, NULL);
	}

	if (spank_init_post_opt() < 0) {
		error("Plugin stack post-option processing failed");
		exit(error_exit);
	}

	_set_spank_env();
	_set_submit_dir_env();
	if (opt.cwd && chdir(opt.cwd)) {
		error("chdir(%s): %m", opt.cwd);
		exit(error_exit);
	}

	if (opt.get_user_env_time >= 0) {
		bool no_env_cache = false;
		char *sched_params;
		char *user = uid_to_string(opt.uid);

		if (xstrcmp(user, "nobody") == 0) {
			error("Invalid user id %u: %m", (uint32_t)opt.uid);
			exit(error_exit);
		}

		sched_params = slurm_get_sched_params();
		no_env_cache = (sched_params &&
				strstr(sched_params, "no_env_cache"));
		xfree(sched_params);

		env = env_array_user_default(user,
					     opt.get_user_env_time,
					     opt.get_user_env_mode,
					     no_env_cache);
		xfree(user);
		if (env == NULL)
			exit(error_exit);    /* error already logged */
		_set_rlimits(env);
	}

	/*
	 * Job control for interactive salloc sessions: only if ...
	 *
	 * a) input is from a terminal (stdin has valid termios attributes),
	 * b) controlling terminal exists (non-negative tpgid),
	 * c) salloc is not run in allocation-only (--no-shell) mode,
	 * NOTE: d and e below are configuration dependent
	 * d) salloc runs in its own process group (true in interactive
	 *    shells that support job control),
	 * e) salloc has been configured at compile-time to support background
	 *    execution and is not currently in the background process group.
	 */
	if (tcgetattr(STDIN_FILENO, &saved_tty_attributes) < 0) {
		/*
		 * Test existence of controlling terminal (tpgid > 0)
		 * after first making sure stdin is not redirected.
		 */
	} else if ((tpgid = tcgetpgrp(STDIN_FILENO)) < 0) {
#ifdef HAVE_ALPS_CRAY
		verbose("no controlling terminal");
#else
		if (!opt.no_shell) {
			error("no controlling terminal: please set --no-shell");
			exit(error_exit);
		}
#endif
#ifdef SALLOC_RUN_FOREGROUND
	} else if ((!opt.no_shell) && (pid == getpgrp())) {
		if (tpgid == pid)
			is_interactive = true;
		while (tcgetpgrp(STDIN_FILENO) != pid) {
			if (!is_interactive) {
				error("Waiting for program to be placed in "
				      "the foreground");
				is_interactive = true;
			}
			killpg(pid, SIGTTIN);
		}
	}
#else
	} else if ((!opt.no_shell) && (getpgrp() == tcgetpgrp(STDIN_FILENO))) {
Example #8
0
int
main(int argc, char **argv)
{
	static struct option options[] = {
		{ "with-disputed",	no_argument,		NULL,	'D' },
		{ "hostname",		required_argument,	NULL,	'h' },
		{ "quiet",		no_argument,		NULL,	'q' },
		{ "log-format",		required_argument,	NULL,	'l' },
		{ "log-file",		required_argument,	NULL,	'f' },
		{ NULL }
	};
	const char *opt_hostname = NULL;
	const char *opt_log_format = NULL;
	const char *opt_log_file = NULL;
	int c;

	while ((c = getopt_long(argc, argv, "Dh:ql:f:", options, NULL)) != EOF) {
		switch (c) {
		case 'D':
			opt_flags |= RPF_DISPUTED;
			break;

		case 'h':
			opt_hostname = optarg;
			break;

		case 'q':
			opt_flags |= RPF_QUIET;
			break;

		case 'l':
			opt_log_format = optarg;
			break;

		case 'f':
			opt_log_file = optarg;
			break;

		default:
		usage:
			fprintf(stderr,
				"Usage:\n"
				"rpctest [-h hostname]\n");
			return 1;
		}
	}

	if (optind != argc)
		goto usage;

	if (opt_flags & RPF_QUIET)
		log_quiet();

	log_init(opt_log_format, "rpcunit", opt_log_file);
	if (!rpctest_init_nettypes())
		return 1;

	rpctest_verify_netpath_all();
	rpctest_verify_netconfig_all();
	rpctest_verify_sockets_all();
	rpctest_verify_pmap_all(opt_flags);
	rpctest_verify_rpcb_all(opt_flags);
	rpctest_verify_svc_register();
	rpctest_verify_clnt_funcs();

	log_finish();

	return num_fails != 0;
}
Example #9
0
int
sftp_server_main(int argc, char **argv, struct passwd *user_pw)
{
	fd_set *rset, *wset;
	int i, r, in, out, max, ch, skipargs = 0, log_stderr = 0;
	ssize_t len, olen, set_size;
	SyslogFacility log_facility = SYSLOG_FACILITY_AUTH;
	char *cp, *homedir = NULL, buf[4*4096];
	long mask;

	extern char *optarg;
	extern char *__progname;

	__progname = ssh_get_progname(argv[0]);
	log_init(__progname, log_level, log_facility, log_stderr);

	pw = pwcopy(user_pw);

	while (!skipargs && (ch = getopt(argc, argv,
	    "d:f:l:P:p:Q:u:cehR")) != -1) {
		switch (ch) {
		case 'Q':
			if (strcasecmp(optarg, "requests") != 0) {
				fprintf(stderr, "Invalid query type\n");
				exit(1);
			}
			for (i = 0; handlers[i].handler != NULL; i++)
				printf("%s\n", handlers[i].name);
			for (i = 0; extended_handlers[i].handler != NULL; i++)
				printf("%s\n", extended_handlers[i].name);
			exit(0);
			break;
		case 'R':
			readonly = 1;
			break;
		case 'c':
			/*
			 * Ignore all arguments if we are invoked as a
			 * shell using "sftp-server -c command"
			 */
			skipargs = 1;
			break;
		case 'e':
			log_stderr = 1;
			break;
		case 'l':
			log_level = log_level_number(optarg);
			if (log_level == SYSLOG_LEVEL_NOT_SET)
				error("Invalid log level \"%s\"", optarg);
			break;
		case 'f':
			log_facility = log_facility_number(optarg);
			if (log_facility == SYSLOG_FACILITY_NOT_SET)
				error("Invalid log facility \"%s\"", optarg);
			break;
		case 'd':
			cp = tilde_expand_filename(optarg, user_pw->pw_uid);
			homedir = percent_expand(cp, "d", user_pw->pw_dir,
			    "u", user_pw->pw_name, (char *)NULL);
			free(cp);
			break;
		case 'p':
			if (request_whitelist != NULL)
				fatal("Permitted requests already set");
			request_whitelist = xstrdup(optarg);
			break;
		case 'P':
			if (request_blacklist != NULL)
				fatal("Refused requests already set");
			request_blacklist = xstrdup(optarg);
			break;
		case 'u':
			errno = 0;
			mask = strtol(optarg, &cp, 8);
			if (mask < 0 || mask > 0777 || *cp != '\0' ||
			    cp == optarg || (mask == 0 && errno != 0))
				fatal("Invalid umask \"%s\"", optarg);
			(void)umask((mode_t)mask);
			break;
		case 'h':
		default:
			sftp_server_usage();
		}
	}

	log_init(__progname, log_level, log_facility, log_stderr);

#if defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE)
	/*
	 * On Linux, we should try to avoid making /proc/self/{mem,maps}
	 * available to the user so that sftp access doesn't automatically
	 * imply arbitrary code execution access that will break
	 * restricted configurations.
	 */
	if (prctl(PR_SET_DUMPABLE, 0) != 0)
		fatal("unable to make the process undumpable");
#endif /* defined(HAVE_PRCTL) && defined(PR_SET_DUMPABLE) */

	/* Drop any fine-grained privileges we don't need */
	platform_pledge_sftp_server();

	if ((cp = getenv("SSH_CONNECTION")) != NULL) {
		client_addr = xstrdup(cp);
		if ((cp = strchr(client_addr, ' ')) == NULL) {
			error("Malformed SSH_CONNECTION variable: \"%s\"",
			    getenv("SSH_CONNECTION"));
			sftp_server_cleanup_exit(255);
		}
		*cp = '\0';
	} else
		client_addr = xstrdup("UNKNOWN");

	logit("session opened for local user %s from [%s]",
	    pw->pw_name, client_addr);

	in = STDIN_FILENO;
	out = STDOUT_FILENO;

#ifdef HAVE_CYGWIN
	setmode(in, O_BINARY);
	setmode(out, O_BINARY);
#endif

	max = 0;
	if (in > max)
		max = in;
	if (out > max)
		max = out;

	if ((iqueue = sshbuf_new()) == NULL)
		fatal("%s: sshbuf_new failed", __func__);
	if ((oqueue = sshbuf_new()) == NULL)
		fatal("%s: sshbuf_new failed", __func__);

	rset = xcalloc(howmany(max + 1, NFDBITS), sizeof(fd_mask));
	wset = xcalloc(howmany(max + 1, NFDBITS), sizeof(fd_mask));

	if (homedir != NULL) {
		if (chdir(homedir) != 0) {
			error("chdir to \"%s\" failed: %s", homedir,
			    strerror(errno));
		}
	}

	set_size = howmany(max + 1, NFDBITS) * sizeof(fd_mask);
	for (;;) {
		memset(rset, 0, set_size);
		memset(wset, 0, set_size);

		/*
		 * Ensure that we can read a full buffer and handle
		 * the worst-case length packet it can generate,
		 * otherwise apply backpressure by stopping reads.
		 */
		if ((r = sshbuf_check_reserve(iqueue, sizeof(buf))) == 0 &&
		    (r = sshbuf_check_reserve(oqueue,
		    SFTP_MAX_MSG_LENGTH)) == 0)
			FD_SET(in, rset);
		else if (r != SSH_ERR_NO_BUFFER_SPACE)
			fatal("%s: sshbuf_check_reserve failed: %s",
			    __func__, ssh_err(r));

		olen = sshbuf_len(oqueue);
		if (olen > 0)
			FD_SET(out, wset);

		if (select(max+1, rset, wset, NULL, NULL) < 0) {
			if (errno == EINTR)
				continue;
			error("select: %s", strerror(errno));
			sftp_server_cleanup_exit(2);
		}

		/* copy stdin to iqueue */
		if (FD_ISSET(in, rset)) {
			len = read(in, buf, sizeof buf);
			if (len == 0) {
				debug("read eof");
				sftp_server_cleanup_exit(0);
			} else if (len < 0) {
				error("read: %s", strerror(errno));
				sftp_server_cleanup_exit(1);
			} else if ((r = sshbuf_put(iqueue, buf, len)) != 0) {
				fatal("%s: buffer error: %s",
				    __func__, ssh_err(r));
			}
		}
		/* send oqueue to stdout */
		if (FD_ISSET(out, wset)) {
			len = write(out, sshbuf_ptr(oqueue), olen);
			if (len < 0) {
				error("write: %s", strerror(errno));
				sftp_server_cleanup_exit(1);
			} else if ((r = sshbuf_consume(oqueue, len)) != 0) {
				fatal("%s: buffer error: %s",
				    __func__, ssh_err(r));
			}
		}

		/*
		 * Process requests from client if we can fit the results
		 * into the output buffer, otherwise stop processing input
		 * and let the output queue drain.
		 */
		r = sshbuf_check_reserve(oqueue, SFTP_MAX_MSG_LENGTH);
		if (r == 0)
			process();
		else if (r != SSH_ERR_NO_BUFFER_SPACE)
			fatal("%s: sshbuf_check_reserve: %s",
			    __func__, ssh_err(r));
	}
}
Example #10
0
File: CUN.c Project: Talustus/culfw
int
main(void)
{
  //ewb((uint8_t*)0x80, erb((uint8_t*)0x80)+1);
  wdt_enable(WDTO_2S);                     // Avoid an early reboot
  clock_prescale_set(clock_div_1);         // Disable Clock Division:1->8MHz
#ifdef HAS_XRAM
  init_memory_mapped(); // First initialize the RAM
#endif

  // if we had been restarted by watchdog check the REQ BootLoader byte in the
  // EEPROM
  if(bit_is_set(MCUSR,WDRF) && erb(EE_REQBL)) {
    ewb( EE_REQBL, 0 ); // clear flag
    start_bootloader();
  }
  while(tx_report);                     // reboot if the bss is not initialized

  // Setup the timers. Are needed for watchdog-reset
  OCR0A  = 249;                            // Timer0: 0.008s = 8MHz/256/250
  TCCR0B = _BV(CS02);       
  TCCR0A = _BV(WGM01);
  TIMSK0 = _BV(OCIE0A);

  TCCR1A = 0;
  TCCR1B = _BV(CS11) | _BV(WGM12);         // Timer1: 1us = 8MHz/8

  MCUSR &= ~(1 << WDRF);                   // Enable the watchdog

  led_init();                              // So we can debug 
  spi_init();
  eeprom_init();
  USB_Init();
  fht_init();
  tx_init();
  ethernet_init();
#ifdef HAS_FS
  df_init(&df);
  fs_init(&fs, df, 0);          // needs df_init
  log_init();                   // needs fs_init & rtc_init
  log_enabled = erb(EE_LOGENABLED);
#endif
  input_handle_func = analyze_ttydata;
  display_channel = DISPLAY_USB;

  LED_OFF();

  for(;;) {
    USB_USBTask();
    CDC_Task();
    RfAnalyze_Task();
    Minute_Task();
    FastRF_Task();
    rf_router_task();
#ifdef HAS_ASKSIN
    rf_asksin_task();
#endif
#ifdef HAS_ETHERNET
    Ethernet_Task();
#endif
  }
}
Example #11
0
int main (int argc, char **argv)
{
	log_options_t logopt = LOG_OPTS_STDERR_ONLY;
	slurm_ctl_conf_t *conf = NULL;
	shares_response_msg_t resp;

	log_init(xbasename(argv[0]), logopt, 0, NULL);
	xfree(slurmctld_conf.priority_type);
	//logopt.stderr_level += 5;
	logopt.prefix_level = 1;
	log_alter(logopt, 0, NULL);
	print_fields_have_header = 0;
	print_fields_parsable_print = PRINT_FIELDS_PARSABLE_ENDING;

	conf = slurm_conf_lock();
	/* force priority type to be multifactor */
	xfree(conf->priority_type);
	conf->priority_type = xstrdup("priority/multifactor");
	conf->priority_flags = 0;
	/* force accounting type to be slurmdbd (It doesn't really talk
	 * to any database, but needs this to work with fairshare
	 * calculation). */
	xfree(conf->accounting_storage_type);
	conf->accounting_storage_type = xstrdup("accounting_storage/slurmdbd");
	/* set up a known environment to test against.  Since we are
	 * only concerned about the fairshare we won't look at the other
	 * factors here. */
	conf->priority_decay_hl = 1;
	conf->priority_favor_small = 0;
	conf->priority_max_age = conf->priority_decay_hl;
	conf->priority_reset_period = 0;
	conf->priority_weight_age = 0;
	conf->priority_weight_fs = 10000;
	conf->priority_weight_js = 0;
	conf->priority_weight_part = 0;
	conf->priority_weight_qos = 0;
	slurm_conf_unlock();

	/* we don't want to do any decay here so make the save state
	 * to /dev/null */
	xfree(slurmctld_conf.state_save_location);
	slurmctld_conf.state_save_location = "/dev/null";
	/* now set up the association tree */
	_setup_assoc_list();
	/* now set up the job list */
	job_list = list_create(_list_delete_job);

	/* now init the priorities of the associations */
	if (slurm_priority_init() != SLURM_SUCCESS)
		fatal("failed to initialize priority plugin");
	/* on some systems that don't have multiple cores we need to
	 * sleep to make sure the thread gets started. */
	sleep(1);
	memset(&resp, 0, sizeof(shares_response_msg_t));
	resp.assoc_shares_list = assoc_mgr_get_shares(NULL, 0, NULL, NULL);
	process(&resp);

	/* free memory */
	if (slurm_priority_fini() != SLURM_SUCCESS)
		fatal("failed to finalize priority plugin");
	if (job_list)
		list_destroy(job_list);
	if (resp.assoc_shares_list)
		list_destroy(resp.assoc_shares_list);
	if (assoc_mgr_association_list)
		list_destroy(assoc_mgr_association_list);
	if (assoc_mgr_qos_list)
		list_destroy(assoc_mgr_qos_list);
	return 0;
}
Example #12
0
/* -------------------------------------------------------------------------
   make_log_entry has 1 main flaws:
   The message in its entirity, must fit into the tempbuffer.
   So it must be shorter than MAXLOGSIZE
   ------------------------------------------------------------------------- */
void make_log_entry(enum loglevels loglevel, enum logtypes logtype,
                    const char *file, int line, char *message, ...)
{
    /* fn is not reentrant but is used in signal handler
     * with LOGGER it's a little late source name and line number
     * are already changed. */
    static int inlog = 0;
    int fd, len;
    char temp_buffer[MAXLOGSIZE];
    char log_details_buffer[MAXLOGSIZE];
    va_list args;
    struct iovec iov[2];

    if (inlog)
        return;

    inlog = 1;

    if (!log_config.inited) {
      log_init();
    }
    
    if (type_configs[logtype].syslog) {
        if (type_configs[logtype].level >= loglevel) {
            /* Initialise the Messages and send it to syslog */
            va_start(args, message);
            vsnprintf(temp_buffer, MAXLOGSIZE -1, message, args);
            va_end(args);
            temp_buffer[MAXLOGSIZE -1] = 0;
            make_syslog_entry(loglevel, logtype, temp_buffer);
        }
        inlog = 0;
        return;
    }

    /* logging to a file */

    log_src_filename = file;
    log_src_linenumber = line;

    /* Check if requested logtype is setup */
    if (type_configs[logtype].set)
        /* Yes */
        fd = type_configs[logtype].fd;
    else
        /* No: use default */
        fd = type_configs[logtype_default].fd;

    if (fd < 0) {
        /* no where to send the output, give up */
        goto exit;
    }

    /* Initialise the Messages */
    va_start(args, message);
    len = vsnprintf(temp_buffer, MAXLOGSIZE -1, message, args);
    va_end(args);

    /* Append \n */
    if (len ==-1 || len >= MAXLOGSIZE -1) {
        /* vsnprintf hit the buffer size*/
        temp_buffer[MAXLOGSIZE-2] = '\n';
        temp_buffer[MAXLOGSIZE-1] = 0;
    }
    else {
        temp_buffer[len] = '\n';
        temp_buffer[len+1] = 0;
    }

    if (type_configs[logtype].level >= log_debug)
        goto log; /* bypass flooding checks */

    /* Prevent flooding: hash the message and check if we got the same one recently */
    int hash = hash_message(temp_buffer) + log_src_linenumber;

    /* Search for the same message by hash */
    for (int i = log_flood_entries - 1; i >= 0; i--) {
        if (log_flood_array[i].hash == hash) {

            /* found same message */
            log_flood_array[i].count++;

            /* Check if that message has reached LOG_FLOODING_MAXCOUNT */
            if (log_flood_array[i].count >= LOG_FLOODING_MAXCOUNT) {
                /* yes, log it and remove from array */

                /* reusing log_details_buffer */
                sprintf(log_details_buffer, "message repeated %i times\n",
                        LOG_FLOODING_MAXCOUNT - 1);
                write(fd, log_details_buffer, strlen(log_details_buffer));

                if ((i + 1) == LOG_FLOODING_ARRAY_SIZE) {
                    /* last array element, just decrement count */
                    log_flood_entries--;
                    goto exit;
                }
                /* move array elements down */
                for (int j = i + 1; j != LOG_FLOODING_ARRAY_SIZE ; j++)
                    log_flood_array[j-1] = log_flood_array[j];
                log_flood_entries--;
            }

            if (log_flood_array[i].count < LOG_FLOODING_MINCOUNT)
                /* log it */
                goto log;
            /* discard it */
            goto exit;
        } /* if */
    }  /* for */

    /* No matching message found, add this message to array*/
    if (log_flood_entries == LOG_FLOODING_ARRAY_SIZE) {
        /* array is full, discard oldest entry printing "message repeated..." if count > 1 */
        if (log_flood_array[0].count >= LOG_FLOODING_MINCOUNT) {
            /* reusing log_details_buffer */
            sprintf(log_details_buffer, "message repeated %i times\n",
                    log_flood_array[0].count - LOG_FLOODING_MINCOUNT + 1);
            write(fd, log_details_buffer, strlen(log_details_buffer));
        }
        for (int i = 1; i < LOG_FLOODING_ARRAY_SIZE; i++) {
            log_flood_array[i-1] = log_flood_array[i];
        }
        log_flood_entries--;
    }
    log_flood_array[log_flood_entries].count = 1;
    log_flood_array[log_flood_entries].hash = hash;
    log_flood_entries++;

log:
    if ( ! log_config.console) {
        generate_message_details(log_details_buffer, sizeof(log_details_buffer),
                                 type_configs[logtype].set ?
                                     type_configs[logtype].display_options :
                                     type_configs[logtype_default].display_options,
                                 loglevel, logtype);

        /* If default wasnt setup its fd is -1 */
        iov[0].iov_base = log_details_buffer;
        iov[0].iov_len = strlen(log_details_buffer);
        iov[1].iov_base = temp_buffer;
        iov[1].iov_len = strlen(temp_buffer);
        writev( fd,  iov, 2);
    } else {
        write(fd, temp_buffer, strlen(temp_buffer));
    }

exit:
    inlog = 0;
}
Example #13
0
/**
 *	Implement func.
 */
int main(int argc, char *argv[])
{
	int			dRet, i, loopCnt;
	int			dNmsIndex;
	//st_MsgQ  	stMsg;
	pst_MsgQ	pstMsg;				/* msgq ==> gifo */
	pst_MsgQSub pstMsgQSub;
	int			dWarnOutCnt = 0;	/* 20040923,poopee */
	char		szCommand[64];
    time_t		tCurTime, tCheckTime, tClientCheck, tLastPingMySQL;
	OFFSET		offset;

	SetUpSignal();

	gdStopFlag = 1;
	gdNumfds = 0;
	gdNumWfds = 0;

	log_init(S_SSHM_LOG_LEVEL, getpid(), SEQ_PROC_MMCD, LOG_PATH"/MMCD", "MMCD");

	/*
	AppLogInit(getpid(), SEQ_PROC_MMCD, MMCD_LOG, "MMCD");
	dRet = dInitLogShm();
	if( dRet < 0 )
		exit(dRet);

	dRet = Init_shm_common();
    if(dRet < 0)
    {
        log_print( LOGN_CRI,"MAIN : Failed in Init_shm_common dRet[%d][%s]", dRet, strerror(errno));
        exit(1);

	*/

	if((dRet = get_db_conf(FILE_MYSQL_CONF, szIP, szName, szPass, szAlias)) < 0)
	{
		log_print(LOGN_CRI, "F=%s:%s.%d: ERROR IN get_db_conf() dRet[%d]", __FILE__, __FUNCTION__, __LINE__, dRet);
		exit(-5);
	}

	if((dRet = db_conn(&stMySQL, szIP, szName, szPass, szAlias)) < 0)
	{
			log_print(LOGN_CRI, "F=%s:%s.%d: ERROR IN db_conn() dRet[%d]", __FILE__, __FUNCTION__, __LINE__, dRet);
		exit(-6);
	}

	/*
	if( (dRet = dInitialMysqlEnvironment(&stConnInfo)) < 0)
	{
		log_print(LOGN_CRI, "F=%s:%s.%d: ERROR IN dInitialMysqlEnvironment() dRet[%d]",
			__FILE__, __FUNCTION__, __LINE__, dRet);
		exit(-2);
	}

	if( (dRet = dConnectMySQL(&stMySQL, &stConnInfo)) < 0)
	{
		log_print(LOGN_CRI, "F=%s:%s.%d: ERROR IN dConnectMySQL() dRet[%d]",
			__FILE__, __FUNCTION__, __LINE__, dRet);
		exit(-3);
	}
	*/

	/*
	* INITIALIZE FOR MMC COMMAND
	*/
	dRet = init_mmc_server();
	if( dRet < 0 ) {
		log_print(LOGN_CRI, "[ERROR] INIT_MMC_SERVER RET[%d]\n", dRet );
		FinishProgram();
		exit(0);
	}
	/*
	* INITIALIZE FOR SHARED MEMORY FIDB
	*/
/*
	dRet = Init_Fidb();
    if( dRet < 0 ) {
        log_print(LOGN_CRI,"[ERROR] FIDB INIT [%d]\n", dRet );
        FinishProgram();
        exit(0);
    }
*/

	/*
	* INITIALIZE SOCKET
	*/
	dRet = dTcpSvrModeInit();
	if( dRet < 0 ) {
		FinishProgram();
		exit(0);
	}

	/*
	* INITIALIZE FOR SOCKET CONNECTION TABLE
	*/
	for( i = 0 ; i < MAX_FDSET2	; i++ ) {
		stConTbl[i].dSfd = -1;
		stConTbl[i].uiCliIP = 0;
		stConTbl[i].dBufLen = 0;
        stConTbl[i].szSendBuffer[0] = 0;
        stConTbl[i].cSockBlock = 0x00;
		gstMsgBuf[i].dWidx = 0;
		gstMsgBuf[i].dRidx = 0;
		memset( gstMsgBuf[i].szBuf, 0x00, sizeof(MAX_MNG_PKT_BUFSIZE) );
	}

	/*
	* GET MESSAGE QUEUE ID USING IN MMCD
	*/
    dRet = dInitIPCs();
	if( dRet < 0 ) {
		log_print(LOGN_CRI,"[ERROR] MyQid GET RET[%d]", dRet );
		FinishProgram();
		exit(0);
	}

	/* moved from init_mmc_server() */
	/* CLEAN UP ALL WARN-OUT DATA */
	for(;;) 
	{

/* msgq ==> gifo */
#if 0
		dRet = msgrcv(gdMyQid, &stMsg, sizeof(st_MsgQ) - sizeof(long int), 0, IPC_NOWAIT | MSG_NOERROR);
		if( dRet <= 0) break;
		else dWarnOutCnt++;
#endif
		offset = gifo_read(gpRECVMEMS, pCIFO, SEQ_PROC_MMCD);
		if(offset <= 0)
		{
			usleep(0);
			break;
		}
		else
		{
			dWarnOutCnt++;
			//pstMsg = (pst_MsgQ)nifo_get_value(gpRECVMEMS, DEF_MSGQ_NUM, offset);
			nifo_node_delete(gpRECVMEMS, nifo_ptr(gpRECVMEMS, offset));
		}	
	}
	log_print(LOGN_INFO, "INITIAL MESSAGE QUEUE WARN-OUT COUNT : [%d]", dWarnOutCnt );

	gdIndex = 0;
	dNmsIndex = GetUserInfo("ntasnms", 1 );

	time(&tCurTime);
	tClientCheck = tCheckTime = tCurTime;

	if( (dRet = set_version(S_SSHM_VERSION, SEQ_PROC_MMCD, vERSION)) < 0)
	{
		log_print(LOGN_WARN, "set_version error(ret=%d,idx=%d,ver=%s)\n", dRet, SEQ_PROC_MMCD, vERSION);
	}
	log_print(LOGN_CRI, "MMCD %s Started", vERSION);

	/*
	* MAIN WHILE LOOP
	*/
	while(gdStopFlag)
	{

		loopCnt = 0;
		while(1)
		{
			/* msgq ==> gifo */
			if( (dRet = dIsRcvedMessage(&pstMsg)) > 0)
			{
				pstMsgQSub	= (pst_MsgQSub)&pstMsg->llMType;
				log_print(LOGN_INFO, "RECEIVED MSGQ: Type[%d] SvcID[%d] MsgID[%d] usBodyLen[%d]", pstMsgQSub->usType, pstMsgQSub->usSvcID, pstMsgQSub->usMsgID, pstMsg->usBodyLen);
				if( (pstMsgQSub->usSvcID == SID_PATCH) && (pstMsgQSub->usMsgID == MID_SMNG_START))
				{
					sprintf(szCommand, "/WNTAMAPP/BIN/StartMC -b S_MNG");
					system(szCommand);
					log_print(LOGN_INFO, "S_MNG START MESSAGE GET");
					continue;
				}
				SendToOMP( (dbm_msg_t*)&pstMsg->szBody[0], pstMsg->usBodyLen);
				
				// TODO 제대로 된 코드인지 확인 필요
				nifo_node_delete(gpRECVMEMS, nifo_ptr(gpRECVMEMS, nifo_get_offset_node(gpRECVMEMS, (U8*)pstMsg)));
			}
			else
			{
				usleep(0);
				loopCnt++;
				if( loopCnt > 100 ){
					break;
				}
			}

#if 0
			memset(&stMsg, 0x00, sizeof(st_MsgQ));
			if( (dRet = dIsRcvedMessage(&stMsg)) > 0)
			{
				pstMsgQSub	= (pst_MsgQSub)&stMsg.llMType;
				log_print(LOGN_INFO, "RECEIVED MSGQ: Type[%d] SvcID[%d] MsgID[%d] usBodyLen[%d]", pstMsgQSub->usType, pstMsgQSub->usSvcID, pstMsgQSub->usMsgID, stMsg.usBodyLen);
				if( (pstMsgQSub->usSvcID == SID_PATCH) && (pstMsgQSub->usMsgID == MID_SMNG_START))
				{
					sprintf(szCommand, "/WNTAMAPP/BIN/StartMC -b S_MNG");
					system(szCommand);
					log_print(LOGN_INFO, "S_MNG START MESSAGE GET");
					continue;
				}
				SendToOMP( (dbm_msg_t*)&stMsg.szBody[0], stMsg.usBodyLen);

				
				
				nifo_node_delete(gpRECVMEMS, nifo_ptr(gpRECVMEMS, offset));
			}
			else if(dRet < 0)
			{
				log_print(LOGN_CRI, "[ERROR] dIsRcvedMessage PROGRAM FINISHED");
				exit(0);
			}
			else
				break;
#endif

		}

		/*
		* MAIN SOCKET CHECK
		*/
		dRet = dSocketCheck();

		/*
		* CHECK COMMAND TIMEOUT
		*/
		time(&tCurTime);

		if(abs(tCurTime-tCheckTime) >= 1)
		{
			Timer(tCurTime);
			tCheckTime = tCurTime;
		}

		/*
		* CHECK CLIENT FOR UNUSUAL CLOSE : CLIENT_CHECK_TIME(10)
		*/
		if(abs(tCurTime-tClientCheck) > CLIENT_CHECK_TIME)
		{
			CheckClient(0);
			tClientCheck = tCurTime;
		}

		if( (tCurTime - tLastPingMySQL) > SEC_OF_HOUR)
		{
			//if( (dRet = dPingMySQL(&stMySQL)) < 0)
			if((dRet = db_check_alive(&stMySQL)) < 0)
			{
				log_print(LOGN_CRI,"F=%s:%s.%d: ERROR IN dPingMySQL() dRet[%d]", __FILE__, __FUNCTION__, __LINE__, dRet);
				return -16;
			}
			tLastPingMySQL = tCurTime;
		}
	}
	FinishProgram();
	log_print(LOGN_CRI, "[EXIT] PROGRAM END !!!\n");

	return 0;
}
Example #14
0
int main(int argc, char **argv)
{
    daemonize_close_stdin();

    parse_cmdline(argc, argv);

    if (!file_read_config())
        g_error("cannot read configuration file\n");

    log_init(file_config.log, file_config.verbose);

    daemonize_init(file_config.daemon_user, file_config.pidfile);

    if (!file_config.no_daemon)
        daemonize_detach();

    daemonize_write_pidfile();
    daemonize_set_user();

#ifndef NDEBUG
    if (!file_config.no_daemon)
#endif
        daemonize_close_stdout_stderr();

    main_loop = g_main_loop_new(NULL, FALSE);

    lmc_connect(file_config.host, file_config.port);
    http_client_init();
    as_init(file_config.scrobblers);

    setup_signals();

    timer = g_timer_new();

    /* set up timeouts */

    save_source_id = g_timeout_add_seconds(file_config.journal_interval,
                                           timer_save_journal, NULL);

    /* run the main loop */

    g_main_loop_run(main_loop);

    /* cleanup */

    g_message("shutting down\n");

    g_source_remove(save_source_id);
    g_main_loop_unref(main_loop);

    g_timer_destroy(timer);

    as_save_cache();
    as_cleanup();
    http_client_finish();
    lmc_disconnect();
    file_cleanup();
    log_deinit();

    daemonize_finish();

    return 0;
}
void amf_cluster_init (void)
{
    log_init ("AMF");
}
Example #16
0
void Rover::init_ardupilot()
{
    // initialise console serial port
    serial_manager.init_console();

	cliSerial->printf_P(PSTR("\n\nInit " FIRMWARE_STRING
						 "\n\nFree RAM: %u\n"),
                        hal.util->available_memory());
                    
	//
	// Check the EEPROM format version before loading any parameters from EEPROM.
	//
	
    load_parameters();

    BoardConfig.init();

    // initialise serial ports
    serial_manager.init();

    ServoRelayEvents.set_channel_mask(0xFFF0);

    set_control_channels();

    battery.init();

    // keep a record of how many resets have happened. This can be
    // used to detect in-flight resets
    g.num_resets.set_and_save(g.num_resets+1);

    // init baro before we start the GCS, so that the CLI baro test works
    barometer.init();

	// init the GCS
    gcs[0].setup_uart(serial_manager, AP_SerialManager::SerialProtocol_Console, 0);

    // we start by assuming USB connected, as we initialed the serial
    // port with SERIAL0_BAUD. check_usb_mux() fixes this if need be.    
    usb_connected = true;
    check_usb_mux();

    // setup serial port for telem1
    gcs[1].setup_uart(serial_manager, AP_SerialManager::SerialProtocol_MAVLink, 0);

#if MAVLINK_COMM_NUM_BUFFERS > 2
    // setup serial port for telem2
    gcs[2].setup_uart(serial_manager, AP_SerialManager::SerialProtocol_MAVLink, 1);
#endif

#if MAVLINK_COMM_NUM_BUFFERS > 3
    // setup serial port for fourth telemetry port (not used by default)
    gcs[3].setup_uart(serial_manager, AP_SerialManager::SerialProtocol_MAVLink, 2);
#endif

    // setup frsky telemetry
#if FRSKY_TELEM_ENABLED == ENABLED
    frsky_telemetry.init(serial_manager);
#endif

	mavlink_system.sysid = g.sysid_this_mav;

#if LOGGING_ENABLED == ENABLED
    log_init();
#endif

    // Register mavlink_delay_cb, which will run anytime you have
    // more than 5ms remaining in your call to hal.scheduler->delay
    hal.scheduler->register_delay_callback(mavlink_delay_cb_static, 5);

#if CONFIG_HAL_BOARD == HAL_BOARD_APM1
    apm1_adc.Init();      // APM ADC library initialization
#endif

	if (g.compass_enabled==true) {
		if (!compass.init()|| !compass.read()) {
            cliSerial->println_P(PSTR("Compass initialisation failed!"));
            g.compass_enabled = false;
        } else {
            ahrs.set_compass(&compass);
            //compass.get_offsets();						// load offsets to account for airframe magnetic interference
        }
	}

	// initialise sonar
    init_sonar();

    // and baro for EKF
    init_barometer();

	// Do GPS init
    gps.init(&DataFlash, serial_manager);

    rc_override_active = hal.rcin->set_overrides(rc_override, 8);

	init_rc_in();		// sets up rc channels from radio
	init_rc_out();		// sets up the timer libs

    relay.init();

#if MOUNT == ENABLED
    // initialise camera mount
    camera_mount.init(serial_manager);
#endif

    /*
      setup the 'main loop is dead' check. Note that this relies on
      the RC library being initialised.
     */
    hal.scheduler->register_timer_failsafe(failsafe_check_static, 1000);


#if CLI_ENABLED == ENABLED
	// If the switch is in 'menu' mode, run the main menu.
	//
	// Since we can't be sure that the setup or test mode won't leave
	// the system in an odd state, we don't let the user exit the top
	// menu; they must reset in order to fly.
	//
    if (g.cli_enabled == 1) {
        const prog_char_t *msg = PSTR("\nPress ENTER 3 times to start interactive setup\n");
        cliSerial->println_P(msg);
        if (gcs[1].initialised && (gcs[1].get_uart() != NULL)) {
            gcs[1].get_uart()->println_P(msg);
        }
        if (num_gcs > 2 && gcs[2].initialised && (gcs[2].get_uart() != NULL)) {
            gcs[2].get_uart()->println_P(msg);
        }
    }
#endif

	init_capabilities();

	startup_ground();
    Log_Write_Startup(TYPE_GROUNDSTART_MSG);

    set_mode((enum mode)g.initial_mode.get());

	// set the correct flight mode
	// ---------------------------
	reset_control_switch();
}
Example #17
0
void parse_vm_arguments1(JavaVMInitArgs *vm_args, size_t *p_string_pool_size,
                         jboolean *p_is_class_data_shared, apr_pool_t* pool)
{
    LogFormat logger_header = LOG_EMPTY;
    *p_string_pool_size = DEFAULT_STRING_TABLE_SIZE;

    // initialize logging system as soon as possible
    log_init(pool);

    for (int i = 0; i < vm_args->nOptions; i++) {
        const char* option = vm_args->options[i].optionString;
        if (begins_with(option, STRING_POOL_SIZE_OPTION)) {
            const char* arg = option + strlen(STRING_POOL_SIZE_OPTION);
            *p_string_pool_size = parse_size(arg);
            if (0 == *p_string_pool_size) {
                LECHO(34, "Negative or invalid string pool size. A default value is used, "
                    << DEFAULT_STRING_TABLE_SIZE << " bytes.");
                *p_string_pool_size = DEFAULT_STRING_TABLE_SIZE;
            }
            TRACE("string_pool_size = " << *p_string_pool_size);
        } else if (!strcmp(option, CLASS_DATA_SHARING_OFF_OPTION)) {
            *p_is_class_data_shared = JNI_FALSE;
        } else if (!strcmp(option, CLASS_DATA_SHARING_ON_OPTION)) {
            *p_is_class_data_shared = JNI_TRUE;
        } else if (!strcmp(option, PORTLIB_OPTION)) {
            log_set_portlib((HyPortLibrary*) vm_args->options[i].extraInfo);
        } else if (!strcmp(option, "vfprintf")) {
            log_set_vfprintf(vm_args->options[i].extraInfo);
        } else if (!strcmp(option, "exit")) {
            log_set_exit(vm_args->options[i].extraInfo);
        } else if (!strcmp(option, "abort")) {
            log_set_abort(vm_args->options[i].extraInfo);
        } else if (!strcmp(option, "-Xfileline")) {
            logger_header |= LOG_FILELINE;
        } else if (!strcmp(option, "-Xthread")) {
            logger_header |= LOG_THREAD_ID;
        } else if (!strcmp(option, "-Xcategory")) {
            logger_header |= LOG_CATEGORY;
        } else if (!strcmp(option, "-Xtimestamp")) {
            logger_header |= LOG_TIMESTAMP;
        } else if (!strcmp(option, "-Xfunction")) {
            logger_header |= LOG_FUNCTION;
        } else if (!strcmp(option, "-Xwarn")) {
            logger_header |= LOG_WARN;
        /*
         * -verbose[:class|:gc|:jni] set specification log filters.
         */
        } else if (!strcmp(option, "-verbose")) {
            log_enable_info_category(LOG_CLASS_INFO, 0);
            log_enable_info_category(LOG_GC_INFO, 0);
            log_enable_info_category(LOG_JNI_INFO, 0);
        }  else if (!strcmp(option, "-verbose:class")) {
            log_enable_info_category(LOG_CLASS_INFO, 0);
        }  else if (!strcmp(option, "-verbose:gc")) {
            log_enable_info_category(LOG_GC_INFO, 0);
        }  else if (!strcmp(option, "-verbose:jni")) {
            log_enable_info_category(LOG_JNI_INFO, 0);
        } else if (begins_with(option, "-Xverboselog:")) {
            const char* file_name = option + strlen("-Xverboselog:");
            FILE *f = fopen(file_name, "w");
            if (NULL != f) {
                log_set_out(f);
            } else {
                WARN(("Cannot open: %s", file_name));
            }
        } else if (begins_with(option, "-Xverbose:")) {
            log_enable_info_category(option + strlen("-Xverbose:"), 1);
        } else if (begins_with(option, "-Xnoverbose:")) {
            log_disable_info_category(option + strlen("-Xnoverbose:"), 1);
#ifdef _DEBUG
        } else if (begins_with(option, "-Xtrace:")) {
            log_enable_trace_category(option + strlen("-Xtrace:"), 1);
        } else if (begins_with(option, "-Xnotrace:")) {
            log_disable_trace_category(option + strlen("-Xnotrace:"), 1);
#endif //_DEBUG
        }
    }
    log_set_header_format(logger_header);
} // parse_vm_arguments1
Example #18
0
/** daemonize, drop user priviliges and chroot if needed */
static void
perform_setup(struct daemon* daemon, struct config_file* cfg, int debug_mode,
	const char** cfgfile)
{
#ifdef HAVE_KILL
	int pidinchroot;
#endif
#ifdef HAVE_GETPWNAM
	struct passwd *pwd = NULL;

	if(cfg->username && cfg->username[0]) {
		if((pwd = getpwnam(cfg->username)) == NULL)
			fatal_exit("user '%s' does not exist.", cfg->username);
		/* endpwent below, in case we need pwd for setusercontext */
	}
#endif
#ifdef UB_ON_WINDOWS
	w_config_adjust_directory(cfg);
#endif

	/* init syslog (as root) if needed, before daemonize, otherwise
	 * a fork error could not be printed since daemonize closed stderr.*/
	if(cfg->use_syslog) {
		log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
	}
	/* if using a logfile, we cannot open it because the logfile would
	 * be created with the wrong permissions, we cannot chown it because
	 * we cannot chown system logfiles, so we do not open at all.
	 * So, using a logfile, the user does not see errors unless -d is
	 * given to unbound on the commandline. */

	/* read ssl keys while superuser and outside chroot */
#ifdef HAVE_SSL
	if(!(daemon->rc = daemon_remote_create(cfg)))
		fatal_exit("could not set up remote-control");
	if(cfg->ssl_service_key && cfg->ssl_service_key[0]) {
		if(!(daemon->listen_sslctx = listen_sslctx_create(
			cfg->ssl_service_key, cfg->ssl_service_pem, NULL)))
			fatal_exit("could not set up listen SSL_CTX");
	}
	if(!(daemon->connect_sslctx = connect_sslctx_create(NULL, NULL, NULL)))
		fatal_exit("could not set up connect SSL_CTX");
#endif

#ifdef HAVE_KILL
	/* true if pidfile is inside chrootdir, or nochroot */
	pidinchroot = !(cfg->chrootdir && cfg->chrootdir[0]) ||
				(cfg->chrootdir && cfg->chrootdir[0] &&
				strncmp(cfg->pidfile, cfg->chrootdir,
				strlen(cfg->chrootdir))==0);

	/* check old pid file before forking */
	if(cfg->pidfile && cfg->pidfile[0]) {
		/* calculate position of pidfile */
		if(cfg->pidfile[0] == '/')
			daemon->pidfile = strdup(cfg->pidfile);
		else	daemon->pidfile = fname_after_chroot(cfg->pidfile, 
				cfg, 1);
		if(!daemon->pidfile)
			fatal_exit("pidfile alloc: out of memory");
		checkoldpid(daemon->pidfile, pidinchroot);
	}
#endif

	/* daemonize because pid is needed by the writepid func */
	if(!debug_mode && cfg->do_daemonize) {
		detach();
	}

	/* write new pidfile (while still root, so can be outside chroot) */
#ifdef HAVE_KILL
	if(cfg->pidfile && cfg->pidfile[0]) {
		writepid(daemon->pidfile, getpid());
		if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1 &&
			pidinchroot) {
#  ifdef HAVE_CHOWN
			if(chown(daemon->pidfile, cfg_uid, cfg_gid) == -1) {
				verbose(VERB_QUERY, "cannot chown %u.%u %s: %s",
					(unsigned)cfg_uid, (unsigned)cfg_gid,
					daemon->pidfile, strerror(errno));
			}
#  endif /* HAVE_CHOWN */
		}
	}
#else
	(void)daemon;
#endif /* HAVE_KILL */

	/* Set user context */
#ifdef HAVE_GETPWNAM
	if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
#ifdef HAVE_SETUSERCONTEXT
		/* setusercontext does initgroups, setuid, setgid, and
		 * also resource limits from login config, but we
		 * still call setresuid, setresgid to be sure to set all uid*/
		if(setusercontext(NULL, pwd, cfg_uid, (unsigned)
			LOGIN_SETALL & ~LOGIN_SETUSER & ~LOGIN_SETGROUP) != 0)
			log_warn("unable to setusercontext %s: %s",
				cfg->username, strerror(errno));
#endif /* HAVE_SETUSERCONTEXT */
	}
#endif /* HAVE_GETPWNAM */

	/* box into the chroot */
#ifdef HAVE_CHROOT
	if(cfg->chrootdir && cfg->chrootdir[0]) {
		if(chdir(cfg->chrootdir)) {
			fatal_exit("unable to chdir to chroot %s: %s",
				cfg->chrootdir, strerror(errno));
		}
		verbose(VERB_QUERY, "chdir to %s", cfg->chrootdir);
		if(chroot(cfg->chrootdir))
			fatal_exit("unable to chroot to %s: %s", 
				cfg->chrootdir, strerror(errno));
		if(chdir("/"))
			fatal_exit("unable to chdir to / in chroot %s: %s",
				cfg->chrootdir, strerror(errno));
		verbose(VERB_QUERY, "chroot to %s", cfg->chrootdir);
		if(strncmp(*cfgfile, cfg->chrootdir, 
			strlen(cfg->chrootdir)) == 0) 
			(*cfgfile) += strlen(cfg->chrootdir);

		/* adjust stored pidfile for chroot */
		if(daemon->pidfile && daemon->pidfile[0] && 
			strncmp(daemon->pidfile, cfg->chrootdir,
			strlen(cfg->chrootdir))==0) {
			char* old = daemon->pidfile;
			daemon->pidfile = strdup(old+strlen(cfg->chrootdir));
			free(old);
			if(!daemon->pidfile)
				log_err("out of memory in pidfile adjust");
		}
		daemon->chroot = strdup(cfg->chrootdir);
		if(!daemon->chroot)
			log_err("out of memory in daemon chroot dir storage");
	}
#else
	(void)cfgfile;
#endif
	/* change to working directory inside chroot */
	if(cfg->directory && cfg->directory[0]) {
		char* dir = cfg->directory;
		if(cfg->chrootdir && cfg->chrootdir[0] &&
			strncmp(dir, cfg->chrootdir, 
			strlen(cfg->chrootdir)) == 0)
			dir += strlen(cfg->chrootdir);
		if(dir[0]) {
			if(chdir(dir)) {
				fatal_exit("Could not chdir to %s: %s",
					dir, strerror(errno));
			}
			verbose(VERB_QUERY, "chdir to %s", dir);
		}
	}

	/* drop permissions after chroot, getpwnam, pidfile, syslog done*/
#ifdef HAVE_GETPWNAM
	if(cfg->username && cfg->username[0] && cfg_uid != (uid_t)-1) {
#  ifdef HAVE_INITGROUPS
		if(initgroups(cfg->username, cfg_gid) != 0)
			log_warn("unable to initgroups %s: %s",
				cfg->username, strerror(errno));
#  endif /* HAVE_INITGROUPS */
#  ifdef HAVE_ENDPWENT
		endpwent();
#  endif

#ifdef HAVE_SETRESGID
		if(setresgid(cfg_gid,cfg_gid,cfg_gid) != 0)
#elif defined(HAVE_SETREGID) && !defined(DARWIN_BROKEN_SETREUID)
		if(setregid(cfg_gid,cfg_gid) != 0)
#else /* use setgid */
		if(setgid(cfg_gid) != 0)
#endif /* HAVE_SETRESGID */
			fatal_exit("unable to set group id of %s: %s", 
				cfg->username, strerror(errno));
#ifdef HAVE_SETRESUID
		if(setresuid(cfg_uid,cfg_uid,cfg_uid) != 0)
#elif defined(HAVE_SETREUID) && !defined(DARWIN_BROKEN_SETREUID)
		if(setreuid(cfg_uid,cfg_uid) != 0)
#else /* use setuid */
		if(setuid(cfg_uid) != 0)
#endif /* HAVE_SETRESUID */
			fatal_exit("unable to set user id of %s: %s", 
				cfg->username, strerror(errno));
		verbose(VERB_QUERY, "drop user privileges, run as %s", 
			cfg->username);
	}
#endif /* HAVE_GETPWNAM */
	/* file logging inited after chroot,chdir,setuid is done so that 
	 * it would succeed on SIGHUP as well */
	if(!cfg->use_syslog)
		log_init(cfg->logfile, cfg->use_syslog, cfg->chrootdir);
}
int
sftp_server_main(int argc, char **argv, struct passwd *user_pw)
{
	fd_set *rset, *wset;
	int in, out, max, ch, skipargs = 0, log_stderr = 0;
        char udp_syslog_server_name[256];
	ssize_t len, olen, set_size;
	SyslogFacility log_facility = SYSLOG_FACILITY_AUTH;
	char *cp, buf[4*4096];
	long mask;

	extern char *optarg;
	extern char *__progname;

	__progname = ssh_get_progname(argv[0]);
	log_init(__progname, log_level, log_facility, log_stderr);

	while (!skipargs && (ch = getopt(argc, argv, "f:l:u:s:cehR")) != -1) {
		switch (ch) {
		case 'R':
			readonly = 1;
			break;
		case 'c':
			/*
			 * Ignore all arguments if we are invoked as a
			 * shell using "sftp-server -c command"
			 */
			skipargs = 1;
			break;
		case 'e':
			log_stderr = 1;
			break;
		case 'l':
			log_level = log_level_number(optarg);
			if (log_level == SYSLOG_LEVEL_NOT_SET)
				error("Invalid log level \"%s\"", optarg);
			break;
		case 'f':
			log_facility = log_facility_number(optarg);
			if (log_facility == SYSLOG_FACILITY_NOT_SET)
				error("Invalid log facility \"%s\"", optarg);
			break;
		case 'u':
			errno = 0;
			mask = strtol(optarg, &cp, 8);
			if (mask < 0 || mask > 0777 || *cp != '\0' ||
			    cp == optarg || (mask == 0 && errno != 0))
				fatal("Invalid umask \"%s\"", optarg);
			(void)umask((mode_t)mask);
			break;
		case 's':
			strlcpy(udp_syslog_server_name,optarg,sizeof(udp_syslog_server_name));
			break;
		case 'h':
		default:
			sftp_server_usage();
		}
	}

	log_init(__progname, log_level, log_facility, log_stderr);
	if (udp_syslog_server_name) {
		udp_log_init(__progname, log_level, log_facility, udp_syslog_server_name);
	}
	if ((cp = getenv("SSH_CONNECTION")) != NULL) {
		client_addr = xstrdup(cp);
		if ((cp = strchr(client_addr, ' ')) == NULL) {
			error("Malformed SSH_CONNECTION variable: \"%s\"",
			    getenv("SSH_CONNECTION"));
			sftp_server_cleanup_exit(255);
		}
		*cp = '\0';
	} else
		client_addr = xstrdup("UNKNOWN");

	pw = pwcopy(user_pw);

	logit("session opened for local user %s from [%s]",
	    pw->pw_name, client_addr);

	in = STDIN_FILENO;
	out = STDOUT_FILENO;

#ifdef HAVE_CYGWIN
	setmode(in, O_BINARY);
	setmode(out, O_BINARY);
#endif

	max = 0;
	if (in > max)
		max = in;
	if (out > max)
		max = out;

	buffer_init(&iqueue);
	buffer_init(&oqueue);

	set_size = howmany(max + 1, NFDBITS) * sizeof(fd_mask);
	rset = (fd_set *)xmalloc(set_size);
	wset = (fd_set *)xmalloc(set_size);

	for (;;) {
		memset(rset, 0, set_size);
		memset(wset, 0, set_size);

		/*
		 * Ensure that we can read a full buffer and handle
		 * the worst-case length packet it can generate,
		 * otherwise apply backpressure by stopping reads.
		 */
		if (buffer_check_alloc(&iqueue, sizeof(buf)) &&
		    buffer_check_alloc(&oqueue, SFTP_MAX_MSG_LENGTH))
			FD_SET(in, rset);

		olen = buffer_len(&oqueue);
		if (olen > 0)
			FD_SET(out, wset);

		if (select(max+1, rset, wset, NULL, NULL) < 0) {
			if (errno == EINTR)
				continue;
			error("select: %s", strerror(errno));
			sftp_server_cleanup_exit(2);
		}

		/* copy stdin to iqueue */
		if (FD_ISSET(in, rset)) {
			len = read(in, buf, sizeof buf);
			if (len == 0) {
				debug("read eof");
				sftp_server_cleanup_exit(0);
			} else if (len < 0) {
				error("read: %s", strerror(errno));
				sftp_server_cleanup_exit(1);
			} else {
				buffer_append(&iqueue, buf, len);
			}
		}
		/* send oqueue to stdout */
		if (FD_ISSET(out, wset)) {
			len = write(out, buffer_ptr(&oqueue), olen);
			if (len < 0) {
				error("write: %s", strerror(errno));
				sftp_server_cleanup_exit(1);
			} else {
				buffer_consume(&oqueue, len);
			}
		}

		/*
		 * Process requests from client if we can fit the results
		 * into the output buffer, otherwise stop processing input
		 * and let the output queue drain.
		 */
		if (buffer_check_alloc(&oqueue, SFTP_MAX_MSG_LENGTH))
			process();
	}
}
Example #20
0
/**
 * main program. Set options given commandline arguments.
 * @param argc: number of commandline arguments.
 * @param argv: array of commandline arguments.
 * @return: exit status of the program.
 */
int 
main(int argc, char* argv[])
{
	int c;
	const char* cfgfile = CONFIGFILE;
	const char* winopt = NULL;
	const char* log_ident_default;
	int cmdline_verbose = 0;
	int debug_mode = 0;
#ifdef UB_ON_WINDOWS
	int cmdline_cfg = 0;
#endif

	log_init(NULL, 0, NULL);
	log_ident_default = strrchr(argv[0],'/')?strrchr(argv[0],'/')+1:argv[0];
	log_ident_set(log_ident_default);
	/* parse the options */
	while( (c=getopt(argc, argv, "c:dhvw:")) != -1) {
		switch(c) {
		case 'c':
			cfgfile = optarg;
#ifdef UB_ON_WINDOWS
			cmdline_cfg = 1;
#endif
			break;
		case 'v':
			cmdline_verbose++;
			verbosity++;
			break;
		case 'd':
			debug_mode++;
			break;
		case 'w':
			winopt = optarg;
			break;
		case '?':
		case 'h':
		default:
			usage();
			return 1;
		}
	}
	argc -= optind;
	argv += optind;

	if(winopt) {
#ifdef UB_ON_WINDOWS
		wsvc_command_option(winopt, cfgfile, cmdline_verbose, 
			cmdline_cfg);
#else
		fatal_exit("option not supported");
#endif
	}

	if(argc != 0) {
		usage();
		return 1;
	}

	run_daemon(cfgfile, cmdline_verbose, debug_mode, log_ident_default);
	log_init(NULL, 0, NULL); /* close logfile */
	return 0;
}
Example #21
0
int main(int argc, char *argv[]) {
    int argchar;
    char* outfn = NULL;
    char* infn;
    int overwrite = 0;
    int loglvl = LOG_MSG;
    anbool do_u8 = TRUE;
    int downsample = 0;
    int downsample_as_reqd = 0;
    int extension = 0;
    int plane = 0;

    simplexy_t sparams;
    simplexy_t* params = &sparams;

    memset(params, 0, sizeof(simplexy_t));

    while ((argchar = getopt (argc, argv, OPTIONS)) != -1) {
        switch (argchar) {
        case 'L':
            params->Lorder = atoi(optarg);
            break;
        case 'w':
            params->dpsf = atof(optarg);
            break;
        case 'a':
            params->saddle = atof(optarg);
            break;
        case 'm':
            params->maxsize = atoi(optarg);
            break;
        case 'g':
            params->sigma = atof(optarg);
            break;
        case 'b':
            params->nobgsub = TRUE;
            break;
        case 'G':
            params->nobgsub = TRUE;
            params->globalbg = atof(optarg);
            break;
        case 'P':
            plane = atoi(optarg);
            break;
        case 's':
            params->halfbox = atoi(optarg);
            break;
        case 'p':
            params->plim = atof(optarg);
            break;
        case 'B':
            params->bgimgfn = optarg;
            break;
        case 'S':
            params->bgsubimgfn = optarg;
            break;
        case 'M':
            params->maskimgfn = optarg;
            break;
        case 'U':
            params->smoothimgfn = optarg;
            break;
        case 'C':
            params->blobimgfn = optarg;
            break;
        case 'e':
            extension = atoi(optarg);
            break;
        case 'D':
            downsample_as_reqd = atoi(optarg);
            break;
        case 'H':
            downsample = 2;
            break;
        case 'd':
            downsample = atoi(optarg);
            break;
        case '8':
            do_u8 = FALSE;
            break;
        case 'v':
            loglvl++;
            break;
        case 'O':
            overwrite = 1;
            break;
        case 'o':
            outfn = strdup(optarg);
            break;
        case '?':
        case 'h':
            printHelp();
            exit(0);
        }
    }
    
    if (optind != argc - 1) {
        printHelp();
        exit(-1);
    }

    infn = argv[optind];

    log_init(loglvl);
    logverb("infile=%s\n", infn);

    if (!outfn) {
        // Create xylist filename (by trimming '.fits')
        asprintf_safe(&outfn, "%.*s.xy.fits", (int)(strlen(infn)-5), infn);
        logverb("outfile=%s\n", outfn);
    }

    if (overwrite && file_exists(outfn)) {
        logverb("Deleting existing output file \"%s\"...\n", outfn);
        if (unlink(outfn)) {
            SYSERROR("Failed to delete existing output file \"%s\"", outfn);
            exit(-1);
        }
    }

    if (downsample)
        logverb("Downsampling by %i\n", downsample);

    if (image2xy_files(infn, outfn, do_u8, downsample, downsample_as_reqd,
                       extension, plane, params)) {
        ERROR("image2xy failed.");
        exit(-1);
    }
    free(outfn);
    return 0;
}
Example #22
0
int main (int argc, char *argv[])
{
    int rc;
    zctx_t *zctx;
    void *zs;
    pthread_t tid;
    pthread_attr_t attr;
    zmsg_t *zmsg;
    int i, ch;
    const char *uritmpl = "ipc://*";
    int timeout_sec = 1;

    log_init (basename (argv[0]));

    while ((ch = getopt_long (argc, argv, OPTIONS, longopts, NULL)) != -1) {
        switch (ch) {
            case 'r':
                raw = true;
                break;
            case 'l':
                lopt = true;
                linger = strtol (optarg, NULL, 10);
                break;
            case 'i':
                iopt = true;
                imm = strtol (optarg, NULL, 10);
                break;
            case 't':
                uritmpl = "tcp://*:*";
                break;
            case 'T':
                timeout_sec = strtoul (optarg, NULL, 10);
                break;
            case 's':
                bufsize = strtoul (optarg, NULL, 10);
                break;
            case 'v':
                vopt = true;
                break;
            case 'S':
                sleep_usec = strtoul (optarg, NULL, 10);;
                break;
            default:
                usage ();
                /*NOTREACHED*/
        }
    }
    if (optind != argc - 1)
        usage ();
    iter = strtoul (argv[optind++], NULL, 10);

    /* Create socket and bind to it.
     * Store uri in global variable.
     */
    if (!(zctx = zctx_new ()))
        log_err_exit ("S: zctx_new");
    if (!(zs = zsocket_new (zctx, ZMQ_ROUTER)))
        log_err_exit ("S: zsocket_new");
    zsocket_set_rcvhwm (zs, 0); /* unlimited */
    if (zsocket_bind (zs, "%s", uritmpl) < 0)
        log_err_exit ("S: zsocket_bind");
    uri = zsocket_last_endpoint (zs);

    /* Spawn thread which will be our client.
     */
    if ((rc = pthread_attr_init (&attr)))
        log_errn (rc, "S: pthread_attr_init");
    if ((rc = pthread_create (&tid, &attr, thread, NULL)))
        log_errn (rc, "S: pthread_create");

    /* Handle 'iter' client messages with timeout
     */
    for (i = 0; i < iter; i++) {
        alarm (timeout_sec);
        if (!(zmsg = zmsg_recv (zs)))
            log_err_exit ("S: zmsg_recv");
        zmsg_destroy (&zmsg);
        alarm (0);
        if (vopt)
            log_msg ("received message %d of %d", i + 1, iter);
    }

    /* Wait for thread to terminate, then clean up.
     */
    if ((rc = pthread_join (tid, NULL)))
        log_errn (rc, "S: pthread_join");
    zctx_destroy (&zctx); /* destroys sockets too */

    if (strstr (uri, "ipc://"))
        (void)unlink (uri);

    log_fini ();

    return 0;
}
Example #23
0
/**
 * Main fake event test program. Setup, teardown and report errors.
 * @param argc: arg count.
 * @param argv: array of commandline arguments.
 * @return program failure if test fails.
 */
int 
main(int argc, char* argv[])
{
	int c, res;
	int pass_argc = 0;
	char* pass_argv[MAXARG];
	char* playback_file = NULL;
	int init_optind = optind;
	char* init_optarg = optarg;
	struct replay_scenario* scen = NULL;

	/* we do not want the test to depend on the timezone */
	(void)putenv("TZ=UTC");

	log_init(NULL, 0, NULL);
	/* determine commandline options for the daemon */
	pass_argc = 1;
	pass_argv[0] = "unbound";
	add_opts("-d", &pass_argc, pass_argv);
	while( (c=getopt(argc, argv, "2egho:p:s")) != -1) {
		switch(c) {
		case 's':
			free(pass_argv[1]);
			testbound_selftest();
			printf("selftest successful\n");
			exit(0);
		case '2':
#if (defined(HAVE_EVP_SHA256) || defined(HAVE_NSS)) && defined(USE_SHA2)
			printf("SHA256 supported\n");
			exit(0);
#else
			printf("SHA256 not supported\n");
			exit(1);
#endif
			break;
		case 'e':
#if defined(USE_ECDSA)
			printf("ECDSA supported\n");
			exit(0);
#else
			printf("ECDSA not supported\n");
			exit(1);
#endif
			break;
		case 'g':
#ifdef USE_GOST
			if(sldns_key_EVP_load_gost_id()) {
				printf("GOST supported\n");
				exit(0);
			} else {
				printf("GOST not supported\n");
				exit(1);
			}
#else
			printf("GOST not supported\n");
			exit(1);
#endif
			break;
		case 'p':
			playback_file = optarg;
			break;
		case 'o':
			add_opts(optarg, &pass_argc, pass_argv);
			break;
		case '?':
		case 'h':
		default:
			testbound_usage();
			return 1;
		}
	}
	argc -= optind;
	argv += optind;
	if(argc != 0) {
		testbound_usage();
		return 1;
	}
	log_info("Start of %s testbound program.", PACKAGE_STRING);
	if(atexit(&remove_configfile) != 0)
		fatal_exit("atexit() failed: %s", strerror(errno));

	/* setup test environment */
	scen = setup_playback(playback_file, &pass_argc, pass_argv);
	/* init fake event backend */
	fake_event_init(scen);

	pass_argv[pass_argc] = NULL;
	echo_cmdline(pass_argc, pass_argv);

	/* reset getopt processing */
	optind = init_optind;
	optarg = init_optarg;

	/* run the normal daemon */
	res = daemon_main(pass_argc, pass_argv);

	fake_event_cleanup();
	for(c=1; c<pass_argc; c++)
		free(pass_argv[c]);
	if(res == 0) {
		log_info("Testbound Exit Success");
#ifdef HAVE_PTHREAD
		/* dlopen frees its thread state (dlopen of gost engine) */
		pthread_exit(NULL);
#endif
	}
	return res;
}
Example #24
0
int main(int argc, char *argv[])
{
    int camera = 0;
    SDL_Joystick *joy = NULL;

    if (!fs_init(argv[0]))
    {
        fprintf(stderr, "Failure to initialize virtual file system (%s)\n",
                fs_error());
        return 1;
    }

    srand((int) time(NULL));

    opt_parse(argc, argv);

    config_paths(opt_data);
    log_init("Neverputt", "neverputt.log");
    fs_mkdir("Screenshots");

    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK) == 0)
    {
        config_init();
        config_load();

        /* Initialize localization. */

        lang_init();

        /* Cache Neverball's camera setting. */

        camera = config_get_d(CONFIG_CAMERA);

        /* Initialize the joystick. */

        if (config_get_d(CONFIG_JOYSTICK) && SDL_NumJoysticks() > 0)
        {
            joy = SDL_JoystickOpen(config_get_d(CONFIG_JOYSTICK_DEVICE));
            if (joy)
            {
                SDL_JoystickEventState(SDL_ENABLE);
                set_joystick(joy);
            }
        }

        /* Initialize the audio. */

        audio_init();

        /* Initialize the video. */

        if (video_init())
        {
            int t1, t0 = SDL_GetTicks();

            /* Material system. */

            mtrl_init();

            /* Run the main game loop. */

            init_state(&st_null);

            if (opt_hole)
            {
                const char *path = fs_resolve(opt_hole);
                int loaded = 0;

                if (path)
                {
                    hole_init(NULL);

                    if (hole_load(0, path) &&
                        hole_load(1, path) &&
                        hole_goto(1, 1))
                    {
                        goto_state(&st_next);
                        loaded = 1;
                    }
                }

                if (!loaded)
                    goto_state(&st_title);
            }
            else
                goto_state(&st_title);

            while (loop())
                if ((t1 = SDL_GetTicks()) > t0)
                {
                    st_timer((t1 - t0) / 1000.f);
                    hmd_step();
                    st_paint(0.001f * t1);
                    video_swap();

                    t0 = t1;

                    if (config_get_d(CONFIG_NICE))
                        SDL_Delay(1);
                }

            mtrl_quit();
        }

        /* Restore Neverball's camera setting. */

        config_set_d(CONFIG_CAMERA, camera);
        config_save();

        SDL_Quit();
    }
    else log_printf("Failure to initialize SDL (%s)\n", SDL_GetError());

    return 0;
}
Example #25
0
/** Main routine for unbound-control */
int main(int argc, char* argv[])
{
	int c, ret;
	int quiet = 0;
	const char* cfgfile = CONFIGFILE;
	char* svr = NULL;
#ifdef USE_WINSOCK
	int r;
	WSADATA wsa_data;
#endif
#ifdef USE_THREAD_DEBUG
	/* stop the file output from unbound-control, overwrites the servers */
	extern int check_locking_order;
	check_locking_order = 0;
#endif /* USE_THREAD_DEBUG */
	log_ident_set("unbound-control");
	log_init(NULL, 0, NULL);
	checklock_start();
#ifdef USE_WINSOCK
	/* use registry config file in preference to compiletime location */
	if(!(cfgfile=w_lookup_reg_str("Software\\Unbound", "ConfigFile")))
		cfgfile = CONFIGFILE;
#endif
	/* parse the options */
	while( (c=getopt(argc, argv, "c:s:qh")) != -1) {
		switch(c) {
		case 'c':
			cfgfile = optarg;
			break;
		case 's':
			svr = optarg;
			break;
		case 'q':
			quiet = 1;
			break;
		case '?':
		case 'h':
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;
	if(argc == 0)
		usage();
	if(argc >= 1 && strcmp(argv[0], "start")==0) {
		if(execlp("unbound", "unbound", "-c", cfgfile, 
			(char*)NULL) < 0) {
			fatal_exit("could not exec unbound: %s",
				strerror(errno));
		}
	}
	if(argc >= 1 && strcmp(argv[0], "stats_shm")==0) {
		print_stats_shm(cfgfile);
		return 0;
	}

#ifdef USE_WINSOCK
	if((r = WSAStartup(MAKEWORD(2,2), &wsa_data)) != 0)
		fatal_exit("WSAStartup failed: %s", wsa_strerror(r));
#endif

#ifdef HAVE_ERR_LOAD_CRYPTO_STRINGS
	ERR_load_crypto_strings();
#endif
#if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
	ERR_load_SSL_strings();
#endif
#if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_CRYPTO)
	OpenSSL_add_all_algorithms();
#else
	OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS
		| OPENSSL_INIT_ADD_ALL_DIGESTS
		| OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
#endif
#if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
	(void)SSL_library_init();
#else
	(void)OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL);
#endif

	if(!RAND_status()) {
		/* try to seed it */
		unsigned char buf[256];
		unsigned int seed=(unsigned)time(NULL) ^ (unsigned)getpid();
		unsigned int v = seed;
		size_t i;
		for(i=0; i<256/sizeof(v); i++) {
			memmove(buf+i*sizeof(v), &v, sizeof(v));
			v = v*seed + (unsigned int)i;
		}
		RAND_seed(buf, 256);
		log_warn("no entropy, seeding openssl PRNG with time\n");
	}

	ret = go(cfgfile, svr, quiet, argc, argv);

#ifdef USE_WINSOCK
	WSACleanup();
#endif
	checklock_stop();
	return ret;
}
Example #26
0
void Plane::init_ardupilot()
{
    // initialise serial port
    serial_manager.init_console();

    cliSerial->printf_P(PSTR("\n\nInit " FIRMWARE_STRING
                         "\n\nFree RAM: %u\n"),
                        hal.util->available_memory());


    //
    // Check the EEPROM format version before loading any parameters from EEPROM
    //
    load_parameters();

#if HIL_SUPPORT
    if (g.hil_mode == 1) {
        // set sensors to HIL mode
        ins.set_hil_mode();
        compass.set_hil_mode();
        barometer.set_hil_mode();
    }
#endif

#if CONFIG_HAL_BOARD == HAL_BOARD_PX4
    // this must be before BoardConfig.init() so if
    // BRD_SAFETYENABLE==0 then we don't have safety off yet
    for (uint8_t tries=0; tries<10; tries++) {
        if (setup_failsafe_mixing()) {
            break;
        }
        hal.scheduler->delay(10);
    }
#endif

    BoardConfig.init();

    // initialise serial ports
    serial_manager.init();

    // allow servo set on all channels except first 4
    ServoRelayEvents.set_channel_mask(0xFFF0);

    set_control_channels();

    // keep a record of how many resets have happened. This can be
    // used to detect in-flight resets
    g.num_resets.set_and_save(g.num_resets+1);

    // init baro before we start the GCS, so that the CLI baro test works
    barometer.init();

    // initialise rangefinder
    init_rangefinder();

    // initialise battery monitoring
    battery.init();

    // init the GCS
    gcs[0].setup_uart(serial_manager, AP_SerialManager::SerialProtocol_Console, 0);

    // we start by assuming USB connected, as we initialed the serial
    // port with SERIAL0_BAUD. check_usb_mux() fixes this if need be.    
    usb_connected = true;
    check_usb_mux();

    // setup serial port for telem1
    gcs[1].setup_uart(serial_manager, AP_SerialManager::SerialProtocol_MAVLink, 0);

#if MAVLINK_COMM_NUM_BUFFERS > 2
    // setup serial port for telem2
    gcs[2].setup_uart(serial_manager, AP_SerialManager::SerialProtocol_MAVLink, 1);
#endif

#if MAVLINK_COMM_NUM_BUFFERS > 3
    // setup serial port for fourth telemetry port (not used by default)
    gcs[3].setup_uart(serial_manager, AP_SerialManager::SerialProtocol_MAVLink, 2);
#endif

    // setup frsky
#if FRSKY_TELEM_ENABLED == ENABLED
    frsky_telemetry.init(serial_manager);
#endif

    mavlink_system.sysid = g.sysid_this_mav;

#if LOGGING_ENABLED == ENABLED
    log_init();
#endif

#if CONFIG_HAL_BOARD == HAL_BOARD_APM1
    apm1_adc.Init();      // APM ADC library initialization
#endif

    // initialise airspeed sensor
    airspeed.init();

    if (g.compass_enabled==true) {
        bool compass_ok = compass.init() && compass.read();
#if HIL_SUPPORT
        compass_ok = true;
#endif
        if (!compass_ok) {
            cliSerial->println_P(PSTR("Compass initialisation failed!"));
            g.compass_enabled = false;
        } else {
            ahrs.set_compass(&compass);
        }
    }
    
#if OPTFLOW == ENABLED
    // make optflow available to libraries
    ahrs.set_optflow(&optflow);
#endif

    // Register mavlink_delay_cb, which will run anytime you have
    // more than 5ms remaining in your call to hal.scheduler->delay
    hal.scheduler->register_delay_callback(mavlink_delay_cb_static, 5);

    // give AHRS the airspeed sensor
    ahrs.set_airspeed(&airspeed);

    // GPS Initialization
    gps.init(&DataFlash, serial_manager);

    init_rc_in();               // sets up rc channels from radio
    init_rc_out();              // sets up the timer libs

    relay.init();

#if MOUNT == ENABLED
    // initialise camera mount
    camera_mount.init(serial_manager);
#endif

#if FENCE_TRIGGERED_PIN > 0
    hal.gpio->pinMode(FENCE_TRIGGERED_PIN, HAL_GPIO_OUTPUT);
    hal.gpio->write(FENCE_TRIGGERED_PIN, 0);
#endif

    /*
     *  setup the 'main loop is dead' check. Note that this relies on
     *  the RC library being initialised.
     */
    hal.scheduler->register_timer_failsafe(failsafe_check_static, 1000);

#if CLI_ENABLED == ENABLED
    if (g.cli_enabled == 1) {
        const prog_char_t *msg = PSTR("\nPress ENTER 3 times to start interactive setup\n");
        cliSerial->println_P(msg);
        if (gcs[1].initialised && (gcs[1].get_uart() != NULL)) {
            gcs[1].get_uart()->println_P(msg);
        }
        if (num_gcs > 2 && gcs[2].initialised && (gcs[2].get_uart() != NULL)) {
            gcs[2].get_uart()->println_P(msg);
        }
    }
#endif // CLI_ENABLED

    init_capabilities();

    startup_ground();
    Log_Write_Startup(TYPE_GROUNDSTART_MSG);

    // choose the nav controller
    set_nav_controller();

    set_mode((FlightMode)g.initial_mode.get());

    // set the correct flight mode
    // ---------------------------
    reset_control_switch();

    // initialise sensor
#if OPTFLOW == ENABLED
    optflow.init();
#endif

}
Example #27
0
int
main (
	int		argc,
	char*		argv[]
	)
{
	pgm_transport_list = NULL;

	g_message ("pgmrecv");
#ifdef CONFIG_WITH_HTTP
	gboolean enable_http = FALSE;
#endif
#ifdef CONFIG_WITH_SNMP
	gboolean enable_snmpx = FALSE;
#endif

/* parse program arguments */
	const char* binary_name = strrchr (argv[0], '/');
	int c;
	while ((c = getopt (argc, argv, "a:s:n:p:lh"
#ifdef CONFIG_WITH_HTTP
					"t"
#endif
#ifdef CONFIG_WITH_SNMP
					"x"
#endif
					)) != -1)
	{
		switch (c) {
		case 'n':	g_network = optarg; break;
		case 'a':	g_source = optarg; break;
		case 's':	g_port = atoi (optarg); break;
		case 'p':	g_udp_encap_port = atoi (optarg); break;

		case 'l':	g_multicast_loop = TRUE; break;
#ifdef CONFIG_WITH_HTTP
		case 't':	enable_http = TRUE; break;
#endif
#ifdef CONFIG_WITH_SNMP
		case 'x':	enable_snmpx = TRUE; break;
#endif

		case 'h':
		case '?': usage (binary_name);
		}
	}

	log_init();
	pgm_init();

#ifdef CONFIG_WITH_HTTP
	if (enable_http)
		pgm_http_init(PGM_HTTP_DEFAULT_SERVER_PORT);
#endif
#ifdef CONFIG_WITH_SNMP
	if (enable_snmpx)
		pgm_snmp_init();
#endif

	g_loop = g_main_loop_new (NULL, FALSE);

/* setup signal handlers */
	signal(SIGSEGV, on_sigsegv);
	pgm_signal_install(SIGINT, on_signal);
	pgm_signal_install(SIGTERM, on_signal);
	pgm_signal_install(SIGHUP, SIG_IGN);

/* delayed startup */
	g_message ("scheduling startup.");
	g_timeout_add (0, (GSourceFunc)on_startup, NULL);

/* dispatch loop */
	g_message ("entering main event loop ... ");
	g_main_loop_run (g_loop);

	g_message ("event loop terminated, cleaning up.");

/* cleanup */
	g_quit = TRUE;
	g_thread_join (g_thread);

	g_main_loop_unref(g_loop);
	g_loop = NULL;

	if (g_transport) {
		g_message ("destroying transport.");

		pgm_transport_destroy (g_transport, TRUE);
		g_transport = NULL;
	}

#ifdef CONFIG_WITH_HTTP
	if (enable_http)
		pgm_http_shutdown();
#endif
#ifdef CONFIG_WITH_SNMP
	if (enable_snmpx)
		pgm_snmp_shutdown();
#endif

	g_message ("finished.");
	return 0;
}
Example #28
0
File: main.c Project: 12019/atmos
int main( void )
#endif
{
	iu8 i, len, b;

	/* TODO: On error? */
	hal_init();

	/* Send ATR */
	/* TODO: Possible from EEPROM? */
	hal_io_sendByteT0( 0x3B );

#if CONF_WITH_LOGGING==1
	log_init();
#endif

	resplen = 0;

#if CONF_WITH_TRANSACTIONS==1
	/* Commit transactions not yet done. */
	/* TODO: On error? */
	ta_commit();
#endif /* CONF_WITH_TRANSACTIONS */

	/* Initialize FS state in RAM. */
	/* TODO: On error? */
	fs_init();

#if CONF_WITH_PINAUTH==1
	/* Initialize authentication state. */
	/* TODO: On error? */
	auth_init();
#endif /* CONF_WITH_PINAUTH==1 */

	if( !(hal_eeprom_read( &len, ATR_LEN_ADDR, 1 ) && (len<=ATR_MAXLEN)) )
		for(;;) {} /* XXX good loop mechanism? what is it anyway */

	for( i=1; i<len; i++ ) {
		if( !hal_eeprom_read( &b, ATR_ADDR+i, 1 ) ) for(;;) {}
		hal_io_sendByteT0( b );
	}

	/* Command loop */
	for(;;) {
		for( i=0; i<5; i++ ) {
			header[i] = hal_io_recByteT0();
		}

#if CONF_WITH_KEYAUTH==1
		if( challvalidity ) challvalidity--;
#endif /* CONF_WITH_KEYAUTH==1 */

#if CONF_WITH_TRNG==1
		hal_rnd_addEntropy();
#endif /* CONF_WITH_TRNG==1 */

		if( (header[0]&0xFC)==CLA_PROP ) {
			switch( header[1]&0xFE ) {
#if CONF_WITH_TESTCMDS==1
			case INS_WRITE:
				cmd_write();
				break;
			case INS_READ:
				cmd_read();
				break;
#endif /* CONF_WITH_TESTCMDS==1 */
#if CONF_WITH_FUNNY==1
			case INS_LED:
				cmd_led();
				break;
#endif /* CONF_WITH_FUNNY==1 */
#if CONF_WITH_PINCMDS==1
			case INS_CHANGE_PIN:
				cmd_changeUnblockPIN();
				break;
#endif /* CONF_WITH_PINCMDS==1 */
#if CONF_WITH_CREATECMD==1
			case INS_CREATE:
				cmd_create();
				break;
#endif /* CONF_WITH_CREATECMD==1 */
#if CONF_WITH_DELETECMD==1
			case INS_DELETE:
				cmd_delete();
				break;
#endif /* CONF_WITH_DELETECMD==1 */
#if CONF_WITH_KEYCMDS==1
			case INS_EXTERNAL_AUTH:
				cmd_extAuth();
				break;
#endif /* CONF_WITH_KEYCMDS==1 */
#if CONF_WITH_KEYCMDS==1
			case INS_GET_CHALLENGE:
				cmd_getChallenge();
				break;
#endif /* CONF_WITH_KEYCMDS==1 */
			case INS_GET_RESPONSE:
				cmd_getResponse();
				break;
#if CONF_WITH_KEYCMDS==1
			case INS_INTERNAL_AUTH:
				cmd_intAuth();
				break;
#endif /* CONF_WITH_KEYCMDS==1 */
			case INS_READ_BINARY:
				cmd_readBinary();
				break;
			case INS_SELECT:
				cmd_select();
				break;
#if CONF_WITH_PINCMDS==1
			case INS_UNBLOCK_PIN:
				cmd_changeUnblockPIN();
				break;
#endif /* CONF_WITH_PINCMDS==1 */
			case INS_UPDATE_BINARY:
				cmd_updateBinary();
				break;
#if CONF_WITH_KEYCMDS==1
			case INS_VERIFY_KEY:
				cmd_verifyKeyPIN();
				break;
#endif /* CONF_WITH_KEYCMDS==1 */
#if CONF_WITH_PINCMDS==1
			case INS_VERIFY_PIN:
				cmd_verifyKeyPIN();
				break;
#endif /* CONF_WITH_PINCMDS==1 */
			default:
				t0_sendWord( SW_WRONG_INS );
			}
		} else {
			t0_sendWord( SW_WRONG_CLA );
		}

#if CONF_WITH_TRNG==1
		hal_rnd_addEntropy();
#endif

		/* Return the SW in sw */
		t0_sendSw();
	}
}
Example #29
0
/* init phase :
 * 1) read configuration file
 * 2) read command line arguments
 * 3) daemonize
 * 4) check and write pid file
 * 5) set startup time stamp
 * 6) compute presentation URL
 * 7) set signal handlers */
static int
init(int argc, char * * argv)
{
	int i;
	int pid;
	int debug_flag = 0;
	int verbose_flag = 0;
	int options_flag = 0;
	struct sigaction sa;
	const char * presurl = NULL;
	const char * optionsfile = "/etc/minidlna.conf";
	char mac_str[13];
	char * string, * word;
	enum media_types type;
	char * path;
	char buf[PATH_MAX];
	char ip_addr[INET_ADDRSTRLEN + 3] = {'\0'};
	char log_str[72] = "general,artwork,database,inotify,scanner,metadata,http,ssdp,tivo=warn";
	char *log_level = NULL;

	/* first check if "-f" option is used */
	for(i=2; i<argc; i++)
	{
		if(0 == strcmp(argv[i-1], "-f"))
		{
			optionsfile = argv[i];
			options_flag = 1;
			break;
		}
	}

	/* set up uuid based on mac address */
	if( getsyshwaddr(mac_str, sizeof(mac_str)) < 0 )
	{
		DPRINTF(E_OFF, L_GENERAL, "No MAC address found.  Falling back to generic UUID.\n");
		strcpy(mac_str, "554e4b4e4f57");
	}
	strcpy(uuidvalue+5, "4d696e69-444c-164e-9d41-");
	strncat(uuidvalue, mac_str, 12);

	getfriendlyname(friendly_name, FRIENDLYNAME_MAX_LEN);
	
	runtime_vars.port = -1;
	runtime_vars.notify_interval = 895;	/* seconds between SSDP announces */
	runtime_vars.root_container = NULL;

	/* read options file first since
	 * command line arguments have final say */
	if(readoptionsfile(optionsfile) < 0)
	{
		/* only error if file exists or using -f */
		if(access(optionsfile, F_OK) == 0 || options_flag)
			DPRINTF(E_ERROR, L_GENERAL, "Error reading configuration file %s\n", optionsfile);
	}
	else
	{
		for(i=0; i<num_options; i++)
		{
			switch(ary_options[i].id)
			{
			case UPNPIFNAME:
				for( string = ary_options[i].value; (word = strtok(string, ",")); string = NULL )
				{
					if(n_lan_addr < MAX_LAN_ADDR)
					{
						if(getifaddr(word, ip_addr, sizeof(ip_addr)) >= 0)
						{
							if( *ip_addr && parselanaddr(&lan_addr[n_lan_addr], ip_addr) == 0 )
								if(n_lan_addr < MAX_LAN_ADDR)
									n_lan_addr++;
						}
					}
					else
					{
						DPRINTF(E_ERROR, L_GENERAL, "Too many listening ips (max: %d), ignoring %s\n",
				    		    MAX_LAN_ADDR, word);
					}
				}
				break;
			case UPNPLISTENING_IP:
				if(n_lan_addr < MAX_LAN_ADDR)
				{
					if(parselanaddr(&lan_addr[n_lan_addr],
					             ary_options[i].value) == 0)
						n_lan_addr++;
				}
				else
				{
					DPRINTF(E_ERROR, L_GENERAL, "Too many listening ips (max: %d), ignoring %s\n",
			    		    MAX_LAN_ADDR, ary_options[i].value);
				}
				break;
			case UPNPPORT:
				runtime_vars.port = atoi(ary_options[i].value);
				break;
			case UPNPPRESENTATIONURL:
				presurl = ary_options[i].value;
				break;
			case UPNPNOTIFY_INTERVAL:
				runtime_vars.notify_interval = atoi(ary_options[i].value);
				break;
			case UPNPSERIAL:
				strncpyt(serialnumber, ary_options[i].value, SERIALNUMBER_MAX_LEN);
				break;				
			case UPNPMODEL_NAME:
				strncpyt(modelname, ary_options[i].value, MODELNAME_MAX_LEN);
				break;
			case UPNPMODEL_NUMBER:
				strncpyt(modelnumber, ary_options[i].value, MODELNUMBER_MAX_LEN);
				break;
			case UPNPFRIENDLYNAME:
				strncpyt(friendly_name, ary_options[i].value, FRIENDLYNAME_MAX_LEN);
				break;
			case UPNPMEDIADIR:
				type = ALL_MEDIA;
				char * myval = NULL;
				switch( ary_options[i].value[0] )
				{
				case 'A':
				case 'a':
					if( ary_options[i].value[0] == 'A' || ary_options[i].value[0] == 'a' )
						type = AUDIO_ONLY;
				case 'V':
				case 'v':
					if( ary_options[i].value[0] == 'V' || ary_options[i].value[0] == 'v' )
						type = VIDEO_ONLY;
				case 'P':
				case 'p':
					if( ary_options[i].value[0] == 'P' || ary_options[i].value[0] == 'p' )
						type = IMAGES_ONLY;
					myval = index(ary_options[i].value, '/');
				case '/':
					path = realpath(myval ? myval:ary_options[i].value, buf);
					if( !path )
						path = (myval ? myval:ary_options[i].value);
					if( access(path, F_OK) != 0 )
					{
						DPRINTF(E_ERROR, L_GENERAL, "Media directory \"%s\" not accessible! [%s]\n",
						        path, strerror(errno));
						break;
					}
					struct media_dir_s * this_dir = calloc(1, sizeof(struct media_dir_s));
					this_dir->path = strdup(path);
					this_dir->type = type;
					if( !media_dirs )
					{
						media_dirs = this_dir;
					}
					else
					{
						struct media_dir_s * all_dirs = media_dirs;
						while( all_dirs->next )
							all_dirs = all_dirs->next;
						all_dirs->next = this_dir;
					}
					break;
				default:
					DPRINTF(E_ERROR, L_GENERAL, "Media directory entry not understood! [%s]\n",
					        ary_options[i].value);
					break;
				}
				break;
			case UPNPALBUMART_NAMES:
				for( string = ary_options[i].value; (word = strtok(string, "/")); string = NULL )
				{
					struct album_art_name_s * this_name = calloc(1, sizeof(struct album_art_name_s));
					int len = strlen(word);
					if( word[len-1] == '*' )
					{
						word[len-1] = '\0';
						this_name->wildcard = 1;
					}
					this_name->name = strdup(word);
					if( !album_art_names )
					{
						album_art_names = this_name;
					}
					else
					{
						struct album_art_name_s * all_names = album_art_names;
						while( all_names->next )
							all_names = all_names->next;
						all_names->next = this_name;
					}
				}
				break;
			case UPNPDBDIR:
				path = realpath(ary_options[i].value, buf);
				if( !path )
					path = (ary_options[i].value);
				make_dir(path, S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO);
				if( access(path, F_OK) != 0 )
				{
					DPRINTF(E_FATAL, L_GENERAL, "Database path not accessible! [%s]\n", path);
					break;
				}
				strncpyt(db_path, path, PATH_MAX);
				break;
			case UPNPLOGDIR:
				path = realpath(ary_options[i].value, buf);
				if( !path )
					path = (ary_options[i].value);
				make_dir(path, S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO);
				if( access(path, F_OK) != 0 )
				{
					DPRINTF(E_FATAL, L_GENERAL, "Log path not accessible! [%s]\n", path);
					break;
				}
				strncpyt(log_path, path, PATH_MAX);
				break;
			case UPNPLOGLEVEL:
				log_level = ary_options[i].value;
				break;
			case UPNPINOTIFY:
				if( (strcmp(ary_options[i].value, "yes") != 0) && !atoi(ary_options[i].value) )
					CLEARFLAG(INOTIFY_MASK);
				break;
			case ENABLE_TIVO:
				if( (strcmp(ary_options[i].value, "yes") == 0) || atoi(ary_options[i].value) )
					SETFLAG(TIVO_MASK);
				break;
			case ENABLE_DLNA_STRICT:
				if( (strcmp(ary_options[i].value, "yes") == 0) || atoi(ary_options[i].value) )
					SETFLAG(DLNA_STRICT_MASK);
				break;
			case ROOT_CONTAINER:
				switch( ary_options[i].value[0] )
				{
				case '.':
					runtime_vars.root_container = NULL;
					break;
				case 'B':
				case 'b':
					runtime_vars.root_container = BROWSEDIR_ID;
					break;
				case 'M':
				case 'm':
					runtime_vars.root_container = MUSIC_ID;
					break;
				case 'V':
				case 'v':
					runtime_vars.root_container = VIDEO_ID;
					break;
				case 'P':
				case 'p':
					runtime_vars.root_container = IMAGE_ID;
					break;
				default:
					DPRINTF(E_ERROR, L_GENERAL, "Invalid root container! [%s]\n",
						ary_options[i].value);
					break;
				}
				break;
			case UPNPMINISSDPDSOCKET:
				minissdpdsocketpath = ary_options[i].value;
				break;
			default:
				DPRINTF(E_DEBUG, L_GENERAL, "Unknown option in file %s\n",
				        optionsfile);
			}
		}
	}
	if( log_path[0] == '\0' )
	{
		if( db_path[0] == '\0' )
			strncpyt(log_path, DEFAULT_LOG_PATH, PATH_MAX);
		else
			strncpyt(log_path, db_path, PATH_MAX);
	}
	if( db_path[0] == '\0' )
		strncpyt(db_path, DEFAULT_DB_PATH, PATH_MAX);

	/* command line arguments processing */
	for(i=1; i<argc; i++)
	{
		if(argv[i][0]!='-')
		{
			DPRINTF(E_ERROR, L_GENERAL, "Unknown option: %s\n", argv[i]);
		}
		else if(strcmp(argv[i], "--help")==0)
		{
			runtime_vars.port = 0;
			break;
		}
		else switch(argv[i][1])
		{
		case 't':
			if(i+1 < argc)
				runtime_vars.notify_interval = atoi(argv[++i]);
			else
				DPRINTF(E_ERROR, L_GENERAL, "Option -%c takes one argument.\n", argv[i][1]);
			break;
		case 's':
			if(i+1 < argc)
				strncpyt(serialnumber, argv[++i], SERIALNUMBER_MAX_LEN);
			else
				DPRINTF(E_ERROR, L_GENERAL, "Option -%c takes one argument.\n", argv[i][1]);
			break;
		case 'm':
			if(i+1 < argc)
				strncpyt(modelnumber, argv[++i], MODELNUMBER_MAX_LEN);
			else
				DPRINTF(E_ERROR, L_GENERAL, "Option -%c takes one argument.\n", argv[i][1]);
			break;
		case 'p':
			if(i+1 < argc)
				runtime_vars.port = atoi(argv[++i]);
			else
				DPRINTF(E_ERROR, L_GENERAL, "Option -%c takes one argument.\n", argv[i][1]);
			break;
		case 'P':
			if(i+1 < argc)
				pidfilename = argv[++i];
			else
				DPRINTF(E_ERROR, L_GENERAL, "Option -%c takes one argument.\n", argv[i][1]);
			break;
		case 'd':
			debug_flag = 1;
		case 'v':
			verbose_flag = 1;
			break;
		case 'L':
			SETFLAG(NO_PLAYLIST_MASK);
			break;
		case 'w':
			if(i+1 < argc)
				presurl = argv[++i];
			else
				DPRINTF(E_ERROR, L_GENERAL, "Option -%c takes one argument.\n", argv[i][1]);
			break;
		case 'a':
			if(i+1 < argc)
			{
				int address_already_there = 0;
				int j;
				i++;
				for(j=0; j<n_lan_addr; j++)
				{
					struct lan_addr_s tmpaddr;
					parselanaddr(&tmpaddr, argv[i]);
					if(0 == strcmp(lan_addr[j].str, tmpaddr.str))
						address_already_there = 1;
				}
				if(address_already_there)
					break;
				if(n_lan_addr < MAX_LAN_ADDR)
				{
					if(parselanaddr(&lan_addr[n_lan_addr], argv[i]) == 0)
						n_lan_addr++;
				}
				else
				{
					DPRINTF(E_ERROR, L_GENERAL, "Too many listening ips (max: %d), ignoring %s\n",
				    	    MAX_LAN_ADDR, argv[i]);
				}
			}
			else
				DPRINTF(E_ERROR, L_GENERAL, "Option -%c takes one argument.\n", argv[i][1]);
			break;
		case 'i':
			if(i+1 < argc)
			{
				int address_already_there = 0;
				int j;
				i++;
				if( getifaddr(argv[i], ip_addr, sizeof(ip_addr)) < 0 )
				{
					DPRINTF(E_FATAL, L_GENERAL, "Required network interface '%s' not found.\n",
						argv[i]);
				}
				for(j=0; j<n_lan_addr; j++)
				{
					struct lan_addr_s tmpaddr;
					parselanaddr(&tmpaddr, ip_addr);
					if(0 == strcmp(lan_addr[j].str, tmpaddr.str))
						address_already_there = 1;
				}
				if(address_already_there)
					break;
				if(n_lan_addr < MAX_LAN_ADDR)
				{
					if(parselanaddr(&lan_addr[n_lan_addr], ip_addr) == 0)
						n_lan_addr++;
				}
				else
				{
					DPRINTF(E_ERROR, L_GENERAL, "Too many listening ips (max: %d), ignoring %s\n",
				    	    MAX_LAN_ADDR, argv[i]);
				}
			}
			else
				DPRINTF(E_ERROR, L_GENERAL, "Option -%c takes one argument.\n", argv[i][1]);
			break;
		case 'f':
			i++;	/* discarding, the config file is already read */
			break;
		case 'h':
			runtime_vars.port = 0; // triggers help display
			break;
		case 'R':
			snprintf(buf, sizeof(buf), "rm -rf %s/files.db %s/art_cache", db_path, db_path);
			if( system(buf) != 0 )
				DPRINTF(E_WARN, L_GENERAL, "Failed to clean old file cache.\n");
			break;
		case 'V':
			printf("Version " MINIDLNA_VERSION "\n");
			exit(0);
			break;
		default:
			DPRINTF(E_ERROR, L_GENERAL, "Unknown option: %s\n", argv[i]);
		}
	}
	/* If no IP was specified, try to detect one */
	if( n_lan_addr < 1 )
	{
		if( getsysaddrs() <= 0 )
		{
			DPRINTF(E_FATAL, L_GENERAL, "No IP address automatically detected!\n");
		}
	}

	if( (n_lan_addr==0) || (runtime_vars.port<=0) )
	{
		DPRINTF(E_ERROR, L_GENERAL, "Usage:\n\t"
		        "%s [-d] [-v] [-f config_file]\n"
			"\t\t[-a listening_ip] [-p port]\n"
			/*"[-l logfile] " not functionnal */
			"\t\t[-s serial] [-m model_number] \n"
			"\t\t[-t notify_interval] [-P pid_filename]\n"
			"\t\t[-w url] [-R] [-V] [-h]\n"
		        "\nNotes:\n\tNotify interval is in seconds. Default is 895 seconds.\n"
			"\tDefault pid file is %s.\n"
			"\tWith -d minidlna will run in debug mode (not daemonize).\n"
			"\t-w sets the presentation url. Default is http address on port 80\n"
			"\t-h displays this text\n"
			"\t-R forces a full rescan\n"
			"\t-L do note create playlists\n"
			"\t-V print the version number\n",
		        argv[0], pidfilename);
		return 1;
	}

	if( verbose_flag )
	{
		strcpy(log_str+65, "debug");
		log_level = log_str;
	}
	else if( !log_level )
	{
		log_level = log_str;
	}
	if(debug_flag)
	{
		pid = getpid();
		log_init(NULL, log_level);
	}
	else
	{
		pid = daemonize();
		#ifdef READYNAS
		log_init("/var/log/upnp-av.log", log_level);
		#else
		if( access(db_path, F_OK) != 0 )
			make_dir(db_path, S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO);
		sprintf(buf, "%s/minidlna.log", log_path);
		log_init(buf, log_level);
		#endif
	}

	if(checkforrunning(pidfilename) < 0)
	{
		DPRINTF(E_ERROR, L_GENERAL, "MiniDLNA is already running. EXITING.\n");
		return 1;
	}	

	set_startup_time();

	/* presentation url */
	if(presurl)
		strncpyt(presentationurl, presurl, PRESENTATIONURL_MAX_LEN);
	else
		strcpy(presentationurl, "/");

	/* set signal handler */
	memset(&sa, 0, sizeof(struct sigaction));
	sa.sa_handler = sigterm;
	if (sigaction(SIGTERM, &sa, NULL))
	{
		DPRINTF(E_FATAL, L_GENERAL, "Failed to set SIGTERM handler. EXITING.\n");
	}
	if (sigaction(SIGINT, &sa, NULL))
	{
		DPRINTF(E_FATAL, L_GENERAL, "Failed to set SIGINT handler. EXITING.\n");
	}

	if(signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
		DPRINTF(E_FATAL, L_GENERAL, "Failed to ignore SIGPIPE signals. EXITING.\n");
	}

	writepidfile(pidfilename, pid);

	return 0;
}
Example #30
0
int
main (int argc, char *argv[])
{
	int error_code = SLURM_SUCCESS, opt_char;
	log_options_t opts = LOG_OPTS_STDERR_ONLY;
	shares_request_msg_t req_msg;
	shares_response_msg_t *resp_msg = NULL;
	char *temp = NULL;
	int option_index;
	bool all_users = 0;
	uint16_t options;

	static struct option long_options[] = {
		{"accounts", 1, 0, 'A'},
		{"all",      0, 0, 'a'},
		{"long",     0, 0, 'l'},
		{"cluster",  1, 0, 'M'},
		{"clusters", 1, 0, 'M'},
		{"noheader", 0, 0, 'h'},
		{"parsable", 0, 0, 'p'},
		{"parsable2",0, 0, 'P'},
		{"users",    1, 0, 'u'},
		{"Users",    0, 0, 'U'},
		{"verbose",  0, 0, 'v'},
		{"version",  0, 0, 'V'},
		{"help",     0, 0, OPT_LONG_HELP},
		{"usage",    0, 0, OPT_LONG_USAGE},
		{NULL,       0, 0, 0}
	};

	exit_code         = 0;
	long_flag	  = 0;
	quiet_flag        = 0;
	verbosity         = 0;
	memset(&req_msg, 0, sizeof(shares_request_msg_t));
	slurm_conf_init(NULL);
	log_init("sshare", opts, SYSLOG_FACILITY_DAEMON, NULL);

	while((opt_char = getopt_long(argc, argv, "aA:hlM:npPqUu:t:vV",
			long_options, &option_index)) != -1) {
		switch (opt_char) {
		case (int)'?':
			fprintf(stderr, "Try \"sshare --help\" "
				"for more information\n");
			exit(1);
			break;
		case 'a':
			all_users = 1;
			break;
		case 'A':
			if (!req_msg.acct_list)
				req_msg.acct_list =
					list_create(slurm_destroy_char);
			slurm_addto_char_list(req_msg.acct_list, optarg);
			break;
		case 'h':
			print_fields_have_header = 0;
			break;
			exit(exit_code);
			break;
		case 'l':
			long_flag = 1;
			break;
		case 'M':
			if (clusters)
				list_destroy(clusters);
			if (!(clusters =
			     slurmdb_get_info_cluster(optarg))) {
				print_db_notok(optarg, 0);
				exit(1);
			}
			working_cluster_rec = list_peek(clusters);
			break;
		case 'n':
			print_fields_have_header = 0;
			break;
		case 'p':
			print_fields_parsable_print =
			PRINT_FIELDS_PARSABLE_ENDING;
			break;
		case 'P':
			print_fields_parsable_print =
			PRINT_FIELDS_PARSABLE_NO_ENDING;
			break;
		case 'u':
			if (!strcmp(optarg, "-1")) {
				all_users = 1;
				break;
			}
			all_users = 0;
			if (!req_msg.user_list)
				req_msg.user_list =
					list_create(slurm_destroy_char);
			_addto_name_char_list(req_msg.user_list, optarg, 0);
			break;
		case 'U':
			options |= PRINT_USERS_ONLY;
			break;
		case 'v':
			quiet_flag = -1;
			verbosity++;
			break;
		case 'V':
			_print_version();
			exit(exit_code);
			break;
		case OPT_LONG_HELP:
		case OPT_LONG_USAGE:
			_usage();
			exit(0);
		default:
			exit_code = 1;
			fprintf(stderr, "getopt error, returned %c\n",
				opt_char);
			exit(exit_code);
		}
	}

	if (verbosity) {
		opts.stderr_level += verbosity;
		opts.prefix_level = 1;
		log_alter(opts, 0, NULL);
	}

	if (all_users) {
		if (req_msg.user_list
		   && list_count(req_msg.user_list)) {
			list_destroy(req_msg.user_list);
			req_msg.user_list = NULL;
		}
		if (verbosity)
			fprintf(stderr, "Users requested:\n\t: all\n");
	} else if (verbosity && req_msg.user_list
	    && list_count(req_msg.user_list)) {
		fprintf(stderr, "Users requested:\n");
		ListIterator itr = list_iterator_create(req_msg.user_list);
		while((temp = list_next(itr)))
			fprintf(stderr, "\t: %s\n", temp);
		list_iterator_destroy(itr);
	} else if (!req_msg.user_list || !list_count(req_msg.user_list)) {
		struct passwd *pwd = getpwuid(getuid());
		if (!req_msg.user_list)
			req_msg.user_list = list_create(slurm_destroy_char);
		temp = xstrdup(pwd->pw_name);
		list_append(req_msg.user_list, temp);
		if (verbosity) {
			fprintf(stderr, "Users requested:\n");
			fprintf(stderr, "\t: %s\n", temp);
		}
	}

	if (req_msg.acct_list && list_count(req_msg.acct_list)) {
		if (verbosity) {
			fprintf(stderr, "Accounts requested:\n");
			ListIterator itr = list_iterator_create(req_msg.acct_list);
			while((temp = list_next(itr)))
				fprintf(stderr, "\t: %s\n", temp);
			list_iterator_destroy(itr);
		}
	} else {
		if (req_msg.acct_list
		   && list_count(req_msg.acct_list)) {
			list_destroy(req_msg.acct_list);
			req_msg.acct_list = NULL;
		}
		if (verbosity)
			fprintf(stderr, "Accounts requested:\n\t: all\n");

	}

	error_code = _get_info(&req_msg, &resp_msg);

	if (req_msg.acct_list)
		list_destroy(req_msg.acct_list);
	if (req_msg.user_list)
		list_destroy(req_msg.user_list);

	if (error_code) {
		slurm_perror("Couldn't get shares from controller");
		exit(error_code);
	}

	/* do stuff with it */
	process(resp_msg, options);

	slurm_free_shares_response_msg(resp_msg);

	exit(exit_code);
}