Exemple #1
0
void process_init()
{
	process_cache = kmem_cache_create("process_cache",
		sizeof(struct process), 32, NULL, NULL);
	if(!process_cache)
		panic("process_init: Not Enough Memory to boot ManRiX\n");

	phash =	(phashtable_t)kmem_alloc(PAGE_SIZE);
	if(!phash)
		panic("process_init: Not Enough Memory to boot ManRiX\n");
	memset(phash, 0, PAGE_SIZE);

	list_init(&kernel_process.threads);
	list_init(&kernel_process.proclist);
	list_init(&kernel_process.child);
	list_init(&kernel_process.sigqueue);
	list_init(&kernel_process.timer);
	kernel_process.parent = kernel;
	list_init(&sysinfo.proclist);
	SPIN_LOCK_INIT(&kernel_process.lock);

	thread_init();
	init_signal();
	id_init();
	fd_init();
	sync_init();
}
Exemple #2
0
int bladerf_sync_config(struct bladerf *dev,
                        bladerf_module module,
                        bladerf_format format,
                        unsigned int num_buffers,
                        unsigned int buffer_size,
                        unsigned int num_transfers,
                        unsigned int stream_timeout)
{
    int status;

    switch (module) {
        case BLADERF_MODULE_RX:
        case BLADERF_MODULE_TX:
            break;

        default:
            return BLADERF_ERR_INVAL;
    }

    MUTEX_LOCK(&dev->ctrl_lock);
    MUTEX_LOCK(&dev->sync_lock[module]);

    dev->transfer_timeout[module] = stream_timeout;

    status = sync_init(dev, module, format, num_buffers, buffer_size,
                       num_transfers, stream_timeout);

    MUTEX_UNLOCK(&dev->sync_lock[module]);
    MUTEX_UNLOCK(&dev->ctrl_lock);

    return status;
}
Exemple #3
0
int
kern_init(void) {
    extern char edata[], end[];
    memset(edata, 0, end - edata);
	
    cons_init();                // init the console

    const char *message = "(THU.CST) os is loading ...";
    kprintf ("%s\n\n", message);

	/* Only to initialize lcpu_count. */
	mp_init ();

	pmm_init();                 // init physical memory management
	pmm_init_ap ();

    pic_init();                 // init interrupt controller

	vmm_init();                 // init virtual memory management
    sched_init();               // init scheduler
	proc_init();                // init process table
    sync_init();                // init sync struct
	
	ide_init();                 // init ide devices
    swap_init();                // init swap
    fs_init();                  // init fs

    clock_init();               // init clock interrupt
    intr_enable();              // enable irq interrupt    

    cpu_idle();                 // run idle process
}
Exemple #4
0
static void
init_commands(void)
{
	attr_init();
	bmap_init();
	fadvise_init();
	file_init();
	flink_init();
	freeze_init();
	fsync_init();
	getrusage_init();
	help_init();
	imap_init();
	inject_init();
	seek_init();
	madvise_init();
	mincore_init();
	mmap_init();
	open_init();
	parent_init();
	pread_init();
	prealloc_init();
	fiemap_init();
	pwrite_init();
	quit_init();
	readdir_init();
	resblks_init();
	sendfile_init();
	shutdown_init();
	sync_init();
	sync_range_init();
	truncate_init();
	reflink_init();
	dedupe_init();
}
threadpool_t tp_alloc(int *count, void (*run)(int thread, void *item))
{
	int i;
	struct threadpool *tp =
				(struct threadpool *) malloc(sizeof(struct threadpool));

	if (!tp)
		return INVALID_THREADPOOL;

	memset(tp, 0, sizeof(struct threadpool));
	sync_init(tp);
	tp->run = run;

	enter_critical_section(tp);

	for (i = 1; i < *count; i++) {
		if (!create_thread(thread_proc, tp))
			tp->thread_count++;
	}

	tp->wait_count = tp->thread_count;
	if (tp->wait_count)
		wait_for_completion(tp);
	*count = tp->thread_count + 1;
	leave_critical_section(tp);

	return tp;
}
Exemple #6
0
int __noreturn
kern_init(void) {
    extern char edata[], end[];
    memset(edata, 0, end - edata);

    cons_init();                // init the console

    const char *message = "(THU.CST) os is loading ...";
    cprintf("%s\n\n", message);

    print_kerninfo();

    pmm_init();                 // init physical memory management

    pic_init();                 // init interrupt controller
    idt_init();                 // init interrupt descriptor table

    vmm_init();                 // init virtual memory management
    sched_init();               // init scheduler
    proc_init();                // init process table
    sync_init();                // init sync struct

    ide_init();                 // init ide devices
    swap_init();                // init swap
    fs_init();                  // init fs

    clock_init();               // init clock interrupt
    intr_enable();              // enable irq interrupt

    cpu_idle();                 // run idle process
}
Exemple #7
0
/**
 * The entry.
 */
int main(int argc, char *argv[], char *envp[])
{
    if (ginfo->status == STATUS_DEBUG)
        raise(SIGTRAP);

    cons_init();

    const char *message = "(THU.CST) os is loading ...";
    kprintf("%s\n\n", message);

    intr_init();
    ide_init();

    host_signal_init();

    /* Only to initialize lcpu_count. */
    mp_init();

    pmm_init();
    pmm_init_ap();
    vmm_init();
    sched_init();
    proc_init();

    swap_init();
    fs_init();
    sync_init();

    umclock_init();
    cpu_idle();

    host_exit(SIGINT);

    return 0;
}
void usbd_msc_init(void)
{
    sync_init();
    build_filesystem();
    vfs_state = VFS_MNGR_STATE_DISCONNECTED;
    vfs_state_next = VFS_MNGR_STATE_DISCONNECTED;
    time_usb_idle = 0;
    USBD_MSC_MediaReady = 0;
}
void usbd_msc_init(void)
{
    sync_init();
    build_filesystem();
    vfs_state = VFS_USER_STATE_DISCONNECTED;
    vfs_state_next = VFS_USER_STATE_DISCONNECTED;
    vfs_state_remaining_ms = 0;
    USBD_MSC_MediaReady = 0;
}
Exemple #10
0
/* On Load */
int __init glasses3d_init(void) {
	
	sync_init();
	
	usb_init();
	//i2c_dev_init();
	
	printk(KERN_INFO "%s succefully loaded\n", DRIVER_NAME);
	return 0;
}
Exemple #11
0
// The kernel main function. Initialize everything and start the kernel
// debugger. The two arguments are the physical address of the Multiboot info
// structure and the bootloader magic number respectively.
void
init()
{
    int r;

    // Initialize the console first to print messages during the initialization
    cons_init();

    kprintf("Argentum Operating System\n");

    arch_init();

    kmem_cache_init();
    kmem_cache_sizes_init();

    vm_init();
    process_init();
    thread_init();
    ipc_init();
    scheduler_init();
    sync_init();
    clock_init();

    if ((r = process_create_system(system_main, NULL)) < 0)
        kprintf("Cannot create system process: %s\n", strerror(-r));

    if (module_start) {
        Boot_image *image = (Boot_image *) module_start;
    
        if(image->magic != 0x12345678)
            panic("invalid bootimage");

        for (unsigned i = 0; i < image->length; i++) {
            uint8_t *binary = (uint8_t *) image + image->headers[i].offset;
            size_t size = image->headers[i].length;

            if (binary < module_start || binary >= module_end)
                panic("invalid bootimage");
            if ((binary + size) <= module_start || (binary + size) > module_end)
                panic("invalid bootimage");

            r = process_create((uint8_t *) image + image->headers[i].offset,
                    image->headers[i].length, PROCESS_TYPE_USER, NULL);
            if (r < 0)
                panic("Cannot create process: %s", strerror(-r));
        }

    }

    scheduler_start();

    for (;;) {
        kdb_main(NULL);
    }
}
void main(int argc,char* argv[])
{
	int i,j,t,k,l,m,yoda,limu,lim,seed,str,etr;
	printf("Enter number of iterations\n");
	scanf("%d",&l);
	printf("Enter number upto which you want to count\n");
	scanf("%d",&seed);
	printf("Enter minimum number of threads\n");
	scanf("%d",&str);
	printf("Enter maximum number of threads\n");
	scanf("%d",&etr);
	assert(etr>=str);
	double records[etr+1-str];
	for(i=0;i<etr+1-str;i++)
	{
		records[i]=0;
	}
	pthread_t p[etr];
	for(m=str;m<=etr;m++)
	{
		//Number of iterations for averaging :
		for(yoda=0;yoda<l;yoda++)
		{
			struct timeval start,end;
			sync_init(&x);
			value=0;
			lim=seed;
			limu=lim/m;
			gettimeofday(&start,NULL);			
			//Create 'm-1' threads
			for(j=0;j<m-1;j++)
			{
				k=pthread_create(&p[j],NULL,counter,(void*)&limu);
				lim-=limu;
			}
			//Remainder added to the last thread:
			k=pthread_create(&p[m-1],NULL,counter,(void*)&lim);

			//Wait for those 'm' threads to finish:
			for(j=0;j<m;j++)
			{
				pthread_join(p[j],NULL);
			}
			gettimeofday(&end,NULL);
			records[m-str]+=((end.tv_sec-start.tv_sec)*1000000 + end.tv_usec-start.tv_usec)/1000000.0;
			value+=sync_get(&x);
		}	
		printf("Final value (average) of counter for %d threads : %d\n",m,sync_get(&x));
	}
	for(j=0;j<etr+1-str;j++)
	{
		printf("Average time taken for %d threads : %lf\n",j+str,records[j]/l);
	}
}
Exemple #13
0
int gpuvm_init(unsigned ndevs, void **devs, int flags) {
	// check arguments
	if(ndevs == 0) {
		fprintf(stderr, "gpuvm_init: zero devices not allowed\n");
		return GPUVM_EARG;
	}
	if(flags & ~(GPUVM_API | GPUVM_STAT | GPUVM_WRITER_SIG_BLOCK | 
							 GPUVM_UNLINK_NO_SYNC_BACK) || !(flags & GPUVM_API)) {
		fprintf(stderr, "gpuvm_init: invalid flags\n");
		return GPUVM_EARG;
	}

	// check state
	if(ndevs_g) {
		fprintf(stderr, "gpuvm_init: GPUVM already initialized\n");
		return GPUVM_ETWICE;
	}
	ndevs_g = ndevs;

	// initialize auxiliary structures
	int err = 0;
	err = salloc_init();
	if(err)
		return err;

	// initialize devices
	devs_g = (void**)smalloc(ndevs * sizeof(void*));
	if(!devs_g)
		return GPUVM_ESALLOC;

	if(flags & GPUVM_OPENCL) {
		if(!devs) {
			fprintf(stderr, "gpuvm_init: null pointer to devices not allowed\n");
			return GPUVM_ENULL;
		}
		memcpy(devs_g, devs, ndevs * sizeof(void*));
	} else if(flags & GPUVM_CUDA) {
		// ignore devs, just zero out devs_g
		memset(devs_g, 0, ndevs * sizeof(void*));
	}

	// continue with initialization
	(err = sync_init()) || 
		(err = devapi_init(flags)) ||
		(err = handler_init()) || 
		(err = stat_init(flags)) || 
		(err = tsem_init()) || 
		(err = wthreads_init());
	if(err)
		return err;
	
	return 0;
}  // gpuvm_init
Exemple #14
0
int main(void) {
	
	init_ctrl();
	adc_init();
	sync_init();
	timer1_init();
	ui_init();
	timer1_load();
	
	while (1) {
		ui_update();
	}
}
Exemple #15
0
int CALL_CONV bladerf_sync_config(struct bladerf *dev,
                                  bladerf_module module,
                                  bladerf_format format,
                                  unsigned int num_buffers,
                                  unsigned int buffer_size,
                                  unsigned int num_transfers,
                                  unsigned int stream_timeout)
{
#ifdef ENABLE_LIBBLADERF_SYNC
    return sync_init(dev, module, format, num_buffers, buffer_size,
                     num_transfers, stream_timeout);
#else
    return BLADERF_ERR_UNSUPPORTED;
#endif
}
Exemple #16
0
void main (void){

    CPU_init();
    CPU_extCLK();

    // Get the id (even/odd)
    id_init();

    // Encoder input
    //fps_init();
    
    // uC synchro
    sync_init();

    // Leds!
    led_init();

    // Serial coms, over bluetooth
    serial_init();

    EnableInterrupts;


    /* --------- TEST ---------- *
    FTM2_setMod(0x0200); // clk/2**12 = bus/2**20
    FTM2_init(7); // bus/2**8
    
    FTM2_enableInterrupts(seg);

	SPI_init(SPI_BAUDS,SPI_MASTER|SPI_INVERTCLK);

    // Negated
    LED_OUT_EN = 0;
    LED_OUT_EN_PORT = 1;
    // Rising
    LED_OUT_CLK = 0;
    LED_OUT_CLK_PORT = 1;

    /* -------- /TEST ---------- */

    for(;;){
        // Polls for UART input
    	serial_update();
    	//__RESET_WATCHDOG();	/* feeds the dog */
    }
}
Exemple #17
0
static void main_service_ready (void)
{
	int res;

	/*
	 * This must occur after totempg is initialized because "this_ip" must be set
	 */
	res = corosync_service_defaults_link_and_init (api);
	if (res == -1) {
		log_printf (LOGSYS_LEVEL_ERROR, "Could not initialize default services");
		corosync_exit_error (COROSYNC_DONE_INIT_SERVICES);
	}
	cs_ipcs_init();
	corosync_totem_stats_init ();
	corosync_fplay_control_init ();
	sync_init (
		corosync_sync_callbacks_retrieve,
		corosync_sync_completed);
}
Exemple #18
0
int main()
{
	state = sync_init("file.txt", 4096*2, "log.txt");
	if (state != 0)
	{
		printf("sync_init fail\n");
		return -1;
	}

	state = sync_read(ans, 10, 4095);
	if (state != 0)
	{	
		printf("sync_read fail\n");
		return -1;
	}
	ans[10] = '\0';
	printf("read answer: %s\n", ans);

	state = sync_write(ans, 10, 1);
	if (state != 0)
	{	
		printf("sync_write fail\n");
		return -1;
	}
	state = sync_read(ans, 10, 1);
	if (state != 0)
	{	
		printf("sync_read fail\n");
		return -1;
	}
	ans[10] = '\0';
	printf("read answer: %s\n", ans);

	state = sync_exit();
	if (state != 0)
	{	
		printf("sync_exit fail\n");
		return -1;
	}

	return 0;
}
Exemple #19
0
int kern_init(void)
{
	extern char edata[], end[];
	memset(edata, 0, end - edata);

	cons_init();		// init the console

	const char *message = "(THU.CST) os is loading ...";
	kprintf("%s\n\n", message);

	print_kerninfo();

	/* Only to initialize lcpu_count. */
	mp_init();

	debug_init();		// init debug registers
	pmm_init();		// init physical memory management
	pmm_init_ap();

	pic_init();		// init interrupt controller
	idt_init();		// init interrupt descriptor table

	vmm_init();		// init virtual memory management
	sched_init();		// init scheduler
	proc_init();		// init process table
	sync_init();		// init sync struct

	ide_init();		// init ide devices
#ifdef UCONFIG_SWAP
	swap_init();		// init swap
#endif
	fs_init();		// init fs

	clock_init();		// init clock interrupt
	mod_init();

	intr_enable();		// enable irq interrupt

	/* do nothing */
	cpu_idle();		// run idle process
}
Exemple #20
0
 
extern void swap_init_nios2(void);

 
int alt_main(void) 
{
	
const char *message = "(THU.CST) os is loading ...";
	
kprintf("%s\n\n", message);
	
 
mp_init();
	
 
pmm_init();		// init physical memory management    
	
pmm_init_ap();
	
 
vmm_init();		// init virtual memory management
Exemple #21
0
/* Adds file descriptors to the child structure to support output_sync; one
   for stdout and one for stderr as long as they are open.  If stdout and
   stderr share a device they can share a temp file too.
   Will reset output_sync on error.  */
static void
setup_tmpfile (struct output *out)
{
  /* Is make's stdout going to the same place as stderr?  */
  static int combined_output = -1;

  if (combined_output < 0)
    combined_output = sync_init ();

  if (STREAM_OK (stdout))
    {
      int fd = output_tmpfd ();
      if (fd < 0)
        goto error;
      CLOSE_ON_EXEC (fd);
      out->out = fd;
    }

  if (STREAM_OK (stderr))
    {
      if (out->out != OUTPUT_NONE && combined_output)
        out->err = out->out;
      else
        {
          int fd = output_tmpfd ();
          if (fd < 0)
            goto error;
          CLOSE_ON_EXEC (fd);
          out->err = fd;
        }
    }

  return;

  /* If we failed to create a temp file, disable output sync going forward.  */
 error:
  output_close (out);
  output_sync = 0;
}
Exemple #22
0
int main(int argc, char *argv[])
{
	mmatic *mm = mmatic_create();
	mmatic *mmtmp = mmatic_create();
	struct mg *mg;
	int i;

	/*
	 * initialize and parse config
	 */

	mg = mmatic_zalloc(mm, sizeof(struct mg));
	mg->mm = mm;
	mg->mmtmp = mmtmp;
	apply_defaults(mg);

	/* get my id number from hostname */
	fetch_myid(mg);

	/* parse command line options */
	if (parse_argv(mg, argc, argv))
		return 1;

	/* parse configuration file options */
	if (mg->options.conf_file) {
		if (parse_config(mg))
			return 4;
	}

	/*
	 * config syntax looks OK, see if it is feasible
	 */

	/* initialize random number generator */
	srand48(mg->options.myid);

	/* init libevent */
	mg->evb = event_init();
	event_set_log_callback(libevent_log);

	/* init stats structures so mgstats_aggregator_add() used somewhere below works */
	mgstats_init(mg);

	/* attach to raw interfaces */
	if (mgi_init(mg, handle_packet) <= 0) {
		dbg(0, "no available interfaces found\n");
		return 2;
	}

	/* parse traffic file */
	if (parse_traffic(mg))
		return 3;

	/*
	 * all OK, prepare to start
	 */

	/* synchronize time reference point on all nodes */
	mgc_sync(mg);

	/* schedule stats writing */
	mgstats_start(mg);

	/* attach global stats */
	_stats_init(mg);

	/* schedule heartbeat and disk sync signals */
	heartbeat_init(mg);
	sync_init(mg);

	/* schedule the real work of this node: line generators */
	for (i = 1; i < TRAFFIC_LINE_MAX; i++) {
		if (!(mg->lines[i] && mg->lines[i]->my))
			continue;

		/* this will schedule first execution */
		mgs_sleep(mg->lines[i], NULL);
		mg->running++;
	}

	/* suppose last frame was received now */
	gettimeofday(&mg->last, NULL);

	/*
	 * start!
	 */

	dbg(0, "Starting\n");
	event_base_dispatch(mg->evb);

	/*******************************/

	/*
	 * cleanup after end of libevent loop
	 */

	event_base_free(mg->evb);
	mmatic_free(mg->mm);
	mmatic_free(mg->mmtmp);

	fflush(NULL);
	sync();

	return 0;
}
int
main(int argc, char *argv[])
{
#ifdef __FreeBSD__
	extern char *__progname;
	FILE *fpid = NULL;
	struct stat dbstat;
	int pt, ge, we;  /* make build on amd64/sparc happy */
#endif
	fd_set *fdsr = NULL, *fdsw = NULL;
	struct sockaddr_in sin;
	struct sockaddr_in lin;
	int ch, s, s2, conflisten = 0, syncfd = 0, i, omax = 0, one = 1;
	socklen_t sinlen;
	u_short port;
	struct servent *ent;
	struct rlimit rlp;
	char *bind_address = NULL;
	const char *errstr;
	char *sync_iface = NULL;
	char *sync_baddr = NULL;

	tzset();
	openlog_r("spamd", LOG_PID | LOG_NDELAY, LOG_DAEMON, &sdata);

	if ((ent = getservbyname("spamd", "tcp")) == NULL)
		errx(1, "Can't find service \"spamd\" in /etc/services");
	port = ntohs(ent->s_port);
	if ((ent = getservbyname("spamd-cfg", "tcp")) == NULL)
		errx(1, "Can't find service \"spamd-cfg\" in /etc/services");
	cfg_port = ntohs(ent->s_port);
	if ((ent = getservbyname("spamd-sync", "udp")) == NULL)
		errx(1, "Can't find service \"spamd-sync\" in /etc/services");
	sync_port = ntohs(ent->s_port);

	if (gethostname(hostname, sizeof hostname) == -1)
		err(1, "gethostname");
	maxfiles = get_maxfiles();
	if (maxcon > maxfiles)
		maxcon = maxfiles;
	if (maxblack > maxfiles)
		maxblack = maxfiles;
	while ((ch =
#ifndef __FreeBSD__
	    getopt(argc, argv, "45l:c:B:p:bdG:h:s:S:M:n:vw:y:Y:")) != -1) {
#else
	    getopt(argc, argv, "45l:c:B:p:bdG:h:s:S:M:n:vw:y:Y:t:m:")) != -1) {
#endif
		switch (ch) {
		case '4':
			nreply = "450";
			break;
		case '5':
			nreply = "550";
			break;
		case 'l':
			bind_address = optarg;
			break;
		case 'B':
			i = atoi(optarg);
			maxblack = i;
			break;
		case 'c':
			i = atoi(optarg);
			if (i > maxfiles) {
				fprintf(stderr,
				    "%d > system max of %d connections\n",
				    i, maxfiles);
				usage();
			}
			maxcon = i;
			break;
		case 'p':
			i = atoi(optarg);
			port = i;
			break;
		case 'd':
			debug = 1;
			break;
		case 'b':
			greylist = 0;
			break;
		case 'G':
			if (sscanf(optarg, "%d:%d:%d", &pt, &ge, &we) != 3)
				usage();
			/* convert to seconds from minutes */
			passtime = pt * 60;
			/* convert to seconds from hours */
			whiteexp = we * (60 * 60);
			/* convert to seconds from hours */
			greyexp  = ge * (60 * 60);
			break;
		case 'h':
			bzero(&hostname, sizeof(hostname));
			if (strlcpy(hostname, optarg, sizeof(hostname)) >=
			    sizeof(hostname))
				errx(1, "-h arg too long");
			break;
		case 's':
			i = strtonum(optarg, 0, 10, &errstr);
			if (errstr)
				usage();
			stutter = i;
			break;
		case 'S':
			i = strtonum(optarg, 0, 90, &errstr);
			if (errstr)
				usage();
			grey_stutter = i;
			break;
		case 'M':
			low_prio_mx_ip = optarg;
			break;
		case 'n':
			spamd = optarg;
			break;
		case 'v':
			verbose = 1;
			break;
		case 'w':
			window = atoi(optarg);
			if (window <= 0)
				usage();
			break;
		case 'Y':
			if (sync_addhost(optarg, sync_port) != 0)
				sync_iface = optarg;
			syncsend++;
			break;
		case 'y':
			sync_baddr = optarg;
			syncrecv++;
			break;
#ifdef __FreeBSD__
		case 't':
			ipfw_tabno = atoi(optarg);
			break;
		case 'm':
			if (strcmp(optarg, "ipfw") == 0)
				use_pf=0;
			break;
#endif
		default:
			usage();
			break;
		}
	}

#ifdef __FreeBSD__
	/* check if PATH_SPAMD_DB is a regular file */
	if (lstat(PATH_SPAMD_DB, &dbstat) == 0 && !S_ISREG(dbstat.st_mode)) {
		syslog(LOG_ERR, "error %s (Not a regular file)", PATH_SPAMD_DB);
		errx(1, "exit \"%s\" : Not a regular file", PATH_SPAMD_DB);
	}
#endif

	setproctitle("[priv]%s%s",
	    greylist ? " (greylist)" : "",
	    (syncrecv || syncsend) ? " (sync)" : "");

	if (!greylist)
		maxblack = maxcon;
	else if (maxblack > maxcon)
		usage();

	rlp.rlim_cur = rlp.rlim_max = maxcon + 15;
	if (setrlimit(RLIMIT_NOFILE, &rlp) == -1)
		err(1, "setrlimit");

	con = calloc(maxcon, sizeof(*con));
	if (con == NULL)
		err(1, "calloc");

	con->obuf = malloc(8192);

	if (con->obuf == NULL)
		err(1, "malloc");
	con->osize = 8192;

	for (i = 0; i < maxcon; i++)
		con[i].fd = -1;

	signal(SIGPIPE, SIG_IGN);

	s = socket(AF_INET, SOCK_STREAM, 0);
	if (s == -1)
		err(1, "socket");

	if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one,
	    sizeof(one)) == -1)
		return (-1);

	conflisten = socket(AF_INET, SOCK_STREAM, 0);
	if (conflisten == -1)
		err(1, "socket");

	if (setsockopt(conflisten, SOL_SOCKET, SO_REUSEADDR, &one,
	    sizeof(one)) == -1)
		return (-1);

	memset(&sin, 0, sizeof sin);
	sin.sin_len = sizeof(sin);
	if (bind_address) {
		if (inet_pton(AF_INET, bind_address, &sin.sin_addr) != 1)
			err(1, "inet_pton");
	} else
		sin.sin_addr.s_addr = htonl(INADDR_ANY);
	sin.sin_family = AF_INET;
	sin.sin_port = htons(port);

	if (bind(s, (struct sockaddr *)&sin, sizeof sin) == -1)
		err(1, "bind");

	memset(&lin, 0, sizeof sin);
	lin.sin_len = sizeof(sin);
	lin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
	lin.sin_family = AF_INET;
	lin.sin_port = htons(cfg_port);

	if (bind(conflisten, (struct sockaddr *)&lin, sizeof lin) == -1)
		err(1, "bind local");

	if (syncsend || syncrecv) {
		syncfd = sync_init(sync_iface, sync_baddr, sync_port);
		if (syncfd == -1)
			err(1, "sync init");
	}

	if ((pw = getpwnam("_spamd")) == NULL)
		errx(1, "no such user _spamd");

#ifdef __FreeBSD__
	/* open the pid file just before daemon */
	fpid = fopen(pid_file, "w");
	if (fpid == NULL) {
		syslog(LOG_ERR, "error can't create pid file %s (%m)", pid_file);
		err(1, "can't create pid file \"%s\"", pid_file);
	}
#endif

	if (debug == 0) {
		if (daemon(1, 1) == -1)
			err(1, "daemon");
	}

	if (greylist) {
#ifdef __FreeBSD__
		if(use_pf){
#endif
			pfdev = open("/dev/pf", O_RDWR);
			if (pfdev == -1) {
				syslog_r(LOG_ERR, &sdata, "open /dev/pf: %m");
				exit(1);
			}
#ifdef __FreeBSD__
		}
#endif

		maxblack = (maxblack >= maxcon) ? maxcon - 100 : maxblack;
		if (maxblack < 0)
			maxblack = 0;

		/* open pipe to talk to greylister */
		if (pipe(greypipe) == -1) {
			syslog(LOG_ERR, "pipe (%m)");
			exit(1);
		}
		/* open pipe to recieve spamtrap configs */
		if (pipe(trappipe) == -1) {
			syslog(LOG_ERR, "pipe (%m)");
			exit(1);
		}
		jail_pid = fork();
		switch (jail_pid) {
		case -1:
			syslog(LOG_ERR, "fork (%m)");
			exit(1);
		case 0:
			/* child - continue */
			signal(SIGPIPE, SIG_IGN);
			grey = fdopen(greypipe[1], "w");
			if (grey == NULL) {
				syslog(LOG_ERR, "fdopen (%m)");
				_exit(1);
			}
			close(greypipe[0]);
			trapfd = trappipe[0];
			trapcfg = fdopen(trappipe[0], "r");
			if (trapcfg == NULL) {
				syslog(LOG_ERR, "fdopen (%m)");
				_exit(1);
			}
			close(trappipe[1]);
			goto jail;
		}
		/* parent - run greylister */
		grey = fdopen(greypipe[0], "r");
		if (grey == NULL) {
			syslog(LOG_ERR, "fdopen (%m)");
			exit(1);
		}
		close(greypipe[1]);
		trapcfg = fdopen(trappipe[1], "w");
		if (trapcfg == NULL) {
			syslog(LOG_ERR, "fdopen (%m)");
			exit(1);
		}
		close(trappipe[0]);
		return (greywatcher());
		/* NOTREACHED */
	}

jail:
#ifdef __FreeBSD__
	/* after switch user and daemon write and close the pid file */
	if (fpid) {
		fprintf(fpid, "%ld\n", (long) getpid());
		if (fclose(fpid) == EOF) {
			syslog(LOG_ERR, "error can't close pid file %s (%m)", pid_file);
			exit(1);
		}
	}
#endif

	if (chroot("/var/empty") == -1 || chdir("/") == -1) {
		syslog(LOG_ERR, "cannot chdir to /var/empty.");
		exit(1);
	}

	if (pw)
		if (setgroups(1, &pw->pw_gid) ||
		    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
		    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
			err(1, "failed to drop privs");

	if (listen(s, 10) == -1)
		err(1, "listen");

	if (listen(conflisten, 10) == -1)
		err(1, "listen");

	if (debug != 0)
		printf("listening for incoming connections.\n");
	syslog_r(LOG_WARNING, &sdata, "listening for incoming connections.");

	while (1) {
		struct timeval tv, *tvp;
		int max, n;
		int writers;

		max = MAX(s, conflisten);
		if (syncrecv)
			max = MAX(max, syncfd);
		max = MAX(max, conffd);
		max = MAX(max, trapfd);

		time(&t);
		for (i = 0; i < maxcon; i++)
			if (con[i].fd != -1)
				max = MAX(max, con[i].fd);

		if (max > omax) {
			free(fdsr);
			fdsr = NULL;
			free(fdsw);
			fdsw = NULL;
			fdsr = (fd_set *)calloc(howmany(max+1, NFDBITS),
			    sizeof(fd_mask));
			if (fdsr == NULL)
				err(1, "calloc");
			fdsw = (fd_set *)calloc(howmany(max+1, NFDBITS),
			    sizeof(fd_mask));
			if (fdsw == NULL)
				err(1, "calloc");
			omax = max;
		} else {
			memset(fdsr, 0, howmany(max+1, NFDBITS) *
			    sizeof(fd_mask));
			memset(fdsw, 0, howmany(max+1, NFDBITS) *
			    sizeof(fd_mask));
		}

		writers = 0;
		for (i = 0; i < maxcon; i++) {
			if (con[i].fd != -1 && con[i].r) {
				if (con[i].r + MAXTIME <= t) {
					closecon(&con[i]);
					continue;
				}
				FD_SET(con[i].fd, fdsr);
			}
			if (con[i].fd != -1 && con[i].w) {
				if (con[i].w + MAXTIME <= t) {
					closecon(&con[i]);
					continue;
				}
				if (con[i].w <= t)
					FD_SET(con[i].fd, fdsw);
				writers = 1;
			}
		}
		FD_SET(s, fdsr);

		/* only one active config conn at a time */
		if (conffd == -1)
			FD_SET(conflisten, fdsr);
		else
			FD_SET(conffd, fdsr);
		if (trapfd != -1)
			FD_SET(trapfd, fdsr);
		if (syncrecv)
			FD_SET(syncfd, fdsr);

		if (writers == 0) {
			tvp = NULL;
		} else {
			tv.tv_sec = 1;
			tv.tv_usec = 0;
			tvp = &tv;
		}

		n = select(max+1, fdsr, fdsw, NULL, tvp);
		if (n == -1) {
			if (errno != EINTR)
				err(1, "select");
			continue;
		}
		if (n == 0)
			continue;

		for (i = 0; i < maxcon; i++) {
			if (con[i].fd != -1 && FD_ISSET(con[i].fd, fdsr))
				handler(&con[i]);
			if (con[i].fd != -1 && FD_ISSET(con[i].fd, fdsw))
				handlew(&con[i], clients + 5 < maxcon);
		}
		if (FD_ISSET(s, fdsr)) {
			sinlen = sizeof(sin);
			s2 = accept(s, (struct sockaddr *)&sin, &sinlen);
			if (s2 == -1)
				/* accept failed, they may try again */
				continue;
			for (i = 0; i < maxcon; i++)
				if (con[i].fd == -1)
					break;
			if (i == maxcon)
				close(s2);
			else {
				initcon(&con[i], s2, (struct sockaddr *)&sin);
				syslog_r(LOG_INFO, &sdata,
				    "%s: connected (%d/%d)%s%s",
				    con[i].addr, clients, blackcount,
				    ((con[i].lists == NULL) ? "" :
				    ", lists:"),
				    ((con[i].lists == NULL) ? "":
				    con[i].lists));
			}
		}
		if (FD_ISSET(conflisten, fdsr)) {
			sinlen = sizeof(lin);
			conffd = accept(conflisten, (struct sockaddr *)&lin,
			    &sinlen);
			if (conffd == -1)
				/* accept failed, they may try again */
				continue;
			else if (ntohs(lin.sin_port) >= IPPORT_RESERVED) {
				close(conffd);
				conffd = -1;
			}
		}
		if (conffd != -1 && FD_ISSET(conffd, fdsr))
			do_config();
		if (trapfd != -1 && FD_ISSET(trapfd, fdsr))
			read_configline(trapcfg);
		if (syncrecv && FD_ISSET(syncfd, fdsr))
			sync_recv();
	}
	exit(1);
}
int
main(int argc, char **argv)
{
#ifdef __FreeBSD__
	FILE		*fpid = NULL;
	struct		stat dbstat;
	int		rst;
#endif
	int		 ch, i;
	const char 	*errstr;
	struct passwd	*pw;
	pcap_handler	 phandler = logpkt_handler;
	int syncfd = 0;
	struct servent *ent;
	char *sync_iface = NULL;
	char *sync_baddr = NULL;

	if ((ent = getservbyname("spamd-sync", "udp")) == NULL)
		errx(1, "Can't find service \"spamd-sync\" in /etc/services");
	sync_port = ntohs(ent->s_port);

#ifndef __FreeBSD__
	while ((ch = getopt(argc, argv, "DIi:l:W:Y:")) != -1) {
#else
	while ((ch = getopt(argc, argv, "DIi:l:W:Y:m:")) != -1) {
#endif
		switch (ch) {
		case 'D':
			flag_debug = 1;
			break;
		case 'I':
			flag_inbound = 1;
			break;
		case 'i':
			networkif = optarg;
			break;
		case 'l':
			pflogif = optarg;
			break;
		case 'W':
			/* limit whiteexp to 2160 hours (90 days) */
			i = strtonum(optarg, 1, (24 * 90), &errstr);
			if (errstr)
				usage();
			whiteexp = (i * 60 * 60);
			break;
		case 'Y':
			if (sync_addhost(optarg, sync_port) != 0)
				sync_iface = optarg;
			syncsend++;
			break;
#ifdef __FreeBSD__
		case 'm':
			if (strcmp(optarg, "ipfw") == 0)
				use_pf=0;
			break;
#endif

		default:
			usage();
			/* NOTREACHED */
		}
	}

#ifdef __FreeBSD__
	/* check if PATH_SPAMD_DB exist and is a regular file */
	rst = lstat(PATH_SPAMD_DB, &dbstat);
	if (rst == -1 && errno == ENOENT){
		syslog(LOG_ERR, "error %s (%m)", PATH_SPAMD_DB);
		err(1, "%s", PATH_SPAMD_DB);
	}
	if (rst == 0 && !S_ISREG(dbstat.st_mode)) {
		syslog(LOG_ERR, "error %s (Not a regular file)", PATH_SPAMD_DB);
		errx(1, "exit \"%s\" : Not a regular file", PATH_SPAMD_DB);
	}
#endif
	signal(SIGINT , sighandler_close);
	signal(SIGQUIT, sighandler_close);
	signal(SIGTERM, sighandler_close);

	logmsg(LOG_DEBUG, "Listening on %s for %s %s", pflogif,
	    (networkif == NULL) ? "all interfaces." : networkif,
	    (flag_inbound) ? "Inbound direction only." : "");

	if (init_pcap() == -1)
		err(1, "couldn't initialize pcap");

	if (syncsend) {
		syncfd = sync_init(sync_iface, sync_baddr, sync_port);
		if (syncfd == -1)
			err(1, "sync init");
	}

#ifdef __FreeBSD__
	/* open the pid file just before switch the user */
	fpid = fopen(pid_file, "w");
	if (fpid == NULL) {
		syslog(LOG_ERR, "error can't create pid file %s (%m)", pid_file);
		err(1, "can't create pid file \"%s\"", pid_file);
	}
#endif

	/* privdrop */
	pw = getpwnam("_spamd");
	if (pw == NULL)
		errx(1, "User '_spamd' not found! ");

	if (setgroups(1, &pw->pw_gid) ||
	    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
	    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
		err(1, "failed to drop privs");

	if (!flag_debug) {
		if (daemon(0, 0) == -1)
			err(1, "daemon");
		tzset();
		openlog_r("spamlogd", LOG_PID | LOG_NDELAY, LOG_DAEMON, &sdata);
	}

#ifdef __FreeBSD__
	/* after switch user and daemon write and close the pid file */
	if (fpid) {
		fprintf(fpid, "%ld\n", (long) getpid());
		if (fclose(fpid) == EOF) {
			syslog(LOG_ERR, "error can't close pid file %s (%m)", pid_file);
			exit (1);
		}
	}
#endif

	pcap_loop(hpcap, -1, phandler, NULL);

	logmsg(LOG_NOTICE, "exiting");
	if (!flag_debug)
		closelog_r(&sdata);

	exit(0);
}
Exemple #25
0
int kern_init(uint64_t mbmagic, uint64_t mbmem)
{
	extern char edata[], end[];
	memset(edata, 0, end - edata);

	/* percpu variable for CPU0 is preallocated */
	percpu_offsets[0] = __percpu_start;

	cons_init();		// init the console

	const char *message = "(THU.CST) os is loading ...";
	kprintf("%s\n\n", message);
	if(mbmagic == MULTIBOOT_BOOTLOADER_MAGIC){
		kprintf("Multiboot dectected: param %p\n", (void*)mbmem);
		mbmem2e820((Mbdata*)VADDR_DIRECT(mbmem));
		parse_initrd((Mbdata*)VADDR_DIRECT(mbmem));
	}

	print_kerninfo();

	/* get_cpu_var not available before tls_init() */
	hz_init();
	gdt_init(per_cpu_ptr(cpus, 0));
	tls_init(per_cpu_ptr(cpus, 0));
	acpitables_init();
	lapic_init();
	numa_init();

	pmm_init_numa();		// init physical memory management, numa awared
	/* map the lapic */
	lapic_init_late();

	//init the acpi stuff

	idt_init();		// init interrupt descriptor table
	pic_init();		// init interrupt controller

//	acpi_conf_init();


	percpu_init();
	cpus_init();
#ifdef UCONFIG_ENABLE_IPI
	ipi_init();
#endif

	refcache_init();

	vmm_init();		// init virtual memory management
	sched_init();		// init scheduler
	proc_init();		// init process table
	sync_init();		// init sync struct

	/* ext int */
	ioapic_init();
	acpi_init();

	ide_init();		// init ide devices
#ifdef UCONFIG_SWAP
	swap_init();		// init swap
#endif
	fs_init();		// init fs

	clock_init();		// init clock interrupt
	mod_init();

	trap_init();

	//XXX put here?
	bootaps();

	intr_enable();		// enable irq interrupt

#ifdef UCONFIG_HAVE_LINUX_DDE36_BASE
	dde_kit_init();
#endif

	/* do nothing */
	cpu_idle();		// run idle process
}
Exemple #26
0
int main(int argc, char *argv[]) {
	int timestamp = time(NULL);
	if(argc >= 2) {
		if(argv[1][0] == 'r' && argc >= 3) {
			readfromfile = 1;
			timestamp = atoi(argv[2]);
		}
		if(argv[1][0] == 'w')
			writetofile = 1;
		if(argv[1][0] == 'W' || argv[1][1] == 'W')
			writetofile2 = 1;
	}
	initsignals();
	sync_init(ndongles, 16384);
	corr_init(ndongles, 32);

	buffers = malloc(ndongles * sizeof(*buffers));
	files = malloc(ndongles * sizeof(*files));
	files2 = malloc(ndongles * sizeof(*files2));
	for(di=0; di < ndongles; di++) {
		char t[32];
		buffers[di] = malloc(blocksize * sizeof(**buffers));
		if(readfromfile || writetofile) {
			sprintf(t, "d%02d_%d", di, timestamp);
			if((files[di] = fopen(t, readfromfile ? "rb" : "wb")) == NULL) {
				fprintf(stderr, "Could not open file\n");
				goto fail;
			}
		}
		if(writetofile2) {
			sprintf(t, "c%02d_%d", di, timestamp);
			if((files2[di] = fopen(t, "wb")) == NULL) {
				fprintf(stderr, "Could not open file2\n");
				goto fail;
			}
		}
	}
	if(readfromfile) {
		for(;;) {
			for(di = 0; di < ndongles; di++) {
				if(fread(buffers[di], blocksize, 1, files[di]) == 0)
					goto fail;
			}
			dodsp(blocksize, (void**)buffers);
		}
	} else {
		int donglesok = coherent_init(ndongles, 2400000, 434e6, 300);

		if(donglesok == ndongles) {
			while(do_exit == 0) {
				if(coherent_read(blocksize, buffers) == -1) break;
				dodsp(blocksize, (void**)buffers);
				if(writetofile) {
					for(di = 0; di < ndongles; di++) {
						fwrite(buffers[di], blocksize, 1, files[di]);
					}
				}
			}
		}

		coherent_exit();
	}
	fail:
	sync_exit();
	return 0;
}
Exemple #27
0
int main(int argc, char **argv) {
  int N_id_2, ns, find_ns;
  cf_t *buffer, *fft_buffer;
  cf_t pss_signal[PSS_LEN];
  float sss_signal0[SSS_LEN]; // for subframe 0
  float sss_signal5[SSS_LEN]; // for subframe 5
  int cid, max_cid; 
  uint32_t find_idx;
  sync_t sync;
  lte_fft_t ifft;

  parse_args(argc, argv);

  buffer = malloc(sizeof(cf_t) * FLEN);
  if (!buffer) {
    perror("malloc");
    exit(-1);
  }

  fft_buffer = malloc(sizeof(cf_t) * 2 * FLEN);
  if (!fft_buffer) {
    perror("malloc");
    exit(-1);
  }

  if (lte_ifft_init(&ifft, cp, 6)) {
    fprintf(stderr, "Error creating iFFT object\n");
    exit(-1);
  }

  if (sync_init(&sync, FLEN, 128, 128)) {
    fprintf(stderr, "Error initiating PSS/SSS\n");
    return -1;
  }

  sync_set_threshold(&sync, 1, 1);

  if (cell_id == -1) {
    cid = 0;
    max_cid = 49;
  } else {
    cid = cell_id;
    max_cid = cell_id;
}
  while(cid <= max_cid) {
    N_id_2 = cid%3;

    /* Generate PSS/SSS signals */
    pss_generate(pss_signal, N_id_2);
    sss_generate(sss_signal0, sss_signal5, cid);

    for (ns=0;ns<2;ns++) {
      memset(buffer, 0, sizeof(cf_t) * FLEN);
      pss_put_slot(pss_signal, buffer, 6, cp);
      sss_put_slot(ns?sss_signal5:sss_signal0, buffer, 6, cp);

      /* Transform to OFDM symbols */
      memset(fft_buffer, 0, sizeof(cf_t) * 2 * FLEN);
      lte_ifft_run_slot(&ifft, buffer, &fft_buffer[offset]);

      sync_find(&sync, fft_buffer, &find_idx);
      find_ns = sync_get_slot_id(&sync);
      printf("cell_id: %d find: %d, offset: %d, ns=%d find_ns=%d\n", cid, find_idx, offset,
          ns, find_ns);
      if (find_idx != offset + 960) {
        printf("offset != find_offset: %d != %d\n", find_idx, offset + 960);
        exit(-1);
      }
      if (ns*10 != find_ns) {
        printf("ns != find_ns\n", 10 * ns, find_ns);
        exit(-1);
      }
      if (sync_get_cp(&sync) != cp) {
        printf("Detected CP should be %s\n", CP_ISNORM(cp)?"Normal":"Extended");
        exit(-1);
      }
    }
    cid++;
  }

  free(fft_buffer);
  free(buffer);

  sync_free(&sync);
  lte_ifft_free(&ifft);

  printf("Ok\n");
  exit(0);
}
Exemple #28
0
int
main(int argc, char *argv[])
{
	int ch, cftest = 0, daemonize = 1, rdomain = -1, udpsockmode = 0;
	char *sync_iface = NULL;
	char *sync_baddr = NULL;
	u_short sync_port = 0;
	struct servent *ent;
	struct in_addr udpaddr;

	/* Initially, log errors to stderr as well as to syslogd. */

	progname = argv[0]; /* XXX: yeah, ugly. */
	opterr = 0;
	while ((ch = getopt(argc, argv, "A:C:L:c:dfl:nu::Y:y:")) != -1)
		switch (ch) {
		case 'Y':
			syncsend = 1;
			break;
		case 'y':
			syncrecv = 1;
			break;
		}
	if (syncsend || syncrecv) {
		if ((ent = getservbyname("dhcpd-sync", "udp")) == NULL)
			errx(1, "Can't find service \"dhcpd-sync\" in "
			    "/etc/services");
		sync_port = ntohs(ent->s_port);
	}
	udpaddr.s_addr = htonl(INADDR_BROADCAST);

	optreset = optind = opterr = 1;
	while ((ch = getopt(argc, argv, "A:C:L:c:dfl:nu::Y:y:")) != -1)
		switch (ch) {
		case 'A':
			abandoned_tab = optarg;
			break;
		case 'C':
			changedmac_tab = optarg;
			break;
		case 'L':
			leased_tab = optarg;
			break;
		case 'c':
			path_dhcpd_conf = optarg;
			break;
		case 'd':
			daemonize = 0;
			log_perror = 1;
			break;
		case 'f':
			daemonize = 0;
			break;
		case 'l':
			path_dhcpd_db = optarg;
			break;
		case 'n':
			daemonize = 0;
			cftest = 1;
			log_perror = 1;
			break;
		case 'u':
			udpsockmode = 1;
			if (optarg != NULL) {
				if (inet_aton(optarg, &udpaddr) != 1)
					errx(1, "Cannot parse binding IP "
					    "address: %s", optarg);
			}
			break;
		case 'Y':
			if (sync_addhost(optarg, sync_port) != 0)
				sync_iface = optarg;
			syncsend = 1;
			break;
		case 'y':
			sync_baddr = optarg;
			syncrecv = 1;
			break;
		default:
			usage();
		}

	argc -= optind;
	argv += optind;

	while (argc > 0) {
		struct interface_info *tmp = calloc(1, sizeof(*tmp));
		if (!tmp)
			error("calloc");
		(void)strlcpy(tmp->name, argv[0], sizeof(tmp->name));
		tmp->next = interfaces;
		interfaces = tmp;
		argc--;
		argv++;
	}

	/* Default DHCP/BOOTP ports. */
	server_port = htons(SERVER_PORT);
	client_port = htons(CLIENT_PORT);

	tzset();

	(void)time(&cur_time);
	if (!readconf())
		error("Configuration file errors encountered");

	if (cftest)
		exit(0);

	db_startup();
	if (!udpsockmode || argc > 0)
		discover_interfaces(&rdomain);
	if (rdomain != -1) {
		if (setfib(rdomain) == -1)
			error("setfib (%m)");
	}
	if (udpsockmode)
		udpsock_startup(udpaddr);
	icmp_startup(1, lease_pinged);

	if (syncsend || syncrecv) {
		syncfd = sync_init(sync_iface, sync_baddr, sync_port);
		if (syncfd == -1)
			err(1, "sync init");
	}

	if ((pw = getpwnam("_dhcp")) == NULL)
		error("user \"_dhcp\" not found");

	if (daemonize)
		(void)daemon(0, 0);

	/* don't go near /dev/pf unless we actually intend to use it */
	if ((abandoned_tab != NULL) ||
	    (changedmac_tab != NULL) ||
	    (leased_tab != NULL)) {
		if (pipe(pfpipe) == -1)
			error("pipe (%m)");
		switch (pfproc_pid = fork()) {
		case -1:
			error("fork (%m)");
			/* NOTREACHED */
			exit(1);
		case 0:
			/* child process. start up table engine */
			(void)close(pfpipe[1]);
			pftable_handler();
			/* NOTREACHED */
			exit(1);
		default:
			(void)close(pfpipe[0]);
			gotpipe = 1;
			break;
		}
	}

	if (chroot("/var/empty") == -1)
		error("chroot %s: %m", "/var/empty");

	if (chdir("/") == -1)
		error("chdir(\"/\"): %m");
	if (setgroups(1, &pw->pw_gid) ||
	    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
	    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
		error("can't drop privileges: %m");

	add_timeout(cur_time + 5, periodic_scan, NULL);
	dispatch();

	/* not reached */
	exit(0);
}
int
main(int argc, char **argv)
{
	int		 ch;
	struct passwd	*pw;
	pcap_handler	 phandler = logpkt_handler;
	int syncfd = 0;
	struct servent *ent;
	char *sync_iface = NULL;
	char *sync_baddr = NULL;

	if ((ent = getservbyname("spamd-sync", "udp")) == NULL)
		errx(1, "Can't find service \"spamd-sync\" in /etc/services");
	sync_port = ntohs(ent->s_port);

	while ((ch = getopt(argc, argv, "DIi:l:Y:")) != -1) {
		switch (ch) {
		case 'D':
			flag_debug = 1;
			break;
		case 'I':
			flag_inbound = 1;
			break;
		case 'i':
			networkif = optarg;
			break;
		case 'l':
			pflogif = optarg;
			break;
		case 'Y':
			if (sync_addhost(optarg, sync_port) != 0)
				sync_iface = optarg;
			syncsend++;
			break;
		default:
			usage();
			/* NOTREACHED */
		}
	}

	signal(SIGINT , sighandler_close);
	signal(SIGQUIT, sighandler_close);
	signal(SIGTERM, sighandler_close);

	logmsg(LOG_DEBUG, "Listening on %s for %s %s", pflogif,
	    (networkif == NULL) ? "all interfaces." : networkif,
	    (flag_inbound) ? "Inbound direction only." : "");

	if (init_pcap() == -1)
		err(1, "couldn't initialize pcap");

	if (syncsend) {
		syncfd = sync_init(sync_iface, sync_baddr, sync_port);
		if (syncfd == -1)
			err(1, "sync init");
	}

	/* privdrop */
	pw = getpwnam("_spamd");
	if (pw == NULL)
		errx(1, "User '_spamd' not found! ");

	if (setgroups(1, &pw->pw_gid) ||
	    setresgid(pw->pw_gid, pw->pw_gid, pw->pw_gid) ||
	    setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid))
		err(1, "failed to drop privs");

	if (!flag_debug) {
		if (daemon(0, 0) == -1)
			err(1, "daemon");
		tzset();
		openlog_r("spamlogd", LOG_PID | LOG_NDELAY, LOG_DAEMON, &sdata);
	}

	pcap_loop(hpcap, -1, phandler, NULL);

	logmsg(LOG_NOTICE, "exiting");
	if (!flag_debug)
		closelog_r(&sdata);

	exit(0);
}
Exemple #30
0
int main(int argc, char **argv) {
  int frame_cnt, valid_frames;
  int freq;
  int cell_id;
  sync_t sfind, strack;
  float max_peak_to_avg;
  float sfo;
  int find_idx, track_idx, last_found;
  enum sync_state state;
  int n;
  filesink_t fs;

  if (argc < 3) {
    usage(argv[0]);
    exit(-1);
  }

  parse_args(argc,argv);

  if (base_init(FLEN)) {
    fprintf(stderr, "Error initializing memory\n");
    exit(-1);
  }

  if (sync_init(&sfind, FLEN)) {
    fprintf(stderr, "Error initiating PSS/SSS\n");
    exit(-1);
  }
  sync_pss_det_peak_to_avg(&sfind);

  if (sync_init(&strack, track_len)) {
    fprintf(stderr, "Error initiating PSS/SSS\n");
    exit(-1);
  }
  sync_pss_det_peak_to_avg(&strack);

  nof_bands = lte_band_get_fd_band(band, channels, earfcn_start, earfcn_end, MAX_EARFCN);
  printf("RSSI scan: %d freqs in band %d, RSSI threshold %.2f dBm\n", nof_bands, band, rssi_threshold);

  n = rssi_scan();
  if (n == -1) {
    exit(-1);
  }

  printf("\nDone. Starting PSS search on %d channels\n", n);
  usleep(500000);
  INFO("Setting sampling frequency %.2f MHz\n", (float) SAMP_FREQ/MHZ);
  cuhd_set_rx_srate(uhd, SAMP_FREQ);

  cuhd_set_rx_gain(uhd, uhd_gain);

  print_to_matlab();

  filesink_init(&fs, "test.dat", COMPLEX_FLOAT_BIN);

  freq=0;
  state = INIT;
  find_idx = 0;
  max_peak_to_avg = 0;
  last_found = 0;
  frame_cnt = 0;
  while(freq<nof_bands) {
    /* scan only bands above rssi_threshold */
    if (!IS_SIGNAL(freq)) {
      INFO("[%3d/%d]: Skipping EARFCN %d %.2f MHz RSSI %.2f dB\n", freq, nof_bands,
                channels[freq].id, channels[freq].fd,10*log10f(rssi[freq]) + 30);
      freq++;
    } else {
      if (state == TRACK || state == FIND) {
        cuhd_recv(uhd, &input_buffer[FLEN], FLEN, 1);
      }
      switch(state) {
      case INIT:
        DEBUG("Stopping receiver...\n",0);
        cuhd_stop_rx_stream(uhd);

        /* set freq */
        cuhd_set_rx_freq(uhd, (double) channels[freq].fd * MHZ);
        cuhd_rx_wait_lo_locked(uhd);
        DEBUG("Set freq to %.3f MHz\n", (double) channels[freq].fd);

        DEBUG("Starting receiver...\n",0);
        cuhd_start_rx_stream(uhd);

        /* init variables */
        frame_cnt = 0;
        max_peak_to_avg = -99;
        cell_id = -1;

        /* receive first frame */
        cuhd_recv(uhd, input_buffer, FLEN, 1);

        /* set find_threshold and go to FIND state */
        sync_set_threshold(&sfind, find_threshold);
        sync_force_N_id_2(&sfind, -1);
        state = FIND;
        break;
      case FIND:
        /* find peak in all frame */
        find_idx = sync_run(&sfind, &input_buffer[FLEN]);
        DEBUG("[%3d/%d]: PAR=%.2f\n", freq, nof_bands, sync_get_peak_to_avg(&sfind));
        if (find_idx != -1) {
          /* if found peak, go to track and set lower threshold */
          frame_cnt = -1;
          last_found = 0;
          sync_set_threshold(&strack, track_threshold);
          sync_force_N_id_2(&strack, sync_get_N_id_2(&sfind));
          state = TRACK;
          INFO("[%3d/%d]: EARFCN %d Freq. %.2f MHz PSS found PAR %.2f dB\n", freq, nof_bands,
                        channels[freq].id, channels[freq].fd,
                        10*log10f(sync_get_peak_to_avg(&sfind)));
        } else {
          if (frame_cnt >= nof_frames_find) {
            state = INIT;
            printf("[%3d/%d]: EARFCN %d Freq. %.2f MHz No PSS found\r", freq, nof_bands,
                          channels[freq].id, channels[freq].fd, frame_cnt - last_found);
            if (VERBOSE_ISINFO()) {
              printf("\n");
            }
            freq++;
          }
        }
        break;
      case TRACK:
        INFO("Tracking PSS find_idx %d offset %d\n", find_idx, find_idx + track_len);

        filesink_write(&fs, &input_buffer[FLEN+find_idx+track_len], track_len);

        track_idx = sync_run(&strack, &input_buffer[FLEN + find_idx - track_len]);
        p2a_v[frame_cnt] = sync_get_peak_to_avg(&strack);

        /* save cell id for the best peak-to-avg */
        if (p2a_v[frame_cnt] > max_peak_to_avg) {
          max_peak_to_avg = p2a_v[frame_cnt];
          cell_id = sync_get_cell_id(&strack);
        }
        if (track_idx != -1) {
          cfo_v[frame_cnt] = sync_get_cfo(&strack);
          last_found = frame_cnt;
          find_idx += track_idx - track_len;
          idx_v[frame_cnt] = find_idx;
        } else {
          idx_v[frame_cnt] = -1;
          cfo_v[frame_cnt] = 0.0;
        }
        /* if we missed to many PSS it is not a cell, next freq */
        if (frame_cnt - last_found > max_track_lost) {
          INFO("\n[%3d/%d]: EARFCN %d Freq. %.2f MHz %d frames lost\n", freq, nof_bands,
              channels[freq].id, channels[freq].fd, frame_cnt - last_found);

          state = INIT;
          freq++;
        } else if (frame_cnt >= nof_frames_track) {
          state = DONE;
        }
        break;
      case DONE:

        cfo[freq] = mean_valid(idx_v, cfo_v, frame_cnt);
        p2a[freq] = mean_valid(idx_v, p2a_v, frame_cnt);
        valid_frames = preprocess_idx(idx_v, idx_valid, t, frame_cnt);
        sfo = sfo_estimate_period(idx_valid, t, valid_frames, FLEN_PERIOD);

        printf("\n[%3d/%d]: FOUND EARFCN %d Freq. %.2f MHz. "
            "PAR %2.2f dB, CFO=%+.2f KHz, SFO=%+2.3f KHz, CELL_ID=%3d\n", freq, nof_bands,
                channels[freq].id, channels[freq].fd,
                10*log10f(p2a[freq]), cfo[freq] * 15, sfo / 1000, cell_id);
        state = INIT;
        freq++;
        break;
      }
      if (state == TRACK || (state == FIND && frame_cnt)) {
        memcpy(input_buffer, &input_buffer[FLEN], FLEN * sizeof(cf_t));
      }
      frame_cnt++;
    }
  }

  print_to_matlab();

  sync_free(&sfind);
  base_free();

  printf("\n\nDone\n");
  exit(0);
}