Example #1
0
bool node_write_devclass(meshlink_handle_t *mesh, node_t *n) {

	if(n->devclass < 0 || n->devclass > _DEV_CLASS_MAX)
		return false;

	bool result = false;

	splay_tree_t *config_tree;
	init_configuration(&config_tree);

	// ignore read errors; in case the file does not exist we will create it
	read_host_config(mesh, config_tree, n->name);

	config_t* cnf = lookup_config(config_tree, "DeviceClass");

	if(!cnf)
	{
		cnf = new_config();
		cnf->variable = xstrdup("DeviceClass");
		config_add(config_tree, cnf);
	}

	set_config_int(cnf, n->devclass);

	if(!write_host_config(mesh, config_tree, n->name))
		goto fail;

	result = true;

fail:
	exit_configuration(&config_tree);
	return result;
}
Example #2
0
int main(int argc, char *argv[])
{
    test();
    init_configuration(argc, argv);

    return 0;
}
Example #3
0
static int lua_likwid_getConfiguration(lua_State* L)
{
    int ret = 0;
    if (config_isInitialized == 0)
    {
        ret = init_configuration();
        if (ret == 0)
        {
            config_isInitialized = 1;
            configfile = get_configuration();
        }
        else
        {
            lua_newtable(L);
            lua_pushstring(L, "configFile");
            lua_pushnil(L);
            lua_settable(L,-3);
            lua_pushstring(L, "topologyFile");
            lua_pushnil(L);
            lua_settable(L,-3);
            lua_pushstring(L, "daemonPath");
            lua_pushnil(L);
            lua_settable(L,-3);
            lua_pushstring(L, "daemonMode");
            lua_pushinteger(L, -1);
            lua_settable(L,-3);
            lua_pushstring(L, "maxNumThreads");
            lua_pushinteger(L, MAX_NUM_THREADS);
            lua_settable(L,-3);
            lua_pushstring(L, "maxNumNodes");
            lua_pushinteger(L, MAX_NUM_NODES);
            lua_settable(L,-3);
            return 1;
        }
    }
    if ((config_isInitialized) && (configfile == NULL))
    {
        configfile = get_configuration();
    }
    lua_newtable(L);
    lua_pushstring(L, "configFile");
    lua_pushstring(L, configfile->configFileName);
    lua_settable(L,-3);
    lua_pushstring(L, "topologyFile");
    lua_pushstring(L, configfile->topologyCfgFileName);
    lua_settable(L,-3);
    lua_pushstring(L, "daemonPath");
    lua_pushstring(L, configfile->daemonPath);
    lua_settable(L,-3);
    lua_pushstring(L, "daemonMode");
    lua_pushinteger(L, (int)configfile->daemonMode);
    lua_settable(L,-3);
    lua_pushstring(L, "maxNumThreads");
    lua_pushinteger(L, configfile->maxNumThreads);
    lua_settable(L,-3);
    lua_pushstring(L, "maxNumNodes");
    lua_pushinteger(L, configfile->maxNumNodes);
    lua_settable(L,-3);
    return 1;
}
Example #4
0
File: numa.c Project: hoangt/likwid
int numa_init(void)
{
    const struct numa_functions funcs = numa_funcs;
    int ret = 0;
    if (init_config == 0)
    {
        init_configuration();
    }
    if (numaInitialized == 1)
    {
        return 0;
    }

    if ((config.topologyCfgFileName == NULL)||(access(config.topologyCfgFileName, R_OK) && numa_info.numberOfNodes <= 0))
    {
        cpu_set_t cpuSet;
        CPU_ZERO(&cpuSet);
        sched_getaffinity(0,sizeof(cpu_set_t), &cpuSet);
        if (cpuid_topology.activeHWThreads < cpuid_topology.numHWThreads)
        {
            ret = proc_numa_init();
        }
        else
        {
            ret = funcs.numa_init();
        }
    }
    numaInitialized = 1;
    return ret;
}
void init()
{
	ResetReason = MCUSR;	
		
 	cli();
    WDT_off();		// Turn off until initialization is done and we can pet the dog.    
    
	init_leds ();
	init_buttons();	
	init_limit_switches();
	init_motor();
	
	float mBaseFrequencyHerz = 500.0;  // 4khz
	pwm_init( mBaseFrequencyHerz, TRUE  );

	init_serial();	
	init_configuration();
//	read_configuration_and_set();
//	init_adc();				
//	start_sampling();	
	
	encoder_init();
//	pot_init   ();
			
	
	WDT_Prescaler_Change();
	
	//delay(100000);					// ~ 2 sec
	//read_cal();					// Read everything including motor stops.
	sei();

	//OS_InitTask();
}
Example #6
0
API_EXPORTED
struct eegdev* egd_open(const char* confstring)
{
	struct conf cf;
	struct eegdev* dev = NULL;
	const char* device;

	// Load global configuration
	if (init_configuration(&cf, confstring)
	 || load_configuration_file(&cf, "eegdev.conf", 1)) {
	 	free_configuration(&cf);
		return NULL;
	}

	// Get device type
	device = get_conf_setting(&cf, "device", "any");
	
	if (!strcmp(device, "any"))
		dev = open_any(&cf);
	else
		dev = open_plugin_device(device, &cf);

	free_configuration(&cf);
	return dev;
}
Example #7
0
/*
  Read Subnets from all host config files
*/
void load_all_subnets(void) {
    DIR *dir;
    struct dirent *ent;
    char *dname;
    char *fname;
    avl_tree_t *config_tree;
    config_t *cfg;
    subnet_t *s, *s2;
    node_t *n;
    bool result;

    xasprintf(&dname, "%s/hosts", confbase);
    dir = opendir(dname);
    if(!dir) {
        logger(LOG_ERR, "Could not open %s: %s", dname, strerror(errno));
        free(dname);
        return;
    }

    while((ent = readdir(dir))) {
        if(!check_id(ent->d_name))
            continue;

        n = lookup_node(ent->d_name);
#ifdef _DIRENT_HAVE_D_TYPE
        //if(ent->d_type != DT_REG)
        //	continue;
#endif

        xasprintf(&fname, "%s/hosts/%s", confbase, ent->d_name);
        init_configuration(&config_tree);
        result = read_config_file(config_tree, fname);
        free(fname);
        if(!result)
            continue;

        if(!n) {
            n = new_node();
            n->name = xstrdup(ent->d_name);
            node_add(n);
        }

        for(cfg = lookup_config(config_tree, "Subnet"); cfg; cfg = lookup_config_next(config_tree, cfg)) {
            if(!get_config_subnet(cfg, &s))
                continue;

            if((s2 = lookup_subnet(n, s))) {
                s2->expires = -1;
            } else {
                subnet_add(n, s);
            }
        }

        exit_configuration(&config_tree);
    }

    closedir(dir);
}
Example #8
0
void plugin_init(GeanyData *data)
{
    init_configuration();

    main_menu_item = gtk_menu_item_new_with_mnemonic(_("Check for Updates"));
    gtk_widget_show(main_menu_item);
    gtk_container_add(GTK_CONTAINER(geany->main_widgets->tools_menu),
        main_menu_item);
    g_signal_connect(main_menu_item, "activate",
        G_CALLBACK(manual_check_activated_cb), NULL);
}
Example #9
0
int test_initconfig()
{
    int ret;
    ret = init_configuration();
    if (ret != 0)
        goto fail;
    Configuration_t config = get_configuration();
    if (config == NULL)
        goto fail;
    if ((config->daemonMode != ACCESSMODE_DIRECT) && (config->daemonMode != ACCESSMODE_DAEMON))
        goto fail;
    if ((config->daemonMode == ACCESSMODE_DAEMON) && (config->daemonPath == NULL))
        goto fail;
    destroy_configuration();
    return 1;
fail:
    destroy_configuration();
    return 0;
}
Example #10
0
/*---------------------------------------------------------------------------*
 * NAME: main
 * DESC: Main Entry Point
 *---------------------------------------------------------------------------*/
int main(int argc, char **argv) {

  config *conf;
  unsigned int first_arg;

  /* create the configuration structure */
  conf = malloc_(sizeof(config));

  /* init the configuration structure */
  init_configuration(conf);

  /* parse the arguments */
  first_arg = parsing_args(argc, argv, conf);
  conf->xml_filename = argv[first_arg];

  /* copy the name of the .ad file */
  conf->output_name = argv[first_arg+1];

  /* basic check */
  if ((conf->output_name == NULL) || (conf->xml_filename == NULL)) {
    usage(argv, conf);
  }

  /* open the output_name file */
  output_desc = fopen(conf->output_name, "w");
  if (!output_desc) {
    error_("cannot write the file: \"%s\": ", conf->output_name);
    perror("");
    error_("QUITTING!\n");
    free(conf);
    exit(-1);
  }
  

  /* xml parsing of the file */
  xml_parsing(conf);

  /* free the configuration structure */
  free(conf);
  
  return 0;
}
/* Answering these questions right is tricky... */
static bool getconf_bool_node_offline(const char *nodename, char *optname) {
	char *fname;
	avl_tree_t *t;
	bool x;

	init_configuration(&t);

	xasprintf(&fname, "%s/hosts/%s", confbase, nodename);

	read_config_options(t, nodename);
	x = read_config_file(t, fname);
	if (!x) goto _end;

	if (!get_config_bool(lookup_config(t, optname), &x)) x = false;

_end:	exit_configuration(&t);
	free(fname);

	return x;
}
Example #12
0
void setup_outgoing_connection(outgoing_t *outgoing) {
	connection_t *c;
	node_t *n;

	outgoing->event = NULL;

	n = lookup_node(outgoing->name);

	if(n)
		if(n->connection) {
			ifdebug(CONNECTIONS) logger(LOG_INFO, "Already connected to %s", outgoing->name);

			n->connection->outgoing = outgoing;
			return;
		}

	c = new_connection();
	c->name = xstrdup(outgoing->name);
	c->outcipher = myself->connection->outcipher;
	c->outdigest = myself->connection->outdigest;
	c->outmaclength = myself->connection->outmaclength;
	c->outcompression = myself->connection->outcompression;

	init_configuration(&c->config_tree);
	read_connection_config(c);

	outgoing->cfg = lookup_config(c->config_tree, "Address");

	if(!outgoing->cfg) {
		logger(LOG_ERR, "No address specified for %s", c->name);
		free_connection(c);
		return;
	}

	c->outgoing = outgoing;
	c->last_ping_time = now;

	connection_add(c);

	do_outgoing_connection(c);
}
Example #13
0
bool node_read_ecdsa_public_key(meshlink_handle_t *mesh, node_t *n) {
	if(ecdsa_active(n->ecdsa))
		return true;

	splay_tree_t *config_tree;
	char *p;

	init_configuration(&config_tree);
	if(!read_host_config(mesh, config_tree, n->name))
		goto exit;

	/* First, check for simple ECDSAPublicKey statement */

	if(get_config_string(lookup_config(config_tree, "ECDSAPublicKey"), &p)) {
		n->ecdsa = ecdsa_set_base64_public_key(p);
		free(p);
	}

exit:
	exit_configuration(&config_tree);
	return n->ecdsa;
}
Example #14
0
bool node_read_devclass(meshlink_handle_t *mesh, node_t *n) {
	
	splay_tree_t *config_tree;
	char *p;

	init_configuration(&config_tree);
	if(!read_host_config(mesh, config_tree, n->name))
		goto exit;

	if(get_config_string(lookup_config(config_tree, "DeviceClass"), &p))
	{
		n->devclass = atoi(p);
		free(p);
	}

	if(n->devclass < 0 || n->devclass > _DEV_CLASS_MAX)
		{ n->devclass = _DEV_CLASS_MAX; }

exit:
	exit_configuration(&config_tree);
	return n->devclass != 0;
}
Example #15
0
bool read_ecdsa_public_key(meshlink_handle_t *mesh, connection_t *c) {
	if(ecdsa_active(c->ecdsa))
		return true;

	char *p;

	if(!c->config_tree) {
		init_configuration(&c->config_tree);
		if(!read_host_config(mesh, c->config_tree, c->name))
			return false;
	}

	/* First, check for simple ECDSAPublicKey statement */

	if(get_config_string(lookup_config(c->config_tree, "ECDSAPublicKey"), &p)) {
		c->ecdsa = ecdsa_set_base64_public_key(p);
		free(p);
		return c->ecdsa;
	}

	return false;
}
Example #16
0
int numa_init(void)
{
    const struct numa_functions funcs = numa_funcs;
    int ret = 0;
    if (init_config == 0)
    {
        init_configuration();
    }
    if (numaInitialized == 1)
    {
        return 0;
    }

    if ((config.topologyCfgFileName != NULL) && (!access(config.topologyCfgFileName, R_OK)) && (numa_info.nodes != NULL))
    {
        /* If we read in the topology file, the NUMA related stuff is already initialized */
        numaInitialized = 1;
        return 0;
    }
    else
    {
        cpu_set_t cpuSet;
        CPU_ZERO(&cpuSet);
        sched_getaffinity(0,sizeof(cpu_set_t), &cpuSet);
        if (cpuid_topology.activeHWThreads < cpuid_topology.numHWThreads)
        {
            ret = proc_numa_init();
        }
        else
        {
            ret = funcs.numa_init();
        }
        if (ret == 0)
            numaInitialized = 1;
    }
    return ret;
}
Example #17
0
int enable_configuration()
{
    init_configuration();
    return 1;
}
/* Well, almost clean copy of read_rsa_public_key */
static bool read_rsa_public_key_offline(const char *nodename, RSA **outkey) {
	avl_tree_t *t;
	FILE *fp;
	char *tname, *fname;
	char *key;
	bool x;
	RSA *rsa_key = NULL;

	init_configuration(&t);
	xasprintf(&tname, "%s/hosts/%s", confbase, nodename);
	x = read_config_file(t, tname);
	if (!x) goto _fail;

	if(!rsa_key) {
		rsa_key = RSA_new();
//		RSA_blinding_on(c->rsa_key, NULL);
	}

	/* First, check for simple PublicKey statement */

	if(get_config_string(lookup_config(t, "PublicKey"), &key)) {
		BN_hex2bn(&rsa_key->n, key);
		BN_hex2bn(&rsa_key->e, "FFFF");
		free(key);
		*outkey = rsa_key;
		goto _done;
	}

	/* Else, check for PublicKeyFile statement and read it */

	if(get_config_string(lookup_config(t, "PublicKeyFile"), &fname)) {
		fp = fopen(fname, "r");

		if(!fp) {
			logger(LOG_ERR, "Error reading RSA public key file `%s': %s",
				   fname, strerror(errno));
			free(fname);
			goto _fail;
		}

		free(fname);
		rsa_key = PEM_read_RSAPublicKey(fp, &rsa_key, NULL, NULL);
		fclose(fp);

		if(rsa_key) {
			*outkey = rsa_key;
			goto _done;		/* Woohoo. */
		}

		/* If it fails, try PEM_read_RSA_PUBKEY. */
		fp = fopen(fname, "r");

		if(!fp) {
			logger(LOG_ERR, "Error reading RSA public key file `%s': %s",
				   fname, strerror(errno));
			free(fname);
			goto _fail;
		}

		free(fname);
		rsa_key = PEM_read_RSA_PUBKEY(fp, &rsa_key, NULL, NULL);
		fclose(fp);

		if(rsa_key) {
//				RSA_blinding_on(c->rsa_key, NULL);
			*outkey = rsa_key;
			goto _done;
		}

		logger(LOG_ERR, "Reading RSA public key file `%s' failed: %s",
			   fname, strerror(errno));
		goto _fail;
	}

	/* Else, check if a harnessed public key is in the config file */

	xasprintf(&fname, "%s/hosts/%s", confbase, nodename);
	fp = fopen(fname, "r");

	if(fp) {
		rsa_key = PEM_read_RSAPublicKey(fp, &rsa_key, NULL, NULL);
		fclose(fp);
	}

	free(fname);

	if(rsa_key) {
		*outkey = rsa_key;
		goto _done;
	}

	/* Try again with PEM_read_RSA_PUBKEY. */

	xasprintf(&fname, "%s/hosts/%s", confbase, nodename);
	fp = fopen(fname, "r");

	if(fp) {
		rsa_key = PEM_read_RSA_PUBKEY(fp, &rsa_key, NULL, NULL);
//		RSA_blinding_on(c->rsa_key, NULL);
		fclose(fp);
	}

	free(fname);

	if(rsa_key) {
		*outkey = rsa_key;
		goto _done;
	}

	logger(LOG_ERR, "No public key for %s specified!", nodename);

_fail:	
	exit_configuration(&t);
	free(tname);
	return false;

_done:	
	exit_configuration(&t);
	free(tname);
	return true;
}
/******************************************************************************
 * Main of the parallel sampling sort
 ******************************************************************************/
int main(int argc, char **argv){
    int mpi_size, mpi_rank;
    double t0, t1;
    int is_help;
    char *final_buff;
    unsigned long long rsize;

    MPI_Comm comm = MPI_COMM_WORLD;
    MPI_Init(&argc, &argv);
    MPI_Comm_size(comm, &mpi_size);
    MPI_Comm_rank(comm, &mpi_rank);

    t0 = MPI_Wtime();

    config_t *config = (config_t *)malloc(sizeof(config_t));
    config_t *config_init = (config_t *)malloc(sizeof(config_t));
    init_configuration(config);
    init_configuration(config_init);

    is_help = get_configuration(argc, argv, mpi_rank, config_init);

    // when -h flag is set to seek help of how to use this program
    if (is_help) {
        free_configuration(config);
        free_configuration(config_init);
        MPI_Finalize();
        return 1;
    }

    copy_configuration(config, config_init);

    int ntf, mtf, tstep, nsteps_tot;
    mtf = config->tmin / config->tinterval;
    ntf = config->tmax / config->tinterval + 1;
    if (config->nsteps == 1) {
        nsteps_tot = ntf;
    } else {
        nsteps_tot = config->tmax;
    }

    // Get the particle tags from sorted-by-energy data of the last time frame,
    // and then sort the tags
    int *tags, qindex;
    int row_size, dataset_num, max_type_size, key_value_type;
    char *tracked_particles, *tracked_particles_sum, *package_data;
    dset_name_item *dname_array;
    hsize_t my_data_size, rest_size;
    if (config->tracking_traj) {
        tags = (int *)malloc(config->nptl_traj * sizeof(int));
        char filename_ene[MAX_FILENAME_LEN];
        tstep = (ntf - 1) * config->tinterval;
        snprintf(filename_ene, MAX_FILENAME_LEN, "%s%s%d%s%s%s",
                config->filepath, "/T.", tstep, "/", config->species,
                "_tracer_energy_sorted.h5p");
        if (config->nsteps != 1) tstep--;
        // get particle tags w.r.t some energy
        get_particle_tags(filename_ene, tstep, config->ratio_emax,
                config->nptl_traj, tags);

        // sort the tags
        qsort(tags, config->nptl_traj, sizeof(int), CompareInt32Value);

        // get the indices for Ux and q in the HDF5 file
        snprintf(config->group_name, MAX_FILENAME_LEN, "%s%d", "/Step#", tstep);
        dname_array = (dset_name_item *)malloc(MAX_DATASET_NUM * sizeof(dset_name_item));
        package_data = get_vpic_pure_data_h5(mpi_rank, mpi_size, filename_ene,
            config->group_name, &row_size, &my_data_size, &rest_size, &dataset_num,
            &max_type_size, &key_value_type, dname_array);
        free(package_data);
        qindex = get_dataset_index("q", dname_array, dataset_num);
        config->ux_kindex = get_dataset_index("Ux", dname_array, dataset_num);

        tracked_particles = (char *)malloc(nsteps_tot * config->nptl_traj * row_size);
        for (int j = 0; j < nsteps_tot*config->nptl_traj*row_size; j++) {
            tracked_particles[j] = 0;
        }
        if (mpi_rank == 0) {
            tracked_particles_sum = (char *)malloc(nsteps_tot * config->nptl_traj * row_size);
            for (int j = 0; j < nsteps_tot*config->nptl_traj*row_size; j++) {
                tracked_particles_sum[j] = 0;
            }
        }
    } // if (config->tracking_traj)

    if (config->multi_tsteps) {
        for (int i = mtf; i < ntf; i++) {
            tstep = i * config->tinterval;
            if (mpi_rank == 0) printf("Time Step: %d\n", tstep);
            if (config->reduced_tracer) {
                set_filenames_reduced(tstep, config->filepath, config->species,
                        config->filename, config->group_name, config->filename_sorted,
                        config->filename_attribute, config->filename_meta);
            } else {
                set_filenames(tstep, config_init, config);
            }
            if (config->nsteps == 1) {
                final_buff = sorting_single_tstep(mpi_size, mpi_rank, config, &rsize);
                if (config->tracking_traj) {
                    get_tracked_particle_info(final_buff, qindex, row_size,
                            rsize, i, ntf, tags, config->nptl_traj, tracked_particles);
                }
                if(config->collect_data == 1) {
                    free(final_buff);
                }
            } else {
                for (tstep = (i-1) * config->tinterval; tstep < i*config->tinterval; tstep++) {
                    snprintf(config->group_name, MAX_FILENAME_LEN, "%s%d", "/Step#",
                            tstep);
                    final_buff = sorting_single_tstep(mpi_size, mpi_rank, config, &rsize);
                    if (config->tracking_traj) {
                        get_tracked_particle_info(final_buff, qindex, row_size,
                                rsize, tstep, nsteps_tot, tags, config->nptl_traj,
                                tracked_particles);
                    }
                    if(config->collect_data == 1) {
                        free(final_buff);
                    }
                }
            }
        }
    } else {
        if (mpi_rank == 0) {
            printf("Input filename: %s\n", config->filename);
            printf("Group name: %s\n", config->group_name);
            printf("Output filename: %s\n", config->filename_sorted);
            printf("Meta data filename: %s\n", config->filename_meta);
        }
        set_filenames(config->tstep, config_init, config);

        final_buff = sorting_single_tstep(mpi_size, mpi_rank, config, &rsize);
        if(config->collect_data == 1) {
            free(final_buff);
        }
    }

    MPI_Barrier(MPI_COMM_WORLD);

    if (config->tracking_traj) {
        MPI_Reduce(tracked_particles, tracked_particles_sum,
                nsteps_tot*config->nptl_traj*row_size, MPI_CHAR, MPI_SUM, 0,
                MPI_COMM_WORLD);

        /* Save the particle data. */
        if (mpi_rank == 0) {
            save_tracked_particles(config->filename_traj, tracked_particles_sum,
                    nsteps_tot, config->nptl_traj, row_size, dataset_num, max_type_size,
                    dname_array, tags);
        }
        free(tracked_particles);
        if (mpi_rank == 0) {
            free(tracked_particles_sum);
        }
        free(tags);
        free(dname_array);
    }

    MPI_Barrier(MPI_COMM_WORLD);
    t1 = MPI_Wtime();
    if(mpi_rank == 0) {
        printf("Overall time is [%f]s \n", (t1 - t0));
    }

    free_configuration(config);
    free_configuration(config_init);

    MPI_Finalize();
    return 0;
}
Example #20
0
File: net.c Project: 95ulisse/tinc
/*
  this is where it all happens...
*/
int main_loop(void) {
	fd_set readset, writeset;
#ifdef HAVE_PSELECT
	struct timespec tv;
	sigset_t omask, block_mask;
	time_t next_event;
#else
	struct timeval tv;
#endif
	int r, maxfd;
	time_t last_ping_check, last_config_check, last_graph_dump;
	event_t *event;

	last_ping_check = now;
	last_config_check = now;
	last_graph_dump = now;
	
	srand(now);

#ifdef HAVE_PSELECT
	if(lookup_config(config_tree, "GraphDumpFile"))
		graph_dump = true;
	/* Block SIGHUP & SIGALRM */
	sigemptyset(&block_mask);
	sigaddset(&block_mask, SIGHUP);
	sigaddset(&block_mask, SIGALRM);
	sigprocmask(SIG_BLOCK, &block_mask, &omask);
#endif

	running = true;

	while(running) {
#ifdef HAVE_PSELECT
		next_event = last_ping_check + pingtimeout;
		if(graph_dump && next_event > last_graph_dump + 60)
			next_event = last_graph_dump + 60;

		if((event = peek_next_event()) && next_event > event->time)
			next_event = event->time;

		if(next_event <= now)
			tv.tv_sec = 0;
		else
			tv.tv_sec = next_event - now;
		tv.tv_nsec = 0;
#else
		tv.tv_sec = 1;
		tv.tv_usec = 0;
#endif

		maxfd = build_fdset(&readset, &writeset);

#ifdef HAVE_MINGW
		LeaveCriticalSection(&mutex);
#endif
#ifdef HAVE_PSELECT
		r = pselect(maxfd + 1, &readset, &writeset, NULL, &tv, &omask);
#else
		r = select(maxfd + 1, &readset, &writeset, NULL, &tv);
#endif
		now = time(NULL);
#ifdef HAVE_MINGW
		EnterCriticalSection(&mutex);
#endif

		if(r < 0) {
			if(!sockwouldblock(sockerrno)) {
				logger(LOG_ERR, "Error while waiting for input: %s", sockstrerror(sockerrno));
				dump_connections();
				return 1;
			}
		}

		if(r > 0)
			check_network_activity(&readset, &writeset);

		if(do_purge) {
			purge();
			do_purge = false;
		}

		/* Let's check if everybody is still alive */

		if(last_ping_check + pingtimeout <= now) {
			check_dead_connections();
			last_ping_check = now;

			if(routing_mode == RMODE_SWITCH)
				age_subnets();

			age_past_requests();

			/* Should we regenerate our key? */

			if(keyexpires <= now) {
				avl_node_t *node;
				node_t *n;

				ifdebug(STATUS) logger(LOG_INFO, "Expiring symmetric keys");

				for(node = node_tree->head; node; node = node->next) {
					n = node->data;
					if(n->inkey) {
						free(n->inkey);
						n->inkey = NULL;
					}
				}

				send_key_changed();
				keyexpires = now + keylifetime;
			}

			/* Detect ADD_EDGE/DEL_EDGE storms that are caused when
			 * two tinc daemons with the same name are on the VPN.
			 * If so, sleep a while. If this happens multiple times
			 * in a row, sleep longer. */

			if(contradicting_del_edge > 100 && contradicting_add_edge > 100) {
				logger(LOG_WARNING, "Possible node with same Name as us! Sleeping %d seconds.", sleeptime);
				usleep(sleeptime * 1000000LL);
				sleeptime *= 2;
				if(sleeptime < 0)
					sleeptime = 3600;
			} else {
				sleeptime /= 2;
				if(sleeptime < 10)
					sleeptime = 10;
			}

			contradicting_add_edge = 0;
			contradicting_del_edge = 0;
		}

		if(sigalrm) {
			avl_node_t *node;
			logger(LOG_INFO, "Flushing event queue");
			expire_events();
			for(node = connection_tree->head; node; node = node->next) {
				connection_t *c = node->data;
				if(c->status.active)
					send_ping(c);
			}
			sigalrm = false;
		}

		while((event = get_expired_event())) {
			event->handler(event->data);
			free_event(event);
		}

		if(sighup) {
			connection_t *c;
			avl_node_t *node, *next;
			char *fname;
			struct stat s;
			
			sighup = false;

			reopenlogger();
			
			/* Reread our own configuration file */

			exit_configuration(&config_tree);
			init_configuration(&config_tree);

			if(!read_server_config()) {
				logger(LOG_ERR, "Unable to reread configuration file, exitting.");
				return 1;
			}

			/* Cancel non-active outgoing connections */

			for(node = connection_tree->head; node; node = next) {
				next = node->next;
				c = node->data;

				c->outgoing = NULL;

				if(c->status.connecting) {
					terminate_connection(c, false);
					connection_del(c);
				}
			}

			/* Wipe list of outgoing connections */

			for(list_node_t *node = outgoing_list->head; node; node = node->next) {
				outgoing_t *outgoing = node->data;

				if(outgoing->event)
					event_del(outgoing->event);
			}

			list_delete_list(outgoing_list);

			/* Close connections to hosts that have a changed or deleted host config file */
			
			for(node = connection_tree->head; node; node = node->next) {
				c = node->data;
				
				xasprintf(&fname, "%s/hosts/%s", confbase, c->name);
				if(stat(fname, &s) || s.st_mtime > last_config_check)
					terminate_connection(c, c->status.active);
				free(fname);
			}

			last_config_check = now;

			/* If StrictSubnet is set, expire deleted Subnets and read new ones in */

			if(strictsubnets) {
				subnet_t *subnet;

				for(node = subnet_tree->head; node; node = node->next) {
					subnet = node->data;
					subnet->expires = 1;
				}

				load_all_subnets();

				for(node = subnet_tree->head; node; node = next) {
					next = node->next;
					subnet = node->data;
					if(subnet->expires == 1) {
						send_del_subnet(everyone, subnet);
						if(subnet->owner->status.reachable)
							subnet_update(subnet->owner, subnet, false);
						subnet_del(subnet->owner, subnet);
					} else if(subnet->expires == -1) {
						subnet->expires = 0;
					} else {
						send_add_subnet(everyone, subnet);
						if(subnet->owner->status.reachable)
							subnet_update(subnet->owner, subnet, true);
					}
				}
			}

			/* Try to make outgoing connections */
			
			try_outgoing_connections();
		}
		
		/* Dump graph if wanted every 60 seconds*/

		if(last_graph_dump + 60 <= now) {
			dump_graph();
			last_graph_dump = now;
		}
	}

#ifdef HAVE_PSELECT
	/* Restore SIGHUP & SIGALARM mask */
	sigprocmask(SIG_SETMASK, &omask, NULL);
#endif

	return 0;
}
Example #21
0
File: tincd.c Project: Rumko/tinc
int main(int argc, char **argv) {
	program_name = argv[0];

	if(!parse_options(argc, argv))
		return 1;
	
	make_names();

	if(show_version) {
		printf("%s version %s (built %s %s, protocol %d)\n", PACKAGE,
			   VERSION, __DATE__, __TIME__, PROT_CURRENT);
		printf("Copyright (C) 1998-2010 Ivo Timmermans, Guus Sliepen and others.\n"
				"See the AUTHORS file for a complete list.\n\n"
				"tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
				"and you are welcome to redistribute it under certain conditions;\n"
				"see the file COPYING for details.\n");

		return 0;
	}

	if(show_help) {
		usage(false);
		return 0;
	}

	if(kill_tincd)
		return !kill_other(kill_tincd);

	openlogger("tinc", use_logfile?LOGMODE_FILE:LOGMODE_STDERR);

	g_argv = argv;

	init_configuration(&config_tree);

	/* Slllluuuuuuurrrrp! */

	RAND_load_file("/dev/urandom", 1024);

	ENGINE_load_builtin_engines();
	ENGINE_register_all_complete();

	OpenSSL_add_all_algorithms();

	if(generate_keys) {
		read_server_config();
		return !keygen(generate_keys);
	}

	if(!read_server_config())
		return 1;

#ifdef HAVE_LZO
	if(lzo_init() != LZO_E_OK) {
		logger(LOG_ERR, "Error initializing LZO compressor!");
		return 1;
	}
#endif

#ifdef HAVE_MINGW
	if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
		logger(LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
		return 1;
	}

	if(!do_detach || !init_service())
		return main2(argc, argv);
	else
		return 1;
}
Example #22
0
bool id_h(connection_t *c, const char *request) {
	char name[MAX_STRING_SIZE];

	if(sscanf(request, "%*d " MAX_STRING " %d.%d", name, &c->protocol_major, &c->protocol_minor) < 2) {
		logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s)", "ID", c->name,
			   c->hostname);
		return false;
	}

	/* Check if this is a control connection */

	if(name[0] == '^' && !strcmp(name + 1, controlcookie)) {
		c->status.control = true;
		c->allow_request = CONTROL;
		c->last_ping_time = now.tv_sec + 3600;

		free(c->name);
		c->name = xstrdup("<control>");

		return send_request(c, "%d %d %d", ACK, TINC_CTL_VERSION_CURRENT, getpid());
	}

	if(name[0] == '?') {
		if(!invitation_key) {
			logger(DEBUG_ALWAYS, LOG_ERR, "Got invitation from %s but we don't have an invitation key", c->hostname);
			return false;
		}

		c->ecdsa = ecdsa_set_base64_public_key(name + 1);
		if(!c->ecdsa) {
			logger(DEBUG_ALWAYS, LOG_ERR, "Got bad invitation from %s", c->hostname);
			return false;
		}

		c->status.invitation = true;
		char *mykey = ecdsa_get_base64_public_key(invitation_key);
		if(!mykey)
			return false;
		if(!send_request(c, "%d %s", ACK, mykey))
			return false;
		free(mykey);

		c->protocol_minor = 2;

		return sptps_start(&c->sptps, c, false, false, invitation_key, c->ecdsa, "tinc invitation", 15, send_meta_sptps, receive_invitation_sptps);
	}

	/* Check if identity is a valid name */

	if(!check_id(name)) {
		logger(DEBUG_ALWAYS, LOG_ERR, "Got bad %s from %s (%s): %s", "ID", c->name,
			   c->hostname, "invalid name");
		return false;
	}

	/* If this is an outgoing connection, make sure we are connected to the right host */

	if(c->outgoing) {
		if(strcmp(c->name, name)) {
			logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s is %s instead of %s", c->hostname, name,
				   c->name);
			return false;
		}
	} else {
		if(c->name)
			free(c->name);
		c->name = xstrdup(name);
	}

	/* Check if version matches */

	if(c->protocol_major != myself->connection->protocol_major) {
		logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s (%s) uses incompatible version %d.%d",
			c->name, c->hostname, c->protocol_major, c->protocol_minor);
		return false;
	}

	if(bypass_security) {
		if(!c->config_tree)
			init_configuration(&c->config_tree);
		c->allow_request = ACK;
		return send_ack(c);
	}

	if(!experimental)
		c->protocol_minor = 0;

	if(!c->config_tree) {
		init_configuration(&c->config_tree);

		if(!read_host_config(c->config_tree, c->name)) {
			logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s had unknown identity (%s)", c->hostname, c->name);
			return false;
		}

		if(experimental)
			read_ecdsa_public_key(c);
			/* Ignore failures if no key known yet */
	}

	if(c->protocol_minor && !ecdsa_active(c->ecdsa))
		c->protocol_minor = 1;

	/* Forbid version rollback for nodes whose Ed25519 key we know */

	if(ecdsa_active(c->ecdsa) && c->protocol_minor < 2) {
		logger(DEBUG_ALWAYS, LOG_ERR, "Peer %s (%s) tries to roll back protocol version to %d.%d",
			c->name, c->hostname, c->protocol_major, c->protocol_minor);
		return false;
	}

	c->allow_request = METAKEY;

	if(c->protocol_minor >= 2) {
		c->allow_request = ACK;
		char label[25 + strlen(myself->name) + strlen(c->name)];

		if(c->outgoing)
			snprintf(label, sizeof label, "tinc TCP key expansion %s %s", myself->name, c->name);
		else
			snprintf(label, sizeof label, "tinc TCP key expansion %s %s", c->name, myself->name);

		return sptps_start(&c->sptps, c, c->outgoing, false, myself->connection->ecdsa, c->ecdsa, label, sizeof label, send_meta_sptps, receive_meta_sptps);
	} else {
		return send_metakey(c);
	}
}
Example #23
0
void Profile::read_into_configuration(Configuration* config)
{
    init_configuration(config, xmlProfileDoc);
}
Example #24
0
/*---------------------------------------------------------------------------*
 * NAME: main
 * DESC: Main Entry Point
 *---------------------------------------------------------------------------*/
int main(int argc, char **argv) {

  config *conf;
  unsigned int first_arg;

  /* create the configuration structure */
  conf = malloc_(sizeof(config));

  /* create the adc structure */
  conf->adc = malloc_(sizeof(struct struct_adc));

  /* initialize the configuration structure */
  init_configuration(conf);

  /* parse the arguments */
  first_arg = parsing_args(argc, argv, conf);

  /* check if selected mode is well defined (dirty) */
  if (
      /* client mode -> port AND host */
      ((conf->mode == 0) && ((conf->port == 0) ||
			     (conf->host == NULL)))
      ||
      /* server mode -> port */
      ((conf->mode == 1) && (conf->port == 0))
      ||
      /* no file.ad defined */
      (argv[first_arg] == NULL)
      ||
      /* debugger and file */
      ((conf->type == 2) && (conf->dbg_mode))
      ||
      /* fuzz udp or tcp or file */
      ((conf->fuzz_file_dir != NULL) && ((conf->host != NULL) ||
					 (conf->port != 0)    ||
					 (conf->type != 2)))
      ) {
    usage(argv, conf);
  }

  /* verbose messages */

  /* autodafe's debugger */
    if (conf->dbg_mode) {
    verbose_("[*] Autodafe's debugger mode activated.\n");
  }

  /* file mode */
  if (conf->type == 2) {
    verbose_("[*] mode *file* - all fuzzed files will be in %s\n", conf->fuzz_file_dir);
  }

  /* network mode */
  else {
    if (conf->mode) {
      if (!conf->type) /* tcp */
	verbose_("[*] mode *server* - listening on port: %d (tcp)\n", conf->port);
      else /* udp */
	verbose_("[*] mode *server* - listening on port: %d (udp)\n", conf->port);
    }
    else {
      if (!conf->type) /* tcp */
	verbose_("[*] mode *client* - connection to %s on port: %d (tcp)\n", conf->host, conf->port);
      else /* udp */
	verbose_("[*] mode *client* - connection to %s on port: %d (udp)\n", conf->host, conf->port);
    }
  }
  /* read the file */
  if(read_adc_file(conf, argv[first_arg])) goto fuzzer_end;

  /* ignore the SIGPIPE signal (ie. "Connection closed by foreign host") */
  signal(SIGPIPE, sigpipe_handler);


  /* start the connection with the debugger */
  if (conf->dbg_mode)
    if (dbg_connection(conf)) goto fuzzer_end;

  /* start the fuzz engine */
  fuzz_engine(conf);


  if (conf->buf_fuzz)    free(conf->buf_fuzz);    /* free the fuzz buffer (in case of error) */
 fuzzer_end:
  if (conf->adc->buffer) free(conf->adc->buffer); /* free the memory-copy of adc file */
  if (conf->adc)         free(conf->adc);         /* free the adc structure */
  if (conf)              free(conf);              /* free the configuration structure */

  return 0;
}
Example #25
0
Timed::Timed(int ac, char **av) :
  QCoreApplication(ac, av),
  peer(NULL)
//  session_bus_name("timed_not_connected"),
//  session_bus_address("invalid_address")
{
  spam() ;
  halted = "" ; // XXX: remove it, as we don't want to halt anymore
  first_boot_date_adjusted = false;
  log_debug() ;

  init_scratchbox_mode() ;
  log_debug() ;

  init_unix_signal_handler() ;
  log_debug() ;

  QMLOG_IF
    init_dbus_peer_info() ;
    log_debug() ;
  QMLOG_ENDIF ;

  // init_act_dead() ;
  // init_dsme_mode() ;
  log_debug() ;

  init_configuration() ;
  log_debug() ;

  init_customization() ;
  log_debug() ;

  init_read_settings() ;
  log_debug() ;

  init_create_event_machine() ;
  log_debug() ;

  init_device_mode() ;
  log_debug() ;

  init_context_objects() ;
  log_debug() ;

  init_backup_object() ;
  log_debug() ;

  init_main_interface_object() ;
  log_debug() ;

  init_backup_dbus_name() ;
  log_debug() ;

  init_main_interface_dbus_name() ;
  log_debug() ;

  start_voland_watcher();
  log_debug() ;

  init_kernel_notification();

  init_first_boot_hwclock_time_adjustment_check();
  log_debug() ;

  init_load_events() ;
  log_debug() ;

#if OFONO
  init_cellular_services() ;
#endif // OFONO

  log_debug() ;

  init_network_events() ;
  log_debug() ;

  init_dst_checker() ;

  log_debug("starting event mahine") ;

  init_start_event_machine() ;
  log_debug() ;

  log_debug("applying time zone settings") ;

  init_apply_tz_settings() ;
  log_debug() ;

  log_info("daemon is up and running") ;
}
Example #26
0
File: imsd.c Project: bedis/imsd
int 
main( int argc, char *argv[] ) {
	CONFIGURATION conf;
	int shm_fd;
	RINGBUFFER rb;
	char *logs;

	/* NETWORK Socket */
	int sockfd;
	ssize_t n;
	socklen_t len;
	struct sockaddr_in cliaddr;
	char msg[NET_BUF_SIZE];
	char clientip[IP_STRLEN];

	/* Other variables */
	int c;

	erase_conf_struct( &conf );

	 /* Analyze command line arguments */
	opterr = 0;
	while ((c = getopt (argc, argv, AVAILABLE_ARGUMENTS)) != -1)
		switch(c) {
			case 'd':
				conf.debug = YES;
				break;
			case 'f':
				break;
			case 'n':
				conf.nb_bytes = atoll(optarg);
				break;
			case 'h':
				help(0);
				break;
			case '?':
				if ( (optopt == 'f') || (optopt == 'n') )
					fprintf(stderr, 
						"-%c: missing arguments\n",
						optopt);
				else if (isprint(optopt))
					fprintf (stderr, 
						"Unknown option `-%c'.\n",
						optopt);
				else
					fprintf (stderr,
						"Unknown option character `\\x%x'.\n", 
						optopt);
				help(1);
				break;
			default:
				help(1);
		}

	/* 
	 * Init phase
	 */
	/* Configuration initialisation */
	init_configuration( &conf );
	if (conf.debug == YES)
		print_configuration( &conf );

	/* SHM setup */
	if ((shm_fd = create_shm(SHM_PATH, conf.nb_bytes)) < 0)
		MANAGE_ERROR("can't create shm", TRUE, EXIT_FAILURE);

	if ((logs = mmap(NULL, conf.nb_bytes, (PROT_READ | PROT_WRITE), 
					MAP_SHARED, shm_fd, 0)) == MAP_FAILED)
		MANAGE_ERROR("mmap", TRUE, EXIT_FAILURE);

	/* ring buffer */
	rb_init(&rb, logs, conf.nb_bytes);
	//rb_info(&rb);

	/* main listening daemon */
	udp_daemon_setup(&sockfd, 1514);

	/* Signals management */
	(void) signal(SIGINT, leave);

	len = sizeof(cliaddr);

	/* 
	 * Main Loop
	 */
	while ((n = recvfrom(sockfd, msg, NET_BUF_SIZE, 0, 
				(struct sockaddr *)&cliaddr, &len)) > 0) {
		/*if (memcmp(msg, "dump logs", 9) == 0) {
			printf("DUMP:\n");
			rb_dump(&rb);
			continue;
		}
		if (memcmp(msg, "print logs", 10) == 0) {
			printf("PRINT:\n");
			rb_print(&rb);
			continue;
		}
		*/
		// n - 1 to remove the remaining \n
		memcpy(clientip, inet_ntoa(cliaddr.sin_addr), IP_STRLEN);
		//rb_add_row(&rb, msg, n);
		rb_add_row(&rb, msg, n, clientip);
		memset(msg, '\0', NET_BUF_SIZE);
	}
	printf("\n");
	unlink_shm(SHM_PATH);

	return EXIT_SUCCESS;
}
Example #27
0
File: tincd.c Project: xentec/tinc
int main(int argc, char **argv) {
    program_name = argv[0];

    if(!parse_options(argc, argv))
        return 1;

    make_names(true);

    if(show_version) {
        printf("%s version %s (built %s %s, protocol %d.%d)\n", PACKAGE,
               BUILD_VERSION, BUILD_DATE, BUILD_TIME, PROT_MAJOR, PROT_MINOR);
        printf("Copyright (C) 1998-2015 Ivo Timmermans, Guus Sliepen and others.\n"
               "See the AUTHORS file for a complete list.\n\n"
               "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
               "and you are welcome to redistribute it under certain conditions;\n"
               "see the file COPYING for details.\n");

        return 0;
    }

    if(show_help) {
        usage(false);
        return 0;
    }

#ifdef HAVE_MINGW
    if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
        logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
        return 1;
    }
#else
    // Check if we got an umbilical fd from the process that started us
    char *umbstr = getenv("TINC_UMBILICAL");
    if(umbstr) {
        umbilical = atoi(umbstr);
        if(fcntl(umbilical, F_GETFL) < 0)
            umbilical = 0;
#ifdef FD_CLOEXEC
        if(umbilical)
            fcntl(umbilical, F_SETFD, FD_CLOEXEC);
#endif
    }
#endif

    openlogger("tinc", use_logfile?LOGMODE_FILE:LOGMODE_STDERR);

    g_argv = argv;

    if(getenv("LISTEN_PID") && atoi(getenv("LISTEN_PID")) == getpid())
        do_detach = false;
#ifdef HAVE_UNSETENV
    unsetenv("LISTEN_PID");
#endif

    init_configuration(&config_tree);

    /* Slllluuuuuuurrrrp! */

    gettimeofday(&now, NULL);
    srand(now.tv_sec + now.tv_usec);
    crypto_init();

    if(!read_server_config())
        return 1;

#ifdef HAVE_MINGW
    io_add_event(&stop_io, stop_handler, NULL, WSACreateEvent());
    if (stop_io.event == FALSE)
        abort();

    int result;
    if(!do_detach || !init_service()) {
        SetConsoleCtrlHandler(console_ctrl_handler, TRUE);
        result = main2(argc, argv);
    } else
        result = 1;

    if (WSACloseEvent(stop_io.event) == FALSE)
        abort();
    io_del(&stop_io);
    return result;
}
Example #28
0
int topology_init(void)
{
    struct topology_functions funcs = topology_funcs;

    if (init)
    {
        return EXIT_SUCCESS;
    }
    init = 1;

    init_configuration();

    if ((config.topologyCfgFileName == NULL) || access(config.topologyCfgFileName, R_OK))
    {
        cpu_set_t cpuSet;
        CPU_ZERO(&cpuSet);
        sched_getaffinity(0,sizeof(cpu_set_t), &cpuSet);
        if (cpu_count(&cpuSet) < sysconf(_SC_NPROCESSORS_CONF))
        {
            funcs.init_cpuInfo = proc_init_cpuInfo;
            funcs.init_cpuFeatures = proc_init_cpuFeatures;
            funcs.init_nodeTopology = proc_init_nodeTopology;
            funcs.init_cacheTopology = proc_init_cacheTopology;
            cpuid_topology.activeHWThreads =
                ((cpu_count(&cpuSet) < sysconf(_SC_NPROCESSORS_CONF)) ?
                cpu_count(&cpuSet) :
                sysconf(_SC_NPROCESSORS_CONF));
        }
        else
        {
            cpuid_topology.activeHWThreads = sysconf(_SC_NPROCESSORS_CONF);
        }
        funcs.init_cpuInfo(cpuSet);
        topology_setName();
        funcs.init_cpuFeatures();
        funcs.init_nodeTopology(cpuSet);
        topology_setupTree();
        funcs.init_cacheTopology();
        sched_setaffinity(0, sizeof(cpu_set_t), &cpuSet);
    }
    else
    {
        cpu_set_t cpuSet;
        CPU_ZERO(&cpuSet);
        sched_getaffinity(0,sizeof(cpu_set_t), &cpuSet);
        DEBUG_PRINT(DEBUGLEV_INFO, Reading topology information from %s, config.topologyCfgFileName);
        readTopologyFile(config.topologyCfgFileName);
        cpuid_topology.activeHWThreads = 0;
        for (int i=0;i<cpuid_topology.numHWThreads;i++)
        {
            if (CPU_ISSET(cpuid_topology.threadPool[i].apicId, &cpuSet))
            {
                cpuid_topology.activeHWThreads++;
                cpuid_topology.threadPool[i].inCpuSet = 1;
            }
        }
        topology_setName();
        topology_setupTree();
    }


    return EXIT_SUCCESS;
}
Example #29
0
bool id_h(connection_t *c) {
	char name[MAX_STRING_SIZE];

	if(sscanf(c->buffer, "%*d " MAX_STRING " %d", name, &c->protocol_version) != 2) {
		logger(LOG_ERR, "Got bad %s from %s (%s)", "ID", c->name,
		       c->hostname);
		return false;
	}

	/* Check if identity is a valid name */

	if(!check_id(name) || !strcmp(name, myself->name)) {
		logger(LOG_ERR, "Got bad %s from %s (%s): %s", "ID", c->name,
		       c->hostname, "invalid name");
		return false;
	}

	/* If this is an outgoing connection, make sure we are connected to the right host */

	if(c->outgoing) {
		if(strcmp(c->name, name)) {
			logger(LOG_ERR, "Peer %s is %s instead of %s", c->hostname, name,
			       c->name);
			return false;
		}
	} else {
		if(c->name) {
			free(c->name);
		}

		c->name = xstrdup(name);
	}

	/* Check if version matches */

	if(c->protocol_version != myself->connection->protocol_version) {
		logger(LOG_ERR, "Peer %s (%s) uses incompatible version %d",
		       c->name, c->hostname, c->protocol_version);
		return false;
	}

	if(bypass_security) {
		if(!c->config_tree) {
			init_configuration(&c->config_tree);
		}

		c->allow_request = ACK;

		if(!c->outgoing) {
			send_id(c);
		}

		return send_ack(c);
	}

	if(!c->config_tree) {
		init_configuration(&c->config_tree);

		if(!read_connection_config(c)) {
			logger(LOG_ERR, "Peer %s had unknown identity (%s)", c->hostname,
			       c->name);
			return false;
		}
	}

	if(!read_rsa_public_key(c)) {
		return false;
	}

	c->allow_request = METAKEY;

	if(!c->outgoing) {
		send_id(c);
	}

	return send_metakey(c);
}
Example #30
0
File: tincd.c Project: seehuhn/tinc
int main(int argc, char **argv) {
	logmode_t logmode;

	program_name = argv[0];

	if(!parse_options(argc, argv)) {
		return 1;
	}

	if(show_version) {
		printf("%s version %s\n", PACKAGE, VERSION);
		printf("Copyright (C) 1998-2018 Ivo Timmermans, Guus Sliepen and others.\n"
			   "See the AUTHORS file for a complete list.\n\n"
			   "tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
			   "and you are welcome to redistribute it under certain conditions;\n"
			   "see the file COPYING for details.\n");

		return 0;
	}

	if(show_help) {
		usage(false);
		return 0;
	}

	make_names();

	if(kill_tincd) {
		return !kill_other(kill_tincd);
	}

	if(use_logfile) {
		logmode = LOGMODE_FILE;
	} else if(use_syslog) {
		logmode = LOGMODE_SYSLOG;
	} else {
		logmode = LOGMODE_STDERR;
	}
	openlogger("tinc", logmode);

	g_argv = argv;

	if(getenv("LISTEN_PID") && atoi(getenv("LISTEN_PID")) == getpid()) {
		do_detach = false;
	}

#ifdef HAVE_UNSETENV
	unsetenv("LISTEN_PID");
#endif

	init_configuration(&config_tree);

#ifndef OPENSSL_NO_ENGINE
	ENGINE_load_builtin_engines();
	ENGINE_register_all_complete();
#endif

#if OPENSSL_VERSION_NUMBER < 0x10100000L
	OpenSSL_add_all_algorithms();
#endif

	if(generate_keys) {
		read_server_config();
		return !keygen(generate_keys);
	}

	if(!read_server_config()) {
		return 1;
	}

#ifdef HAVE_LZO

	if(lzo_init() != LZO_E_OK) {
		logger(LOG_ERR, "Error initializing LZO compressor!");
		return 1;
	}

#endif

#ifdef HAVE_MINGW

	if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
		logger(LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
		return 1;
	}

	if(!do_detach || !init_service()) {
		return main2(argc, argv);
	} else {
		return 1;
	}
}