Example #1
0
int
chunker_cmd(
    chunker_t *chunker,
    cmd_t cmd,
    disk_t *dp,
    char   *mesg)
{
    char *cmdline = NULL;
    char number[NUM_STR_SIZE];
    char chunksize[NUM_STR_SIZE];
    char use[NUM_STR_SIZE];
    char *o;
    int activehd=0;
    assignedhd_t **h=NULL;
    char *features;
    char *qname;
    char *qdest;

    switch(cmd) {
    case START:
	cmdline = vstralloc(cmdstr[cmd], " ", mesg, "\n", NULL);
	break;
    case PORT_WRITE:
	if(dp && sched(dp) && sched(dp)->holdp) {
	    h = sched(dp)->holdp;
	    activehd = sched(dp)->activehd;
	}

	if (dp && h) {
	    qname = quote_string(dp->name);
	    qdest = quote_string(sched(dp)->destname);
	    h[activehd]->disk->allocated_dumpers++;
	    g_snprintf(number, SIZEOF(number), "%d", sched(dp)->level);
	    g_snprintf(chunksize, SIZEOF(chunksize), "%lld",
		    (long long)holdingdisk_get_chunksize(h[0]->disk->hdisk));
	    g_snprintf(use, SIZEOF(use), "%lld",
		    (long long)h[0]->reserved);
	    features = am_feature_to_string(dp->host->features);
	    o = optionstr(dp, dp->host->features, NULL);
	    if ( o == NULL ) {
	      error(_("problem with option string, check the dumptype definition.\n"));
	    }
	    cmdline = vstralloc(cmdstr[cmd],
			    " ", disk2serial(dp),
			    " ", qdest,
			    " ", dp->host->hostname,
			    " ", features,
			    " ", qname,
			    " ", number,
			    " ", sched(dp)->dumpdate,
			    " ", chunksize,
			    " ", dp->program,
			    " ", use,
			    " |", o,
			    "\n", NULL);
	    amfree(features);
	    amfree(o);
	    amfree(qdest);
	    amfree(qname);
	} else {
		error(_("%s command without disk and holding disk.\n"),
		      cmdstr[cmd]);
		/*NOTREACHED*/
	}
	break;
    case CONTINUE:
	if(dp && sched(dp) && sched(dp)->holdp) {
	    h = sched(dp)->holdp;
	    activehd = sched(dp)->activehd;
	}

	if(dp && h) {
	    qname = quote_string(dp->name);
	    qdest = quote_string(h[activehd]->destname);
	    h[activehd]->disk->allocated_dumpers++;
	    g_snprintf(chunksize, SIZEOF(chunksize), "%lld", 
		     (long long)holdingdisk_get_chunksize(h[activehd]->disk->hdisk));
	    g_snprintf(use, SIZEOF(use), "%lld", 
		     (long long)(h[activehd]->reserved - h[activehd]->used));
	    cmdline = vstralloc(cmdstr[cmd],
				" ", disk2serial(dp),
				" ", qdest,
				" ", chunksize,
				" ", use,
				"\n", NULL );
	    amfree(qdest);
	    amfree(qname);
	} else {
	    cmdline = stralloc2(cmdstr[cmd], "\n");
	}
	break;
    case QUIT:
    case ABORT:
	{
	    char *q = quote_string(mesg);
	    cmdline = vstralloc(cmdstr[cmd], " ", q, "\n", NULL);
	    amfree(q);
	}
	break;
    case DONE:
    case FAILED:
	if( dp ) {
	    cmdline = vstralloc(cmdstr[cmd],
				" ", disk2serial(dp),
				"\n",  NULL);
	} else {
	    cmdline = vstralloc(cmdstr[cmd], "\n");
	}
	break;
    default:
	error(_("Don't know how to send %s command to chunker"), cmdstr[cmd]);
	/*NOTREACHED*/
    }

    /*
     * Note: cmdline already has a '\n'.
     */
    g_printf(_("driver: send-cmd time %s to %s: %s"),
	   walltime_str(curclock()), chunker->name, cmdline);
    fflush(stdout);
    if (full_write(chunker->fd, cmdline, strlen(cmdline)) < strlen(cmdline)) {
	g_printf(_("writing %s command: %s\n"), chunker->name, strerror(errno));
	fflush(stdout);
	amfree(cmdline);
	return 0;
    }
    if (cmd == QUIT) aclose(chunker->fd);
    amfree(cmdline);
    return 1;
}
Example #2
0
void
set_disk(
    char *	dsk,
    char *	mtpt)
{
    char *cmd = NULL;
    char *qdsk;
    char *uqdsk;
    char *uqmtpt = NULL;

    if (is_extract_list_nonempty())
    {
	g_printf(_("Must clear extract list before changing disk\n"));
	return;
    }

    /* if mount point specified, check it is valid */
    if (mtpt != NULL) {
	uqmtpt = unquote_string(mtpt);
	if (*mtpt != '/') {
	    g_printf(_("Mount point \"%s\" invalid - must start with /\n"), uqmtpt);
	    amfree(uqmtpt);
	    return;
	}
    }

    clear_dir_list();
    uqdsk = unquote_string(dsk);
    qdsk = quote_string(uqdsk);
    cmd = stralloc2("DISK ", qdsk);
    amfree(qdsk);
    if (converse(cmd) == -1)
	exit(1);
    amfree(cmd);

    if (!server_happy()) {
	amfree(uqmtpt);
	amfree(uqdsk);
	return;
    }

    disk_name = newstralloc(disk_name, uqdsk);
    if (mtpt == NULL)
    {
	/* mount point not specified */
	if (*uqdsk == '/')
	{
	    /* disk specified by mount point, hence use it */
	    mount_point = newstralloc(mount_point, uqdsk);
	}
	else
	{
	    /* device name given, use '/' because nothing better */
	    mount_point = newstralloc(mount_point, "/");
	}
    }
    else
    {
	/* mount point specified */
	mount_point = newstralloc(mount_point, uqmtpt);
    }

    /* set the working directory to the mount point */
    /* there is the possibility that there are no index records for the
       disk for the given date, hence setting the directory to the
       mount point will fail. Preempt this by checking first so we can write
       a more informative message. */
    if (exchange("OISD /") == -1)
	exit(1);
    if (server_happy())
    {
	disk_path = newstralloc(disk_path, "/");
	suck_dir_list_from_server();	/* get list of directory contents */
    }
    else
    {
	g_printf(_("No index records for disk for specified date\n"));
	g_printf(_("If date correct, notify system administrator\n"));
	disk_path = newstralloc(disk_path, "/");	/* fake it */
	clear_dir_list();
    }
    amfree(uqmtpt);
    amfree(uqdsk);

    if (am_has_feature(indexsrv_features, fe_amindexd_DLE)) {
	char *dle_str;
	char *errmsg = NULL;

	cmd = stralloc("DLE");
	if (exchange(cmd) == -1)
	    exit(1);
	amfree(cmd);

	if (!server_happy())
	    return;

	dle_str = reply_line();
	if (BSTRNCMP(dle_str+4, "NODLE") == 0) {
	    dump_dle = NULL;
	} else {
	    dle_str = unquote_string(dle_str+4);
	    dump_dle = amxml_parse_node_CHAR(dle_str, &errmsg);
	    amfree(dle_str);
	}
    }
}
Example #3
0
void
set_host(
    const char *host)
{
    char *cmd = NULL;
    struct hostent *hp = NULL;
    char **hostp;
    int found_host = 0;
    char *uqhost = unquote_string(host);

    if (is_extract_list_nonempty())
    {
	g_printf(_("Must clear extract list before changing host\n"));
	amfree(uqhost);
	return;
    }

    /*
     * The idea here is to try as many permutations of the hostname
     * as we can imagine.  The server will reject anything it doesn't
     * recognize.
     */

    cmd = stralloc2("HOST ", uqhost);
    if (converse(cmd) == -1)
	exit(1);
    if (server_happy())
	found_host = 1;

    /*
     * Try converting the given host to a fully qualified, canonical
     * name.
     */
    if (!found_host) {
	if ((hp = gethostbyname(uqhost)) != NULL) {
	    host = hp->h_name;
	    g_printf(_("Trying host %s ...\n"), host);
	    cmd = newstralloc2(cmd, "HOST ", host);
	    if (converse(cmd) == -1)
		exit(1);
	    if(server_happy())
		found_host = 1;
	}
    }

    /*
     * Since we have them, try any CNAMEs that were traversed from uqhost
     * to the canonical name (this assumes gethostbyname was called above)
     */
    if (!found_host) {
	if (hp) {
	    for (hostp = hp->h_aliases; (host = *hostp) != NULL; hostp++)
	    {
		g_printf(_("Trying host %s ...\n"), host);
		cmd = newstralloc2(cmd, "HOST ", host);
		if (converse(cmd) == -1)
		    exit(1);
		if(server_happy())
		{
		    found_host = 1;
		    break;
		}
	    }
	}
    }

    /* Try looking up the canonical name of the host */
    if (!found_host) {
	char *canonname;
	int result;

	result = resolve_hostname(uqhost, 0, NULL, &canonname);
	if (result == 0 && canonname) {
	    host = canonname;
	    g_printf(_("Trying host %s ...\n"), host);
	    cmd = newstralloc2(cmd, "HOST ", host);
	    if (converse(cmd) == -1)
		exit(1);
	    if(server_happy())
		found_host = 1;
	}
    }

    if(found_host) {
	dump_hostname = newstralloc(dump_hostname, host);
	amfree(disk_name);
	amfree(mount_point);
	amfree(disk_path);
	clear_dir_list();
    }
    amfree(cmd);
    amfree(uqhost);
}
Example #4
0
static int crypt_test (unsigned int len)
{    

    if (len <= 0) {
        g_printf (" [%s] line %d: len must be positive.\n", __func__, __LINE__);
        return -1;
    }
    
    char *msg = "Hello World!\n";
    
    GString *gstr = g_string_new (NULL);

    while (gstr->len < len) {
        g_string_append (gstr, msg);
    }

    char *enc_out = NULL;
    int enc_out_len;

    g_printf ("[setup] The input is %d bytes\n", len);
    
    int res = seafile_encrypt (&enc_out,
                               &enc_out_len,
                               gstr->str,
                               len,
                               CODE,
                               strlen(CODE));

    if (res == 0 && enc_out_len != -1)
        g_printf ("[ENC] [PASS] Encrypted output length is %d bytes\n", enc_out_len);
    else {
        g_printf ("[ENC] FAILED.\n");
        goto error;
    }

    char *dec_out = NULL;
    int dec_len;
    
    res = seafile_decrypt (&dec_out,
                           &dec_len,
                           enc_out,
                           enc_out_len,
                           CODE,
                           strlen(CODE));

    
    if (res != 0 || (unsigned int)dec_len != len ||
        strncmp (dec_out, gstr->str, len) != 0) {
       
        g_printf ("[DEC] FAILED.\n");
        goto error;
    }                
    else
        g_printf ("[DEC] [PASS] Decrypted output is the totally same as input\n");
        
    g_string_free (gstr, TRUE);
    g_free (enc_out);
    g_free (dec_out);

    g_printf ("[TEST] Finished Successfully.\n");

    return 0;
    
    
error:    

    g_string_free (gstr, TRUE);
    g_free (enc_out);
    g_free (dec_out);

    g_printf ("[TEST] FAILED.\n");
    
    return -1;

}
Example #5
0
int main(int argc, char** argv, char** environ)
{
	pthread_t Xevent_thread, Vchannel_thread;
	void *ret;
	l_config = g_malloc(sizeof(struct log_config), 1);
	if (cliprdr_init() != LOG_STARTUP_OK)
	{
		g_printf("cliprdr[main]: Unable to init log system\n");
		g_free(l_config);
		return 1;
	}
	if (vchannel_init() == ERROR)
	{
		g_printf("cliprdr[main]: Unable to init channel system\n");
		g_free(l_config);
		return 1;
	}

	pthread_cond_init(&reply_cond, NULL);
	pthread_mutex_init(&mutex, NULL);

	cliprdr_channel = vchannel_open("cliprdr");
	if( cliprdr_channel == ERROR)
	{
		log_message(l_config, LOG_LEVEL_ERROR, "cliprdr[main]: "
				"Error while connecting to vchannel provider");
		g_free(l_config);
		return 1;
	}

	XInitThreads();
	log_message(l_config, LOG_LEVEL_DEBUG, "cliprdr[main]: "
			"Opening the default display : %s",getenv("DISPLAY"));

	if ((display = XOpenDisplay(0))== 0){
		log_message(l_config, LOG_LEVEL_ERROR, "cliprdr[main]: "
				"Unable to open the default display : %s ",getenv("DISPLAY"));
		g_free(l_config);
		return 1;
	}
	XSynchronize(display, 1);
	XSetErrorHandler(error_handler);

	running = 1;

	if (pthread_create (&Xevent_thread, NULL, thread_Xvent_process, (void*)0) < 0)
	{
		log_message(l_config, LOG_LEVEL_ERROR, "cliprdr[main]: "
				"Pthread_create error for thread : Xevent_thread");
		g_free(l_config);
		return 1;
	}
	if (pthread_create (&Vchannel_thread, NULL, thread_vchannel_process, (void*)0) < 0)
	{
		log_message(l_config, LOG_LEVEL_ERROR, "cliprdr[main]: "
				"Pthread_create error for thread : Vchannel_thread");
		g_free(l_config);
		return 1;
	}

	(void)pthread_join (Xevent_thread, &ret);
	//(void)pthread_join (Vchannel_thread, &ret);
	pthread_mutex_destroy(&mutex);
	XCloseDisplay(display);
	g_free(l_config);
	return 0;
}
Example #6
0
double _parse(gchar *args, struct global_vars *gvars)
{
	gdouble minus_one = -1.0;
	gdouble null = 0;
	gint args_len = strlen(args);
	
	struct stack *arguments = stack_init(sizeof(gdouble));
	struct stack *operators = stack_init(sizeof(gchar));

	gint i = 0;
	gint j = 0;
	gint local_nest_level = 0;

	gint8 last_p = 0;  /** priority of last parsed operator */
	gboolean coef_flag = FALSE;  /** set if value might preceed a bracket and thus become a coefficient */
	gboolean func_flag = FALSE;  /** set if result of next bracket is to be passed as an argument to function <symbol> */
	gboolean nest_flag = FALSE;  /** indicates characters are being collected and not parsed */
	gboolean nest_init_flag = FALSE;  /** necessary to skip first character '(' during string collection */
	gboolean value_flag = FALSE; /** indicates previously parsed value as opposed to an operator */
	gboolean frac_flag = FALSE;
	
	gboolean no_input_flag = FALSE;
	if (strlen(args) == 0) {no_input_flag = TRUE;}
	
	GString *nested_term = g_string_new("\0"); /** collector string for contents of nested term */
	GString *symbol = g_string_new("\0"); /** collector string for symbol name */

	if (!no_input_flag) {
		for (i=0; i < args_len; i++)
		{
	
			if (nest_init_flag) {nest_init_flag = FALSE;}
	
			/** lock computing by raising nest level, substitute '*' if coefficient exists */
			if (args[i] == '(')
			{
				if (!nest_flag) /** nested interpreting is just about to be initialized */
				{
					if (coef_flag) {stack_push(operators, "*"); last_p = priority('*');}
					coef_flag = TRUE;
					nest_flag = TRUE;
					nest_init_flag = TRUE;
					gvars->nest_level += 1;
					nested_term = g_string_new("\0");
				}
				else  /** nested interpreting is in progress */
				{
					local_nest_level += 1;
				}
			}
	
			else if (args[i] == ')')
			{
				if (nest_flag && local_nest_level == 0) /** nesting has reached end */
				{
					nest_flag = FALSE; value_flag = TRUE;
					gdouble nested_term_result = _parse(nested_term->str, gvars);
					gvars->nest_level -= 1;
					g_string_free(nested_term, TRUE);
					nested_term = g_string_new("\0");
					if (func_flag)
					{
						gdouble compute_function_results =
							compute_function(symbol->str, nested_term_result, gvars);
						stack_push(arguments, &compute_function_results);
						func_flag = FALSE;
						g_string_free(symbol, TRUE);
						symbol = g_string_new("\0");
					}
					else {stack_push(arguments, &nested_term_result);}
				}
				else  /** nested interpreting is in progress, passing by uninterpreted ')' */
				{
					local_nest_level -= 1;
				}
			}
	
	
			if (!nest_flag)
			{
	
				if (args[i] == '.' || args[i] == ',')
				{
					if (g_ascii_isdigit(char_at(args,i+1))) {frac_flag = TRUE;}
					else {gvars->error_type = 3; return 0;}
				}
	
				else if (g_ascii_isdigit(args[i]))  /** parse number */
				{
					if (gvars->debug)
						{for (j=0;j<gvars->nest_level;j++) {g_printf("   ");} g_printf("args[%d] is digit\n", i);}
	
					gint8 dig = to_d(args[i]);
					stack_push(gvars->digits, &dig);
					if (frac_flag) {gvars->frac_point -= 1;}
					/** check if there is more than one digit or fractal part */
					if (!(g_ascii_isdigit(char_at(args, i+1)) || char_at(args, i+1) == '.' || char_at(args, i+1) == ','))
					{
						if (coef_flag) {stack_push(operators, "*"); last_p = priority('*');}
						gdouble joined_dig =  join_digits(gvars->digits, gvars->frac_point);
						stack_push(arguments, &joined_dig);
						coef_flag = TRUE; frac_flag = FALSE; value_flag = TRUE; gvars->frac_point = 0;
					}
				}
	
				else if (isoperator(args[i]))  /** parse operators */
				{
					if (gvars->debug)
						{for (j=0;j<gvars->nest_level;j++) {g_printf("   ");} g_printf("args[%d] is operator\n", i);}
	
					if (args[i] == '-')  /** check if preceeding minus changes sign of next symbol */
					{
						if (value_flag)
						{
							compute(arguments, operators, gvars);
							stack_push(operators, "+");
						}
						stack_push(arguments, &minus_one);
						stack_push(operators, "*"); last_p = priority('*');
						
						coef_flag = FALSE;
					}
					else
					{
						if (stack_length(arguments) <= stack_length(operators)) {gvars->error_type = 4; break;}
						/** check beforehand if lower priority operator is encountered */
						if (priority(args[i]) < last_p) {compute(arguments, operators, gvars);}
						last_p = priority(args[i]);
						stack_push(operators, &args[i]);
						if (args[i] == '!') {stack_push(arguments, &null);}  // dummy zero to avoid complications due to missing second args for faculty
						coef_flag = FALSE;
						value_flag = FALSE;
					}
				}
	
				else if (g_ascii_isalpha(args[i])) /** parse letters */
				{
					if (gvars->debug)
						{for (j=0;j<gvars->nest_level;j++) {g_printf("   ");} printf("args[%d] is letter\n", i);}
	
					if (coef_flag) {coef_flag = FALSE; stack_push(operators, "*"); last_p = priority('*');}
					g_string_append_c(symbol, args[i]);
					if (char_at(args,i+1) == '(')
					{
						compute_function(symbol->str, 0, gvars);
						if (gvars->error_type != 0)
						{
							gvars->error_type = 0;
							gdouble looked_up_c = lookup_constant(symbol->str, gvars);
							stack_push(arguments, &looked_up_c);
							g_string_free(symbol, TRUE);
							symbol = g_string_new("\0");
							coef_flag = TRUE;
							value_flag = TRUE;
						}
						else {func_flag = TRUE;}
					}
					else if (!g_ascii_isalpha(char_at(args,i+1)))
					{
						gdouble looked_up_c = lookup_constant(symbol->str, gvars);
						stack_push(arguments, &looked_up_c);
						g_string_free(symbol, TRUE);
						symbol = g_string_new("\0");
						coef_flag = TRUE;
						value_flag = TRUE;
					}
				}
	
			}
	
			else if (!nest_init_flag) /** this collector block needs to be skipped once so the first '(' isn't collected */
			{
				g_string_append_c(nested_term, args[i]);
			}

			if (args[i] == ' ') {coef_flag = FALSE;}

			if (char_at(args,i) == '#') {break;}  /** failsafe, in case array bounds are left */
		}
	}
	if (gvars->debug)
		{printf("<args>\n");stack_dump(arguments, 'd');printf("<ops>\n");stack_dump(operators, 'c');printf("<>\n");
		printf("errors so far: %d\n", gvars->error_type);}

	if (local_nest_level != 0 && gvars->error_type == 0) {gvars->error_type = 1;}
	if (!no_input_flag && gvars->error_type == 0) {compute(arguments, operators, gvars);}
	if (stack_length(arguments) > 1 && gvars->error_type == 0) {gvars->error_type = 4;}

	gdouble return_value = 0;
	if (gvars->error_type == 0 && !no_input_flag) {stack_pop(arguments, &return_value);}
	stack_destroy(arguments);
	stack_destroy(operators);

	return return_value;
}
Example #7
0
int
main(
    int		argc,
    char **	argv)
{
    int i;
    time_t timer;
    char *lineread = NULL;
    struct sigaction act, oact;
    extern char *optarg;
    extern int optind;
    char *line = NULL;
    const security_driver_t *secdrv;
    char *req = NULL;
    int response_error;
    struct tm *tm;
    config_overwrites_t *cfg_ovr;

    /*
     * Configure program for internationalization:
     *   1) Only set the message locale for now.
     *   2) Set textdomain for all amanda related programs to "amanda"
     *      We don't want to be forced to support dozens of message catalogs.
     */  
    setlocale(LC_MESSAGES, "C");
    textdomain("amanda"); 

    safe_fd(-1, 0);

    set_pname("amrecover");

    /* Don't die when child closes pipe */
    signal(SIGPIPE, SIG_IGN);

    dbopen(DBG_SUBDIR_CLIENT);

    localhost = alloc(MAX_HOSTNAME_LENGTH+1);
    if (gethostname(localhost, MAX_HOSTNAME_LENGTH) != 0) {
	error(_("cannot determine local host name\n"));
	/*NOTREACHED*/
    }
    localhost[MAX_HOSTNAME_LENGTH] = '\0';

    /* load the base client configuration */
    config_init(CONFIG_INIT_CLIENT, NULL);

    if (config_errors(NULL) >= CFGERR_WARNINGS) {
	config_print_errors();
	if (config_errors(NULL) >= CFGERR_ERRORS) {
	    g_critical(_("errors processing config file"));
	}
    }

    /* treat amrecover-specific command line options as the equivalent
     * -o command-line options to set configuration values */
    cfg_ovr = new_config_overwrites(argc/2);

    /* If the first argument is not an option flag, then we assume
     * it is a configuration name to match the syntax of the other
     * Amanda utilities. */
    if (argc > 1 && argv[1][0] != '-') {
	add_config_overwrite(cfg_ovr, "conf", argv[1]);

	/* remove that option from the command line */
	argv[1] = argv[0];
	argv++; argc--;
    }

    /* now parse regular command-line '-' options */
    while ((i = getopt(argc, argv, "o:C:s:t:d:U")) != EOF) {
	switch (i) {
	    case 'C':
		add_config_overwrite(cfg_ovr, "conf", optarg);
		break;

	    case 's':
		add_config_overwrite(cfg_ovr, "index_server", optarg);
		break;

	    case 't':
		add_config_overwrite(cfg_ovr, "tape_server", optarg);
		break;

	    case 'd':
		add_config_overwrite(cfg_ovr, "tapedev", optarg);
		break;

	    case 'o':
		add_config_overwrite_opt(cfg_ovr, optarg);
		break;

	    case 'U':
	    case '?':
		(void)g_printf(USAGE);
		return 0;
	}
    }
    if (optind != argc) {
	(void)g_fprintf(stderr, USAGE);
	exit(1);
    }

    /* and now try to load the configuration named in that file */
    apply_config_overwrites(cfg_ovr);
    config_init(CONFIG_INIT_CLIENT | CONFIG_INIT_EXPLICIT_NAME | CONFIG_INIT_OVERLAY,
		getconf_str(CNF_CONF));
    reapply_config_overwrites();

    check_running_as(RUNNING_AS_ROOT);

    dbrename(get_config_name(), DBG_SUBDIR_CLIENT);

    our_features = am_init_feature_set();
    our_features_string = am_feature_to_string(our_features);

    server_name = NULL;
    if (getconf_seen(CNF_INDEX_SERVER) == -2) { /* command line argument */
	server_name = getconf_str(CNF_INDEX_SERVER);
    }
    if (!server_name) {
	server_name = getenv("AMANDA_SERVER");
	if (server_name) {
	    g_printf(_("Using index server from environment AMANDA_SERVER (%s)\n"), server_name);
	}
    }
    if (!server_name) {
	server_name = getconf_str(CNF_INDEX_SERVER);
    }
    if (!server_name) {
	error(_("No index server set"));
	/*NOTREACHED*/
    }
    server_name = stralloc(server_name);

    tape_server_name = NULL;
    if (getconf_seen(CNF_TAPE_SERVER) == -2) { /* command line argument */
	tape_server_name = getconf_str(CNF_TAPE_SERVER);
    }
    if (!tape_server_name) {
	tape_server_name = getenv("AMANDA_TAPE_SERVER");
	if (!tape_server_name) {
	    tape_server_name = getenv("AMANDA_TAPESERVER");
	    if (tape_server_name) {
		g_printf(_("Using tape server from environment AMANDA_TAPESERVER (%s)\n"), tape_server_name);
	    }
	} else {
	    g_printf(_("Using tape server from environment AMANDA_TAPE_SERVER (%s)\n"), tape_server_name);
	}
    }
    if (!tape_server_name) {
	tape_server_name = getconf_str(CNF_TAPE_SERVER);
    }
    if (!tape_server_name) {
	error(_("No tape server set"));
	/*NOTREACHED*/
    }
    tape_server_name = stralloc(tape_server_name);

    amfree(tape_device_name);
    tape_device_name = getconf_str(CNF_TAPEDEV);
    if (!tape_device_name ||
	strlen(tape_device_name) == 0 ||
	!getconf_seen(CNF_TAPEDEV)) {
	tape_device_name = NULL;
    } else {
	tape_device_name = stralloc(tape_device_name);
    }

    authopt = stralloc(getconf_str(CNF_AUTH));


    amfree(disk_name);
    amfree(mount_point);
    amfree(disk_path);
    dump_date[0] = '\0';

    /* Don't die when child closes pipe */
    signal(SIGPIPE, SIG_IGN);

    /* set up signal handler */
    act.sa_handler = sigint_handler;
    sigemptyset(&act.sa_mask);
    act.sa_flags = 0;
    if (sigaction(SIGINT, &act, &oact) != 0) {
	error(_("error setting signal handler: %s"), strerror(errno));
	/*NOTREACHED*/
    }

    protocol_init();

    /* We assume that amindexd support fe_amindexd_options_features */
    /*                             and fe_amindexd_options_auth     */
    /* We should send a noop to really know                         */
    req = vstrallocf("SERVICE amindexd\n"
		    "OPTIONS features=%s;auth=%s;\n",
		    our_features_string, authopt);

    secdrv = security_getdriver(authopt);
    if (secdrv == NULL) {
	error(_("no '%s' security driver available for host '%s'"),
	    authopt, server_name);
	/*NOTREACHED*/
    }

    protocol_sendreq(server_name, secdrv, generic_client_get_security_conf,
		     req, STARTUP_TIMEOUT, amindexd_response, &response_error);

    amfree(req);
    protocol_run();

    g_printf(_("AMRECOVER Version %s. Contacting server on %s ...\n"),
	   version(), server_name);

    if(response_error != 0) {
	g_fprintf(stderr,"%s\n",errstr);
	exit(1);
    }

    /* get server's banner */
    if (grab_reply(1) == -1) {
        aclose(server_socket);
	exit(1);
    }
    if (!server_happy()) {
	dbclose();
	aclose(server_socket);
	exit(1);
    }

    /* try to get the features from the server */
    {
	char *their_feature_string = NULL;

	indexsrv_features = NULL;

	line = vstrallocf("FEATURES %s", our_features_string);
	if(exchange(line) == 0) {
	    their_feature_string = stralloc(server_line+13);
	    indexsrv_features = am_string_to_feature(their_feature_string);
	    if (!indexsrv_features)
		g_printf(_("Bad feature string from server: %s"), their_feature_string);
	}
	if (!indexsrv_features)
	    indexsrv_features = am_set_default_feature_set();

	amfree(their_feature_string);
	amfree(line);
    }

    /* set the date of extraction to be today */
    (void)time(&timer);
    tm = localtime(&timer);
    if (tm) 
	strftime(dump_date, sizeof(dump_date), "%Y-%m-%d", tm);
    else
	error(_("BAD DATE"));

    g_printf(_("Setting restore date to today (%s)\n"), dump_date);
    line = vstrallocf("DATE %s", dump_date);
    if (converse(line) == -1) {
        aclose(server_socket);
	exit(1);
    }
    amfree(line);

    line = vstrallocf("SCNF %s", get_config_name());
    if (converse(line) == -1) {
        aclose(server_socket);
	exit(1);
    }
    amfree(line);

    if (server_happy()) {
	/* set host we are restoring to this host by default */
	amfree(dump_hostname);
	set_host(localhost);
	if (dump_hostname)
	    g_printf(_("Use the setdisk command to choose dump disk to recover\n"));
	else
	    g_printf(_("Use the sethost command to choose a host to recover\n"));

    }

    quit_prog = 0;
    do {
	if ((lineread = readline("amrecover> ")) == NULL) {
	    clearerr(stdin);
	    putchar('\n');
	    break;
	}
	if (lineread[0] != '\0') 
	{
	    add_history(lineread);
	    dbprintf(_("user command: '%s'\n"), lineread);
	    process_line(lineread);	/* act on line's content */
	}
	amfree(lineread);
    } while (!quit_prog);

    dbclose();

    aclose(server_socket);
    return 0;
}
LDevices *enum_devices( gchar *videodevice, struct udev *udev, int debug)
{
    struct udev_enumerate *enumerate;
    struct udev_list_entry *devices, *dev_list_entry;
    struct udev_device *dev;
    
    int num_dev = 0;
    int fd = 0;
    struct v4l2_capability v4l2_cap;
    
    if (!udev) 
    {
        /*use fall through method (sysfs)*/
        g_printf("Can't create udev...using sysfs method\n");
        return(list_devices(videodevice));
    }
    
    LDevices *listDevices = NULL;
    listDevices = g_new0( LDevices, 1);
    listDevices->listVidDevices = NULL;
    
    /* Create a list of the devices in the 'v4l2' subsystem. */
    enumerate = udev_enumerate_new(udev);
    udev_enumerate_add_match_subsystem(enumerate, "video4linux");
    udev_enumerate_scan_devices(enumerate);
    devices = udev_enumerate_get_list_entry(enumerate);
    /* For each item enumerated, print out its information.
        udev_list_entry_foreach is a macro which expands to
        a loop. The loop will be executed for each member in
        devices, setting dev_list_entry to a list entry
        which contains the device's path in /sys. */
    udev_list_entry_foreach(dev_list_entry, devices) 
    {
        const char *path;

        /* Get the filename of the /sys entry for the device
            and create a udev_device object (dev) representing it */
        path = udev_list_entry_get_name(dev_list_entry);
        dev = udev_device_new_from_syspath(udev, path);

        /* usb_device_get_devnode() returns the path to the device node
            itself in /dev. */
        const gchar *v4l2_device = udev_device_get_devnode(dev);
        if (debug) 
            g_printf("Device Node Path: %s\n", v4l2_device);
        
        /* open the device and query the capabilities */
        if ((fd = v4l2_open(v4l2_device, O_RDWR | O_NONBLOCK, 0)) < 0) 
        {
            g_printerr("ERROR opening V4L2 interface for %s\n", v4l2_device);
            v4l2_close(fd);
            continue; /*next dir entry*/
        }

        if (xioctl(fd, VIDIOC_QUERYCAP, &v4l2_cap) < 0) 
        {
            perror("VIDIOC_QUERYCAP error");
            g_printerr("   couldn't query device %s\n", v4l2_device);
            v4l2_close(fd);
            continue; /*next dir entry*/
        }
        v4l2_close(fd);
        
        num_dev++;
        /* Update the device list*/
        listDevices->listVidDevices = g_renew(VidDevice, 
            listDevices->listVidDevices, 
            num_dev);
        listDevices->listVidDevices[num_dev-1].device = g_strdup(v4l2_device);
        listDevices->listVidDevices[num_dev-1].name = g_strdup((gchar *) v4l2_cap.card);
        listDevices->listVidDevices[num_dev-1].driver = g_strdup((gchar *) v4l2_cap.driver);
        listDevices->listVidDevices[num_dev-1].location = g_strdup((gchar *) v4l2_cap.bus_info);
        listDevices->listVidDevices[num_dev-1].valid = 1;
        if(g_strcmp0(videodevice,listDevices->listVidDevices[num_dev-1].device)==0) 
        {
            listDevices->listVidDevices[num_dev-1].current = 1;
            listDevices->current_device = num_dev-1;
        }
        else
            listDevices->listVidDevices[num_dev-1].current = 0;
        
        /* The device pointed to by dev contains information about
            the v4l2 device. In order to get information about the
            USB device, get the parent device with the
            subsystem/devtype pair of "usb"/"usb_device". This will
            be several levels up the tree, but the function will find
            it.*/
        dev = udev_device_get_parent_with_subsystem_devtype(
                dev,
                "usb",
                "usb_device");
        if (!dev) 
        {
            printf("Unable to find parent usb device.");
            continue;
        }
        
        /* From here, we can call get_sysattr_value() for each file
            in the device's /sys entry. The strings passed into these
            functions (idProduct, idVendor, serial, etc.) correspond
            directly to the files in the directory which represents
            the USB device. Note that USB strings are Unicode, UCS2
            encoded, but the strings returned from
            udev_device_get_sysattr_value() are UTF-8 encoded. */
        if (debug) 
        {
            g_printf("  VID/PID: %s %s\n",
                udev_device_get_sysattr_value(dev,"idVendor"),
                udev_device_get_sysattr_value(dev, "idProduct"));
            g_printf("  %s\n  %s\n",
                udev_device_get_sysattr_value(dev,"manufacturer"),
                udev_device_get_sysattr_value(dev,"product"));
            g_printf("  serial: %s\n",
                udev_device_get_sysattr_value(dev, "serial"));
        }
        
        listDevices->listVidDevices[num_dev-1].vendor = g_ascii_strtoull(udev_device_get_sysattr_value(dev,"idVendor"), NULL, 16);
        listDevices->listVidDevices[num_dev-1].product = g_ascii_strtoull(udev_device_get_sysattr_value(dev, "idProduct"), NULL, 16);
        
        udev_device_unref(dev);
    }
    /* Free the enumerator object */
    udev_enumerate_unref(enumerate);
    
    listDevices->num_devices = num_dev;
    return(listDevices);

}
/* (fall through - DEPRECATED)
 * enumerates system video devices
 * by checking /sys/class/video4linux
 * args: 
 * videodevice: current device string (default "/dev/video0")
 * 
 * returns: pointer to LDevices struct containing the video devices list */
LDevices *list_devices( gchar *videodevice )
{
	int ret=0;
	int fd=0;
	LDevices *listDevices = NULL;
	listDevices = g_new0( LDevices, 1);
	listDevices->listVidDevices = NULL;
	struct v4l2_capability v4l2_cap;
	GDir *v4l2_dir=NULL;
	GError *error=NULL;
	
	v4l2_dir = g_dir_open("/sys/class/video4linux",0,&error);
	if(v4l2_dir == NULL)
	{
		g_printerr ("opening '/sys/class/video4linux' failed: %s\n", 
			 error->message);
		g_error_free ( error );
		error=NULL;
		return NULL;
	}
	const gchar *v4l2_device;
	int num_dev = 0;
	
	while((v4l2_device = g_dir_read_name(v4l2_dir)) != NULL)
	{
		if(!(g_str_has_prefix(v4l2_device, "video")))
			continue;
		gchar *device = NULL;
		device = g_strjoin("/","/dev",v4l2_device,NULL);
		
		if ((fd = v4l2_open(device, O_RDWR | O_NONBLOCK, 0)) < 0) 
		{
			g_printerr("ERROR opening V4L interface for %s\n",
				device);
			g_free(device);
			continue; /*next dir entry*/
		} 
		else
		{
			ret = xioctl(fd, VIDIOC_QUERYCAP, &v4l2_cap);
			if (ret < 0) 
			{
				perror("VIDIOC_QUERYCAP error");
				g_printerr("   couldn't query device %s\n",
					device);
				g_free(device);
				v4l2_close(fd);
				continue; /*next dir entry*/
			}
			else
			{
				num_dev++;
				g_printf("%s - device %d\n", device, num_dev);
				listDevices->listVidDevices = g_renew(VidDevice, 
					listDevices->listVidDevices, 
					num_dev);
				listDevices->listVidDevices[num_dev-1].device = g_strdup(device);
				listDevices->listVidDevices[num_dev-1].name = g_strdup((gchar *) v4l2_cap.card);
				listDevices->listVidDevices[num_dev-1].driver = g_strdup((gchar *) v4l2_cap.driver);
				listDevices->listVidDevices[num_dev-1].location = g_strdup((gchar *) v4l2_cap.bus_info);
				listDevices->listVidDevices[num_dev-1].valid = 1;
				if(g_strcmp0(videodevice,listDevices->listVidDevices[num_dev-1].device)==0) 
				{
					listDevices->listVidDevices[num_dev-1].current = 1;
					listDevices->current_device = num_dev-1;
				}
				else
					listDevices->listVidDevices[num_dev-1].current = 0;
			}
		}
		g_free(device);
		v4l2_close(fd);
		
		listDevices->listVidDevices[num_dev-1].vendor = 0;
		listDevices->listVidDevices[num_dev-1].product = 0;
		
		gchar *vid_dev_lnk = g_strjoin("/","/sys/class/video4linux",v4l2_device,"device",NULL);
		gchar *device_lnk = g_file_read_link (vid_dev_lnk,&error);
		g_free(vid_dev_lnk);
		
		if(device_lnk == NULL)
		{
			g_printerr ("reading link '/sys/class/video4linux/%s/device' failed: %s\n",
				v4l2_device,
				error->message);
			g_error_free ( error );
			error=NULL;
			//if standard way fails try to get vid, pid from uvc device name 
			//we only need this info for Dynamic controls - uvc driver 
			listDevices->listVidDevices[num_dev-1].vendor = 0;  /*reset vid */
			listDevices->listVidDevices[num_dev-1].product = 0; /*reset pid */
			if(g_strcmp0(listDevices->listVidDevices[num_dev-1].driver,"uvcvideo") == 0)
			{
				sscanf(listDevices->listVidDevices[num_dev-1].name,"UVC Camera (%04x:%04x)",
					&(listDevices->listVidDevices[num_dev-1].vendor),
					&(listDevices->listVidDevices[num_dev-1].product));
			}
		}
		else
		{
			gchar *d_dir = g_strjoin("/","/sys/class/video4linux", v4l2_device, device_lnk, NULL);
			gchar *id_dir = g_path_get_dirname(d_dir);
			g_free(d_dir);
			
			gchar *idVendor = g_strjoin("/", id_dir, "idVendor" ,NULL);
			gchar *idProduct = g_strjoin("/", id_dir, "idProduct" ,NULL);
			
			//g_printf("idVendor: %s\n", idVendor);
			//g_printf("idProduct: %s\n", idProduct);
			FILE *vid_fp = g_fopen(idVendor,"r");
			if(vid_fp != NULL)
			{
				gchar code[5];
				if(fgets(code, sizeof(code), vid_fp) != NULL)
				{
					listDevices->listVidDevices[num_dev-1].vendor = g_ascii_strtoull(code, NULL, 16);
				}
				fclose (vid_fp);
			}
			else
			{
				g_printerr("couldn't open idVendor: %s\n", idVendor);
			}
			
			vid_fp = g_fopen(idProduct,"r");
			if(vid_fp != NULL)
			{
				gchar code[5];
				if(fgets(code, sizeof(code), vid_fp) != NULL)
				{
					listDevices->listVidDevices[num_dev-1].product = g_ascii_strtoull(code, NULL, 16);
				}
				fclose (vid_fp);
			}
			else
			{
				g_printerr("couldn't open idProduct: %s\n", idProduct);
			}
			
			g_free(id_dir);
			g_free(idVendor);
			g_free(idProduct);
		}
		
		g_free(device_lnk);
	}
	
	if(v4l2_dir != NULL) g_dir_close(v4l2_dir);
	
	listDevices->num_devices = num_dev;
	return(listDevices);
}
Example #10
0
 void SetScreenColor(const char *color)
 {
	 g_printf("%s", color);
 }
Example #11
0
/*------------------------------------------------------------------------
 * Multiboot support (show parameters passed back from GRUB)
 *------------------------------------------------------------------------
 */
void show_kernel_parameters( unsigned long magic, unsigned long addr )
{
	/* Set to 0 to quiet display. */
	uint8_t print_values = 1;

	/* Initialise serial port if necessary. */
	vInitializeGalileoSerialPort(DEBUG_SERIAL_PORT);

	if (print_values != 0)
	{
		ClearScreen();
		g_printf(DEFAULT_SCREEN_COLOR);
		MoveToScreenPosition(1, 2);
		g_printf ("\n\r ...MULTIBOOT VALUES RETURNED FROM GRUB...\n\n\r");
		g_printf(ANSI_COLOR_WHITE);
	}

	if (magic != MULTIBOOT_BOOTLOADER_MAGIC)
	{
		printf(ANSI_COLOR_RED);
		if (print_values != 0)
			g_printf (" Invalid magic number returned: 0x%08x\n\r", (unsigned) magic);
		g_printf(ANSI_COLOR_RESET);
	}
	else
	{
	   multiboot_info_t *mbi;
	   /* Set MBI to the address of the Multiboot information structure. */
	   mbi = (multiboot_info_t *) addr;

	   /* Is the command line passed? */
	   if (CHECK_FLAG (mbi->flags, 2))
			if (print_values != 0)
				g_printf (" cmdline = %s\n\r", (char *) mbi->cmdline);

	   /* Print out the flags. */
	   if (print_values != 0)
		   g_printf (" flags = 0x%08x\n\r", (unsigned) mbi->flags);

	   /* Are mem_* valid? */
	   if (CHECK_FLAG (mbi->flags, 0))
			if (print_values != 0)
				g_printf (" mem_lower = %u KB, mem_upper = %u KB\n\r",
				(unsigned) mbi->mem_lower, (unsigned) mbi->mem_upper);

	   /* Is boot_device valid? */
	   if (CHECK_FLAG (mbi->flags, 1))
			if (print_values != 0)
				g_printf (" boot_device = 0x%08x\n\r", (unsigned) mbi->boot_device);

	   if (CHECK_FLAG (mbi->flags, 3))
	   {
		   module_t *mod;
		   int i;
		   if (print_values != 0)
			   g_printf (" mods_count = %d, mods_addr = 0x%08x\n\r",
				(int) mbi->mods_count, (int) mbi->mods_addr);
		   for (i = 0, mod = (module_t *) mbi->mods_addr;
				i < (int)mbi->mods_count;
			    i++, mod++)
		   {
				if (print_values != 0)
					g_printf ("    mod_start = 0x%08x, mod_end = 0x%08x, cmdline = %s\n\r",
					(unsigned) mod->mod_start,
					(unsigned) mod->mod_end,
					(char *) mod->string);
		   }
	   }

       /* Bits 4 and 5 are mutually exclusive! */
       if (CHECK_FLAG (mbi->flags, 4) && CHECK_FLAG (mbi->flags, 5))
       {
    	   if (print_values != 0)
    		   g_printf (" Both bits 4 and 5 are set.\n\r");
       }
       else
       {
           /* Is the symbol table of a.out valid? */
           if (CHECK_FLAG (mbi->flags, 4))
           {
        	   aout_symbol_table_t *multiboot_aout_sym = &(mbi->u.aout_sym);
        	   if (print_values != 0)
        		   g_printf (" multiboot_aout_symbol_table: tabsize = 0x%08x, "
        		    "strsize = 0x%08x, addr = 0x%08x\n\r",
    				(unsigned) multiboot_aout_sym->tabsize,
    				(unsigned) multiboot_aout_sym->strsize,
    				(unsigned) multiboot_aout_sym->addr);
           }

           /* Is the section header table of ELF valid? */
           if (CHECK_FLAG (mbi->flags, 5))
           {
        	   elf_section_header_table_t *multiboot_elf_sec = &(mbi->u.elf_sec);
        	   if (print_values != 0)
        		    g_printf (" multiboot_elf_sec: num = %u, size = 0x%08x,"
    				" addr = 0x%08x, shndx = 0x%04x\n\r",
    				(unsigned) multiboot_elf_sec->num, (unsigned) multiboot_elf_sec->size,
    				(unsigned) multiboot_elf_sec->addr, (unsigned) multiboot_elf_sec->shndx);
           }

           /* Are mmap_* valid? */
           if (CHECK_FLAG (mbi->flags, 6))
           {
        	   memory_map_t *mmap;
        	   if (print_values != 0)
        		   g_printf (" mmap_addr = 0x%08x, mmap_length = 0x%08x\n\r",
    			   (unsigned) mbi->mmap_addr, (unsigned) mbi->mmap_length);
               for (mmap = (memory_map_t *) mbi->mmap_addr;
                    (unsigned long) mmap < mbi->mmap_addr + mbi->mmap_length;
                    mmap = (memory_map_t *) ((unsigned long) mmap
                    + mmap->size + sizeof (mmap->size)))
               {
            	   if (print_values != 0)
            		   g_printf ("    size = 0x%08x, base_addr = 0x%04x%04x,"
    				   " length = 0x%04x%04x, type = 0x%04x\n\r",
    				   (unsigned) mmap->size,
    				   (uint16_t) mmap->base_addr_high,
    				   (uint16_t)mmap->base_addr_low,
    				   (uint16_t)mmap->length_high,
    				   (uint16_t)mmap->length_low,
    				   (unsigned) mmap->type);
               }
           }

    	   if (print_values != 0)
    	   {
    		   g_printf(DEFAULT_SCREEN_COLOR);
    		   g_printf ("\n\r Press any key to continue.\n\r");
			   while (ucGalileoGetchar() == 0)
			   {
					__asm volatile( "NOP" );
			   }
    	   }
           main();
       }
	}
Example #12
0
 void MoveToScreenPosition(uint8_t row, uint8_t col)
 {
	g_printf("%c[%d;%dH", (char) 0x1B, row, col);
 }
Example #13
0
 void ClearScreen(void)
 {
	g_printf(ANSI_CLEAR_SB);
	g_printf(ANSI_CLEAR_SCREEN);
 }
Example #14
0
GstElement *create_video_sink()
{
	GstElement *bin, *decoder = NULL;
	GstIterator *iter;
	GstIteratorResult res;
	GError *error = NULL;
	GstPad *pad;
	gpointer element = NULL;
	const char* decoder_name;

#ifndef DESKTOP 
	/* create pipeline */                                                                                 
	decoder_name = "tividdec20";
	bin = gst_parse_launch_full("TIViddec2 genTimeStamps=FALSE \
			    engineName=decode \
			    codecName=h264dec numFrames=-1 \
			! videoscale method=0 \
			! video/x-raw-yuv, format=(fourcc)I420, width=320, height=240 \
			! ffmpegcolorspace \
			! video/x-raw-rgb, bpp=16 \
			! TIDmaiVideoSink displayStd=fbdev displayDevice=/dev/fb0 videoStd=QVGA \
			    videoOutput=LCD resizer=FALSE accelFrameCopy=TRUE",
			NULL, 0, &error);                                      
#else
	decoder_name = "decodebin";
	bin = gst_parse_launch_full("decodebin \
			! videoscale method=0 \
			! video/x-raw-yuv, format=(fourcc)I420, width=320, height=240 \
			! xvimagesink",
			NULL, 0, &error);                                      
#endif

	if (!bin) {
		g_error("GStreamer: failed to parse video sink pipeline\n");
		return NULL;
	}              

	gst_object_set_name(GST_OBJECT(bin), "video-sink");

	iter = gst_bin_iterate_elements(GST_BIN(bin));
	res = gst_iterator_next (iter, &element);
	while (res == GST_ITERATOR_OK) {
		gchar *name;

		name = gst_object_get_name(GST_OBJECT (element));
		if (name) {
			if (!strncmp(name, decoder_name, strlen(decoder_name))) {
				decoder = GST_ELEMENT(element); 
			}
			g_printf("GS: video sink element: %s \n", name);
			g_free (name);
		}

		gst_object_unref (element);
		element = NULL;

		res = gst_iterator_next (iter, &element);
	}
	gst_iterator_free (iter);

	if (!decoder) {
		/* mem leak */
		g_printf("decoder element not found\n");
		return NULL;
	}

	/* add ghostpad */
	pad = gst_element_get_static_pad (decoder, "sink");
	gst_element_add_pad(bin, gst_ghost_pad_new("sink", pad));
	gst_object_unref(GST_OBJECT(pad));

	return bin;
}
Example #15
0
static int execute_command(const gchar *command, const gchar *username,
    const gchar *password, const gchar *lttd_path)
{
  pid_t pid;
  int fdpty;
  pid = forkpty(&fdpty, NULL, NULL, NULL);
  int retval = 0;

  if(pid > 0) {
    /* parent */
    gchar buf[256];
    int status;
    ssize_t count;
    /* discuss with su */

    struct pollfd pollfd;
    int num_rdy;
    int num_hup = 0;
		enum read_state { GET_LINE, GET_SEMI, GET_SPACE } read_state = GET_LINE;

		retval = fcntl(fdpty, F_SETFL, O_WRONLY);
		if(retval == -1) {
			perror("Error in fcntl");
			goto wait_child;
		}

    /* Read the output from the child terminal before the prompt. If no data in
     * 200 ms, we stop reading to give the password */
    g_info("Reading from child console...");
    while(1) {
      pollfd.fd = fdpty;
      pollfd.events = POLLIN|POLLPRI|POLLERR|POLLHUP|POLLNVAL;

      num_rdy = poll(&pollfd, 1, -1);
      if(num_rdy == -1) {
        perror("Poll error");
        goto wait_child;
      }
      
      /* Timeout : Stop waiting for chars */
      if(num_rdy == 0) goto wait_child;

      /* Check for fatal errors */
      if(pollfd.revents & POLLERR) {
          g_warning("Error returned in polling fd\n");
          num_hup++;
      }
      if(pollfd.revents & POLLNVAL) {
	g_warning("Polling fd tells it is not open");
	num_hup++;
      }

      if(pollfd.revents & POLLHUP) {

	g_info("Polling FD : hung up.");
	num_hup++;

      }

      if(pollfd.revents & (POLLIN | POLLPRI)) {
	int count;
	count = read (fdpty, buf, 256);
	if(count > 0) {
	  unsigned int i;
	  buf[count] = '\0';
	  g_printf("%s", buf);
	  for(i=0; i<count; i++) {
	    switch(read_state) {
	    case GET_LINE:
	      if(buf[i] == '\n') {
		read_state = GET_SEMI;
		g_debug("Tracecontrol input line skip\n");
	      }
	      break;
	    case GET_SEMI:
	      if(buf[i] == ':') {
		g_debug("Tracecontrol input  : marker found\n");
		read_state = GET_SPACE;
	      }
	      break;
	    case GET_SPACE:
	      if(buf[i] == ' ') {
		g_debug("Tracecontrol input space marker found\n");
		goto write_password;
	      }
	      break;
	    }
	  }
	} else if(count == -1) {
	  perror("Error in read");
	  goto wait_child;
	}

      }

      if(num_hup > 0) {
        g_warning("Child hung up without returning a full reply");
        goto wait_child;
      }
    }
write_password:
		fsync(fdpty);
		pollfd.fd = fdpty;
		pollfd.events = POLLOUT|POLLERR|POLLHUP|POLLNVAL;

		num_rdy = poll(&pollfd, 1, -1);
		if(num_rdy == -1) {
			perror("Poll error");
			goto wait_child;
		}

    /* Write the password */
    g_info("Got su prompt, now writing password...");
    int ret;
		sleep(1);
    ret = write(fdpty, password, strlen(password));
    if(ret < 0) perror("Error in write");
    ret = write(fdpty, "\n", 1);
    if(ret < 0) perror("Error in write");
    fsync(fdpty);
    /* Take the output from the terminal and show it on the real console */
    g_info("Getting data from child terminal...");
    while(1) {
      int num_hup = 0;
      pollfd.fd = fdpty;
      pollfd.events = POLLIN|POLLPRI|POLLERR|POLLHUP|POLLNVAL;

      num_rdy = poll(&pollfd, 1, -1);
      if(num_rdy == -1) {
        perror("Poll error");
        goto wait_child;
      }
      if(num_rdy == 0) break;
	
			if(pollfd.revents & (POLLERR|POLLNVAL)) {
				g_warning("Error returned in polling fd\n");
				num_hup++;
			}

			if(pollfd.revents & (POLLIN|POLLPRI) ) {
				count = read (fdpty, buf, 256);
				if(count > 0) {
					buf[count] = '\0';
					printf("%s", buf);
				} else if(count == -1) {
					perror("Error in read");
					goto wait_child;
				}
			}

			if(pollfd.revents & POLLHUP) {
        g_info("Polling FD : hung up.");
        num_hup++;
			}

      if(num_hup > 0) goto wait_child;
    }
wait_child:
    g_info("Waiting for child exit...");
    
    ret = waitpid(pid, &status, 0);
    
    if(ret == -1) {
      g_warning("An error occured in wait : %s",
          strerror(errno));
    } else {
      if(WIFEXITED(status))
        if(WEXITSTATUS(status) != 0) {
          retval = WEXITSTATUS(status);
          g_warning("An error occured in the su command : %s",
              strerror(retval));
        }
    }

    g_info("Child exited.");

  } else if(pid == 0) {
    /* Setup environment variables */
    if(strcmp(lttd_path, "") != 0)
      setenv("LTT_DAEMON", lttd_path, 1);
   
		/* One comment line (must be only one) */
    g_printf("Executing (as %s) : %s\n", username, command);
    
    execlp("su", "su", "-p", "-c", command, username, NULL);
    exit(-1); /* not supposed to happen! */
    
    //gint ret = execvp();
  
  } else {
    /* error */
    g_warning("Error happened when forking for su");
  }

  return retval;
}
int
main (int argc, char **argv)
{
	GnomeVFSAsyncHandle *handle;
	gchar *text_uri;
	GTimer *timer;
	CallbackData callback_data;

	GOptionContext *ctx = NULL;
	GError *error = NULL;

	g_printf("Initializing gnome-libs...");

	ctx = g_option_context_new("test-vfs");
	g_option_context_add_main_entries(ctx, options, NULL);

	if (!g_option_context_parse(ctx, &argc, &argv, &error)) {
		g_printerr("main: %s\n", error->message);

		g_error_free(error);
		g_option_context_free(ctx);
		return 1;
	}

	g_option_context_free(ctx);

	if (argc != 2 || argv[1] == NULL) {
		g_printerr("Usage: %s [<options>] <uri>\n", argv[0]);
		return 1;
	}

	text_uri = g_strdup(argv[1]);

	puts ("Initializing gnome-vfs...");
	gnome_vfs_init ();

	printf ("%d item(s) per notification\n", items_per_notification);

	if (measure_speed) {
		timer = g_timer_new ();
		g_timer_start (timer);
	} else {
		timer = NULL;
	}

	callback_data.num_entries_read = 0;
	callback_data.parent_uri = text_uri;
	async_task_counter = 1;
	gnome_vfs_async_load_directory
		(&handle,
		 text_uri,
		 (GNOME_VFS_FILE_INFO_GET_MIME_TYPE | GNOME_VFS_FILE_INFO_FOLLOW_LINKS),
		 items_per_notification,
		 0,
		 directory_load_callback,
		 &callback_data);

	if (!measure_speed)
		puts ("main loop running.");

	main_loop = g_main_loop_new (NULL, TRUE);
	g_main_loop_run (main_loop);
	g_main_loop_unref (main_loop);

	if (measure_speed) {
		gdouble elapsed_seconds;

		g_timer_stop (timer);
		elapsed_seconds = g_timer_elapsed (timer, NULL);
		printf ("%.5f seconds for %d entries, %.5f entries/sec.\n",
			elapsed_seconds, callback_data.num_entries_read,
			(double) callback_data.num_entries_read / elapsed_seconds);
	}

	if (!measure_speed)
		puts ("GTK+ main loop finished."); fflush (stdout);

	puts ("All done");

	gnome_vfs_shutdown ();

	return 0;
}
Example #17
0
static DeskmenuObject
*check_file_cache (Deskmenu *deskmenu, gchar *filename) {
	DeskmenuObject *dm_object;
	gchar *user_default = g_build_path (G_DIR_SEPARATOR_S,  g_get_user_config_dir (),
									"compiz",
									"boxmenu",
									"menu.xml",
									NULL);

	//TODO: add a size column to cache for possible autorefresh
		g_print("Checking cache...\n");
	if (strlen(filename) == 0)
    filename = g_build_path (G_DIR_SEPARATOR_S,
                               g_get_user_config_dir (),
                               "compiz",
                               "boxmenu",
                               "menu.xml",
                               NULL);
	if (strcmp(filename, user_default) == 0) {
		g_print("Looking up default menu...\n");
			/*
			set default filename to be [configdir]/compiz/boxmenu/menu.xml
			*/
			gboolean success = FALSE;
		if (!g_file_test(filename, G_FILE_TEST_EXISTS)) {
				g_print("Getting default system menu...\n");
				const gchar* const *cursor = g_get_system_config_dirs ();
				gchar *path = NULL;
				while (*cursor)
				{
					g_free (path);
					path = g_strdup (*cursor);
					filename = g_build_path (G_DIR_SEPARATOR_S,
											path,
											"compiz",
											"boxmenu",
											"menu.xml",
											NULL);

					if (g_file_test(filename, G_FILE_TEST_EXISTS))
					{
						if (g_hash_table_lookup(deskmenu->file_cache, filename) == NULL)
						{
							g_hash_table_insert (deskmenu->file_cache, g_strdup(filename), deskmenu_parse_file(filename));
							g_print("Prepared default system menu!\n");
						}
						else
						{
							g_print("Retrieving default system menu!\n");
						}
						g_free (path);
						success = TRUE;
						break;
					}
						cursor++;
				}
			}
		else
			{
				if (g_hash_table_lookup(deskmenu->file_cache, user_default) == NULL)
				{
					if (g_file_test(filename, G_FILE_TEST_EXISTS)) {
						g_print("Preparing default menu!\n");
						g_hash_table_insert (deskmenu->file_cache, g_strdup(filename), deskmenu_parse_file(filename));
						success = TRUE;
					}
				}
				else
				{
					g_print("Retrieving cached default user menu...\n");
					success = TRUE;
				}
			}
		if (!success)
		{
			g_printerr ("Couldn't find a menu file...\n");
			exit (1);
		}
	}
	else {
		if (g_hash_table_lookup(deskmenu->file_cache, filename) == NULL) {
			if (g_file_test(filename, G_FILE_TEST_EXISTS))
			{
				g_print("Preparing new non-default menu...\n");
				g_hash_table_insert (deskmenu->file_cache, g_strdup(filename), deskmenu_parse_file(filename));
			}
			else 
			{
				if (g_hash_table_lookup(deskmenu->file_cache, user_default) != NULL)
				{
					g_print("Couldn't find specified file, loading default...\n");
					filename = user_default;
				}
				else
				{
					g_printerr ("Couldn't find a menu file...\n");
					exit (1);
				}
			}
		}
	}

	dm_object = g_hash_table_lookup (deskmenu->file_cache, filename);

	g_printf("Done loading %s!\n", filename);

	return dm_object;
}
Example #18
0
/*GUardar lo de la interfaz*/
void save(GtkWidget *widget, gpointer user_data){ 
printf("Entre a save %s\n",gtk_entry_get_text (GTK_ENTRY(txtNewFile)));
int a,b,x; 
char newfile[50];
//char text; 
 //strcpy(nombreArchivo,gtk_entry_get_text(GTK_ENTRY(txtfileCreate)));
strcpy(newfile,gtk_entry_get_text (GTK_ENTRY(txtNewFile)) );
printf("Newfile=%s\n",newfile );
    g_printf("--------------------- %d\n");  
    printf("%d \n", tamanio);  
    for(x=0; x<tamanio;x++){ 
        if(x==0){
            g_printf("%s\0", gtk_entry_get_text(GTK_ENTRY(nombres[x])));
        } 
        else{ 
            g_printf(",%s\0", gtk_entry_get_text(GTK_ENTRY(nombres[x])));
        }
    }  
    printf("\n");
    for (a = 0; a < tamanio; a++){
        for (b = 0; b < tamanio; b++){ 
            printf("v%d",a); 
            printf("-v%d",b); 
            printf("=%s\n", gtk_entry_get_text (distancias[b][a]) );
        }
    }

printf("--------------------- %d\n"); 

   FILE *fp;

   fp = fopen(newfile, "w"); 

    fprintf(fp, "%d \n", tamanio);  
        for(x=0; x<tamanio;x++){   
        if(strcmp(gtk_entry_get_text(GTK_ENTRY(nombres[x])), " ")){
            if(x==0){
                fprintf(fp, "%s\0", gtk_entry_get_text(GTK_ENTRY(nombres[x])));
            } 
            else{ 
                fprintf(fp, ",%s\0", gtk_entry_get_text(GTK_ENTRY(nombres[x])));
            } 
        } 
        else{  
            if(x==0){
                fprintf(fp, "inf \0");
            } 
            else{ 
                fprintf(fp, ",inf \0");
            } 

        }
    } 
    fprintf(fp, "\n");
    for (a = 0; a < tamanio; a++){
        for (b = 0; b < tamanio; b++){ 
            fprintf(fp,"v%d",a); 
            fprintf(fp, "-v%d",b); 
            fprintf(fp, "=%s\n", gtk_entry_get_text (distancias[b][a]));
        }
    }

   fclose(fp);
} 
Example #19
0
/* Internal function: flush a window's text buffer to the screen. */
void
flush_window_buffer(winid_t win)
{
#ifdef DEBUG_STYLES
	g_printf("%s\n", win->buffer->str);
#endif
	if(win->type != wintype_TextBuffer && win->type != wintype_TextGrid)
		return;

	if(win->buffer->len == 0)
		return;

	gdk_threads_enter();

	GtkTextBuffer *buffer = gtk_text_view_get_buffer( GTK_TEXT_VIEW(win->widget) );

	switch(win->type) {
	case wintype_TextBuffer:
	{
		GtkTextIter start, end;
		gtk_text_buffer_get_end_iter(buffer, &end);
		gint start_offset;

		start_offset = gtk_text_iter_get_offset(&end);
		gtk_text_buffer_insert(buffer, &end, win->buffer->str, -1);
		gtk_text_buffer_get_iter_at_offset(buffer, &start, start_offset);
		style_apply(win, &start, &end);

		ChimaraGlk *glk = CHIMARA_GLK(gtk_widget_get_ancestor(win->widget, CHIMARA_TYPE_GLK));
		g_assert(glk);
		g_signal_emit_by_name(glk, "text-buffer-output", win->rock, win->librock, win->buffer->str);
	}
		break;

	case wintype_TextGrid:
	{
		/* Number of characters to insert */
		glong length = win->buffer->len;
		glong chars_left = length;
		
		GtkTextMark *cursor = gtk_text_buffer_get_mark(buffer, "cursor_position");
		
		/* Get cursor position */
		GtkTextIter start, insert;
		gint start_offset;

		gtk_text_buffer_get_iter_at_mark(buffer, &insert, cursor);

		while(chars_left > 0 && !gtk_text_iter_is_end(&insert))
		{
			/* Spaces available on this line */
			gint available_space = win->width - gtk_text_iter_get_line_offset(&insert);
		
			GtkTextIter end = insert;
			if(chars_left <= available_space)
				gtk_text_iter_forward_chars(&end, chars_left);
			else
				gtk_text_iter_forward_to_line_end(&end);

			gtk_text_buffer_delete(buffer, &insert, &end);

			start_offset = gtk_text_iter_get_offset(&insert);
			gtk_text_buffer_insert(buffer, &insert, win->buffer->str + (length - chars_left), MIN(chars_left, available_space));
			gtk_text_buffer_get_iter_at_offset(buffer, &start, start_offset);
			style_apply(win, &start, &insert);
			
			chars_left -= available_space;

			if(gtk_text_iter_get_line_offset(&insert) >= win->width)
				gtk_text_iter_forward_line(&insert);
		}

		gtk_text_buffer_move_mark(buffer, cursor, &insert);
	}
		break;
	}

	gdk_threads_leave();

	g_string_truncate(win->buffer, 0);
}
Example #20
0
File: conf.c Project: Nimain/riofs
/**
 * Prints content of config file to stdout
 */
void conf_print (ConfData *conf)
{
    g_printf ("=============== \n");
    g_hash_table_foreach (conf->h_conf, conf_node_print, NULL);
    g_printf ("=============== \n");
}
Example #21
0
void
gegl_exit (void)
{
  if (!config)
    {
      g_warning("gegl_exit() called without matching call to gegl_init()");
      return;
    }

  GEGL_INSTRUMENT_START()

  gegl_tile_backend_swap_cleanup ();
  gegl_tile_cache_destroy ();
  gegl_operation_gtype_cleanup ();
  gegl_extension_handler_cleanup ();
  gegl_random_cleanup ();
  gegl_cl_cleanup ();

  gegl_temp_buffer_free ();

  if (module_db != NULL)
    {
      g_object_unref (module_db);
      module_db = NULL;
    }

  babl_exit ();

  GEGL_INSTRUMENT_END ("gegl", "gegl_exit")

  /* used when tracking buffer and tile leaks */
  if (g_getenv ("GEGL_DEBUG_BUFS") != NULL)
    {
      gegl_buffer_stats ();
      gegl_tile_backend_ram_stats ();
      gegl_tile_backend_file_stats ();
    }
  global_time = gegl_ticks () - global_time;
  gegl_instrument ("gegl", "gegl", global_time);

  if (gegl_instrument_enabled)
    {
      g_printf ("\n%s", gegl_instrument_utf8 ());
    }

  if (gegl_buffer_leaks ())
    {
      g_printf ("EEEEeEeek! %i GeglBuffers leaked\n", gegl_buffer_leaks ());
#ifdef GEGL_ENABLE_DEBUG
      if (!(gegl_debug_flags & GEGL_DEBUG_BUFFER_ALLOC))
        g_printerr ("To debug GeglBuffer leaks, set the environment "
                    "variable GEGL_DEBUG to \"buffer-alloc\"\n");
#endif
    }
  gegl_tile_cache_destroy ();

  if (gegl_swap_dir ())
    {
      /* remove all files matching <$GEGL_SWAP>/GEGL-<pid>-*.swap */

      guint         pid     = getpid ();
      GDir         *dir     = g_dir_open (gegl_swap_dir (), 0, NULL);

      gchar        *glob    = g_strdup_printf ("%i-*", pid);
      GPatternSpec *pattern = g_pattern_spec_new (glob);
      g_free (glob);

      if (dir != NULL)
        {
          const gchar *name;

          while ((name = g_dir_read_name (dir)) != NULL)
            {
              if (g_pattern_match_string (pattern, name))
                {
                  gchar *fname = g_build_filename (gegl_swap_dir (),
                                                   name,
                                                   NULL);
                  g_unlink (fname);
                  g_free (fname);
                }
            }

          g_dir_close (dir);
        }

      g_pattern_spec_free (pattern);
    }
  g_object_unref (config);
  config = NULL;
  global_time = 0;
}
static gboolean on_timeout(gpointer user_data)
{
    g_printf("timeout!\n");
    gtk_main_quit();
    return FALSE;
}
Example #23
0
int
cliprdr_init()
{
  char filename[256];
  struct list* names;
  struct list* values;
  char* name;
  char* value;
  int index;
  int display_num;

  display_num = g_get_display_num_from_display(g_getenv("DISPLAY"));
	if(display_num == 0)
	{
		g_printf("cliprdr[cliprdr_init]: Display must be different of 0\n");
		return ERROR;
	}
	l_config = g_malloc(sizeof(struct log_config), 1);
	l_config->program_name = "cliprdr";
	l_config->log_file = 0;
	l_config->fd = 0;
	l_config->log_level = LOG_LEVEL_DEBUG;
	l_config->enable_syslog = 0;
	l_config->syslog_level = LOG_LEVEL_DEBUG;

  names = list_create();
  names->auto_free = 1;
  values = list_create();
  values->auto_free = 1;
  g_snprintf(filename, 255, "%s/cliprdr.conf", XRDP_CFG_PATH);
  if (file_by_name_read_section(filename, CLIPRDR_CFG_GLOBAL, names, values) == 0)
  {
    for (index = 0; index < names->count; index++)
    {
      name = (char*)list_get_item(names, index);
      value = (char*)list_get_item(values, index);
      if (0 == g_strcasecmp(name, CLIPRDR_CFG_NAME))
      {
        if( g_strlen(value) > 1)
        {
        	l_config->program_name = (char*)g_strdup(value);
        }
      }
    }
  }
  if (file_by_name_read_section(filename, CLIPRDR_CFG_LOGGING, names, values) == 0)
  {
    for (index = 0; index < names->count; index++)
    {
      name = (char*)list_get_item(names, index);
      value = (char*)list_get_item(values, index);
      if (0 == g_strcasecmp(name, CLIPRDR_CFG_LOG_LEVEL))
      {
      	l_config->log_level = log_text2level(value);
      }
    }
  }
  list_delete(names);
  list_delete(values);

	if(log_start(l_config) != LOG_STARTUP_OK)
	{
		g_printf("vchannel[vchannel_init]: Unable to start log system\n");
		return ERROR;
	}
  else
  {
  	return LOG_STARTUP_OK;
  }
  return 0;
}
static void on_finish_loading(FmFolder* folder)
{
    g_printf("finished\n");
    g_main_loop_quit(loop);
}
Example #25
0
int
main(
    int		argc,
    char **	argv)
{
    const char *v;
    char *verstr;
    size_t v_len;

    (void)argc;	/* Quiet unused parameter warning */
    (void)argv;	/* Quiet unused parameter warning */

    /*
     * Configure program for internationalization:
     *   1) Only set the message locale for now.
     *   2) Set textdomain for all amanda related programs to "amanda"
     *      We don't want to be forced to support dozens of message catalogs.
     */  
    setlocale(LC_MESSAGES, "C");
    textdomain("amanda"); 

    g_printf(_("/* version.c - generated by genversion.c - DO NOT EDIT! */\n"));
    g_printf("const char * const version_info[] = {\n");

    startline("build:");
    v = VERSION;
    v_len = sizeof("Amanda-") + strlen(v) + 1;
    verstr = malloc(v_len);
    if (!verstr) {
	g_fprintf(stderr, _("genversion: Not enough memory"));
	abort();
	/*NOTREACHED*/
    }
    g_snprintf(verstr, v_len, "Amanda-%s", v);		/* safe */
    prvar("VERSION", verstr);
    free(verstr);

#ifdef BUILT_DATE
    prvar("BUILT_DATE", BUILT_DATE);
#else
    prundefvar("BUILT_DATE");
#endif

#ifdef BUILT_MACH
    prvar("BUILT_MACH", BUILT_MACH);
#else
    prundefvar("BUILT_MACH");
#endif

#ifdef BUILT_REV
    prvar("BUILT_REV", BUILT_REV);
#else
    prundefvar("BUILT_REV");
#endif

#ifdef BUILT_BRANCH
    prvar("BUILT_BRANCH", BUILT_BRANCH);
#else
    prundefvar("BUILT_BRANCH");
#endif

#ifdef CC
    prvar("CC", CC);
#else
    prundefvar("CC");
#endif

    endline();

    startline("paths:");

    prvar("bindir", bindir);
    prvar("sbindir", sbindir);
    prvar("libexecdir", libexecdir);
    prvar("amlibexecdir", amlibexecdir);
    prvar("mandir", mandir);
    prvar("AMANDA_TMPDIR", AMANDA_TMPDIR);
#ifdef AMANDA_DBGDIR
    prvar("AMANDA_DBGDIR", AMANDA_DBGDIR);
#else
    prundefvar("AMANDA_DBGDIR");
#endif
    prvar("CONFIG_DIR", CONFIG_DIR);

#ifdef DEV_PREFIX
    prvar("DEV_PREFIX", DEV_PREFIX);
#else
    prundefvar("DEV_PREFIX");
#endif

#ifdef RDEV_PREFIX
    prvar("RDEV_PREFIX", RDEV_PREFIX);
#else
    prundefvar("RDEV_PREFIX");
#endif

#ifdef DUMP
    prvar("DUMP", DUMP);
    prvar("RESTORE", RESTORE);
#else
    prundefvar("DUMP");
    prundefvar("RESTORE");
#endif

#ifdef VDUMP
    prvar("VDUMP", VDUMP);
    prvar("VRESTORE", VRESTORE);
#else
    prundefvar("VDUMP");
    prundefvar("VRESTORE");
#endif

#ifdef XFSDUMP
    prvar("XFSDUMP", XFSDUMP);
    prvar("XFSRESTORE", XFSRESTORE);
#else
    prundefvar("XFSDUMP");
    prundefvar("XFSRESTORE");
#endif

#ifdef VXDUMP
    prvar("VXDUMP", VXDUMP);
    prvar("VXRESTORE", VXRESTORE);
#else
    prundefvar("VXDUMP");
    prundefvar("VXRESTORE");
#endif

#ifdef SAMBA_CLIENT
    prvar("SAMBA_CLIENT", SAMBA_CLIENT);
#else
    prundefvar("SAMBA_CLIENT");
#endif

#ifdef GNUTAR
    prvar("GNUTAR", GNUTAR);
#else
    prundefvar("GNUTAR");
#endif

#ifdef COMPRESS_PATH
    prvar("COMPRESS_PATH", COMPRESS_PATH);
#else
    prundefvar("COMPRESS_PATH");
#endif

#ifdef UNCOMPRESS_PATH
    prvar("UNCOMPRESS_PATH", UNCOMPRESS_PATH);
#else
    prundefvar("UNCOMPRESS_PATH");
#endif

#ifdef LPRCMD
    prvar("LPRCMD", LPRCMD);
#else
    prundefvar(" LPRCMD");
#endif

#ifdef MAILER
    prvar("MAILER", MAILER);
#else
    prundefvar(" MAILER");
#endif

#ifdef GNUTAR_LISTED_INCREMENTAL_DIR
    prvar("listed_incr_dir", GNUTAR_LISTED_INCREMENTAL_DIR);
#else
    prundefvar("GNUTAR_LISTED_INCREMENTAL_DIR");
#endif
    endline();

    startline("defs:");

    prvar("DEFAULT_SERVER", DEFAULT_SERVER);
    prvar("DEFAULT_CONFIG", DEFAULT_CONFIG);
    prvar("DEFAULT_TAPE_SERVER", DEFAULT_TAPE_SERVER);

#ifdef DEFAULT_TAPE_DEVICE
    prvar("DEFAULT_TAPE_DEVICE", DEFAULT_TAPE_DEVICE);
#endif

#ifdef AIX_BACKUP
    prstr("AIX_BACKUP");
#endif

#ifdef BROKEN_VOID
    prstr("BROKEN_VOID");
#endif

#ifdef DUMP_RETURNS_1
    prstr("DUMP_RETURNS_1");
#endif

#ifdef HAVE_MMAP
    prstr("HAVE_MMAP");
#endif

#ifndef HAVE_STRERROR
    prstr("NEED_STRERROR");
#endif

#ifndef HAVE_STRSTR
    prstr("NEED_STRSTR");
#endif

#ifdef HAVE_SYSVSHM
    prstr("HAVE_SYSVSHM");
#endif

#ifdef WANT_AMFLOCK_POSIX
    prstr("AMFLOCK_POSIX");
#endif
#ifdef WANT_AMFLOCK_FLOCK
    prstr("AMFLOCK_FLOCK");
#endif
#ifdef WANT_AMFLOCK_LOCKF
    prstr("AMFLOCK_LOCKF");
#endif
#ifdef WANT_AMFLOCK_LNLOCK
    prstr("AMFLOCK_LNLOCK");
#endif

#ifdef STATFS_BSD
    prstr("STATFS_BSD");
#endif

#ifdef STATFS_OSF1
    prstr("STATFS_OSF1");
#endif

#ifdef STATFS_ULTRIX
    prstr("STATFS_ULTRIX");
#endif

#ifdef SETPGRP_VOID
    prstr("SETPGRP_VOID");
#endif

#ifdef ASSERTIONS
    prstr("ASSERTIONS");
#endif

#ifdef AMANDA_DEBUG_DAYS
    prnum("AMANDA_DEBUG_DAYS", AMANDA_DEBUG_DAYS);
#endif

#ifdef BSD_SECURITY
    prstr("BSD_SECURITY");
#endif

#ifdef KRB5_SECURITY
    prstr("KRB5_SECURITY");
#endif

#ifdef RSH_SECURITY
    prstr("RSH_SECURITY");
#endif

#ifdef USE_AMANDAHOSTS
    prstr("USE_AMANDAHOSTS");
#endif

#ifdef USE_RUNDUMP
    prstr("USE_RUNDUMP");
#endif

    prvar("CLIENT_LOGIN", CLIENT_LOGIN);

#ifdef CHECK_USERID
    prstr("CHECK_USERID");
#endif

#ifdef HAVE_GZIP
    prstr("HAVE_GZIP");
#endif

#ifdef COMPRESS_SUFFIX
    prvar("COMPRESS_SUFFIX", COMPRESS_SUFFIX);
#endif

#ifdef COMPRESS_FAST_OPT
    prvar("COMPRESS_FAST_OPT", COMPRESS_FAST_OPT);
#endif

#ifdef COMPRESS_BEST_OPT
    prvar("COMPRESS_BEST_OPT", COMPRESS_BEST_OPT);
#endif

#ifdef UNCOMPRESS_OPT
    prvar("UNCOMPRESS_OPT", UNCOMPRESS_OPT);
#endif

    endline();

    g_printf("  0\n};\n");

    return (0); /* exit */
}
Example #26
0
static void run(
  const gchar *     name,
  gint              nparams,
	const GimpParam * param,
	gint *            nreturn_vals,
	GimpParam **      return_vals)
{
  static GimpParam values[2];   /* Gimp return values. !!! Allow 2: status and error message. */
  TGimpAdapterParameters pluginParameters;
  TImageSynthParameters engineParameters;
  
  GimpDrawable *drawable = NULL;
  GimpDrawable *corpus_drawable = NULL; 
  GimpDrawable *map_in_drawable= NULL; 
  GimpDrawable *map_out_drawable= NULL; 
  gboolean ok, with_map;
  
  /* 
  Local copies of pixmaps (not using gimp regions.) 
  2-D arrays of Pixel, addressable by Coordinates (Point).
  c++: static Bitmap<Pixelel>
  */
  Map targetMap;
  Map corpusMap;
  Map targetMaskMap;
  Map corpusMaskMap;
  
  int cancelFlag = 0;
  
  #ifdef SYNTH_THREADED
  // This is as early as it can be called.  Not sure it needs to be called.  See later call to it.
  // Call it early since calls to gdk, gtk might require this?
  g_thread_init(NULL);
  #endif

  #ifdef DEBUG
  gimp_message_set_handler(1); // To console instead of GUI
  start_time = clock();
  #endif
  
  // internationalization i18n
  // Note these constants are defined in the build environment.
  /*  Initialize i18n support  */
#if defined(G_OS_WIN32)
  bindtextdomain (GETTEXT_PACKAGE, gimp_locale_directory());
#else
  bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
#endif
#ifdef HAVE_BIND_TEXTDOMAIN_CODESET
  bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
#endif
  textdomain (GETTEXT_PACKAGE);

  *nreturn_vals = 1;
  *return_vals = values;
  values[0].type = GIMP_PDB_STATUS;
  values[0].data.d_status = GIMP_PDB_EXECUTION_ERROR; /* Unless everything succeeds. */
  
  drawable = gimp_drawable_get(param[2].data.d_drawable);

  /* Check image type (could be called non-interactive) */
  if (!gimp_drawable_is_rgb(drawable->drawable_id) &&
      !gimp_drawable_is_gray(drawable->drawable_id)) 
  {
    ERROR_RETURN(_("Incompatible image mode."));
  }


  /* Deal with run mode */
  ok = FALSE;
  switch(param[0].data.d_int32) 
  {
    case GIMP_RUN_INTERACTIVE :
      ok = get_last_parameters(&pluginParameters,drawable->drawable_id, RESYNTH_ENGINE_PDB_NAME);
      gimp_message("Resynthesizer engine should not be called interactively");
      /* But keep going with last (or default) parameters, really no harm. */
      break;
    case GIMP_RUN_NONINTERACTIVE :
      ok = get_parameters_from_list(&pluginParameters, nparams, param); 
      break;
    case GIMP_RUN_WITH_LAST_VALS :
      ok = get_last_parameters(&pluginParameters,drawable->drawable_id, RESYNTH_ENGINE_PDB_NAME); 
      break;
  }

  if (!ok) 
  {
    ERROR_RETURN(_("Resynthesizer failed to get parameters."));
  }
  
  /* Limit neighbours parameter to size allocated. */
  if (pluginParameters.neighbours > IMAGE_SYNTH_MAX_NEIGHBORS )
    pluginParameters.neighbours = IMAGE_SYNTH_MAX_NEIGHBORS;
  
  corpus_drawable = gimp_drawable_get(pluginParameters.corpus_id);
  
  /* The target and corpus must have the same base type.
  In earlier version, they must have the same bpp.
  But now we don't compare the alphas, so they can differ in presence of alpha.
  */
  if (! equal_basetypes(drawable, corpus_drawable) )
  {
    ERROR_RETURN(_("The input texture and output image must have the same number of color channels."));
  }
  
  
  with_map = (pluginParameters.input_map_id != -1 && pluginParameters.output_map_id != -1);
  /* If only one map is passed, it is ignored quietly. */
  map_in_drawable=0;
  map_out_drawable=0;

  if (with_map) 
  {
    map_in_drawable = gimp_drawable_get(pluginParameters.input_map_id);
    map_out_drawable = gimp_drawable_get(pluginParameters.output_map_id);
    /* All these can be wrong at the same time.  
    Forego userfriendliness for ease of programming: abort on first error
    */
    if ( ! equal_basetypes(map_in_drawable, map_out_drawable) )
    {
      /* Maps need the same base type. Formerly needed the same bpp. */
      ERROR_RETURN(_("The input and output maps must have the same mode"));
    } 
    if (map_in_drawable->width != corpus_drawable->width || 
               map_in_drawable->height != corpus_drawable->height) 
    {
      ERROR_RETURN(_("The input map should be the same size as the input texture image"));
    } 
    if (map_out_drawable->width != drawable->width || 
               map_out_drawable->height != drawable->height) 
    {
      ERROR_RETURN(_("The output map should be the same size as the output image"));
    }
  }

  /* 
  The engine should not be run interactively so no need to store last values. 
  I.E. the meaning of "last" is "last values set by user interaction".
  */
  
  #ifdef ANIMATE
  // Copy local pointer vars to globals
  targetDrawableCopy = drawable;
  targetMapCopy = &targetMap;
  #endif
  
  /* Error checks done, initialization work begins.  So start progress callbacks. */
  progressStart("Initializing...");
  
  /* 
  Set flags for presence of alpha channels. 
  The flag is an optimization.  Alternatives:
  - a function
  - OR standardize the internal pixmap to ALWAYS have an alpha pixelel
  initialized to VISIBLE and set from any alpha pixelel.
  */
  gboolean is_alpha_image = gimp_drawable_has_alpha(drawable->drawable_id);
  gboolean is_alpha_corpus = gimp_drawable_has_alpha(corpus_drawable->drawable_id);
  
  // Image adaption requires format indices
  // WAS  prepareImageFormatIndices(drawable, corpus_drawable, with_map, map_in_drawable);
  TFormatIndices formatIndices;
  
  guint map_count = (with_map? count_color_channels(map_in_drawable) : 0 );
    
  prepareImageFormatIndices(
    &formatIndices,
    count_color_channels(drawable),
    map_count,
    is_alpha_image,
    is_alpha_corpus,
    with_map
    );
  
  #ifdef ADAPT_SIMPLE
    /* Adapt Gimp to an engine with a simpler interface. */
    setDefaultParams(&parameters);
    ImageBuffer imageBuffer;
    ImageBuffer maskBuffer;
    
    // TODO change to new signature
    adaptGimpToSimple(drawable, &imageBuffer, &maskBuffer);  // From Gimp to simple
    g_printf("Here3\n");
    adaptSimpleAPI(&imageBuffer, &maskBuffer);        // From simple to existing engine API
    
  #else
    g_printf("Gimp adaption\n");
    /* target/context adaption */
    fetch_image_mask_map(drawable, &targetMap, formatIndices.total_bpp, 
      &targetMaskMap, 
      MASK_TOTALLY_SELECTED, 
      map_out_drawable, formatIndices.map_start_bip);
    
      #ifdef ANIMATE
      clear_target_pixels(formatIndices.colorEndBip);  // For debugging, blacken so new colors sparkle
      #endif
  
    /*  corpus adaption */
    fetch_image_mask_map(corpus_drawable, &corpusMap, formatIndices.total_bpp, 
      &corpusMaskMap,
      MASK_TOTALLY_SELECTED, 
      map_in_drawable, formatIndices.map_start_bip);
      
    // TODO These are artifacts of earlier design, not used.
    free_map(&corpusMaskMap);
    free_map(&targetMaskMap);
    
    adaptPluginToLibraryParameters(&pluginParameters, &engineParameters);
    
  #endif
  
  // After possible adaption, check size again
  g_assert(targetMap.width * targetMap.height); // Image is not empty
  g_assert(corpusMap.width * corpusMap.height); // Corpus is not empty
  
  // Done with adaption: now main image data in canonical pixmaps, etc.
  // Begin real work
  progressStart(_("synthesizing..."));
  
  int result = engine(
    engineParameters, 
    &formatIndices, 
    &targetMap, 
    &corpusMap,
    progressUpdate,
    (void *) 0,
    &cancelFlag
    );
  
  if (result == IMAGE_SYNTH_ERROR_EMPTY_CORPUS)
  {
    ERROR_RETURN(_("The texture source is empty. Does any selection include non-transparent pixels?"));
  }
  else if  (result == IMAGE_SYNTH_ERROR_EMPTY_TARGET )
  {
    ERROR_RETURN(_("The output layer is empty. Does any selection have visible pixels in the active layer?"));
  }
  
  // Normal post-process adaption follows

  /* dump_target_points(); */ /* detailed debugging. */
  // print_post_stats();
  
  // Update Gimp image from local pixmap
  // Note this works even for test harness where ADAPT_SIMPLE
  // but then it does NOT test returning results in buffer.
  
  /* 
  We could test antiAdaptImage() here.
  But antiAdaptImage() has already been tested once on the incoming side.
  So no compelling need to test it again here.
  */
  post_results_to_gimp(drawable, targetMap); 
  
  /* Clean up */
  // Adapted
  free_map(&targetMap);
  free_map(&corpusMap);
  // GIMP
  detach_drawables(drawable, corpus_drawable, map_in_drawable, map_out_drawable);
  gimp_progress_end();
  values[0].data.d_status = GIMP_PDB_SUCCESS;
} 
Example #27
0
int
set_directory(
    char *	dir,
    int		verbose)
{
    char *cmd = NULL;
    char *new_dir = NULL;
    char *qnew_dir;
    char *dp, *de;
    char *ldir = NULL;
    int   result;

    /* do nothing if "." */
    if(strcmp(dir,".")==0) {
	show_directory();		/* say where we are */
	return 1;
	/*NOTREACHED*/
    }

    if (disk_name == NULL) {
	g_printf(_("Must select disk before setting directory\n"));
	return 0;
	/*NOTREACHED*/
    }

    ldir = stralloc(dir);
    clean_pathname(ldir);

    /* convert directory into absolute path relative to disk mount point */
    if (ldir[0] == '/')
    {
	/* absolute path specified, must start with mount point */
	if (strcmp(mount_point, "/") == 0)
	{
	    new_dir = stralloc(ldir);
	}
	else
	{
	    if (strncmp(mount_point, ldir, strlen(mount_point)) != 0)
	    {
		g_printf(_("Invalid directory - Can't cd outside mount point \"%s\"\n"),
		       mount_point);
		amfree(ldir);
		return 0;
		/*NOTREACHED*/
	    }
	    new_dir = stralloc(ldir+strlen(mount_point));
	    if (strlen(new_dir) == 0) {
		new_dir = newstralloc(new_dir, "/");
					/* i.e. ldir == mount_point */
	    }
	}
    }
    else
    {
	new_dir = stralloc(disk_path);
	dp = ldir;
	/* strip any leading ..s */
	while (strncmp(dp, "../", 3) == 0)
	{
	    de = strrchr(new_dir, '/');	/* always at least 1 */
	    if (de == new_dir)
	    {
		/* at top of disk */
		*(de + 1) = '\0';
		dp = dp + 3;
	    }
	    else
	    {
		*de = '\0';
		dp = dp + 3;
	    }
	}
	if (strcmp(dp, "..") == 0) {
	    if (strcmp(new_dir, "/") == 0) {
		/* at top of disk */
		g_printf(_("Invalid directory - Can't cd outside mount point \"%s\"\n"),
		       mount_point);
		/*@ignore@*/
		amfree(new_dir);
		/*@end@*/
		amfree(ldir);
		return 0;
		/*NOTREACHED*/
	    }
	    de = strrchr(new_dir, '/');	/* always at least 1 */
	    if (de == new_dir)
	    {
		/* at top of disk */
		*(de+1) = '\0';
	    }
	    else
	    {
		*de = '\0';
 	    }
	} else {
	    /*@ignore@*/
	    if (strcmp(new_dir, "/") != 0) {
		strappend(new_dir, "/");
	    }
	    strappend(new_dir, ldir);
	    /*@end@*/
	}
    }

    qnew_dir = quote_string(new_dir);
    cmd = stralloc2("OISD ", qnew_dir);
    amfree(qnew_dir);
    if (exchange(cmd) == -1) {
	exit(1);
	/*NOTREACHED*/
    }
    amfree(cmd);

    if (server_happy())
    {
	disk_path = newstralloc(disk_path, new_dir);
	suck_dir_list_from_server();	/* get list of directory contents */
	if (verbose)
	    show_directory();		/* say where we moved to */
	result = 1;
    }
    else
    {
	g_printf(_("Invalid directory - %s\n"), dir);
	result = 0;
    }

    /*@ignore@*/
    amfree(new_dir);
    amfree(ldir);
    /*@end@*/

    return result;
}
Example #28
0
G_MODULE_EXPORT
void ElbowMainToolOpen(GtkWidget * object, gpointer user_data) {
    g_printf("Hello there.\n");
    return;
}
Example #29
0
int DEFAULT_CC
main(int argc, char** argv)
{
  int sck;
  int code;
  int i;
  int size;
  int version;
  int width;
  int height;
  int bpp;
  int keylayout;
  int display;
  struct stream* in_s;
  struct stream* out_s;
  char* username;
  char* password;
  char* exec;
  long data;

  if (0 != config_read(&g_cfg))
  {
    g_printf("sesrun: error reading config. quitting.\n");
    return 1;
  }

  g_pid = g_getpid();
  if (argc == 1)
  {
    g_printf("xrdp session starter v0.2\n");
    g_printf("\nusage:\n");
    g_printf("sesrun <server> <username> <password> <exec> <width> <height> <bpp> <keylayout>\n");
  }
  else if (argc == 9)
  {
    username = argv[2];
    password = argv[3];
    exec = argv[4];
    width = g_atoi(argv[5]);
    height = g_atoi(argv[6]);
    bpp = g_atoi(argv[7]);
    keylayout = g_atoi(argv[8]);
    make_stream(in_s);
    init_stream(in_s, 8192);
    make_stream(out_s);
    init_stream(out_s, 8192);
    sck = g_tcp_socket();
    if (g_tcp_connect(sck, argv[1], "3350") == 0)
    {
      s_push_layer(out_s, channel_hdr, 8);
      out_uint16_be(out_s, 20); /* code */
      i = g_strlen(username);
      out_uint16_be(out_s, i);
      out_uint8a(out_s, username, i);
      i = g_strlen(password);
      out_uint16_be(out_s, i);
      out_uint8a(out_s, password, i);
      i = g_strlen(exec);
      out_uint16_be(out_s, i);
      out_uint8a(out_s, exec, i);
      out_uint16_be(out_s, width);
      out_uint16_be(out_s, height);
      out_uint16_be(out_s, bpp);
      out_uint16_be(out_s, keylayout);
      s_mark_end(out_s);
      s_pop_layer(out_s, channel_hdr);
      out_uint32_be(out_s, 0); /* version */
      out_uint32_be(out_s, out_s->end - out_s->data); /* size */
      tcp_force_send(sck, out_s->data, out_s->end - out_s->data);
      if (tcp_force_recv(sck, in_s->data, 8) == 0)
      {
        in_uint32_be(in_s, version);
        in_uint32_be(in_s, size);
        init_stream(in_s, 8192);
        if (tcp_force_recv(sck, in_s->data, size - 8) == 0)
        {
          if (version == 0)
          {
            in_uint16_be(in_s, code);
            if (code == 3)
            {
              in_uint16_be(in_s, data);
              in_uint16_be(in_s, display);
              g_printf("ok %d display %d\n", data, display);
            }
          }
        }
      }
    }
    else
    {
      g_printf("connect error\n");
    }
    g_tcp_close(sck);
    free_stream(in_s);
    free_stream(out_s);
  }
  return 0;
}
Example #30
0
int
dumper_cmd(
    dumper_t *dumper,
    cmd_t cmd,
    disk_t *dp,
    char   *mesg)
{
    char *cmdline = NULL;
    char number[NUM_STR_SIZE];
    char numberport[NUM_STR_SIZE];
    char *o;
    char *device;
    char *features;
    char *qname;
    char *qmesg;

    switch(cmd) {
    case START:
	cmdline = vstralloc(cmdstr[cmd], " ", mesg, "\n", NULL);
	break;
    case PORT_DUMP:
	if(dp && dp->device) {
	    device = dp->device;
	}
	else {
	    device = "NODEVICE";
	}

	if (dp != NULL) {
	    application_t *application = NULL;
	    char *plugin;
	    char *qplugin;
	    char *qamandad_path;
	    char *qclient_username;
	    char *qclient_port;
	    char *qssh_keys;

	    if (dp->application != NULL) {
		application = lookup_application(dp->application);
		g_assert(application != NULL);
	    }

	    device = quote_string((dp->device) ? dp->device : "NODEVICE");
	    qname = quote_string(dp->name);
	    g_snprintf(number, SIZEOF(number), "%d", sched(dp)->level);
	    g_snprintf(numberport, SIZEOF(numberport), "%d", dumper->output_port);
	    features = am_feature_to_string(dp->host->features);
	    if (am_has_feature(dp->host->features, fe_req_xml)) {
		o = xml_optionstr(dp, dp->host->features, NULL, 1);
		if (application) {
		    char *xml_app;
		    xml_app = xml_application(dp, application,
					      dp->host->features);
		    vstrextend(&o, xml_app, NULL);
		    amfree(xml_app);
		}
		o = quote_string(o);
	    } else {
		o = optionstr(dp, dp->host->features, NULL);
	    }
	    if ( o == NULL ) {
	      error(_("problem with option string, check the dumptype definition.\n"));
	    }

	    g_assert(dp->program);
	    if (0 == strcmp(dp->program, "APPLICATION")) {
		g_assert(application != NULL);
		plugin = application_get_plugin(application);
	    } else {
		plugin = dp->program;
	    }
	    qplugin = quote_string(plugin);
	    qamandad_path = quote_string(dp->amandad_path);
	    qclient_username = quote_string(dp->client_username);
	    qclient_port = quote_string(dp->client_port);
	    qssh_keys = quote_string(dp->ssh_keys);
	    dbprintf("security_driver %s\n", dp->auth);

	    cmdline = vstralloc(cmdstr[cmd],
			    " ", disk2serial(dp),
			    " ", numberport,
			    " ", dp->host->hostname,
			    " ", features,
			    " ", qname,
			    " ", device,
			    " ", number,
			    " ", sched(dp)->dumpdate,
			    " ", qplugin,
			    " ", qamandad_path,
			    " ", qclient_username,
			    " ", qclient_port,
			    " ", qssh_keys,
			    " ", dp->auth,
			    " ", data_path_to_string(dp->data_path),
			    " |", o,
			    "\n", NULL);
	    amfree(qplugin);
	    amfree(qamandad_path);
	    amfree(qclient_username);
	    amfree(qclient_port);
	    amfree(qssh_keys);
	    amfree(features);
	    amfree(o);
	    amfree(qname);
	    amfree(device);
	} else {
		error(_("PORT-DUMP without disk pointer\n"));
		/*NOTREACHED*/
	}
	break;
    case QUIT:
    case ABORT:
	qmesg = quote_string(mesg);
	cmdline = vstralloc(cmdstr[cmd], " ", qmesg, "\n", NULL );
	amfree(qmesg);
	break;
    default:
	error(_("Don't know how to send %s command to dumper"), cmdstr[cmd]);
	/*NOTREACHED*/
    }

    /*
     * Note: cmdline already has a '\n'.
     */
    if(dumper->down) {
	g_printf(_("driver: send-cmd time %s ignored to down dumper %s: %s"),
	       walltime_str(curclock()), dumper->name, cmdline);
    } else {
	g_printf(_("driver: send-cmd time %s to %s: %s"),
	       walltime_str(curclock()), dumper->name, cmdline);
	fflush(stdout);
	if (full_write(dumper->fd, cmdline, strlen(cmdline)) < strlen(cmdline)) {
	    g_printf(_("writing %s command: %s\n"), dumper->name, strerror(errno));
	    fflush(stdout);
	    amfree(cmdline);
	    return 0;
	}
	if (cmd == QUIT) aclose(dumper->fd);
    }
    amfree(cmdline);
    return 1;
}