Пример #1
0
/*
 * That function takes a raw KKD/MR2 binary buffer,
 * typically read from LvProp in table MSysbjects
 * and returns a GPtrArray of MdbProps*
 */
GArray*
mdb_kkd_to_props(MdbHandle *mdb, void *buffer, size_t len) {
	guint32 record_len;
	guint16 record_type;
	size_t pos;
	GPtrArray *names = NULL;
	MdbProperties *props;
	GArray *result;

#if MDB_DEBUG
	mdb_buffer_dump(buffer, 0, len);
#endif
	mdb_debug(MDB_DEBUG_PROPS,"starting prop parsing of type %s", buffer);

	if (strcmp("KKD", buffer) && strcmp("MR2", buffer)) {
		fprintf(stderr, "Unrecognized format.\n");
		mdb_buffer_dump(buffer, 0, len);
		return NULL;
	}

	result = g_array_new(0, 0, sizeof(MdbProperties*));

	pos = 4;
	while (pos < len) {
		record_len = mdb_get_int32(buffer, pos);
		record_type = mdb_get_int16(buffer, pos + 4);
		mdb_debug(MDB_DEBUG_PROPS,"prop chunk type:0x%04x len:%d", record_type, record_len);
		//mdb_buffer_dump(buffer, pos+4, record_len);
		switch (record_type) {
			case 0x80:
				if (names) free_names(names);
				names = mdb_read_props_list(mdb, buffer+pos+6, record_len - 6);
				break;
			case 0x00:
			case 0x01:
				if (!names) {
					fprintf(stderr,"sequence error!\n");
					break;
				}
				props = mdb_read_props(mdb, names, buffer+pos+6, record_len - 6);
				g_array_append_val(result, props);
				//mdb_dump_props(props, stderr, 1);
				break;
			default:
				fprintf(stderr,"Unknown record type %d\n", record_type);
				break;
		}
		pos += record_len;
	}
	if (names) free_names(names);
	return result;
}
Пример #2
0
static struct sysfs_names *find_device(char *name)
{
	char		dname[256];
	char		*input = "rc";
	static struct sysfs_names *names, *cur;
	/*
	 * Get event sysfs node
	 */
	snprintf(dname, sizeof(dname), "/sys/class/rc/");

	names = seek_sysfs_dir(dname, input);
	if (!names)
		return NULL;

	if (debug) {
		for (cur = names; cur->next; cur = cur->next) {
			fprintf(stderr, "Found device %s\n", cur->name);
		}
	}

	if (name) {
		static struct sysfs_names *tmp;
		char *p, *n;
		int found = 0;

		n = malloc(strlen(name) + 2);
		strcpy(n, name);
		strcat(n,"/");
		for (cur = names; cur->next; cur = cur->next) {
			if (cur->name) {
				p = cur->name + strlen(dname);
				if (p && !strcmp(p, n)) {
					found = 1;
					break;
				}
			}
		}
		free(n);
		if (!found) {
			free_names(names);
			fprintf(stderr, "Not found device %s\n", name);
			return NULL;
		}
		tmp = calloc(sizeof(*names), 1);
		tmp->name = cur->name;
		cur->name = NULL;
		free_names(names);
		return tmp;
	}

	return names;
}
Пример #3
0
static void main_fini( void )
/***************************/
{
    free_names();
    GenMSOmfFini();
    AsmShutDown();
}
Пример #4
0
static struct sysfs_names *seek_sysfs_dir(char *dname, char *node_name)
{
	DIR             	*dir;
	struct dirent   	*entry;
	struct sysfs_names	*names, *cur_name;

	names = calloc(sizeof(*names), 1);

	cur_name = names;

	dir = opendir(dname);
	if (!dir) {
		perror(dname);
		return NULL;
	}
	entry = readdir(dir);
	while (entry) {
		if (!node_name || !strncmp(entry->d_name, node_name, strlen(node_name))) {
			cur_name->name = malloc(strlen(dname) + strlen(entry->d_name) + 2);
			if (!cur_name->name)
				goto err;
			strcpy(cur_name->name, dname);
			strcat(cur_name->name, entry->d_name);
			if (node_name)
				strcat(cur_name->name, "/");
			cur_name->next = calloc(sizeof(*cur_name), 1);
			if (!cur_name->next)
				goto err;
			cur_name = cur_name->next;
		}
		entry = readdir(dir);
	}
	closedir(dir);

	if (names == cur_name) {
		fprintf(stderr, "Couldn't find any node at %s%s*.\n",
			dname, node_name);
		free (names);
		names = NULL;
	}
	return names;

err:
	perror("Seek dir");
	free_names(names);
	return NULL;
}
Пример #5
0
static int
u_dpm_create_class(const char *u_name, char **u_op_names, unsigned nops)
{
	int ret;
	char *name;
	char **op_names;

	if ((ret = u_get_name(&name, u_name)))
		return ret;
	if ((ret = u_get_names(&op_names, u_op_names, nops)))
		goto free_name;
	ret = dpm_create_class(name, op_names, nops);
	free_names(op_names, nops);
 free_name:
	free_name(name);
	return ret;
}
void sub_file(char *t)
/******************************************************************
 * Do our substitutions on a single file.
 ******************************************************************/
{
Name *ll, *n;
FILE *sfile;

sfile = must_open(t, "r");
printf("Subbing %s\n", t);
ll = NULL;
llcount = 0;
ltitle = t;
dirty = FALSE;
for (;;)
	{
	if (fgets(b1, sizeof(b1)-1, sfile) == NULL)
		break;
	if (embedded)
		embedded_subline();
	else
		csym_subline();
	n = begmem(sizeof(*n));
	n->name = clone_string(b2);
	n->next = ll;
	ll = n;
	llcount += 1;
	}
fclose(sfile);
if (dirty && writeit)
	{
	printf("saving new %s\n", t);
	ll = reverse_list(ll);
	n = ll;
	if (backup)
		backitup(t);
	sfile = must_open(t, "w");
	while (n != NULL)
		{
		fputs(n->name, sfile);
		n = n->next;
		}
	fclose(sfile);
	}
free_names(ll);
}
Пример #7
0
static int
u_dpm_create_policy(const char *u_name, char **u_class_names)
{
	int ret;
	char *name;
	char **class_names;

	trace("u_dpm_create_policy");
	if ((ret = u_get_name(&name, u_name)))
		return ret;
	if ((ret = u_get_names(&class_names, u_class_names, DPM_STATES)))
		goto free_name;
	ret = dpm_create_policy(name, class_names);
	free_names(class_names, DPM_STATES);
 free_name:
	free_name(name);
	return ret;
}
Пример #8
0
/**
   Free all memory allocated by the program.
   This mainly means we have to free a lot of strings
   and GArrays. */
void
free_memory(void)
{
#ifdef DEBUG
    printf("free_memory\n");
#endif

    free_variables();
    free_names(FALSE);
    free_transfer_list();
    free_strategies();
    free_country(&country, FALSE);
    free_users(FALSE);
    free_bets(FALSE);
    free_lg_commentary(FALSE);
    free_news(FALSE);
    free_newspaper(FALSE);
    free_support_dirs();
    free_jobs(FALSE);

    free_g_array(&live_games);
}
Пример #9
0
static int
u_get_names(char ***names, char **u_names, int n)
{
	char **local_names;
	char *local_name;
	int i, ret;

	if (!(local_names = kmalloc(n * sizeof (char *), GFP_KERNEL)))
		return -ENOMEM;
	memset(local_names, 0, n * sizeof (char *));
	for (i = 0; i < n; i++) {
		ret = -EFAULT;
		if (copy_from_user(&local_name, &u_names[i], sizeof (char *)))
			goto free_names;
		if ((ret = u_get_name(&local_names[i], local_name)))
			goto free_names;
	}
	*names = local_names;
	return 0;
free_names:
	free_names(local_names, n);
	return ret;
}
Пример #10
0
Файл: tincd.c Проект: Rumko/tinc
int main2(int argc, char **argv) {
	InitializeCriticalSection(&mutex);
	EnterCriticalSection(&mutex);
#endif

	if(!detach())
		return 1;

#ifdef HAVE_MLOCKALL
	/* Lock all pages into memory if requested.
	 * This has to be done after daemon()/fork() so it works for child.
	 * No need to do that in parent as it's very short-lived. */
	if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
		logger(LOG_ERR, "System call `%s' failed: %s", "mlockall",
		   strerror(errno));
		return 1;
	}
#endif

	/* Setup sockets and open device. */

	if(!setup_network())
		goto end;

	/* Initiate all outgoing connections. */

	try_outgoing_connections();

	/* Change process priority */

        char *priority = 0;

        if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
                if(!strcasecmp(priority, "Normal")) {
                        if (setpriority(NORMAL_PRIORITY_CLASS) != 0) {
                                logger(LOG_ERR, "System call `%s' failed: %s",
                                       "setpriority", strerror(errno));
                                goto end;
                        }
                } else if(!strcasecmp(priority, "Low")) {
                        if (setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
                                       logger(LOG_ERR, "System call `%s' failed: %s",
                                       "setpriority", strerror(errno));
                                goto end;
                        }
                } else if(!strcasecmp(priority, "High")) {
                        if (setpriority(HIGH_PRIORITY_CLASS) != 0) {
                                logger(LOG_ERR, "System call `%s' failed: %s",
                                       "setpriority", strerror(errno));
                                goto end;
                        }
                } else {
                        logger(LOG_ERR, "Invalid priority `%s`!", priority);
                        goto end;
                }
        }

	/* drop privileges */
	if (!drop_privs())
		goto end;

	/* Start main loop. It only exits when tinc is killed. */

	status = main_loop();

	/* Shutdown properly. */

	ifdebug(CONNECTIONS)
		dump_device_stats();

	close_network_connections();

end:
	logger(LOG_NOTICE, "Terminating");

#ifndef HAVE_MINGW
	remove_pid(pidfilename);
#endif

	EVP_cleanup();
	ENGINE_cleanup();
	CRYPTO_cleanup_all_ex_data();
	ERR_remove_state(0);
	ERR_free_strings();

	exit_configuration(&config_tree);
	free_names();

	return status;
}
Пример #11
0
/* 
 * main function - reads instantaneous power values (in W) from a trace
 * file (e.g. "gcc.ptrace") and outputs instantaneous temperature values (in C) to
 * a trace file("gcc.ttrace"). also outputs steady state temperature values
 * (including those of the internal nodes of the model) onto stdout. the
 * trace files are 2-d matrices with each column representing a functional
 * functional block and each row representing a time unit(sampling_intvl).
 * columns are tab-separated and each row is a separate line. the first
 * line contains the names of the functional blocks. the order in which
 * the columns are specified doesn't have to match that of the floorplan 
 * file.
 */
int main(int argc, char **argv)
{
	int i, j, idx, base = 0, count = 0, n = 0;
	int num, size, lines = 0, do_transient = TRUE;
	char **names;
	double *vals;
	/* trace file pointers	*/
	FILE *pin, *tout = NULL;
	/* floorplan	*/
	flp_t *flp;
	/* hotspot temperature model	*/
	RC_model_t *model;
	/* instantaneous temperature and power values	*/
	double *temp = NULL, *power;
	double total_power = 0.0;
	
	/* steady state temperature and power values	*/
	double *overall_power, *steady_temp;
	/* thermal model configuration parameters	*/
	thermal_config_t thermal_config;
	/* global configuration parameters	*/
	global_config_t global_config;
	/* table to hold options and configuration */
	str_pair table[MAX_ENTRIES];
	
	/* variables for natural convection iterations */
	int natural = 0; 
	double avg_sink_temp = 0;
	int natural_convergence = 0;
	double r_convec_old;

	if (!(argc >= 5 && argc % 2)) {
		usage(argc, argv);
		return 1;
	}
	
	size = parse_cmdline(table, MAX_ENTRIES, argc, argv);
	global_config_from_strs(&global_config, table, size);

	/* no transient simulation, only steady state	*/
	if(!strcmp(global_config.t_outfile, NULLFILE))
		do_transient = FALSE;

	/* read configuration file	*/
	if (strcmp(global_config.config, NULLFILE))
		size += read_str_pairs(&table[size], MAX_ENTRIES, global_config.config);

	/* 
	 * earlier entries override later ones. so, command line options 
	 * have priority over config file 
	 */
	size = str_pairs_remove_duplicates(table, size);

	/* get defaults */
	thermal_config = default_thermal_config();
	/* modify according to command line / config file	*/
	thermal_config_add_from_strs(&thermal_config, table, size);
	
	/* if package model is used, run package model */
	if (((idx = get_str_index(table, size, "package_model_used")) >= 0) && !(table[idx].value==0)) {
		if (thermal_config.package_model_used) {
			avg_sink_temp = thermal_config.ambient + SMALL_FOR_CONVEC;
			natural = package_model(&thermal_config, table, size, avg_sink_temp);
			if (thermal_config.r_convec<R_CONVEC_LOW || thermal_config.r_convec>R_CONVEC_HIGH)
				printf("Warning: Heatsink convection resistance is not realistic, double-check your package settings...\n"); 
		}
	}

	/* dump configuration if specified	*/
	if (strcmp(global_config.dump_config, NULLFILE)) {
		size = global_config_to_strs(&global_config, table, MAX_ENTRIES);
		size += thermal_config_to_strs(&thermal_config, &table[size], MAX_ENTRIES-size);
		/* prefix the name of the variable with a '-'	*/
		dump_str_pairs(table, size, global_config.dump_config, "-");
	}

	/* initialization: the flp_file global configuration 
	 * parameter is overridden by the layer configuration 
	 * file in the grid model when the latter is specified.
	 */
	flp = read_flp(global_config.flp_file, FALSE);

	/* allocate and initialize the RC model	*/
	model = alloc_RC_model(&thermal_config, flp);
	populate_R_model(model, flp);
	
	if (do_transient)
		populate_C_model(model, flp);

	#if VERBOSE > 2
	debug_print_model(model);
	#endif

	/* allocate the temp and power arrays	*/
	/* using hotspot_vector to internally allocate any extra nodes needed	*/
	if (do_transient)
		temp = hotspot_vector(model);
	power = hotspot_vector(model);
	steady_temp = hotspot_vector(model);
	overall_power = hotspot_vector(model);
	
	/* set up initial instantaneous temperatures */
	if (do_transient && strcmp(model->config->init_file, NULLFILE)) {
		if (!model->config->dtm_used)	/* initial T = steady T for no DTM	*/
			read_temp(model, temp, model->config->init_file, FALSE);
		else	/* initial T = clipped steady T with DTM	*/
			read_temp(model, temp, model->config->init_file, TRUE);
	} else if (do_transient)	/* no input file - use init_temp as the common temperature	*/
		set_temp(model, temp, model->config->init_temp);

	/* n is the number of functional blocks in the block model
	 * while it is the sum total of the number of functional blocks
	 * of all the floorplans in the power dissipating layers of the 
	 * grid model. 
	 */
	if (model->type == BLOCK_MODEL)
		n = model->block->flp->n_units;
	else if (model->type == GRID_MODEL) {
		for(i=0; i < model->grid->n_layers; i++)
			if (model->grid->layers[i].has_power)
				n += model->grid->layers[i].flp->n_units;
	} else 
		fatal("unknown model type\n");

	if(!(pin = fopen(global_config.p_infile, "r")))
		fatal("unable to open power trace input file\n");
	if(do_transient && !(tout = fopen(global_config.t_outfile, "w")))
		fatal("unable to open temperature trace file for output\n");

	/* names of functional units	*/
	names = alloc_names(MAX_UNITS, STR_SIZE);
	if(read_names(pin, names) != n)
		fatal("no. of units in floorplan and trace file differ\n");

	/* header line of temperature trace	*/
	if (do_transient)
		write_names(tout, names, n);

	/* read the instantaneous power trace	*/
	vals = dvector(MAX_UNITS);
	while ((num=read_vals(pin, vals)) != 0) {
		if(num != n)
			fatal("invalid trace file format\n");

		/* permute the power numbers according to the floorplan order	*/
		if (model->type == BLOCK_MODEL)
			for(i=0; i < n; i++)
				power[get_blk_index(flp, names[i])] = vals[i];
		else
			for(i=0, base=0, count=0; i < model->grid->n_layers; i++) {
				if(model->grid->layers[i].has_power) {
					for(j=0; j < model->grid->layers[i].flp->n_units; j++) {
						idx = get_blk_index(model->grid->layers[i].flp, names[count+j]);
						power[base+idx] = vals[count+j];
					}
					count += model->grid->layers[i].flp->n_units;
				}	
				base += model->grid->layers[i].flp->n_units;	
			}

		/* compute temperature	*/
		if (do_transient) {
			/* if natural convection is considered, update transient convection resistance first */
			if (natural) {
				avg_sink_temp = calc_sink_temp(model, temp);
				natural = package_model(model->config, table, size, avg_sink_temp);
				populate_R_model(model, flp);
			}
			/* for the grid model, only the first call to compute_temp
			 * passes a non-null 'temp' array. if 'temp' is  NULL, 
			 * compute_temp remembers it from the last non-null call. 
			 * this is used to maintain the internal grid temperatures 
			 * across multiple calls of compute_temp
			 */
			if (model->type == BLOCK_MODEL || lines == 0)
				compute_temp(model, power, temp, model->config->sampling_intvl);
			else
				compute_temp(model, power, NULL, model->config->sampling_intvl);
	
			/* permute back to the trace file order	*/
			if (model->type == BLOCK_MODEL)
				for(i=0; i < n; i++)
					vals[i] = temp[get_blk_index(flp, names[i])];
			else
				for(i=0, base=0, count=0; i < model->grid->n_layers; i++) {
					if(model->grid->layers[i].has_power) {
						for(j=0; j < model->grid->layers[i].flp->n_units; j++) {
							idx = get_blk_index(model->grid->layers[i].flp, names[count+j]);
							vals[count+j] = temp[base+idx];
						}
						count += model->grid->layers[i].flp->n_units;	
					}	
					base += model->grid->layers[i].flp->n_units;	
				}
		
			/* output instantaneous temperature trace	*/
			write_vals(tout, vals, n);
		}		
	
		/* for computing average	*/
		if (model->type == BLOCK_MODEL)
			for(i=0; i < n; i++)
				overall_power[i] += power[i];
		else
			for(i=0, base=0; i < model->grid->n_layers; i++) {
				if(model->grid->layers[i].has_power)
					for(j=0; j < model->grid->layers[i].flp->n_units; j++)
						overall_power[base+j] += power[base+j];
				base += model->grid->layers[i].flp->n_units;	
			}

		lines++;
	}    
	if(!lines)
		fatal("no power numbers in trace file\n");
		
	/* for computing average	*/
	if (model->type == BLOCK_MODEL)
		for(i=0; i < n; i++) {
			overall_power[i] /= lines;
			//overall_power[i] /=150; //reduce input power for natural convection
			total_power += overall_power[i];
		}
	else
		for(i=0, base=0; i < model->grid->n_layers; i++) {
			if(model->grid->layers[i].has_power)
				for(j=0; j < model->grid->layers[i].flp->n_units; j++) {
					overall_power[base+j] /= lines;
					total_power += overall_power[base+j];
				}
			base += model->grid->layers[i].flp->n_units;	
		}
		
	/* natural convection r_convec iteration, for steady-state only */ 		
	natural_convergence = 0;
	if (natural) { /* natural convection is used */
		while (!natural_convergence) {
			r_convec_old = model->config->r_convec;
			/* steady state temperature	*/
			steady_state_temp(model, overall_power, steady_temp);
			avg_sink_temp = calc_sink_temp(model, steady_temp) + SMALL_FOR_CONVEC;
			natural = package_model(model->config, table, size, avg_sink_temp);
			populate_R_model(model, flp);
			if (avg_sink_temp > MAX_SINK_TEMP)
				fatal("too high power for a natural convection package -- possible thermal runaway\n");
			if (fabs(model->config->r_convec-r_convec_old)<NATURAL_CONVEC_TOL) 
				natural_convergence = 1;
		}
	}	else /* natural convection is not used, no need for iterations */
	/* steady state temperature	*/
	steady_state_temp(model, overall_power, steady_temp);

	/* print steady state results	*/
	fprintf(stdout, "Unit\tSteady(Kelvin)\n");
	dump_temp(model, steady_temp, "stdout");

	/* dump steady state temperatures on to file if needed	*/
	if (strcmp(model->config->steady_file, NULLFILE))
		dump_temp(model, steady_temp, model->config->steady_file);

	/* for the grid model, optionally dump the most recent 
	 * steady state temperatures of the grid cells	
	 */
	if (model->type == GRID_MODEL &&
		strcmp(model->config->grid_steady_file, NULLFILE))
		dump_steady_temp_grid(model->grid, model->config->grid_steady_file);

	#if VERBOSE > 2
	if (model->type == BLOCK_MODEL) {
		if (do_transient) {
			fprintf(stdout, "printing temp...\n");
			dump_dvector(temp, model->block->n_nodes);
		}
		fprintf(stdout, "printing steady_temp...\n");
		dump_dvector(steady_temp, model->block->n_nodes);
	} else {
		if (do_transient) {
			fprintf(stdout, "printing temp...\n");
			dump_dvector(temp, model->grid->total_n_blocks + EXTRA);
		}
		fprintf(stdout, "printing steady_temp...\n");
		dump_dvector(steady_temp, model->grid->total_n_blocks + EXTRA);
	}
	#endif

	/* cleanup	*/
	fclose(pin);
	if (do_transient)
		fclose(tout);
	delete_RC_model(model);
	free_flp(flp, FALSE);
	if (do_transient)
		free_dvector(temp);
	free_dvector(power);
	free_dvector(steady_temp);
	free_dvector(overall_power);
	free_names(names);
	free_dvector(vals);

	return 0;
}
Пример #12
0
int main(int argc, char *argv[])
{
	int dev_from_class = 0, write_cnt;
	int fd;
	static struct sysfs_names *names;
	struct rc_device	  rc_dev;

	argp_parse(&argp, argc, argv, 0, 0, 0);

	/* Just list all devices */
	if (!clear && !read && !keys.next && !ch_proto && !cfg.next) {
		static struct sysfs_names *names, *cur;

		names = find_device(NULL);
		if (!names)
			return -1;
		for (cur = names; cur->next; cur = cur->next) {
			if (cur->name) {
				if (get_attribs(&rc_dev, cur->name))
					return -1;
				fprintf(stderr, "Found %s (%s) with:\n",
					rc_dev.sysfs_name,
					rc_dev.input_name);
				fprintf(stderr, "\tDriver %s, %s decoder, table %s\n",
					rc_dev.drv_name,
					(rc_dev.type == SOFTWARE_DECODER) ?
						"raw software" : "hardware",
					rc_dev.keytable_name);
				fprintf(stderr, "\tSupported protocols: ");
				show_proto(rc_dev.supported);
				fprintf(stderr, "\t");
				display_proto(&rc_dev);
			}
		}
		return 0;
	}

	if (cfg.next && (clear || keys.next || ch_proto || devname)) {
		fprintf (stderr, "Auto-mode can be used only with --read, --debug and --sysdev options\n");
		return -1;
	}
	if (!devname) {
		names = find_device(devclass);
		if (!names)
			return -1;
		rc_dev.sysfs_name = names->name;
		if (get_attribs(&rc_dev, names->name)) {
			free_names(names);
			return -1;
		}
		names->name = NULL;
		free_names(names);

		devname = rc_dev.input_name;
		dev_from_class++;
	}

	if (cfg.next) {
		struct cfgfile *cur;
		char *fname, *name;
		int rc;

		for (cur = &cfg; cur->next; cur = cur->next) {
			if (strcasecmp(cur->driver, rc_dev.drv_name) && strcasecmp(cur->driver, "*"))
				continue;
			if (strcasecmp(cur->table, rc_dev.keytable_name) && strcasecmp(cur->table, "*"))
				continue;
			break;
		}

		if (!cur->next) {
			if (debug)
				fprintf(stderr, "Table for %s, %s not found. Keep as-is\n",
				       rc_dev.drv_name, rc_dev.keytable_name);
			return 0;
		}
		if (debug)
			fprintf(stderr, "Table for %s, %s is on %s file.\n",
				rc_dev.drv_name, rc_dev.keytable_name,
				cur->fname);
		if (cur->fname[0] == '/' || ((cur->fname[0] == '.') && strchr(cur->fname, '/'))) {
			fname = cur->fname;
		} else {
			fname = malloc(strlen(cur->fname) + strlen(CFGDIR) + 2);
			strcpy(fname, CFGDIR);
			strcat(fname, "/");
			strcat(fname, cur->fname);
		}
		rc = parse_keyfile(fname, &name);
		if (rc < 0 || !keys.next) {
			fprintf(stderr, "Can't load %s table or empty table\n", fname);
			return -1;
		}
		clear = 1;
	}

	if (debug)
		fprintf(stderr, "Opening %s\n", devname);
	fd = open(devname, O_RDONLY);
	if (fd < 0) {
		perror(devname);
		return -1;
	}
	if (dev_from_class)
		free(devname);

	/*
	 * First step: clear, if --clear is specified
	 */
	if (clear) {
		clear_table(fd);
		fprintf(stderr, "Old keytable cleared\n");
	}

	/*
	 * Second step: stores key tables from file or from commandline
	 */
	write_cnt = add_keys(fd);
	if (write_cnt)
		fprintf(stderr, "Wrote %d keycode(s) to driver\n", write_cnt);

	/*
	 * Third step: change protocol
	 */
	if (ch_proto) {
		rc_dev.current = ch_proto;
		if (set_proto(&rc_dev))
			fprintf(stderr, "Couldn't change the IR protocols\n");
		else {
			fprintf(stderr, "Protocols changed to ");
			show_proto(rc_dev.current);
			fprintf(stderr, "\n");
		}
	}

	/*
	 * Fourth step: display current keytable
	 */
	if (read)
		display_table(&rc_dev, fd);

	return 0;
}
Пример #13
0
int cvsremove (int argc, char **argv)
{
    int c, err;

    if (argc == -1)
	usage (remove_usage);

    optind = 0;
    while ((c = getopt (argc, argv, "+flR")) != -1)
    {
	switch (c)
	{
	    case 'f':
		force = 1;
		break;
	    case 'l':
		local = 1;
		break;
	    case 'R':
		local = 0;
		break;
	    case '?':
	    default:
		usage (remove_usage);
		break;
	}
    }
    argc -= optind;
    argv += optind;

    if (current_parsed_root->isremote) {
	/* Call expand_wild so that the local removal of files will
           work.  It's ok to do it always because we have to send the
           file names expanded anyway.  */
	expand_wild (argc, argv, &argc, &argv);
	
	if (force)
	{
	    if (!noexec)
	    {
		start_recursion (remove_force_fileproc, (FILESDONEPROC) NULL,
				 (PREDIRENTPROC) NULL, (DIRENTPROC) NULL, (DIRLEAVEPROC) NULL,
				 (void *) NULL, argc, argv, local, W_LOCAL,
				 0, 0, (char *) NULL, NULL, 0, NULL, NULL);
	    }
	    /* else FIXME should probably act as if the file doesn't exist
	       in doing the following checks.  */
	}

	if (local)
	    send_arg("-l");
	send_arg("--");
	/* FIXME: Can't we set SEND_NO_CONTENTS here?  Needs investigation.  */
	send_files (argc, argv, local, 0, 0);
	send_file_names (argc, argv, 0);
	free_names (&argc, argv);
	send_to_server ("remove\n", 0);
        return get_responses_and_close ();
    }

    /* start the recursion processor */
    err = start_recursion (remove_fileproc, (FILESDONEPROC) NULL,
                           (PREDIRENTPROC) NULL, remove_dirproc, (DIRLEAVEPROC) NULL, NULL,
			   argc, argv,
                           local, W_LOCAL, 0, 1, (char *) NULL, NULL, 1,
			   verify_create, NULL);

    if (removed_files && !really_quiet)
		error (0, 0, "use '%s commit' to remove %s permanently", program_name,
	       (removed_files == 1) ? "this file" : "these files");

    if (existing_files)
	{
		error (0, 0,
	       ((existing_files == 1) ? "%d file exists; remove it first" :	"%d files exist; remove them first"),
	       existing_files);
		err=1;
	}

	if(bad_files)
		err=1;

    return (err);
}
Пример #14
0
int main(int argc, char *argv[])
{
	int dev_from_class = 0, write_cnt;
	int fd;
	static struct sysfs_names *names;
	struct rc_device	  rc_dev;

	argp_parse(&argp, argc, argv, 0, 0, 0);

	/* Just list all devices */
	if (!clear && !readtable && !keys.next && !ch_proto && !cfg.next && !test && !delay && !period) {
		if (devicename) {
			fd = open(devicename, O_RDONLY);
			if (fd < 0) {
				perror("Can't open device");
				return -1;
			}
			device_info(fd, "");
			close(fd);
			return 0;
		}
		if (show_sysfs_attribs(&rc_dev))
			return -1;

		return 0;
	}

	if (cfg.next && (clear || keys.next || ch_proto || devicename)) {
		fprintf (stderr, "Auto-mode can be used only with --read, --debug and --sysdev options\n");
		return -1;
	}
	if (!devicename) {
		names = find_device(devclass);
		if (!names)
			return -1;
		rc_dev.sysfs_name = names->name;
		if (get_attribs(&rc_dev, names->name)) {
			free_names(names);
			return -1;
		}
		names->name = NULL;
		free_names(names);

		devicename = rc_dev.input_name;
		dev_from_class++;
	}

	if (cfg.next) {
		struct cfgfile *cur;
		char *fname, *name;
		int rc;

		for (cur = &cfg; cur->next; cur = cur->next) {
			if ((!rc_dev.drv_name || strcasecmp(cur->driver, rc_dev.drv_name)) && strcasecmp(cur->driver, "*"))
				continue;
			if ((!rc_dev.keytable_name || strcasecmp(cur->table, rc_dev.keytable_name)) && strcasecmp(cur->table, "*"))
				continue;
			break;
		}

		if (!cur->next) {
			if (debug)
				fprintf(stderr, "Table for %s, %s not found. Keep as-is\n",
				       rc_dev.drv_name, rc_dev.keytable_name);
			return 0;
		}
		if (debug)
			fprintf(stderr, "Table for %s, %s is on %s file.\n",
				rc_dev.drv_name, rc_dev.keytable_name,
				cur->fname);
		if (cur->fname[0] == '/' || ((cur->fname[0] == '.') && strchr(cur->fname, '/'))) {
			fname = cur->fname;
			rc = parse_keyfile(fname, &name);
			if (rc < 0) {
				fprintf(stderr, "Can't load %s table\n", fname);
				return -1;
			}
		} else {
			fname = malloc(strlen(cur->fname) + strlen(IR_KEYTABLE_USER_DIR) + 2);
			strcpy(fname, IR_KEYTABLE_USER_DIR);
			strcat(fname, "/");
			strcat(fname, cur->fname);
			rc = parse_keyfile(fname, &name);
			if (rc != 0) {
				fname = malloc(strlen(cur->fname) + strlen(IR_KEYTABLE_SYSTEM_DIR) + 2);
				strcpy(fname, IR_KEYTABLE_SYSTEM_DIR);
				strcat(fname, "/");
				strcat(fname, cur->fname);
				rc = parse_keyfile(fname, &name);
			}
			if (rc != 0) {
				fprintf(stderr, "Can't load %s table from %s or %s\n", cur->fname, IR_KEYTABLE_USER_DIR, IR_KEYTABLE_SYSTEM_DIR);
				return -1;
			}
		}
		if (!keys.next) {
			fprintf(stderr, "Empty table %s\n", fname);
			return -1;
		}
		clear = 1;
	}

	if (debug)
		fprintf(stderr, "Opening %s\n", devicename);
	fd = open(devicename, O_RDONLY);
	if (fd < 0) {
		perror(devicename);
		return -1;
	}
	if (dev_from_class)
		free(devicename);
	if (get_input_protocol_version(fd))
		return -1;

	/*
	 * First step: clear, if --clear is specified
	 */
	if (clear) {
		clear_table(fd);
		fprintf(stderr, "Old keytable cleared\n");
	}

	/*
	 * Second step: stores key tables from file or from commandline
	 */
	write_cnt = add_keys(fd);
	if (write_cnt)
		fprintf(stderr, "Wrote %d keycode(s) to driver\n", write_cnt);

	/*
	 * Third step: change protocol
	 */
	if (ch_proto) {
		rc_dev.current = ch_proto;
		if (set_proto(&rc_dev))
			fprintf(stderr, "Couldn't change the IR protocols\n");
		else {
			fprintf(stderr, "Protocols changed to ");
			show_proto(rc_dev.current);
			fprintf(stderr, "\n");
		}
	}

	/*
	 * Fourth step: display current keytable
	 */
	if (readtable)
		display_table(&rc_dev, fd);

	/*
	 * Fiveth step: change repeat rate/delay
	 */
	if (delay || period) {
		unsigned int new_delay, new_period;
		get_rate(fd, &new_delay, &new_period);
		if (delay)
			new_delay = delay;
		if (period)
			new_period = period;
		set_rate(fd, new_delay, new_period);
	}

	if (test)
		test_event(fd);

	return 0;
}
Пример #15
0
/* Start a recursive command.

   Command line arguments (ARGC, ARGV) dictate the directories and
   files on which we operate.  In the special case of no arguments, we
   default to ".".  */
int start_recursion (FILEPROC fileproc, FILESDONEPROC filesdoneproc,
    PREDIRENTPROC predirentproc, DIRENTPROC direntproc, DIRLEAVEPROC dirleaveproc,
    void *callerdat,

    int argc,
    char **argv,
    int local,

    /* This specifies the kind of recursion.  There are several cases:

       1.  W_LOCAL is not set but W_REPOS is.  The current
       directory when we are called must be the repository and
       recursion proceeds according to what exists in the repository.

       2a.  W_LOCAL is set but W_REPOS is not.  The
       current directory when we are called must be the working
       directory.  Recursion proceeds according to what exists in the
       working directory, never (I think) consulting any part of the
       repository which does not correspond to the working directory
       ("correspond" == Name_Repository).

       2b.  W_LOCAL is set and so is W_REPOS.  This is the
       weird one.  The current directory when we are called must be
       the working directory.  We recurse through working directories,
       but we recurse into a directory if it is exists in the working
       directory *or* it exists in the repository.  If a directory
       does not exist in the working directory, the direntproc must
       either tell us to skip it (R_SKIP_ALL), or must create it (I
       think those are the only two cases).  */
    int which,

    int aflag,
    int readlock,
    const char *update_preload,
	const char *repos_preload,
    int dosrcs,
    PERMPROC permproc,
    const char *tag)
{
    int i, err = 0;
    List *args_to_send_when_finished = NULL;
    List *files_by_dir = NULL;
    struct recursion_frame frame;

	TRACE(3,"start_recursion()");	

    frame.fileproc = fileproc;
    frame.filesdoneproc = filesdoneproc;
	frame.predirentproc = predirentproc;
    frame.direntproc = direntproc;
    frame.dirleaveproc = dirleaveproc;
    frame.callerdat = callerdat;
    frame.flags = local ? R_SKIP_DIRS : R_PROCESS;
    frame.which = which;
    frame.aflag = aflag;
    frame.readlock = readlock;
    frame.dosrcs = dosrcs;
    frame.permproc = permproc;
    frame.tag = tag;

    expand_wild (argc, argv, &argc, &argv);

    if (update_preload == NULL)
	update_dir = xstrdup ("");
    else
	update_dir = xstrdup (update_preload);

    /* clean up from any previous calls to start_recursion */
	xfree (repository);
    if (filelist)
	dellist (&filelist); /* FIXME-krp: no longer correct. */
    if (dirlist)
	dellist (&dirlist);

	update_repos = xstrdup(repos_preload);

	for (i = 0; i < argc; ++i)
	{
#ifdef SERVER_SUPPORT
	    if (server_active)
		    server_pathname_check (argv[i]);
		else
#endif
			if(isabsolute(argv[i]))
				error(1,0,"Absolute filenames not allowed");
    }

    if (argc == 0)
    {
	int just_subdirs = (which & W_LOCAL) && !noexec && !isdir (CVSADM);

	if (!just_subdirs
	    && CVSroot_cmdline == NULL
	    && current_parsed_root->isremote)
	{
	    char *root = Name_Root (NULL, update_dir);
	    if (root && strcmp (root, current_parsed_root->original) != 0)
		/* We're skipping this directory because it is for
		   a different root.  Therefore, we just want to
		   do the subdirectories only.  Processing files would
		   cause a working directory from one repository to be
		   processed against a different repository, which could
		   cause all kinds of spurious conflicts and such.

		   Question: what about the case of "cvs update foo"
		   where we process foo/bar and not foo itself?  That
		   seems to be handled somewhere (else) but why should
		   it be a separate case?  Needs investigation...  */
		just_subdirs = 1;
	    xfree (root);
	}

	/*
	 * There were no arguments, so we'll probably just recurse. The
	 * exception to the rule is when we are called from a directory
	 * without any CVS administration files.  That has always meant to
	 * process each of the sub-directories, so we pretend like we were
	 * called with the list of sub-dirs of the current dir as args
	 */
	if (just_subdirs)
	{
	    dirlist = Find_Directories ((char *) NULL, W_LOCAL, (List *) NULL, NULL);
	    /* If there are no sub-directories, there is a certain logic in
	       favor of doing nothing, but in fact probably the user is just
	       confused about what directory they are in, or whether they
	       cvs add'd a new directory.  In the case of at least one
	       sub-directory, at least when we recurse into them we
	       notice (hopefully) whether they are under CVS control.  */
	    if (list_isempty (dirlist) && !noexec)
	    {
		if (update_dir[0] == '\0')
		    error (0, 0, "in directory .:");
		else
		    error (0, 0, "in directory %s:", update_dir);
		error (1, 0,
		       "there is no version here; run '%s checkout' first",
		       program_name);
	    }
	    else if (current_parsed_root->isremote && server_started)
	    {
		/* In the the case "cvs update foo bar baz", a call to
		   send_file_names in update.c will have sent the
		   appropriate "Argument" commands to the server.  In
		   this case, that won't have happened, so we need to
		   do it here.  While this example uses "update", this
		   generalizes to other commands.  */

		/* This is the same call to Find_Directories as above.
                   FIXME: perhaps it would be better to write a
                   function that duplicates a list. */
		args_to_send_when_finished = Find_Directories ((char *) NULL,
							       W_LOCAL,
							       (List *) NULL, NULL);
	    }
	}
	else
	{
	    addlist (&dirlist, ".");
	}

	goto do_the_work;
    }


    /*
     * There were arguments, so we have to handle them by hand. To do
     * that, we set up the filelist and dirlist with the arguments and
     * call do_recursion.  do_recursion recognizes the fact that the
     * lists are non-null when it starts and doesn't update them.
     *
     * explicitly named directories are stored in dirlist.
     * explicitly named files are stored in filelist.
     * other possibility is named entities whicha are not currently in
     * the working directory.
     */
    
    for (i = 0; i < argc; i++)
    {
	/* if this argument is a directory, then add it to the list of
	   directories. */

	if (isdir (argv[i]))
	{
	    strip_trailing_slashes (argv[i]);
	    addlist (&dirlist, argv[i]);
	}
	else
	{
	    /* otherwise, split argument into directory and component names. */
	    char *dir;
	    char *comp;
	    char *file_to_try;

	    /* Now break out argv[i] into directory part (DIR) and file part (COMP).
		   DIR and COMP will each point to a newly malloc'd string.  */
	    dir = xstrdup (argv[i]);
	    comp = (char*)last_component (dir);
	    if (comp == dir)
	    {
		/* no dir component.  What we have is an implied "./" */
		dir = xstrdup(".");
	    }
	    else
	    {
		char *p = comp;

		p[-1] = '\0';
		comp = xstrdup (p);
	    }

	    /* if this argument exists as a file in the current
	       working directory tree, then add it to the files list.  */

	    if (!(which & W_LOCAL))
	    {
		/* If doing rtag, we've done a chdir to the repository. */
		file_to_try = (char*)xmalloc (strlen (argv[i]) + sizeof (RCSEXT) + 5);
		sprintf (file_to_try, "%s%s", argv[i], RCSEXT);
	    }
	    else
		file_to_try = xstrdup (argv[i]);

	    if (isfile (file_to_try))
	    {
			const char *tag;
			const char *date;
			int nonbranch;
			const char *message;
			const char *v_type;
			/* before we do anything else, see if we have any
			   per-directory tags */

			ParseTag_Dir (dir, &tag, &date, &nonbranch, NULL);
			
	        if (! verify_access (frame.permproc, dir, file_to_try, update_dir,tag,&message,&v_type))
			{
				if(tag && !quiet && !(which&W_QUIET))
					error (0, 0, "User %s is unable to %s %s/%s on branch/tag %s - ignoring",CVS_Username,v_type,dir,file_to_try?file_to_try:"",tag);
				else if(!quiet && !(which&W_QUIET))
					error (0, 0, "User %s is unable to %s %s/%s - ignoring",CVS_Username,v_type,dir,file_to_try?file_to_try:"");
				if(message && !quiet && !(which&W_QUIET))
					error (0, 0, "%s", message);
			}
			else
		{
		   addfile (&files_by_dir, dir, comp);
		}
	    }
	    else if (isdir (dir))
	    {
		if ((which & W_LOCAL) && isdir (CVSADM)
		    && !current_parsed_root->isremote
		    )
		{
		    /* otherwise, look for it in the repository. */
		    char *tmp_update_dir;
		    char *repos;
		    char *reposfile;

		    tmp_update_dir = (char*)xmalloc (strlen (update_dir)
					      + strlen (dir)
					      + 5);
		    strcpy (tmp_update_dir, update_dir);

		    if (*tmp_update_dir != '\0')
			(void) strcat (tmp_update_dir, "/");

		    (void) strcat (tmp_update_dir, dir);

		    /* look for it in the repository. */
		    repos = Name_Repository (dir, tmp_update_dir);
		    reposfile = (char*)xmalloc (strlen (repos)
					 + strlen (comp)
					 + 5);
		    (void) sprintf (reposfile, "%s/%s", repos, comp);
		    xfree (repos);

		    if (isdir (reposfile))
			{
			addlist (&dirlist, argv[i]);
			}
		    else
			addfile (&files_by_dir, dir, comp);

		    xfree (tmp_update_dir);
		    xfree (reposfile);
		}
		else
		    addfile (&files_by_dir, dir, comp);
	    }
	    else
		{
			error (1, 0, "no such directory `%s'", dir);
		}

	    xfree (file_to_try);
	    xfree (dir);
	    xfree (comp);
	}
    }

    /* At this point we have looped over all named arguments and built
       a coupla lists.  Now we unroll the lists, setting up and
       calling do_recursion. */

    err += walklist (files_by_dir, unroll_files_proc, (void *) &frame);
    if (files_by_dir)
    dellist(&files_by_dir);

    /* then do_recursion on the dirlist. */
    if (dirlist != NULL)
    {
    do_the_work:
	err += do_recursion (&frame, 1);
    }
	
    /* Free the data which expand_wild allocated.  */
    free_names (&argc, argv);

    xfree (update_dir);
	xfree (update_repos);

    if (args_to_send_when_finished != NULL)
    {
	/* FIXME (njc): in the multiroot case, we don't want to send
	   argument commands for those top-level directories which do
	   not contain any subdirectories which have files checked out
	   from current_parsed_root->original.  If we do, and two repositories
	   have a module with the same name, nasty things could happen.

	   This is hard.  Perhaps we should send the Argument commands
	   later in this procedure, after we've had a chance to notice
	   which directores we're using (after do_recursion has been
	   called once).  This means a _lot_ of rewriting, however.

	   What we need to do for that to happen is descend the tree
	   and construct a list of directories which are checked out
	   from current_cvsroot.  Now, we eliminate from the list all
	   of those directories which are immediate subdirectories of
	   another directory in the list.  To say that the opposite
	   way, we keep the directories which are not immediate
	   subdirectories of any other in the list.  Here's a picture:

			      a
			     / \
			    B   C
			   / \
			  D   e
			     / \
			    F   G
			       / \
			      H   I

	   The node in capitals are those directories which are
	   checked out from current_cvsroot.  We want the list to
	   contain B, C, F, and G.  D, H, and I are not included,
	   because their parents are also checked out from
	   current_cvsroot.

	   The algorithm should be:
		   
	   1) construct a tree of all directory names where each
	   element contains a directory name and a flag which notes if
	   that directory is checked out from current_cvsroot

			      a0
			     / \
			    B1  C1
			   / \
			  D1  e0
			     / \
			    F1  G1
			       / \
			      H1  I1

	   2) Recursively descend the tree.  For each node, recurse
	   before processing the node.  If the flag is zero, do
	   nothing.  If the flag is 1, check the node's parent.  If
	   the parent's flag is one, change the current entry's flag
	   to zero.

			      a0
			     / \
			    B1  C1
			   / \
			  D0  e0
			     / \
			    F1  G1
			       / \
			      H0  I0

	   3) Walk the tree and spit out "Argument" commands to tell
	   the server which directories to munge.
		   
	   Yuck.  It's not clear this is worth spending time on, since
	   we might want to disable cvs commands entirely from
	   directories that do not have CVSADM files...

	   Anyways, the solution as it stands has modified server.c
	   (dirswitch) to create admin files [via server.c
	   (create_adm_p)] in all path elements for a client's
	   "Directory xxx" command, which forces the server to descend
	   and serve the files there.  client.c (send_file_names) has
	   also been modified to send only those arguments which are
	   appropriate to current_parsed_root->original.

	*/
		
	/* Construct a fake argc/argv pair. */
		
	int our_argc = 0, i;
	char **our_argv = NULL;

	if (! list_isempty (args_to_send_when_finished))
	{
	    Node *head, *p;

	    head = args_to_send_when_finished->list;

	    /* count the number of nodes */
	    i = 0;
	    for (p = head->next; p != head; p = p->next)
		i++;
	    our_argc = i;

	    /* create the argument vector */
	    our_argv = (char **) xmalloc (sizeof (char *) * our_argc);

	    /* populate it */
	    i = 0;
	    for (p = head->next; p != head; p = p->next)
		our_argv[i++] = xstrdup (p->key);
	}

	/* We don't want to expand widcards, since we've just created
	   a list of directories directly from the filesystem. */
	send_file_names (our_argc, our_argv, 0);

	/* Free our argc/argv. */
	if (our_argv != NULL)
	{
	    for (i = 0; i < our_argc; i++)
		xfree (our_argv[i]);
	    xfree (our_argv);
	}

	if (args_to_send_when_finished)
	dellist (&args_to_send_when_finished);
    }
    
    return (err);
}
Пример #16
0
static int
diskset_info(mdsetname_t *sp)
{
	md_error_t		error = *mdl_mdnullerror;
	md_replicalist_t	*replica_list = NULL;
	mdnamelist_t		*trans_list = NULL;
	mdnamelist_t		*raid_list = NULL;
	mdnamelist_t		*stripe_list = NULL;
	mdnamelist_t		*sp_list = NULL;
	mdnamelist_t		*spare_list = NULL;

	if ((mdl_metareplicalist)(sp, MD_BASICNAME_OK, &replica_list, &error)
	    >= 0) {
	    md_replicalist_t	*nlp;

	    for (nlp = replica_list; nlp != NULL; nlp = nlp->rl_next) {
		if (new_entry(nlp->rl_repp->r_namep->bname, "mdb",
		    nlp->rl_repp->r_namep->cname, sp)) {
		    (mdl_metafreereplicalist)(replica_list);
		    return (ENOMEM);
		}
	    }
	    (mdl_metafreereplicalist)(replica_list);

	} else {
	    (mdl_mdclrerror)(&error);
	    /* there are no metadb's; that is ok, no need to check the rest */
	    return (0);
	}
	(mdl_mdclrerror)(&error);

	if ((mdl_meta_get_trans_names)(sp, &trans_list, 0, &error) >= 0) {
	    mdnamelist_t *nlp;

	    for (nlp = trans_list; nlp != NULL; nlp = nlp->next) {
		if (new_entry(nlp->namep->bname, "trans", nlp->namep->cname,
		    sp)) {
		    free_names(trans_list);
		    return (ENOMEM);
		}
	    }

	    free_names(trans_list);
	}
	(mdl_mdclrerror)(&error);

	if ((mdl_meta_get_raid_names)(sp, &raid_list, 0, &error) >= 0) {
	    mdnamelist_t *nlp;

	    for (nlp = raid_list; nlp != NULL; nlp = nlp->next) {
		mdname_t	*mdn;
		md_raid_t	*raid;

		mdn = (mdl_metaname)(&sp, nlp->namep->cname,
		    META_DEVICE, &error);
		(mdl_mdclrerror)(&error);
		if (mdn == NULL) {
		    continue;
		}

		raid = (mdl_meta_get_raid)(sp, mdn, &error);
		(mdl_mdclrerror)(&error);

		if (raid != NULL) {
		    int i;

		    for (i = 0; i < raid->cols.cols_len; i++) {
			if (new_entry(raid->cols.cols_val[i].colnamep->bname,
			    "raid", nlp->namep->cname, sp)) {
			    free_names(raid_list);
			    return (ENOMEM);
			}
		    }
		}
	    }

	    free_names(raid_list);
	}
	(mdl_mdclrerror)(&error);

	if ((mdl_meta_get_stripe_names)(sp, &stripe_list, 0, &error) >= 0) {
	    mdnamelist_t *nlp;

	    for (nlp = stripe_list; nlp != NULL; nlp = nlp->next) {
		mdname_t	*mdn;
		md_stripe_t	*stripe;

		mdn = (mdl_metaname)(&sp, nlp->namep->cname,
		    META_DEVICE, &error);
		(mdl_mdclrerror)(&error);
		if (mdn == NULL) {
		    continue;
		}

		stripe = (mdl_meta_get_stripe)(sp, mdn, &error);
		(mdl_mdclrerror)(&error);

		if (stripe != NULL) {
		    int i;

		    for (i = 0; i < stripe->rows.rows_len; i++) {
			md_row_t	*rowp;
			int		j;

			rowp = &stripe->rows.rows_val[i];

			for (j = 0; j < rowp->comps.comps_len; j++) {
			    md_comp_t	*component;

			    component = &rowp->comps.comps_val[j];
			    if (new_entry(component->compnamep->bname, "stripe",
				nlp->namep->cname, sp)) {
				free_names(stripe_list);
				return (ENOMEM);
			    }
			}
		    }
		}
	    }

	    free_names(stripe_list);
	}
	(mdl_mdclrerror)(&error);

	if ((mdl_meta_get_sp_names)(sp, &sp_list, 0, &error) >= 0) {
	    mdnamelist_t *nlp;

	    for (nlp = sp_list; nlp != NULL; nlp = nlp->next) {
		mdname_t	*mdn;
		md_sp_t		*soft_part;

		mdn = (mdl_metaname)(&sp, nlp->namep->cname,
		    META_DEVICE, &error);
		(mdl_mdclrerror)(&error);
		if (mdn == NULL) {
		    continue;
		}

		soft_part = (mdl_meta_get_sp)(sp, mdn, &error);
		(mdl_mdclrerror)(&error);

		if (soft_part != NULL) {
		    if (new_entry(soft_part->compnamep->bname, "sp",
			nlp->namep->cname, sp)) {
			free_names(sp_list);
			return (ENOMEM);
		    }
		}
	    }

	    free_names(sp_list);
	}
	(mdl_mdclrerror)(&error);

	if ((mdl_meta_get_hotspare_names)(sp, &spare_list, 0, &error) >= 0) {
	    mdnamelist_t *nlp;

	    for (nlp = spare_list; nlp != NULL; nlp = nlp->next) {
		if (new_entry(nlp->namep->bname, "hs", nlp->namep->cname, sp)) {
		    free_names(spare_list);
		    return (ENOMEM);
		}
	    }

	    free_names(spare_list);
	}

	(mdl_mdclrerror)(&error);

	return (0);
}
Пример #17
0
int main2(int argc, char **argv) {
#endif
    char *priority = NULL;

    if(!detach())
        return 1;

#ifdef HAVE_MLOCKALL
    /* Lock all pages into memory if requested.
     * This has to be done after daemon()/fork() so it works for child.
     * No need to do that in parent as it's very short-lived. */
    if(do_mlock && mlockall(MCL_CURRENT | MCL_FUTURE) != 0) {
        logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "mlockall",
               strerror(errno));
        return 1;
    }
#endif

    /* Setup sockets and open device. */

    if(!setup_network())
        goto end;

    /* Change process priority */

    if(get_config_string(lookup_config(config_tree, "ProcessPriority"), &priority)) {
        if(!strcasecmp(priority, "Normal")) {
            if (setpriority(NORMAL_PRIORITY_CLASS) != 0) {
                logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
                goto end;
            }
        } else if(!strcasecmp(priority, "Low")) {
            if (setpriority(BELOW_NORMAL_PRIORITY_CLASS) != 0) {
                logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
                goto end;
            }
        } else if(!strcasecmp(priority, "High")) {
            if (setpriority(HIGH_PRIORITY_CLASS) != 0) {
                logger(DEBUG_ALWAYS, LOG_ERR, "System call `%s' failed: %s", "setpriority", strerror(errno));
                goto end;
            }
        } else {
            logger(DEBUG_ALWAYS, LOG_ERR, "Invalid priority `%s`!", priority);
            goto end;
        }
    }

    /* drop privileges */
    if (!drop_privs())
        goto end;

    /* Start main loop. It only exits when tinc is killed. */

    logger(DEBUG_ALWAYS, LOG_NOTICE, "Ready");

    if(umbilical) { // snip!
        write(umbilical, "", 1);
        close(umbilical);
        umbilical = 0;
    }

    try_outgoing_connections();

    status = main_loop();

    /* Shutdown properly. */

end:
    close_network_connections();

    logger(DEBUG_ALWAYS, LOG_NOTICE, "Terminating");

    free(priority);

    crypto_exit();

    exit_configuration(&config_tree);
    free(cmdline_conf);
    free_names();

    return status;
}
Пример #18
0
static int get_attribs(struct rc_device *rc_dev, char *sysfs_name)
{
	struct uevents  *uevent;
	char		*input = "input", *event = "event";
	char		*DEV = "/dev/";
	static struct sysfs_names *input_names, *event_names, *attribs, *cur;

	/* Clean the attributes */
	memset(rc_dev, 0, sizeof(*rc_dev));

	rc_dev->sysfs_name = sysfs_name;

	input_names = seek_sysfs_dir(rc_dev->sysfs_name, input);
	if (!input_names)
		return EINVAL;
	if (input_names->next->next) {
		fprintf(stderr, "Found more than one input interface."
				"This is currently unsupported\n");
		return EINVAL;
	}
	if (debug)
		fprintf(stderr, "Input sysfs node is %s\n", input_names->name);

	event_names = seek_sysfs_dir(input_names->name, event);
	free_names(input_names);
	if (!event_names) {
		free_names(event_names);
		return EINVAL;
	}
	if (event_names->next->next) {
		free_names(event_names);
		fprintf(stderr, "Found more than one event interface."
				"This is currently unsupported\n");
		return EINVAL;
	}
	if (debug)
		fprintf(stderr, "Event sysfs node is %s\n", event_names->name);

	uevent = read_sysfs_uevents(event_names->name);
	free_names(event_names);
	if (!uevent)
		return EINVAL;

	while (uevent->next) {
		if (!strcmp(uevent->key, "DEVNAME")) {
			rc_dev->input_name = malloc(strlen(uevent->value) + strlen(DEV) + 1);
			strcpy(rc_dev->input_name, DEV);
			strcat(rc_dev->input_name, uevent->value);
			break;
		}
		uevent = uevent->next;
	}
	free_uevent(uevent);

	if (!rc_dev->input_name) {
		fprintf(stderr, "Input device name not found.\n");
		return EINVAL;
	}

	uevent = read_sysfs_uevents(rc_dev->sysfs_name);
	if (!uevent)
		return EINVAL;
	while (uevent->next) {
		if (!strcmp(uevent->key, "DRV_NAME")) {
			rc_dev->drv_name = malloc(strlen(uevent->value) + 1);
			strcpy(rc_dev->drv_name, uevent->value);
		}
		if (!strcmp(uevent->key, "NAME")) {
			rc_dev->keytable_name = malloc(strlen(uevent->value) + 1);
			strcpy(rc_dev->keytable_name, uevent->value);
		}
		uevent = uevent->next;
	}
	free_uevent(uevent);

	if (debug)
		fprintf(stderr, "input device is %s\n", rc_dev->input_name);

	sysfs++;

	rc_dev->type = SOFTWARE_DECODER;

	/* Get the other attribs - basically IR decoders */
	attribs = seek_sysfs_dir(rc_dev->sysfs_name, NULL);
	for (cur = attribs; cur->next; cur = cur->next) {
		if (!cur->name)
			continue;
		if (strstr(cur->name, "/protocols")) {
			rc_dev->version = VERSION_2;
			rc_dev->type = UNKNOWN_TYPE;
			v2_get_protocols(rc_dev, cur->name);
		} else if (strstr(cur->name, "/protocol")) {
			rc_dev->version = VERSION_1;
			rc_dev->type = HARDWARE_DECODER;
			rc_dev->current = v1_get_hw_protocols(cur->name);
		} else if (strstr(cur->name, "/supported_protocols")) {
			rc_dev->version = VERSION_1;
			rc_dev->supported = v1_get_hw_protocols(cur->name);
		} else if (strstr(cur->name, "/nec_decoder")) {
			rc_dev->supported |= NEC;
			if (v1_get_sw_enabled_protocol(cur->name))
				rc_dev->current |= NEC;
		} else if (strstr(cur->name, "/rc5_decoder")) {
			rc_dev->supported |= RC_5;
			if (v1_get_sw_enabled_protocol(cur->name))
				rc_dev->current |= RC_5;
		} else if (strstr(cur->name, "/rc6_decoder")) {
			rc_dev->supported |= RC_6;
			if (v1_get_sw_enabled_protocol(cur->name))
				rc_dev->current |= RC_6;
		} else if (strstr(cur->name, "/jvc_decoder")) {
			rc_dev->supported |= JVC;
			if (v1_get_sw_enabled_protocol(cur->name))
				rc_dev->current |= JVC;
		} else if (strstr(cur->name, "/sony_decoder")) {
			rc_dev->supported |= SONY;
			if (v1_get_sw_enabled_protocol(cur->name))
				rc_dev->current |= SONY;
		} else if (strstr(cur->name, "/xmp_decoder")) {
			rc_dev->supported |= XMP;
			if (v1_get_sw_enabled_protocol(cur->name))
				rc_dev->current |= XMP;
		}
	}

	return 0;
}
Пример #19
0
/*
 * This is the recursive function that processes a module name.
 * It calls back the passed routine for each directory of a module
 * It runs the post checkout or post tag proc from the modules file
 */
int
my_module (DBM *db, char *mname, enum mtype m_type, char *msg,
            CALLBACKPROC callback_proc, char *where, int shorten,
            int local_specified, int run_module_prog, int build_dirs,
            char *extra_arg, List *stack)
{
    char *checkout_prog = NULL;
    char *export_prog = NULL;
    char *tag_prog = NULL;
    struct saved_cwd cwd;
    int cwd_saved = 0;
    char *line;
    int modargc;
    int xmodargc;
    char **modargv = NULL;
    char **xmodargv = NULL;
    /* Found entry from modules file, including options and such.  */
    char *value = NULL;
    char *mwhere = NULL;
    char *mfile = NULL;
    char *spec_opt = NULL;
    char *xvalue = NULL;
    int alias = 0;
    datum key, val;
    char *cp;
    int c, err = 0;
    int nonalias_opt = 0;

#ifdef SERVER_SUPPORT
    int restore_server_dir = 0;
    char *server_dir_to_restore = NULL;
#endif

    TRACE (TRACE_FUNCTION, "my_module (%s, %s, %s, %s)",
           mname ? mname : "(null)", msg ? msg : "(null)",
           where ? where : "NULL", extra_arg ? extra_arg : "NULL");

    /* Don't process absolute directories.  Anything else could be a security
     * problem.  Before this check was put in place:
     *
     *   $ cvs -d:fork:/cvsroot co /foo
     *   cvs server: warning: cannot make directory CVS in /: Permission denied
     *   cvs [server aborted]: cannot make directory /foo: Permission denied
     *   $
     */
    if (ISABSOLUTE (mname))
	error (1, 0, "Absolute module reference invalid: `%s'", mname);

    /* Similarly for directories that attempt to step above the root of the
     * repository.
     */
    if (pathname_levels (mname) > 0)
	error (1, 0, "up-level in module reference (`..') invalid: `%s'.",
               mname);

    /* if this is a directory to ignore, add it to that list */
    if (mname[0] == '!' && mname[1] != '\0')
    {
	ign_dir_add (mname+1);
	goto do_module_return;
    }

    /* strip extra stuff from the module name */
    strip_trailing_slashes (mname);

    /*
     * Look up the module using the following scheme:
     *	1) look for mname as a module name
     *	2) look for mname as a directory
     *	3) look for mname as a file
     *  4) take mname up to the first slash and look it up as a module name
     *	   (this is for checking out only part of a module)
     */

    /* look it up as a module name */
    key.dptr = mname;
    key.dsize = strlen (key.dptr);
    if (db != NULL)
	val = dbm_fetch (db, key);
    else
	val.dptr = NULL;
    if (val.dptr != NULL)
    {
	/* copy and null terminate the value */
	value = xmalloc (val.dsize + 1);
	memcpy (value, val.dptr, val.dsize);
	value[val.dsize] = '\0';

	/* If the line ends in a comment, strip it off */
	if ((cp = strchr (value, '#')) != NULL)
	    *cp = '\0';
	else
	    cp = value + val.dsize;

	/* Always strip trailing spaces */
	while (cp > value && isspace ((unsigned char) *--cp))
	    *cp = '\0';

	mwhere = xstrdup (mname);
	goto found;
    }
    else
    {
	char *file;
	char *attic_file;
	char *acp;
	int is_found = 0;

	/* check to see if mname is a directory or file */
	file = xmalloc (strlen (current_parsed_root->directory)
			+ strlen (mname) + sizeof(RCSEXT) + 2);
	(void) sprintf (file, "%s/%s", current_parsed_root->directory, mname);
	attic_file = xmalloc (strlen (current_parsed_root->directory)
			      + strlen (mname)
			      + sizeof (CVSATTIC) + sizeof (RCSEXT) + 3);
	if ((acp = strrchr (mname, '/')) != NULL)
	{
	    *acp = '\0';
	    (void) sprintf (attic_file, "%s/%s/%s/%s%s", current_parsed_root->directory,
			    mname, CVSATTIC, acp + 1, RCSEXT);
	    *acp = '/';
	}
	else
	    (void) sprintf (attic_file, "%s/%s/%s%s",
	                    current_parsed_root->directory,
			    CVSATTIC, mname, RCSEXT);

	if (isdir (file))
	{
	    modargv = xmalloc (sizeof (*modargv));
	    modargv[0] = xstrdup (mname);
	    modargc = 1;
	    is_found = 1;
	}
	else
	{
	    (void) strcat (file, RCSEXT);
	    if (isfile (file) || isfile (attic_file))
	    {
		/* if mname was a file, we have to split it into "dir file" */
		if ((cp = strrchr (mname, '/')) != NULL && cp != mname)
		{
		    modargv = xnmalloc (2, sizeof (*modargv));
		    modargv[0] = xmalloc (strlen (mname) + 2);
		    strncpy (modargv[0], mname, cp - mname);
		    modargv[0][cp - mname] = '\0';
		    modargv[1] = xstrdup (cp + 1);
		    modargc = 2;
		}
		else
		{
		    /*
		     * the only '/' at the beginning or no '/' at all
		     * means the file we are interested in is in CVSROOT
		     * itself so the directory should be '.'
		     */
		    if (cp == mname)
		    {
			/* drop the leading / if specified */
			modargv = xnmalloc (2, sizeof (*modargv));
			modargv[0] = xstrdup (".");
			modargv[1] = xstrdup (mname + 1);
			modargc = 2;
		    }
		    else
		    {
			/* otherwise just copy it */
			modargv = xnmalloc (2, sizeof (*modargv));
			modargv[0] = xstrdup (".");
			modargv[1] = xstrdup (mname);
			modargc = 2;
		    }
		}
		is_found = 1;
	    }
	}
	free (attic_file);
	free (file);

	if (is_found)
	{
	    assert (value == NULL);

	    /* OK, we have now set up modargv with the actual
	       file/directory we want to work on.  We duplicate a
	       small amount of code here because the vast majority of
	       the code after the "found" label does not pertain to
	       the case where we found a file/directory rather than
	       finding an entry in the modules file.  */
	    if (save_cwd (&cwd))
		error (1, errno, "Failed to save current directory.");
	    cwd_saved = 1;

	    err += callback_proc (modargc, modargv, where, mwhere, mfile,
				  shorten,
				  local_specified, mname, msg);

	    free_names (&modargc, modargv);

	    /* cd back to where we started.  */
	    if (restore_cwd (&cwd))
		error (1, errno, "Failed to restore current directory, `%s'.",
		       cwd.name);
	    free_cwd (&cwd);
	    cwd_saved = 0;

	    goto do_module_return;
	}
    }

    /* look up everything to the first / as a module */
    if (mname[0] != '/' && (cp = strchr (mname, '/')) != NULL)
    {
	/* Make the slash the new end of the string temporarily */
	*cp = '\0';
	key.dptr = mname;
	key.dsize = strlen (key.dptr);

	/* do the lookup */
	if (db != NULL)
	    val = dbm_fetch (db, key);
	else
	    val.dptr = NULL;

	/* if we found it, clean up the value and life is good */
	if (val.dptr != NULL)
	{
	    char *cp2;

	    /* copy and null terminate the value */
	    value = xmalloc (val.dsize + 1);
	    memcpy (value, val.dptr, val.dsize);
	    value[val.dsize] = '\0';

	    /* If the line ends in a comment, strip it off */
	    if ((cp2 = strchr (value, '#')) != NULL)
		*cp2 = '\0';
	    else
		cp2 = value + val.dsize;

	    /* Always strip trailing spaces */
	    while (cp2 > value  &&  isspace ((unsigned char) *--cp2))
		*cp2 = '\0';

	    /* mwhere gets just the module name */
	    mwhere = xstrdup (mname);
	    mfile = cp + 1;
	    assert (strlen (mfile));

	    /* put the / back in mname */
	    *cp = '/';

	    goto found;
	}

	/* put the / back in mname */
	*cp = '/';
    }

    /* if we got here, we couldn't find it using our search, so give up */
    error (0, 0, "cannot find module `%s' - ignored", mname);
    err++;
    goto do_module_return;


    /*
     * At this point, we found what we were looking for in one
     * of the many different forms.
     */
  found:

    /* remember where we start */
    if (save_cwd (&cwd))
	error (1, errno, "Failed to save current directory.");
    cwd_saved = 1;

    assert (value != NULL);

    /* search the value for the special delimiter and save for later */
    if ((cp = strchr (value, CVSMODULE_SPEC)) != NULL)
    {
	*cp = '\0';			/* null out the special char */
	spec_opt = cp + 1;		/* save the options for later */

	/* strip whitespace if necessary */
	while (cp > value  &&  isspace ((unsigned char) *--cp))
	    *cp = '\0';
    }

    /* don't do special options only part of a module was specified */
    if (mfile != NULL)
	spec_opt = NULL;

    /*
     * value now contains one of the following:
     *    1) dir
     *	  2) dir file
     *    3) the value from modules without any special args
     *		    [ args ] dir [file] [file] ...
     *	     or     -a module [ module ] ...
     */

    /* Put the value on a line with XXX prepended for getopt to eat */
    line = Xasprintf ("XXX %s", value);

    /* turn the line into an argv[] array */
    line2argv (&xmodargc, &xmodargv, line, " \t");
    free (line);
    modargc = xmodargc;
    modargv = xmodargv;

    /* parse the args */
    getoptreset ();
    while ((c = getopt (modargc, modargv, CVSMODULE_OPTS)) != -1)
    {
	switch (c)
	{
	    case 'a':
		alias = 1;
		break;
	    case 'd':
		if (mwhere)
		    free (mwhere);
		mwhere = xstrdup (optarg);
		nonalias_opt = 1;
		break;
	    case 'l':
		local_specified = 1;
		nonalias_opt = 1;
		break;
	    case 'o':
		if (checkout_prog)
		    free (checkout_prog);
		checkout_prog = xstrdup (optarg);
		nonalias_opt = 1;
		break;
	    case 'e':
		if (export_prog)
		    free (export_prog);
		export_prog = xstrdup (optarg);
		nonalias_opt = 1;
		break;
	    case 't':
		if (tag_prog)
		    free (tag_prog);
		tag_prog = xstrdup (optarg);
		nonalias_opt = 1;
		break;
	    case '?':
		error (0, 0,
		       "modules file has invalid option for key %s value %s",
		       key.dptr, value);
		err++;
		goto do_module_return;
	}
    }
    modargc -= optind;
    modargv += optind;
    if (modargc == 0  &&  spec_opt == NULL)
    {
	error (0, 0, "modules file missing directory for module %s", mname);
	++err;
	goto do_module_return;
    }

    if (alias && nonalias_opt)
    {
	/* The documentation has never said it is valid to specify
	   -a along with another option.  And I believe that in the past
	   CVS has ignored the options other than -a, more or less, in this
	   situation.  */
	error (0, 0, "\
-a cannot be specified in the modules file along with other options");
	++err;
	goto do_module_return;
    }