Ejemplo n.º 1
0
int		main(UNUSED int ac, UNUSED char **av, char **env)
{
  t_main	s;
  int		*jobs;

  if ((jobs = malloc(1 * sizeof(int))) == NULL)
    return (-1);
  jobs[0] = -1;
  jobs = update_jobs(jobs, 1);
  init_env(env, &s.my_env);
  init_history(&s.cmd, &s.history, &s.term, &s.stop);
  while (!s.stop && get_return_value(0, 0, 0, 0) == 0
	 && update_fils(0, -1) != -1)
    {
      save_pid(2, 0);
      get_signal();
      if ((s.paths = get_paths()) != NULL)
	end_main(&s);
      is_too_much(0);
    }
  end_shell(s.history, s.term);
  save_pid(2, 0);
  close_fg(jobs, 0);
  return (get_return_value(0, 0, 0, 1));
}
Ejemplo n.º 2
0
/*
**		If a SIGTSTP is received (CTRL+Z)
**		=> send the signal to current process.
**		=> add process to suspend jobs list.
*/
void		my_sigstop(int signal)
{
  t_job		*jobs;
  int		i;

  i = 1;
  if (signal == SIGTSTP)
    {
      if ((jobs = save_pid(0, 1)) && jobs != NULL + 1 && jobs != NULL + 2)
	  {
	    while (jobs->next && i++)
	      jobs = jobs->next;
	    if (jobs->pid >= 0)
	      {
		if (kill(jobs->pid, SIGTSTP) == -1)
		  msg_error("mysh: kill error.\n");
		my_putstr("\n[");
		my_put_nbr(i);
		my_putstr("]\tStopped\t\t");
		my_putstr(jobs->cmd);
		my_putstr("\n");
		save_pid(-1, 0);
	      }
	  }
    }
}
Ejemplo n.º 3
0
int main (int argc, char *argv[])
{
  int listener;

  setup_signals();
  listener = open_listener(SOCK_PATH);

  /* Turn ourselves into a daemon, but do not redirect stdout/stderr
   * to /dev/null.
   */
  if (daemon(0, 1) != 0)
    {
      perror("daemon");
      exit(1);
    }

  /* Save our PID. */
  save_pid(PID_PATH);

  /* Clean up any stale lock file. */
  unlink(LOCK_PATH);

  /* Wait for clients. */
  wait_for_events(listener);

  /* Work is done.  Clean up our socket for next time. */
  close(listener);
  unlink(SOCK_PATH);
  unlink(PID_PATH);

  return 0;
}
Ejemplo n.º 4
0
/*
**		If a SIGINT is received, it will kill current process.
**		If no current process is executing, it will re-display prompt.
*/
void		my_sigint(int signal)
{
  if (signal == SIGINT)
    if (save_pid(0, 3) == NULL + 2)
      {
	my_putstr("^C\n");
	display_prompt(0, 0, 0);
      }
}
Ejemplo n.º 5
0
Archivo: core.c Proyecto: shenzhe/bsp
// Init BSP-core
int core_init()
{
    if (!core_settings.initialized)
    {
        init_core_setting();
    }

    if (core_settings.is_daemonize)
    {
        proc_daemonize();
    }

    fd_init(0);
    log_init();
    load_runtime_setting();
    status_op_core(STATUS_OP_INSTANCE_ID, (size_t) core_settings.instance_id);
    thread_init();
    save_pid();
    signal_init();
    socket_init();
    memdb_init();
    online_init();

    // Load modules
    BSP_VALUE *val = object_get_hash_str(runtime_settings, "modules");
    BSP_OBJECT *vobj = value_get_object(val);
    BSP_STRING *vstr = NULL;
    if (vobj && OBJECT_TYPE_ARRAY == vobj->type)
    {
        size_t varr_size = object_size(vobj), i;
        if (varr_size > MAX_MODULES)
        {
            varr_size = MAX_MODULES;
        }

        reset_object(vobj);
        for (i = 0; i < varr_size; i ++)
        {
            val = object_get_array(vobj, i);
            vstr = value_get_string(val);
            if (vstr)
            {
                script_load_module(vstr, 1);
            }
        }
    }

    return BSP_RTN_SUCCESS;
}
Ejemplo n.º 6
0
Archivo: worker.c Proyecto: maczpc/csf
int 
main(int argc, char **argv)
{
	int o;
	
	printf("\nCSF[%d] starting...\n", (int)getpid());

	realpath(argv[0], exec_path);
	if (set_working_dir(exec_path) != 0) {
		PRINT("Can not set the working directory.");
		return (2);
	}
	set_conf_file(CONF_FILE);

	while(-1 != (o = getopt(argc, argv, "f:hv"))) {
		switch(o) {
		case 'f':
			set_conf_file(optarg);
			break;

		case 'v': output_config(); return 0;
		case 'h': show_help(); return 0;
		default:
			break;
		}

	}

    /* init each modules */
	if (csf_init() < 0) {
        PRINT("CSF init failed. Exited.");
        return (2);
    }
	set_signals();
	save_pid(argv[0]);	

    /* starts the server */

    server_init(&main_conf);

    WLOG_ERR("Fatal Error, SERVER DOWN!");
	logger_deinit();
    PRINT("Fatal Error, SERVER DOWN!");
    
	return (2);
}
Ejemplo n.º 7
0
void deamonize(void) {
	log_file_enable();
	log_shell_disable();
	/* Get the pid of the fork */
	pid_t npid = fork();
	switch(npid) {
		case 0:
		break;
		case -1:
			logprintf(LOG_ERR, "could not daemonize program");
			exit(1);
		break;
		default:
			save_pid(npid);
			logprintf(LOG_INFO, "daemon started with pid: %d", npid);
			exit(0);
		break;
	}
}
Ejemplo n.º 8
0
void main_rest(void){
	ssize_t                ret;
	sigset_t               set;
	
	/* options init */
	if(opt_daemon != 0)
		daemonize();
	
	save_pid(opt_pidfile);
	
	if(frozen_init() != 0){
		fprintf(stderr, "libfrozen init failed\n");
		exit(255);
	}
	
	signal(SIGHUP,signal_handler); /* catch hangup signal */ // TODO rewrite to sigaction
	signal(SIGINT,signal_handler);
	signal(SIGTERM,signal_handler); /* catch kill signal */  // NOTICE after modules_load() coz Go override TERM
	
	sigfillset(&set);
	sigprocmask(SIG_BLOCK, &set, NULL);                     // block all signals, main thread will handler that
	
	config_t *pipelines = configs_file_parse(opt_config_file);
	if(pipelines == NULL){
		fprintf(stderr, "config file not exist, empty or invalid\n");
		exit(255);
	}
	
	sigprocmask(SIG_UNBLOCK, &set, NULL);           // enable all signals for this thread
	
	if( (ret = pipelines_execute(pipelines)) < 0){
		errors_log("pipelines_execute error: %d: %s\n", ret, errors_describe(ret));
		exit(255);
	}
	hash_free(pipelines);
}
Ejemplo n.º 9
0
int main(int argc, char *argv[])
{
	char errbuf[PCAP_ERRBUF_SIZE];
	char *dev;
	struct iface_config *ifc;
	int optind;
	int i;


	bzero(&cfg, sizeof(cfg));

	/* Default configuration */
//	cfg.ratelimit = 0;
	cfg.hashsize = 1;
//	cfg.quiet = 0;
	cfg.promisc_flag = 1;
//	cfg.ratelimit = 0;
//	cfg.sqlite_file = NULL;
//	cfg.uname = NULL;
	cfg.shm_data.size = DEFAULT_SHM_LOG_SIZE;
	cfg.shm_data.name = DEFAULT_SHM_LOG_NAME;
#if HAVE_LIBSQLITE3
	cfg.sqlite_table = PACKAGE;
#endif
	log_open(PACKAGE_NAME);
	argp_parse(&argp, argc, argv, 0, &optind, 0);

	if (!cfg.hostname) {
		cfg.hostname_len = sysconf(_SC_HOST_NAME_MAX);
		cfg.hostname = (char *)calloc(cfg.hostname_len, sizeof(char));
		gethostname(cfg.hostname, cfg.hostname_len);
	}

	daemonize();
	save_pid();

	libevent_init();


	if (cfg.ratelimit > 0)
		log_msg(LOG_DEBUG, "Ratelimiting duplicate entries to 1 per %d seconds", cfg.ratelimit);
	else if (cfg.ratelimit == -1)
		log_msg(LOG_DEBUG, "Duplicate entries supressed indefinitely");
	else
		log_msg(LOG_DEBUG, "Duplicate entries ratelimiting disabled");

	if (cfg.promisc_flag)
		log_msg(LOG_DEBUG, "PROMISC mode enabled");
	else
		log_msg(LOG_DEBUG, "PROMISC mode disabled");

	if (argc > optind) {
		for (i = optind; i < argc; i++)
			add_iface(argv[i]);
	} else {
		dev = pcap_lookupdev(errbuf);
		if (dev != NULL)
			add_iface(dev);
	}

	if (!cfg.interfaces)
		log_msg(LOG_ERR, "No suitable interfaces found!");

	if (cfg.uname)
		drop_root(cfg.uname);

	output_flatfile_init();
	output_sqlite_init();
	output_shm_init();

	/* main loop */
#if HAVE_LIBEVENT2
	event_base_dispatch(cfg.eb);
#else
	event_dispatch();
#endif

	output_shm_close();
	output_sqlite_close();
	output_flatfile_close();

	for (ifc = cfg.interfaces; ifc != NULL; ifc = del_iface(ifc));


	libevent_close();
	log_close();

	del_pid();
	blacklist_free();

	free(cfg.hostname);

	return 0;
}
Ejemplo n.º 10
0
int main(int argc, char *argv[])
{
    struct sockaddr_in si_me, si_other;
    int sk;
    socklen_t slen = sizeof(si_other);
    int len, ret;

    fd_set readsock;

    struct packet p;
    char buf[PAYLOAD_SIZE];

    char log_file[LINE_LENGTH];
    char serial_file[LINE_LENGTH];

    unsigned int crc32_value;
    struct hostent *hostentry;
    unsigned int i;
    int mask;

    memset(log_file, 0, LINE_LENGTH);
    memset(serial_file, 0, LINE_LENGTH);
    memset(buf, 0, PAYLOAD_SIZE);

    if (argv[1] != NULL)
    {
        if(!strcmp(argv[1], "debug"))
            mask = (LOG_MASK(LOG_ERR) | LOG_MASK(LOG_DEBUG));
        else
            mask = LOG_MASK(LOG_ERR);
    }
    else
        mask = LOG_MASK(LOG_ERR);

    /* Our process ID and Session ID */
    pid_t pid, sid;

    /* Fork off the parent process */
    pid = fork();
    if (pid < 0)
    {
        exit(1);
    }

    /* If we got a good PID, then
       we can exit the parent process. */
    if (pid > 0)
    {
        save_pid(PID_FILE, pid);
        exit(0);
    }

    /* Change the file mode mask */
    umask(0);

    /* Open any logs here */

    /* Create a new SID for the child process */
    sid = setsid();
    if (sid < 0)
    {
        /* Log the failure */
        exit(1);
    }


    /* Change the current working directory */
    if ((chdir("/")) < 0)
    {
        /* Log the failure */
        exit(1);
    }

    /* Close out the standard file descriptors */
    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);

    /* Daemon-specific initialization goes here */
    openlog("USBlogger server", LOG_PID | LOG_CONS | LOG_NDELAY | LOG_NOWAIT, LOG_LOCAL0);
    setlogmask(mask);

    ret = parse_config(CONFIG_FILE, log_file, serial_file, CONFIG_NUM_PARAMS);
    if (ret)
    {
        syslog(LOG_ERR, "Something wrong happened while reading configuration. Please check config file - %s", CONFIG_FILE);
        exit(1);
    }

    /* Initialize the socket to recv messages */
    sk = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (sk == -1)
    {
        syslog(LOG_ERR, "socket creation failed");
        exit(1);
    }

    memset(&si_me, 0, sizeof(si_me));
    si_me.sin_family = AF_INET;
    si_me.sin_port = htons(PORT);
    si_me.sin_addr.s_addr = htonl(INADDR_ANY);

    ret = bind(sk, (struct sockaddr *)&si_me, sizeof(si_me));
    if (ret == -1)
    {
        syslog(LOG_ERR, "bind failed");
        exit(1);
    }

    /* The Big Loop */
    while (1)
    {
        FD_ZERO(&readsock);
        FD_SET(sk, &readsock);
        ret = select(FD_SETSIZE, &readsock, NULL, NULL, NULL);
        if (ret == -1)
        {
            syslog(LOG_ERR, "error in select() at main loop");
            exit(1);
        }
        else if (ret > 0)
        {
            if (FD_ISSET(sk, &readsock))
            {
                len = recvfrom(sk, buf, PAYLOAD_SIZE, 0, (struct sockaddr *)&si_other, &slen);
                if (len == -1)
                {
                    syslog(LOG_ERR, "recvfrom returned an error");
                    continue;
                }

                syslog(LOG_DEBUG, "len = %d, Received the message from client ... ", len);
//				for(i = 0; i < len; i++)
//					putchar(buf[i]);
//				putchar('\n');

                ret = parse_packet(&p, buf, len);
                if(ret)
                {
                    syslog(LOG_ERR, "parser found an error during parsing a packet");
                    //clear_packet(&p);
                    memset(buf, 0, PAYLOAD_SIZE);
                    continue;
                }
                print_packet(&p);

                ret = is_serial_allowed(serial_file, p.fields[2].value_val);
                if (ret != 0)
                {
                    //serial is not in the list, so saving log
                    save_packet(log_file, &p);
                }
                // serial in the list, nothing to do

                crc32_value = crc32(buf, len);
                syslog(LOG_DEBUG, "CRC32 value of the message is = %x", crc32_value);

                hostentry = gethostbyname(p.fields[1].value_val);
                if(hostentry == NULL)
                {
                    syslog(LOG_ERR, "Resolving hostname failed");
                    clear_packet(&p);
                    memset(buf, 0, PAYLOAD_SIZE);
                    continue;
                }
                syslog(LOG_DEBUG, "Client IP: %s", inet_ntoa(*((struct in_addr *)hostentry->h_addr_list[0])) );

                clear_packet(&p);
                memset(buf, 0, PAYLOAD_SIZE);

                ret = send_buffer_to_client(sk, (struct in_addr *)hostentry->h_addr_list[0], (char *)&crc32_value, sizeof(crc32_value));

                /*
                				// Any device plugged into server
                				if (bus_msg->msgtype == '1')
                				{
                					tableret = add_to_table(bus_msg);
                					if (tableret != 0)
                					{
                						printf("No hub any more.\n");
                						return -1;
                					}
                					print_table();
                					printf("Received a bus (%s) from %s\n", bus_msg->busname, inet_ntoa(si_other.sin_addr));
                					sprintf(cmd, "usbip_attach ");
                					strcat(cmd, inet_ntoa(si_other.sin_addr));
                					strcat(cmd, " ");
                					strcat(cmd, bus_msg->busname);
                					system(cmd);
                				}

                				// Any device unplugged from server
                				if (bus_msg->msgtype == '0')
                				{
                					char str[2];
                					tableret = del_from_table(bus_msg);
                					if (tableret == -1)
                					{
                						printf("Device not found.\n");
                						return -1;
                					}
                					print_table();
                					printf("Received a bus (%s) from %s\n", bus_msg->busname, inet_ntoa(si_other.sin_addr));
                					sprintf(cmd, "usbip_detach ");
                					sprintf(str, "%d", tableret);
                					strcat(cmd, str);
                					system(cmd);
                				}
                */
            }
        }
    }
    close(sk);
    return 0;
}
Ejemplo n.º 11
0
int main() {
	configure();
	save_pid();
	if (head != NULL) {
		pfree(head);
	}
	head = NULL;
	getData();
	signal(SIGUSR1, sigroutine);
	/*
	 if(head!=NULL);
	 display(head);
	 printf("%d\n",search(50505920));
	 if(head!=NULL);
	 pfree(head);
	 exit(0);
	 */
	char error_content[PCAP_ERRBUF_SIZE];
	int http_len;
	struct pcap_pkthdr protocol_header;
	pcap_t *pcap_handle;
	const u_char *packet_content;
	bpf_u_int32 net_mask;
	bpf_u_int32 net_ip;
	char *net_interface;

	struct ether_header *eptr; //以太网帧
	struct iphdr *ipptr; //ip数据报
	struct in_addr addr;
	struct tcphdr *tcpptr; //tcp
	char *data;
	char hostbuf[500];
	char getbuf[100];
	char url[100];

	unsigned int syn_ack_seq = 0;
	net_interface = conf.interface;
	pcap_lookupnet(net_interface, &net_ip, &net_mask, error_content);
	pcap_handle = pcap_open_live(net_interface, BUFSIZ, 1, 0, error_content);
	printf("Capture a packet from : %s\n", net_interface);
	while (1) {
		packet_content = pcap_next(pcap_handle, &protocol_header);
		if (packet_content == NULL)
			continue;
		eptr = (struct ether_header *) packet_content;
		int i = 0;
		memset(smac, 0, sizeof(smac));
		for (i = 0; i < 6; i++)
			sprintf(smac, "%s%02x", smac, eptr->ether_shost[i]);

		if (ntohs(eptr->ether_type) == ETHERTYPE_IP) //http 基于tcp/ip,只捕获此类型的帧
		{
			ipptr = (struct iphdr *) (packet_content
					+ sizeof(struct ether_header)); //获得ip数据报的内存地址
			if (ipptr->protocol == 6) //筛选出tcp报文
					{
				tcpptr = (struct tcphdr *) (packet_content
						+ sizeof(struct ether_header) + sizeof(struct iphdr));

				if (ntohs(tcpptr->dest) == 80) {
					http_redirector(packet_content);

				}

			}
		}
	}
	pcap_close(pcap_handle);
}
Ejemplo n.º 12
0
Archivo: rfxd.c Proyecto: hyper/librisp
static void timeout_handler(const int fd, const short which, void *arg) {
	struct timeval t = {.tv_sec = 1, .tv_usec = 0};
	timeout_t *ptr;
	unsigned int inmem, outmem, filemem;
	int i;
	
	ptr  = (timeout_t *) arg;

	assert(ptr != NULL);
	assert(ptr->clockevent.ev_base != NULL);

	// reset the timer to go off again in 1 second.
	evtimer_del(&ptr->clockevent);
	evtimer_set(&ptr->clockevent, timeout_handler, arg);
	event_base_set(ptr->clockevent.ev_base, &ptr->clockevent);
	evtimer_add(&ptr->clockevent, &t);
	
 	assert(fd == INVALID_HANDLE);
	assert(ptr->server != NULL);

	assert(ptr->stats != NULL);
	
	if (ptr->stats->in_bytes || ptr->stats->out_bytes || ptr->stats->commands || ptr->stats->operations) {

		inmem=0;
		outmem=0;
		filemem = 0;

		for(i=0; i<ptr->server->maxconns; i++) {
			if (ptr->server->nodes[i] != NULL) {
				inmem += ptr->server->nodes[i]->in.length;
				outmem += ptr->server->nodes[i]->out.length;
				filemem += ptr->server->nodes[i]->filebuf.length;
			}
		}

		if (inmem > 0) { inmem /= 1024; }
		if (outmem > 0) { outmem /= 1024; }
		if (filemem > 0) { filemem /= 1024; }

	
		printf("Bytes [%u/%u], Commands [%u], Operations[%u], Mem[%uk/%uk/%uk], Cycles[%u], Undone[%u], RW[%u/%u]\n", ptr->stats->in_bytes, ptr->stats->out_bytes, ptr->stats->commands, ptr->stats->operations, inmem, outmem, filemem, ptr->stats->cycles, ptr->stats->undone, ptr->stats->reads, ptr->stats->writes);
		ptr->stats->in_bytes = 0;
		ptr->stats->out_bytes = 0;
		ptr->stats->commands = 0;
		ptr->stats->operations = 0;
		ptr->stats->cycles = 0;
		ptr->stats->undone = 0;
		ptr->stats->reads = 0;
		ptr->stats->writes = 0;
	}
}



void timeout_init(timeout_t *ptr, struct event_base *base) 
{
	struct timeval t = {.tv_sec = 1, .tv_usec = 0};
	assert(ptr != NULL);
	assert(ptr->clockevent.ev_base == NULL);
	
	evtimer_set(&ptr->clockevent, timeout_handler, (void *) ptr);
	event_base_set(ptr->clockevent.ev_base, &ptr->clockevent);
	evtimer_add(&ptr->clockevent, &t);
	assert(ptr->clockevent.ev_base != NULL);
}




//-----------------------------------------------------------------------------
// Main... process command line parameters, and then setup our listening 
// sockets and event loop.
int main(int argc, char **argv) 
{
	int c;
	settings_t     *settings = NULL;
	server_t       *server   = NULL;
	timeout_t      *timeout  = NULL;
	stats_t        *stats    = NULL;
	risp_t         *risp     = NULL;

	// handle SIGINT 
	signal(SIGINT, sig_handler);
	
	// init settings
	settings = (settings_t *) malloc(sizeof(settings_t));
	assert(settings != NULL);
	settings_init(settings);

	// set stderr non-buffering (for running under, say, daemontools)
	setbuf(stderr, NULL);


	// process arguments 
	/// Need to check the options in here, there're possibly ones that we dont need.
	while ((c = getopt(argc, argv, "p:k:c:hvd:u:P:l:s:")) != -1) {
		switch (c) {
			case 'p':
				settings->port = atoi(optarg);
				assert(settings->port > 0);
				break;
			case 'c':
				settings->maxconns = atoi(optarg);
				assert(settings->maxconns > 0);
				break;
			case 'h':
				usage();
				exit(EXIT_SUCCESS);
			case 'v':
				settings->verbose++;
				break;
			case 'd':
				assert(settings->daemonize == false);
				settings->daemonize = true;
				break;
			case 's':
				assert(settings->storepath == NULL);
				settings->storepath = optarg;
				assert(settings->storepath != NULL);
				assert(settings->storepath[0] != '\0');
				break;
			case 'u':
				assert(settings->username == NULL);
				settings->username = optarg;
				assert(settings->username != NULL);
				assert(settings->username[0] != '\0');
				break;
			case 'P':
				assert(settings->pid_file == NULL);
				settings->pid_file = optarg;
				assert(settings->pid_file != NULL);
				assert(settings->pid_file[0] != '\0');
				break;
			case 'l':
				assert(settings->interface == NULL);
				settings->interface = strdup(optarg);
				assert(settings->interface != NULL);
				assert(settings->interface[0] != '\0');
				break;
				
			default:
				fprintf(stderr, "Illegal argument \"%c\"\n", c);
				return 1;
		}
	}

	if (settings->verbose) printf("Finished processing command-line args\n");

	// If needed, increase rlimits to allow as many connections as needed.
	if (settings->verbose) printf("Settings Max connections: %d\n", settings->maxconns);
	assert(settings->maxconns > 0);
 	set_maxconns(settings->maxconns);

	// if we are supplied with a username, drop privs to it.  This will only 
	// work if we are running as root, and is really only needed when running as 
	// a daemon.
	if (settings->username != NULL) {
		if (settings->verbose) printf("Dropping privs and changing username: '******'\n", settings->username);
		if (drop_privs(settings->username) != 0) {
			usage();
			exit(EXIT_FAILURE);
		}
	}

	// daemonize if requested
	// if we want to ensure our ability to dump core, don't chdir to /
	if (settings->daemonize) {
		int res;
		if (settings->verbose) printf("Daemonising\n");
		res = daemon(0, settings->verbose);
		if (res == -1) {
			fprintf(stderr, "failed to daemon() in order to daemonize\n");
			exit(EXIT_FAILURE);
		}
	}

	// initialize main thread libevent instance
	if (settings->verbose) printf("Initialising the event system.\n");
	main_event_base = event_init();


	if (settings->verbose) printf("Ignoring SIGPIPE interrupts\n");
	ignore_sigpipe();
    
	// save the PID in if we're a daemon, do this after thread_init due to a 
	// file descriptor handling bug somewhere in libevent
	if (settings->daemonize && settings->pid_file) {
		if (settings->verbose) printf("Saving Pid file: %s\n", settings->pid_file);
		save_pid(getpid(), settings->pid_file);
	}

	// create and init the 'server' structure.
	if (settings->verbose) printf("Starting server listener on port %d.\n", settings->port);
	server = server_new(settings->port, settings->maxconns, settings->interface);
	if (server == NULL) {
		fprintf(stderr, "Failed to listen on port %d\n", settings->port);
		exit(EXIT_FAILURE);
	}
	assert(server != NULL);
	server->verbose = settings->verbose;

	server->storepath = settings->storepath;
	
	
	// add the server to the event base
	assert(main_event_base != NULL);
	server_add_event(server, main_event_base);



	// initialise clock event.  The clock event is used to keep up our node 
	// network.  If we dont have enough connections, we will need to make some 
	// requests.  
	// create the timeout structure, and the timeout event.   This is used to 
	// perform certain things spread over time.   Such as indexing the 
	// 'complete' paths that we have, and ensuring that the 'chunks' parts are 
	// valid.
	if (settings->verbose) printf("Setting up Timeout event.\n");
	timeout = (timeout_t *) malloc(sizeof(timeout_t));

	assert(timeout != NULL);
	assert(main_event_base != NULL);
	if (settings->verbose) printf("Initialising timeout.\n");
	timeout_init(timeout, main_event_base);
	timeout->server = server;

	stats = (stats_t *) malloc(sizeof(stats_t));
	stats->out_bytes = 0;
	stats->in_bytes = 0;
	stats->commands = 0;
	stats->operations = 0;

	server->stats = stats;
	timeout->stats = stats;

	// Initialise the risp system.
	risp = risp_init();
	assert(risp != NULL);
	risp_add_invalid(risp, cmdInvalid);
	risp_add_command(risp, CMD_CLEAR, 	     &cmdClear);
	risp_add_command(risp, CMD_EXECUTE,      &cmdExecute);
	risp_add_command(risp, CMD_LIST,         &cmdList);
	risp_add_command(risp, CMD_LISTING, 	 &cmdListing);
	risp_add_command(risp, CMD_LISTING_DONE, &cmdListingDone);
	risp_add_command(risp, CMD_PUT,      	 &cmdPut);
	risp_add_command(risp, CMD_GET,          &cmdGet);
	risp_add_command(risp, CMD_SIZE,         &cmdSize);
	risp_add_command(risp, CMD_OFFSET,       &cmdOffset);
	risp_add_command(risp, CMD_FILE,         &cmdFile);
	risp_add_command(risp, CMD_DATA,         &cmdData);

	assert(server->risp == NULL);
	server->risp = risp;

	

	// enter the event loop.
	if (settings->verbose) printf("Starting Event Loop\n\n");
		event_base_loop(main_event_base, 0);
    
	// cleanup risp library.
	risp_shutdown(risp);
	risp = NULL;
    
	// cleanup 'server', which should cleanup all the 'nodes'
    
	if (settings->verbose) printf("\n\nExiting.\n");
    
	// remove the PID file if we're a daemon
	if (settings->daemonize && settings->pid_file != NULL) {
		if (settings->verbose) printf("Removing pid file: %s\n", settings->pid_file);
		remove_pidfile(settings->pid_file);
	}

	assert(settings != NULL);
	settings_cleanup(settings);
	settings = NULL;

	return 0;
}
Ejemplo n.º 13
0
int main (int argc, char **argv) {
    int c;
    conn *l_conn;
    struct in_addr addr;
    int lock_memory = 0;
    int daemonize = 0;
    int maxcore = 0;
    char *username = 0;
    struct passwd *pw;
    struct sigaction sa;
    struct rlimit rlim;
    char *pid_file = NULL;

    /* init settings */
    settings_init();

    /* process arguments */
    while ((c = getopt(argc, argv, "p:m:Mc:khirvdl:u:P:")) != -1) {
        switch (c) {
        case 'p':
            settings.port = atoi(optarg);
            break;
        case 'm':
            settings.maxbytes = atoi(optarg)*1024*1024;
            break;
        case 'M':
            settings.evict_to_free = 0;
            break;
        case 'c':
            settings.maxconns = atoi(optarg);
            break;
        case 'h':
            usage();
            exit(0);
        case 'i':
            usage_license();
            exit(0);
        case 'k':
            lock_memory = 1;
            break;
        case 'v':
            settings.verbose++;
            break;
        case 'l':
            if (!inet_aton(optarg, &addr)) {
                fprintf(stderr, "Illegal address: %s\n", optarg);
                return 1;
            } else {
                settings.interface = addr;
            }
            break;
        case 'd':
            daemonize = 1;
            break;
        case 'r':
            maxcore = 1;
            break;
        case 'u':
            username = optarg;
            break;
        case 'P':
            pid_file = optarg;
            break;
        default:
            fprintf(stderr, "Illegal argument \"%c\"\n", c);
            return 1;
        }
    }

    if (maxcore) {
        struct rlimit rlim_new;
        /*
         * First try raising to infinity; if that fails, try bringing
         * the soft limit to the hard.
         */
        if (getrlimit(RLIMIT_CORE, &rlim)==0) {
            rlim_new.rlim_cur = rlim_new.rlim_max = RLIM_INFINITY;
            if (setrlimit(RLIMIT_CORE, &rlim_new)!=0) {
                /* failed. try raising just to the old max */
                rlim_new.rlim_cur = rlim_new.rlim_max =
                                        rlim.rlim_max;
                (void) setrlimit(RLIMIT_CORE, &rlim_new);
            }
        }
        /*
         * getrlimit again to see what we ended up with. Only fail if
         * the soft limit ends up 0, because then no core files will be
         * created at all.
         */

        if ((getrlimit(RLIMIT_CORE, &rlim)!=0) || rlim.rlim_cur==0) {
            fprintf(stderr, "failed to ensure corefile creation\n");
            exit(1);
        }
    }

    /*
     * If needed, increase rlimits to allow as many connections
     * as needed.
     */

    if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
        fprintf(stderr, "failed to getrlimit number of files\n");
        exit(1);
    } else {
        int maxfiles = settings.maxconns;
        if (rlim.rlim_cur < maxfiles)
            rlim.rlim_cur = maxfiles + 3;
        if (rlim.rlim_max < rlim.rlim_cur)
            rlim.rlim_max = rlim.rlim_cur;
        if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) {
            fprintf(stderr, "failed to set rlimit for open files. Try running as root or requesting smaller maxconns value.\n");
            exit(1);
        }
    }

    /*
     * initialization order: first create the listening socket
     * (may need root on low ports), then drop root if needed,
     * then daemonise if needed, then init libevent (in some cases
     * descriptors created by libevent wouldn't survive forking).
     */

    /* create the listening socket and bind it */
    l_socket = server_socket(settings.port);
    if (l_socket == -1) {
        fprintf(stderr, "failed to listen\n");
        exit(1);
    }

    /* lose root privileges if we have them */
    if (getuid()== 0 || geteuid()==0) {
        if (username==0 || *username=='\0') {
            fprintf(stderr, "can't run as root without the -u switch\n");
            return 1;
        }
        if ((pw = getpwnam(username)) == 0) {
            fprintf(stderr, "can't find the user %s to switch to\n", username);
            return 1;
        }
        if (setgid(pw->pw_gid)<0 || setuid(pw->pw_uid)<0) {
            fprintf(stderr, "failed to assume identity of user %s\n", username);
            return 1;
        }
    }

    /* daemonize if requested */
    /* if we want to ensure our ability to dump core, don't chdir to / */
    if (daemonize) {
        int res;
        res = daemon(maxcore, settings.verbose);
        if (res == -1) {
            fprintf(stderr, "failed to daemon() in order to daemonize\n");
            return 1;
        }
    }


    /* initialize other stuff */
    item_init();
    event_init();
    stats_init();
    assoc_init();
    conn_init();
    slabs_init(settings.maxbytes);

    /* lock paged memory if needed */
    if (lock_memory) {
#ifdef HAVE_MLOCKALL
        mlockall(MCL_CURRENT | MCL_FUTURE);
#else
        fprintf(stderr, "warning: mlockall() not supported on this platform.  proceeding without.\n");
#endif
    }

    /*
     * ignore SIGPIPE signals; we can use errno==EPIPE if we
     * need that information
     */
    sa.sa_handler = SIG_IGN;
    sa.sa_flags = 0;
    if (sigemptyset(&sa.sa_mask) == -1 ||
            sigaction(SIGPIPE, &sa, 0) == -1) {
        perror("failed to ignore SIGPIPE; sigaction");
        exit(1);
    }

    /* create the initial listening connection */
    if (!(l_conn = conn_new(l_socket, conn_listening, EV_READ | EV_PERSIST))) {
        fprintf(stderr, "failed to create listening connection");
        exit(1);
    }

    /* initialise deletion array and timer event */
    deltotal = 200;
    delcurr = 0;
    todelete = malloc(sizeof(item *)*deltotal);
    delete_handler(0,0,0); /* sets up the event */

    /* save the PID in if we're a daemon */
    if (daemonize)
        save_pid(getpid(),pid_file);

    /* enter the loop */
    event_loop(0);

    /* remove the PID file if we're a daemon */
    if (daemonize)
        remove_pidfile(pid_file);

    return 0;
}
Ejemplo n.º 14
0
Archivo: server.c Proyecto: yumm007/C
int main(int argc, char *argv[])
{
	int chnr = 0;
	struct channel_item_st *link = NULL;
	pthread_t pthd;

	openlog("netradio", LOG_PID, LOG_DAEMON);
	syslog(LOG_INFO, "daemon start.");

	sep_arg(&args);
	my_daemon();

	if (install_signal() != 0) {
		syslog(LOG_ERR, "install signal failed, exit.");
		closelog();
		exit(1);
	}

	if (save_pid(LOCK_FILE) == -1) {
		closelog();
		exit(1);
	}

	if ((sd = create_socket(args.multicast_group)) == -1) {
		syslog(LOG_ERR, "create socket failed, exit.");
		closelog();
		exit(1);
	}

	if (medialib_get_channellist(&chnr, &link) != 0) {
		syslog(LOG_ERR, "init channellist failed, exit.");
		closelog();
		close(sd);
		exit(1);
	}

	if (pthread_create(&pthd, NULL, channel_0_pth, link) != 0) {
		syslog(LOG_ERR, "init channel 0 failed, exit.");
		medialib_free_channellist(link);
		closelog();
		close(sd);
		exit(1);
	}

	//失败时会释放link 和已经打开的线程
	if (create_channel_pthread(link) == -1) {
		syslog(LOG_ERR, "init channel pthread failed, exit.");
		closelog();
		close(sd);
		exit(1);
	}

	wait_until_exit(link, chnr);

	pthread_cancel(pthd); /*cancel pth 0*/
	pthread_join(pthd, NULL);

	syslog(LOG_INFO, "netradio daemon exit.");
	closelog();
	close(sd);

	return 0;
}
Ejemplo n.º 15
0
/* server_main()
 * -> sb_run_* APIs are enabled
 * -> all registries are enabled
 * -> all configs are enabled. config should follow and overwrite registry.
 */
int server_main()
{
	module *mod=NULL;

  /***********************************************************************
   * first-pass config 
   */

	set_proc_desc(NULL, "softbotd: master - loading static modules");
	/* load_static_modules()
	 *  -> hooking APIs. we cannot call sb_run_* APIs before this
	 */
	load_static_modules();

    /* FIXME why should i load kbo module?? */
	//load_kbo_module();

	if (read_config(mConfigFile, NULL) != SUCCESS) {
		crit("failed to read config file");
		exit(1);
	}
	/* 1. load dynamic modules -> make linked list of whole modules
	 * 2. setup each modules's configuration -> call each config function
	 */

	open_error_log(gErrorLogFile, gQueryLogFile);
#ifdef USE_TIMELOG
    if(sb_tstat_log_init(mTimeLogFile) != SUCCESS) {
        exit(1);
    }
#endif

	save_pid(mPidFile);

	load_dynamic_modules();
  /***********************************************************************
   * all the modules has been loaded.
   */

	sb_sort_hook();

	load_each_registry();
	/* 1. register each module to registry
	 * 2. do the shared memory related stuff...
	 * 3. XXX registry module does not guarantee shared memory locking...
	 */

	restore_registry_file(gRegistryFile);

	/* TODO second-pass config */

  /***********************************************************************
   * runtime configuration is done.
   */
	init_all_scoreboards();

	/* method 3 of doc/README.init */
	set_proc_desc(NULL, "softbotd: master - init each module");
	if ( init_core_modules(first_module) != SUCCESS ) goto STOP;
	if ( init_standard_modules(first_module) != SUCCESS ) goto STOP;

	if (clc_listen_port >= 2) { /* show using ports */
		show_portinfo();
		goto STOP;
	}
	set_proc_desc(NULL, "softbotd: master - spawning child");
	/* check debug_module */
	if ( strlen(debug_module) > 0 ) {
		mod = find_module(debug_module);
		if ( mod == NULL ) {
			error("no such module [%s]", debug_module);
			return FAIL;
		}
		else {
			info("debugging module [%s]", debug_module);
			// XXX: in debugging mode, isn't it better not to fork? is it?
			if (mod->main) 
				sb_run_spawn_process_for_module(scoreboard, mod);
			else {
				error("module[%s] has no main",debug_module);
				exit(1);
			}
		}
	}
	else if (unittest) {
		crit("unittesting started");
		do_unittest();
		crit("unittesting ended");
		goto STOP;
	}
	else
		sb_run_spawn_processes_for_each_module(scoreboard, first_module);

	CRIT("*** master monitoring loop ***");
	setproctitle("softbotd: master - monitoring");
	set_proc_desc(NULL, "softbotd: master - monitoring");
	scoreboard->period = CHILD_MONITORING_PERIOD;
	sb_run_monitor_processes_for_modules(scoreboard, first_module);

  /***********************************************************************
   * stopping state.
   */
STOP:	
	if ( save_registry_file(gRegistryFile) != SUCCESS )
		error("save_registry_file(%s) failed: %s",
			gRegistryFile, strerror(errno));
	free_ipcs(); /* release shared memory and semaphore */
	close_error_log(); /* close error_log file and semaphore */

#ifdef USE_TIMELOG
    sb_tstat_log_destroy();
#endif

	return SUCCESS;
}
Ejemplo n.º 16
0
void
init_netsukuku(char **argv)
{
	xsrand();

	if (geteuid())
		fatal("Need root privileges");

	destroy_netsukuku_mutex = pid_saved = 0;
	sigterm_timestamp = sighup_timestamp = sigalrm_timestamp = 0;
	setzero(&me, sizeof(struct current_globals));

	if (is_ntkd_already_running())
		fatal("ntkd is already running. If it is not, remove \"%s\"",
			  server_opt.pid_file);
	else
		save_pid();

	my_family = server_opt.family;
	restricted_mode = server_opt.restricted;
	restricted_class =
		server_opt.restricted_class ? RESTRICTED_172 : RESTRICTED_10;

	/* Check if the DATA_DIR exists, if not create it */
	if (check_and_create_dir(DATA_DIR))
		fatal("Cannot access to the %s directory. Exiting.", DATA_DIR);

	/*
	 * Device initialization
	 */
	if (if_init_all(server_opt.ifs, server_opt.ifs_n,
					me.cur_ifs, &me.cur_ifs_n) < 0)
		fatal("Cannot initialize any network interfaces");

	/*
	 * ANDNA init
	 */
	if (!server_opt.disable_andna)
		andna_init();

	/*
	 * Initialize the Internet gateway stuff
	 */
	if (server_opt.my_upload_bw && server_opt.my_dnload_bw)
		me.my_bandwidth = bandwidth_in_8bit((server_opt.my_upload_bw +
											 server_opt.my_dnload_bw) / 2);
	init_internet_gateway_search();

	pkts_init(me.cur_ifs, me.cur_ifs_n, 0);
	qspn_init(FAMILY_LVLS);

	me.cur_erc = e_rnode_init(&me.cur_erc_counter);

	/* Radar init */
	rq_wait_idx_init(rq_wait_idx);
	first_init_radar();
	total_radars = 0;

	ntk_load_maps();

#if 0
	/* TODO: activate and test it !! */
	debug(DBG_NORMAL, "ACPT: Initializing the accept_tbl: \n"
		  "	max_connections: %d,\n"
		  "	max_accepts_per_host: %d,\n"
		  "	max_accept_per_host_time: %d",
		  server_opt.max_connections,
		  server_opt.max_accepts_per_host,
		  server_opt.max_accepts_per_host_time);
	init_accept_tbl(server_opt.max_connections,
					server_opt.max_accepts_per_host,
					server_opt.max_accepts_per_host_time);
#endif

	if (restricted_mode)
		loginfo("NetsukukuD is in restricted mode. "
				"Restricted class: %s",
				server_opt.
				restricted_class ? RESTRICTED_172_STR : RESTRICTED_10_STR);

	hook_init();
	rehook_init();

	me.uptime = time(0);
}
Ejemplo n.º 17
0
int main(int argc, char *argv[])
{
	int fd;
	int pid;
	int len;
	char buf[1024];
	char *pipename;
	int is_wait;
	char *pipe_dir = get_pipe_dir();
	int timeout = 0;

	is_wait = !strcmp(basename(argv[0]), "wait");

	while (1) {
		int c;
		int option_index = 0;
		static struct option long_options[] = {
			{"timeout", required_argument, 0, 't'},
			{0,         0,                 0,  0 }
		};

		c = getopt_long(argc, argv, "t:", long_options, &option_index);
		if (c == -1)
			break;

		switch (c) {
		case 't':
			timeout = atoi(optarg);
			break;
		}
	}

	if (optind < argc) {
		pipename = argv[optind];
	} else {
		printf("Usage: %s [-t|--timeout seconds] PIPE_NAME\n", argv[0]);
		exit(0);
	}

	mkdir(pipe_dir, 0770);
	chdir(pipe_dir);
	mkfifo(pipename, 0660);

	if (is_wait) {
		if (timeout) {
			signal(SIGALRM, do_timeout);
			alarm(timeout);
		}
		/*
		 * wait processes will be blocked here until the
		 * wakeup process writes some data to the pipe
		 */
		fd = open(pipename, O_RDONLY);
	} else
		fd = open(pipename, O_RDWR|O_NONBLOCK);
	if (fd < 0) {
		perror(pipename);
		exit(1);
	}

	if (is_wait)
		exit(0);

	len = write(fd, buf, sizeof(buf));
	if (len < sizeof(buf)) {
		fprintf(stderr, "%s: write error or short write: %d\n", argv[0], len);
		exit(1);
	}

	/* keep the fd open for sufficient long time */
	if ((pid = fork())) {
		save_pid(pid);
		exit(0);
	}

	for (--fd; fd; --fd)
		close(fd);
	setsid();
	signal(SIGCHLD, SIG_IGN);
	signal(SIGTSTP, SIG_IGN);
	signal(SIGTTOU, SIG_IGN);
	signal(SIGTTIN, SIG_IGN);

	sleep(100);

	return 0;
}