Example #1
0
int
dgram_bind(
    dgram_t *	dgram,
    sa_family_t family,
    in_port_t *	portp)
{
    int s, retries;
    socklen_t_equiv len;
    sockaddr_union name;
    int save_errno;
    int *portrange;
    int sndbufsize = MAX_DGRAM;

    portrange = getconf_intrange(CNF_RESERVED_UDP_PORT);
    *portp = (in_port_t)0;
    g_debug("dgram_bind: setting up a socket with family %d", family);
    if((s = socket(family, SOCK_DGRAM, 0)) == -1) {
	save_errno = errno;
	dbprintf(_("dgram_bind: socket() failed: %s\n"),
		  strerror(save_errno));
	errno = save_errno;
	return -1;
    }
    if(s < 0 || s >= (int)FD_SETSIZE) {
	dbprintf(_("dgram_bind: socket out of range: %d\n"),
		  s);
	aclose(s);
	errno = EMFILE;				/* out of range */
	return -1;
    }

    /* try setting the buffer size (= maximum allowable UDP packet size) */
    if (setsockopt(s, SOL_SOCKET, SO_SNDBUF,
		   (void *) &sndbufsize, sizeof(sndbufsize)) < 0) {
       dbprintf("dgram_bind: could not set udp send buffer to %d: %s (ignored)\n",
		 sndbufsize, strerror(errno));
    }

    SU_INIT(&name, family);
    SU_SET_INADDR_ANY(&name);

    /*
     * If a port range was specified, we try to get a port in that
     * range first.  Next, we try to get a reserved port.  If that
     * fails, we just go for any port.
     * 
     * In all cases, not to use port that's assigned to other services. 
     *
     * It is up to the caller to make sure we have the proper permissions
     * to get the desired port, and to make sure we return a port that
     * is within the range it requires.
     */
    for (retries = 0; ; retries++) {
	if (bind_portrange(s, &name, portrange[0], portrange[1], "udp") == 0)
	    goto out;
	dbprintf(_("dgram_bind: Could not bind to port in range: %d - %d.\n"),
		  portrange[0], portrange[1]);
	if (retries >= BIND_CYCLE_RETRIES) {
	    dbprintf(_("dgram_bind: Giving up...\n"));
	    break;
	}

	dbprintf(_("dgram_bind: Retrying entire range after 10 second delay.\n"));
	sleep(15);
    }

    save_errno = errno;
    dbprintf(_("dgram_bind: bind(in6addr_any) failed: %s\n"),
		  strerror(save_errno));
    aclose(s);
    errno = save_errno;
    return -1;

out:
    /* find out what name was actually used */

    len = (socklen_t_equiv)sizeof(name);
    if(getsockname(s, (struct sockaddr *)&name, &len) == -1) {
	save_errno = errno;
	dbprintf(_("dgram_bind: getsockname() failed: %s\n"), strerror(save_errno));
	errno = save_errno;
	aclose(s);
	return -1;
    }
    *portp = SU_GET_PORT(&name);
    dgram->socket = s;

    dbprintf(_("dgram_bind: socket %d bound to %s\n"),
	      dgram->socket, str_sockaddr(&name));
    return 0;
}
Example #2
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;
}
Example #3
0
/*extern "C" */void __attribute__((constructor)) IFR_Init(void){
  signal(SIGINT, sigint);
  signal(SIGKILL, sigint);

  dbprintf(stderr,"Initializing IFR Runtime\n");

#ifdef IFRIT_ARRAY
  fprintf(stderr, "[IFRit] Array-based implementation in use.\n");
#endif

#ifdef IFRIT_HASH_TABLE
  fprintf(stderr, "[IFRit] Hash-table-based implementation in use.\n");
#endif

#ifdef SINGLE_THREADED_OPT
  fprintf(stderr, "[IFRit] Single-threaded optimization enabled.\n");
#endif

#ifdef THREAD_LOCAL_OPT
  fprintf(stderr, "[IFRit] Thread-local optimization enabled.\n");
#endif

#ifdef READ_SHARED_OPT
  fprintf(stderr, "[IFRit] Read-shared optimization enabled.\n");
#endif

#ifdef PROGRAM_POINT_OPT
  fprintf(stderr, "[IFRit] Program point optimization enabled.\n");
#endif

#ifdef CHECK_FOR_RACES
#ifdef VARG_MASK_BITS
  fprintf(stderr, "[IFRit] Partitioning global state into %d partitions.\n",
	  NUM_VARG_MASKS);
#endif
#else
  fprintf(stderr, "[IFRit] Not checking for races.\n");
#endif

  g_thread_init(NULL);
  
  pthread_mutex_init(&allThreadsLock, NULL);
  int i ;
  for(i = 0; i < MAX_THDS; i++){
    allThreads[i] = (pthread_t)0;
  }

  allThreads[0] = pthread_self();

#ifdef SINGLE_THREADED_OPT
  num_threads = 1;
#endif

#ifdef SAMPLING
  //Release allThreads to samplingAlarmThread
  pthread_create(&samplingAlarmThread,NULL,sample,NULL);
#else
  fprintf (stderr, "[IFRit] Sampling disabled.\n");
#endif

  pthread_key_create(&dkey,thd_dtr);

#ifdef CHECK_FOR_RACES
#ifdef USE_TBB
  ActiveMayWriteIFR = new IFRMapMap();
  ActiveMustWriteIFR = new IFRMap();
  fprintf(stderr, "[IFRit] Using TBB concurrent_hash_map.\n");
#else
#ifdef VARG_MASK_BITS
  for (i = 0; i < NUM_VARG_MASKS; i++) {
    pthread_mutex_init(&drMutex[i], NULL);
    ActiveMustWriteIFR[i] = g_hash_table_new(g_direct_hash,g_direct_equal);
    ActiveMayWriteIFR[i] = g_hash_table_new(g_direct_hash,g_direct_equal);
#ifdef VARG_MASK_COUNT
    partition_counters[i] = 0;
#endif
  }
#else
  pthread_mutex_init(&drMutex, NULL);
  ActiveMustWriteIFR = g_hash_table_new(g_direct_hash,g_direct_equal);
  ActiveMayWriteIFR = g_hash_table_new(g_direct_hash,g_direct_equal);
#endif
#endif
#endif

  //warningCount = 0;

#ifdef IFRIT_ARRAY
  curWIFRVar = 0;
  curRIFRVar = 0;
  maxWIFRVar = INIT_ACTIVE;
  maxRIFRVar = INIT_ACTIVE;
  myWIFRVars = (unsigned long *) calloc(INIT_ACTIVE , sizeof(unsigned long));
  myRIFRVars = (unsigned long *) calloc(INIT_ACTIVE , sizeof(unsigned long));
#endif

#ifdef IFRIT_HASH_TABLE
  myWriteIFRs = g_hash_table_new(g_direct_hash, g_direct_equal);
  myReadIFRs = g_hash_table_new(g_direct_hash, g_direct_equal);
#endif

  //wq = g_queue_new();
  //rq = g_queue_new();

#ifdef THREAD_LOCAL_OPT
  ThreadLocalTable = g_hash_table_new(g_direct_hash, g_direct_equal);
  pthread_mutex_init(&TLMutex, NULL);
#endif

#ifdef READ_SHARED_OPT
  ReadSharedTable = g_hash_table_new(g_direct_hash, g_direct_equal);
  pthread_mutex_init(&RSMutex, NULL);
#endif

  raceCheckIFR = new_ifr(pthread_self(), 0, 0, 0);

#ifdef PROGRAM_POINT_OPT
  PCTable = g_hash_table_new(g_direct_hash, g_direct_equal);
#endif
}
Example #4
0
int
main(
    int		argc,
    char **	argv)
{
#ifdef TEST
/* standalone test to ckeck wether the calculated file size is ok */
    struct stat finfo;
    int i;
    off_t dump_total = (off_t)0;
    off_t gtar_total = (off_t)0;
    char *d;
    int l, w;

    glib_init();

    /*
     * 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("calcsize");

    dbopen(NULL);
    config_init(CONFIG_INIT_CLIENT|CONFIG_INIT_GLOBAL, NULL);

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

    if (argc < 2) {
	g_fprintf(stderr,_("Usage: %s file[s]\n"),argv[0]);
	return 1;
    }
    for(i=1; i<argc; i++) {
	if(lstat(argv[i], &finfo) == -1) {
	    g_fprintf(stderr, "%s: %s\n", argv[i], strerror(errno));
	    continue;
	}
	g_printf("%s: st_size=%lu", argv[i],(unsigned long)finfo.st_size);
	g_printf(": blocks=%llu\n", ST_BLOCKS(finfo));
	dump_total += (ST_BLOCKS(finfo) + (off_t)1) / (off_t)2 + (off_t)1;
	gtar_total += ROUND(4,(ST_BLOCKS(finfo) + (off_t)1));
    }
    g_printf("           gtar           dump\n");
    g_printf("total      %-9lu         %-9lu\n",gtar_total,dump_total);
    return 0;
#else
    int i;
    char *dirname=NULL;
    char *amname=NULL, *qamname=NULL;
    char *filename=NULL, *qfilename = NULL;

    if (argc > 1 && argv[1] && g_str_equal(argv[1], "--version")) {
	printf("calcsize-%s\n", VERSION);
	return (0);
    }

    safe_fd(-1, 0);
    safe_cd();

    set_pname("calcsize");

    dbopen(DBG_SUBDIR_CLIENT);
    config_init(CONFIG_INIT_CLIENT|CONFIG_INIT_GLOBAL, NULL);
    dbprintf(_("version %s\n"), VERSION);

    /* drop root privileges; we'll regain them for the required operations */
#ifdef WANT_SETUID_CLIENT
    check_running_as(RUNNING_AS_CLIENT_LOGIN | RUNNING_AS_UID_ONLY);
    if (!set_root_privs(0)) {
	error(_("calcsize must be run setuid root"));
    }
#else
    check_running_as(RUNNING_AS_CLIENT_LOGIN);
#endif

    argc--, argv++;	/* skip program name */

    /* need at least program, amname, and directory name */

    if(argc < 4) {
	error(_("Usage: %s config [BSDTAR|DUMP|STAR|GNUTAR] name dir [-X exclude-file] [-I include-file] [level date]*"),
	      get_pname());
        /*NOTREACHED*/
    }

    dbprintf(_("config: %s\n"), *argv);
    if (!g_str_equal(*argv, "NOCONFIG")) {
	dbrename(*argv, DBG_SUBDIR_CLIENT);
    }
    argc--;
    argv++;

    /* parse backup program name */

    if(g_str_equal(*argv, "DUMP")) {
#if !defined(DUMP) && !defined(XFSDUMP)
	error("dump not available on this system");
	/*NOTREACHED*/
#else
	add_file_name = add_file_name_dump;
	add_file = add_file_dump;
	final_size = final_size_dump;
#endif
    }
    else if(g_str_equal(*argv, "BSDTAR")) {
	add_file_name = add_file_name_gnutar;
	add_file = add_file_gnutar;
	final_size = final_size_gnutar;
	use_gtar_excl++;
    }
    else if(g_str_equal(*argv, "GNUTAR")) {
#ifndef GNUTAR
	error("gnutar not available on this system");
	/*NOTREACHED*/
#else
	add_file_name = add_file_name_gnutar;
	add_file = add_file_gnutar;
	final_size = final_size_gnutar;
	use_gtar_excl++;
#endif
    }
    else {
	add_file_name = add_file_name_unknown;
	add_file = add_file_unknown;
	final_size = final_size_unknown;
    }
    argc--, argv++;

    /* the amanda name can be different from the directory name */

    if (argc > 0) {
	amname = *argv;
	qamname = quote_string(amname);
	argc--, argv++;
    } else {
	error("missing <name>");
	/*NOTREACHED*/
    }

    /* the toplevel directory name to search from */
    if (argc > 0) {
	dirname = *argv;
	argc--, argv++;
    } else {
	error("missing <dir>");
	/*NOTREACHED*/
    }

    if ((argc > 1) && g_str_equal(*argv, "-X")) {
	argv++;

	if (!(use_gtar_excl || use_star_excl)) {
	  error("exclusion specification not supported");
	  /*NOTREACHED*/
	}
	
	filename = g_strdup(*argv);
	qfilename = quote_string(filename);
	if (access(filename, R_OK) != 0) {
	    g_fprintf(stderr,"Cannot open exclude file %s\n", qfilename);
	    use_gtar_excl = use_star_excl = 0;
	} else {
	    exclude_sl = calc_load_file(filename);
	    if (!exclude_sl) {
		g_fprintf(stderr,"Cannot open exclude file %s: %s\n", qfilename,
			strerror(errno));
		use_gtar_excl = use_star_excl = 0;
	    }
	}
	amfree(qfilename);
	amfree(filename);
	argc -= 2;
	argv++;
    } else {
	use_gtar_excl = use_star_excl = 0;
    }

    if ((argc > 1) && g_str_equal(*argv, "-I")) {
	argv++;
	
	filename = g_strdup(*argv);
	qfilename = quote_string(filename);
	if (access(filename, R_OK) != 0) {
	    g_fprintf(stderr,"Cannot open include file %s\n", qfilename);
	    use_gtar_excl = use_star_excl = 0;
	} else {
	    include_sl = calc_load_file(filename);
	    if (!include_sl) {
		g_fprintf(stderr,"Cannot open include file %s: %s\n", qfilename,
			strerror(errno));
		use_gtar_excl = use_star_excl = 0;
	    }
	}
	amfree(qfilename);
	amfree(filename);
	argc -= 2;
	argv++;
    }

    /* the dump levels to calculate sizes for */

    ndumps = 0;
    while(argc >= 2) {
	if(ndumps < MAXDUMPS) {
	    dumplevel[ndumps] = atoi(argv[0]);
	    dumpdate [ndumps] = (time_t) atol(argv[1]);
	    ndumps++;
	    argc -= 2, argv += 2;
	}
    }

    if(argc) {
	error("leftover arg \"%s\", expected <level> and <date>", *argv);
	/*NOTREACHED*/
    }

    if(is_empty_sl(include_sl)) {
	traverse_dirs(dirname,".");
    }
    else {
	sle_t *an_include = include_sl->first;
	while(an_include != NULL) {
/*
	    char *adirname = stralloc2(dirname, an_include->name+1);
	    traverse_dirs(adirname);
	    amfree(adirname);
*/
	    traverse_dirs(dirname, an_include->name);
	    an_include = an_include->next;
	}
    }
    for(i = 0; i < ndumps; i++) {

	amflock(1, "size");

	dbprintf("calcsize: %s %d SIZE %lld\n",
	       qamname, dumplevel[i],
	       (long long)final_size(i, dirname));
	g_fprintf(stderr, "%s %d SIZE %lld\n",
	       qamname, dumplevel[i],
	       (long long)final_size(i, dirname));
	fflush(stderr);

	amfunlock(1, "size");
    }
    amfree(qamname);

    return 0;
#endif
}
Example #5
0
int FileRead(int handle, void *mem, int num_bytes)
{
	int bytes_read;
	int filesize;

	if(handle > (FILE_MAX_OPEN_FILES-1))
	{
		printf("FileRead -- FD handle number greater than %d!\n", FILE_MAX_OPEN_FILES-1);
		return(FILE_FAIL);
	}

	if(fd_array[handle].FD_Valid == 0)
	{
		printf("FileRead -- FD handle not valid!\n");
		return(FILE_FAIL);
	}

	if(fd_array[handle].FD_PID != GetCurrentPid())
	{
		printf("FileRead -- FD handle does not belong to current process #%d,\n", GetCurrentPid());
		return(FILE_FAIL);
	}

	if(fd_array[handle].FD_Mode == FILE_WRITE)
	{
		printf("FileRead -- FD handle does not have read privileges\n");
		return(FILE_FAIL);
	}

	if(num_bytes < 0)
	{
		printf("FileRead -- num_bytes is less than zero!\n");
		return(FILE_FAIL);
	}

	filesize = DfsInodeFilesize(fd_array[handle].FD_InodeHandle);
	if(filesize == -1)
	{
		printf("FileRead -- Could not get filesize\n");
		return(FILE_FAIL);
	}

	if( (fd_array[handle].FD_CurrentPosition+num_bytes) > filesize )
	{
		printf("FileRead -- EOF reached!\n");
		fd_array[handle].FD_EOF_Flag = 1;
		return(FILE_FAIL);
	}

	bytes_read = DfsInodeReadBytes(fd_array[handle].FD_InodeHandle, mem, fd_array[handle].FD_CurrentPosition, num_bytes);

	if(bytes_read == -1)
	{
		printf("FileRead -- Read from file failed!\n");
		return(FILE_FAIL);
	}

	fd_array[handle].FD_CurrentPosition += bytes_read;

	dbprintf('F', "FileRead -- read of %d bytes successful\n", bytes_read);
	dbprintf('F',"FileRead -- New position for File Descriptor #%d ", handle);
	dbprintf('F',"is %d\n", fd_array[handle].FD_CurrentPosition);

	return(bytes_read);

}
//----------------------------------------------------------------------
//
//	doInterrupt
//
//	Handle an interrupt or trap.
//
//----------------------------------------------------------------------
void
dointerrupt (unsigned int cause, unsigned int iar, unsigned int isr,
	     uint32 *trapArgs)
{
  int	result;
  int	i;
  uint32	args[4];
  int	intrs;

  dbprintf ('t',"Interrupt cause=0x%x iar=0x%x isr=0x%x args=0x%08x.\n",
	    cause, iar, isr, (int)trapArgs);
  // If the TRAP_INSTR bit is set, this was from a trap instruction.
  // If the bit isn't set, this was a system interrupt.
  if (cause & TRAP_TRAP_INSTR) {
    cause &= ~TRAP_TRAP_INSTR;
    switch (cause) {
    case TRAP_CONTEXT_SWITCH:
      dbprintf ('t', "Got a context switch trap!\n");
      ProcessSchedule ();
      break;
    case TRAP_EXIT:
      dbprintf ('t', "Got an exit trap!\n");
      ProcessDestroy (currentPCB);
      ProcessSchedule ();
      break;
    case TRAP_PROCESS_FORK:
      dbprintf ('t', "Got a fork trap!\n");
      break;
    case TRAP_PROCESS_SLEEP:
      dbprintf ('t', "Got a process sleep trap!\n");
      ProcessSuspend (currentPCB);
      ProcessSchedule ();
      break;
    case TRAP_PRINTF:
      // Call the trap printf handler and pass the arguments and a flag
      // indicating whether the trap was called from system mode.
      dbprintf ('t', "Got a printf trap!\n");
      TrapPrintfHandler (trapArgs, isr & DLX_STATUS_SYSMODE);
      break;
    case TRAP_OPEN:
      // Get the arguments to the trap handler.  If this is a user mode trap,
      // copy them from user space.
      if (isr & DLX_STATUS_SYSMODE) {
	args[0] = trapArgs[0];
	args[1] = trapArgs[1];
      } else {
	char	filename[32];
	// trapArgs points to the trap arguments in user space.  There are
	// two of them, so copy them to to system space.  The first argument
	// is a string, so it has to be copied to system space and the
	// argument replaced with a pointer to the string in system space.
	MemoryCopyUserToSystem (currentPCB, trapArgs, args, sizeof(args[0])*2);
	MemoryCopyUserToSystem (currentPCB, args[0], filename, 31);
	// Null-terminate the string in case it's longer than 31 characters.
	filename[31] = '\0';
	// Set the argument to be the filename
	args[0] = (uint32)filename;
      }
      // Allow Open() calls to be interruptible!
      intrs = EnableIntrs ();
      ProcessSetResult (currentPCB, args[1] + 0x10000);
      printf ("Got an open with parameters ('%s',0x%x)\n", (char *)args[0], args[1]);
      RestoreIntrs (intrs);
      break;
    case TRAP_CLOSE:
      // Allow Close() calls to be interruptible!
      intrs = EnableIntrs ();
      ProcessSetResult (currentPCB, -1);
      RestoreIntrs (intrs);
      break;
    case TRAP_READ:
      // Allow Read() calls to be interruptible!
      intrs = EnableIntrs ();
      ProcessSetResult (currentPCB, -1);
      RestoreIntrs (intrs);
      break;
    case TRAP_WRITE:
      // Allow Write() calls to be interruptible!
      intrs = EnableIntrs ();
      ProcessSetResult (currentPCB, -1);
      RestoreIntrs (intrs);
      break;
    case TRAP_DELETE:
      intrs = EnableIntrs ();
      ProcessSetResult (currentPCB, -1);
      RestoreIntrs (intrs);
      break;
    case TRAP_SEEK:
      intrs = EnableIntrs ();
      ProcessSetResult (currentPCB, -1);
      RestoreIntrs (intrs);
      break;
    case TRAP_PROCESS_GETPID:
      intrs = EnableIntrs ();
      ProcessSetResult (currentPCB, GetCurrentPid());
      RestoreIntrs (intrs);
      break;
    default:
      printf ("Got an unrecognized trap (0x%x) - exiting!\n",
	      cause);
      exitsim ();
      break;
    }
  } else {
    switch (cause) {
    case TRAP_TIMER:
      dbprintf ('t', "Got a timer interrupt!\n");
      ProcessSchedule ();
      break;
    case TRAP_KBD:
      do {
	i = *((uint32 *)DLX_KBD_NCHARSIN);
	result = *((uint32 *)DLX_KBD_GETCHAR);
	printf ("Got a keyboard interrupt (char=0x%x(%c), nleft=%d)!\n",
		result, result, i);
      } while (i > 1);
      break;
    case TRAP_ACCESS:
      printf ("Exiting after illegal access at iar=0x%x, isr=0x%x\n",
	      iar, isr);
      exitsim ();
      break;
    case TRAP_ADDRESS:
      printf ("Exiting after illegal address at iar=0x%x, isr=0x%x\n",
	      iar, isr);
      exitsim ();
      break;
    case TRAP_ILLEGALINST:
      printf ("Exiting after illegal instruction at iar=0x%x, isr=0x%x\n",
	      iar, isr);
      exitsim ();
      break;
    case TRAP_PAGEFAULT:
      printf ("Exiting after page fault at iar=0x%x, isr=0x%x\n",
	      iar, isr);
      exitsim ();
      break;
    default:
      printf ("Got an unrecognized system interrupt (0x%x) - exiting!\n",
	      cause);
      exitsim ();
      break;
    }
  }
  dbprintf ('t',"About to return from dointerrupt.\n");
  // Note that this return may schedule a new process!
  intrreturn ();
}
Example #7
0
/* Returns true/false if initialization was successful */
bool VMware::InitHardware(void)
{
	/* This has to be done first, otherwise we can't
	 * access the SVGA registers */
	if(!setupIoPorts())
	{
		dbprintf("VMware - Failed to setup the IO ports.\n");
		return false;
	}


	/*** Grab the SVGA Id ***/
	m_regId = vmwareGetSvgaId();
	if(m_regId == (uint32)SVGA_ID_2)
	{
		dbprintf("VMware - SVGA Id is SVGA_ID_2\n");
	}
	else if(m_regId == (uint32)SVGA_ID_1)
	{
		dbprintf("VMware - SVGA Id is SVGA_ID_1\n");
		return false;
	}
	else if(m_regId == (uint32)SVGA_ID_0)
	{
		dbprintf("VMware - SVGA Id is SVGA_ID_0\n");
		return false;
	}
	else
	{
		dbprintf("VMware - SVGA Id is SVGA_ID_INVALID\n");
		return false;
	}

	/*** Map the frame buffer and the command FIFO ***/
	if(!CreateFb())
	{
		dbprintf("VMware -Failed to map the frame buffer.\n");
		return false;
	}
	dbprintf("VMware - Successfully mapped the frame buffer.\n");


	if(!CreateFifo())
	{
		dbprintf("VMware - Failed to map the command FIFO.\n");
		return false;
	}
	dbprintf("VMware - Successfully mapped the command FIFO.\n");


	/*** Initialize the FB ***/
	if(!InitFb())
	{
		dbprintf("VMware - Failed to initialized the frame buffer.\n");
		return false;
	}
	dbprintf("VMware - Successfully initialized the frame buffer.\n");


	/*** Initialize the command FIFO ***/
	if(!InitFifo())
	{
		dbprintf("VMware - Failed to initialized the command FIFO.\n");
		return false;
	}
	dbprintf("VMware - Successfully initialized the command FIFO.\n");


	/*** Initially disable hardware cursor ***/
	vmwareWriteReg(SVGA_REG_CURSOR_X, 0);
	vmwareWriteReg(SVGA_REG_CURSOR_Y, 0);
	vmwareWriteReg(SVGA_REG_CURSOR_ON, SVGA_CURSOR_ON_HIDE);

	return true;
}
Example #8
0
bool DacTVP3026::CalcPixPLL( long vTarget, long vMax, short *nN, short *nM, short *nP )
{
	short nBestN = 0, nBestM = 0, nBestP = 0;
	double nPixN, nPixM, nPixP;
	double vPLL = 0, vVCO = 0, vDiffVCO = 0, vBestVCO = (double)vTarget;

	dbprintf("Target is %li\n", vTarget );
	if( vTarget < TVP_MIN_PLL || vTarget > TVP_MAX_PLL )
	{
		dbprintf("PLL target of %li is out of range (Min %i, Max %i)\n", vTarget, TVP_MIN_PLL, TVP_MAX_PLL );
		return( false );
	}

	// Choose P first from the target VCO, where the PLL frequency is VCO / ( 2 ^ P ) and the
	// PLL frequency falls within TVP_MIN_PLL and vMax.
	for( nPixP = TVP_MIN_P; nPixP < TVP_MAX_P; nPixP++ )
	{
		vPLL = vTarget * ( pow( 2, nPixP ) );
		if( vPLL >= TVP_MIN_VCO && vPLL <= vMax )
			break;
	}

	nBestP = (short)nPixP;	// Note that if we tried P = 3 and still did not get a match, we'll
								// default to P = 3

	// Now we try all possible value of N and M and try to get as close as possible to the target VCO
	for( nPixM = TVP_MIN_M; nPixM <= TVP_MAX_M; nPixM++ )
	{
		for( nPixN = TVP_MIN_N; nPixN <= TVP_MAX_N; nPixN++ )
		{
			vVCO = ( 8 * TVP_REF_FREQ ) * ( 65 - nPixM ) / ( 65 - nPixN );

			// Discard any that are outside the min. & max. VCO limits
			if( vVCO < TVP_MIN_VCO || vVCO > vMax )
				continue;

			if( nPixP > 0 )
				vVCO /= pow( 2, nPixP );

			// The difference between the target could be positive or negative; we don't care, we just want
			// the closest to the target.
			// If we get a closer match than the one we already have, then we store the M & N values and
			// carry on checking.
			vDiffVCO = vTarget - vVCO;
			if( ( vDiffVCO > 0 && ( vDiffVCO < vBestVCO ) ) || ( vDiffVCO < 0 ) && ( vDiffVCO > vBestVCO ) )
			{
				vBestVCO = vDiffVCO;
				nBestM = (short)nPixM;
				nBestN = (short)nPixN;

				dbprintf("Got a new best VCO of %li with N=%i M=%i P=%i\n", (long int)vBestVCO, nBestN, nBestM, nBestP );
			}
		}
	}

	// We must have something now, even if it is only the maximum possible mode setting.  Note that the
	// values we have will be valid (E.g. they will produce an output within the allowable PLL ranges) but
	// they may not be as close to the target frequency as we would like for some very odd targets.  There
	// is not much we can do about that.
	*nM = (short)nBestM;
	*nN = (short)nBestN;
	*nP = (short)nBestP;

	return( true );
}
Example #9
0
bool DacTVP3026::SetPixPLL( long vTargetFrequency, int nDepth )
{
	short nN, nM, nP;
	short nLm, nLn, nLp, nLq;
	int i;
	short nMiscCtrl = 0, nLatchCtrl = 0, nTcolCtrl = 0, nMulCtrl = 0;
	bool bRet = false;

	bRet = CalcPixPLL( vTargetFrequency/1000, TI_MAX_PCLK_FREQ, &nN, &nM, &nP );
	if( bRet )
	{
		dbprintf("Got N=%i M=%i P=%i for target frequency of %li\n", nN, nM, nP, (long)vTargetFrequency );

		m_nDacClk[ 0 ] = ( nN & 0x3f ) | 0xc0;
		m_nDacClk[ 1 ] = ( nM & 0x3f );
		m_nDacClk[ 2 ] = ( nP & 0x03 ) | 0xb0;

		// Now that the pixel clock PLL is setup,
		// the loop clock PLL must be setup.
		bRet = CalcLoopPLL( (double)vTargetFrequency/1000, nDepth, &nLn, &nLm, &nLp, &nLq );
		if( bRet )
		{
			dbprintf("Got N=%i M=%i P=%i Q=%i for target frequency of %li\n", nLn, nLm, nLp, nLq, (long)vTargetFrequency );

			// Values for the loop clock PLL registers
			if ( nDepth == 24 )
			{
				// Packed pixel mode values
				m_nDacClk[ 3 ] = ( nLn & 0x3f ) | 0x80;
				m_nDacClk[ 4 ] = ( nLm & 0x3f ) | 0x80;
				m_nDacClk[ 5 ] = ( nLp & 0x03 ) | 0xf8;
			}
			else
			{
				// Non-packed pixel mode values
				m_nDacClk[ 3 ] = ( nLn & 0x3f ) | 0xc0;
				m_nDacClk[ 4 ] = ( nLm & 0x3f );
				m_nDacClk[ 5 ] = ( nLp & 0x03 ) | 0xf0;
			}
			m_nDacClk[ 7 ] = nLq | 0x38;	// pReg->DacRegs[ 18 ]
		}
		else
		{
			dbprintf("Unable to get Loop PLL timing values fortarget frequency %li\n", (long int)vTargetFrequency );
			return( false );
		}
	}
	else
	{
		dbprintf("Unable to get Pix PLL timing values for target frequency %li\n", (long int)vTargetFrequency );
		return( false );
	}

	// Now program the Pixel & Loop PLL with the values we have calculated
	//
	// Set loop and pixel clock PLL PLLEN bits to 0
	outTi3026(TVP3026_PLL_ADDR, 0, 0x2A);
	outTi3026(TVP3026_LOAD_CLK_DATA, 0, 0);
	outTi3026(TVP3026_PIX_CLK_DATA, 0, 0);

	// Program pixel clock PLL
	outTi3026(TVP3026_PLL_ADDR, 0, 0x00);
	for (i = 0; i < 3; i++)
		outTi3026(TVP3026_PIX_CLK_DATA, 0, m_nDacClk[i]);

	// Poll until pixel clock PLL LOCK bit is set
	outTi3026(TVP3026_PLL_ADDR, 0, 0x3F);
	while ( ! (inTi3026(TVP3026_PIX_CLK_DATA) & 0x40) );

	dbprintf("Pixel Clock PLL locked\n");

	// Select pixel clock PLL as clock source
	switch( nDepth )
	{
		case 15:
		case 16:
			outTi3026(TVP3026_CLK_SEL, 0, 0x15);	// Dot Clock / 2, select PIX PLL as source
			break;

		case 24:
			outTi3026(TVP3026_CLK_SEL, 0, 0x25);	// Dot Clock / 4, select PIX PLL as source
			break;

		case 32:
			outTi3026(TVP3026_CLK_SEL, 0, 0x05);	// Dot Clock / 0, select PIX PLL as source
			break;
	}

	// Set Q divider for loop clock PLL
	outTi3026(TVP3026_MCLK_CTL, 0, m_nDacClk[7]);

	// Program loop PLL
	outTi3026(TVP3026_PLL_ADDR, 0, 0x00);
	for (i = 3; i < 6; i++)
		outTi3026(TVP3026_LOAD_CLK_DATA, 0, m_nDacClk[i]);

	// Poll until loop PLL LOCK bit is set
	outTi3026(TVP3026_PLL_ADDR, 0, 0x3F);
	while ( ! (inTi3026(TVP3026_LOAD_CLK_DATA) & 0x40) );

	dbprintf("Loop Clock PLL locked\n");

	SetMemPLL( vTargetFrequency/1000 );

	// Set the correct values for the Misc, Latch, True Color Control &
	// Multiplex Control registers
	//
	// Consult Table 2-17 of the TVP3026 manual for the TCOLCTRL & MULCTRL
	// values

	switch( nDepth )
	{
		case 15:
		{
			nMiscCtrl = 0x20;		// Set PSEL to select True Color
			nLatchCtrl = 0x06;	// 1:1. 2:1, 8:1 & 16:1 multiplex modes
			nTcolCtrl = 0x44;		// 16bit X-R-G-B
			nMulCtrl = 0x54;		// 32bit Pixel Bus, interlaced

			break;
		}

		case 16:
		{
			nMiscCtrl = 0x20;		// Set PSEL to select True Color
			nLatchCtrl = 0x06;	// 1:1. 2:1, 8:1 & 16:1 multiplex modes
			nTcolCtrl = 0x45;		// 16bit R-G-B
			nMulCtrl = 0x54;		// 32bit Pixel Bus, interlaced

			break;
		}

		case 24:
		{
			nMiscCtrl = 0x20;		// Set PSEL to select True Color
			nLatchCtrl = 0x07;	// 2:1 multiplex mode or 8:3 Packed 24bit or 4:3 packed 24bit
			nTcolCtrl = 0x56;		// 24bit R-G-B
			nMulCtrl = 0x5c;		// 32bit Pixel Bus, interlaced

			break;
		}

		case 32:
		{
			nMiscCtrl = 0x20;		// Set PSEL to select True Color
			nLatchCtrl = 0x07;	// 2:1 multiplex mode or 8:3 Packed 24bit or 4:3 packed 24bit
			nTcolCtrl = 0x46;		// 32bit X-R-G-B
			nMulCtrl = 0x5c;		// 32bit Pixel Bus, interlaced

			break;
		}
	}

	outTi3026( TVP3026_MISCCTRL, 0, nMiscCtrl );			// Misc. Control
	outTi3026( TVP3026_LATCHCTRL, 0, nLatchCtrl  );		// Latch Control
	outTi3026( TVP3026_TCOLCTRL, 0, nTcolCtrl );			// True Color Control
	outTi3026( TVP3026_MULCTRL, 0, nMulCtrl );			// Multiplex Control

	dbprintf("DacTVP3026::SetPixPLL has completed\n");
	return( bRet );
}
Example #10
0
int
main(
    int		argc,
    char **	argv)
{
    int ch;
    char *exitstr;
    amwait_t status;

    /*
     * 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);
    safe_cd();

    set_pname("killpgrp");

    dbopen(DBG_SUBDIR_CLIENT);
    if (argc < 2) {
        error("Need at least 2 arguments\n");
        /*NOTREACHED*/
    }
    dbprintf(_("version %s\n"), VERSION);
    dbprintf(_("config: %s\n"), argv[1]);
    if (strcmp(argv[1], "NOCONFIG") != 0)
        dbrename(argv[1], DBG_SUBDIR_CLIENT);

#ifdef WANT_SETUID_CLIENT
    check_running_as(RUNNING_AS_CLIENT_LOGIN | RUNNING_AS_UID_ONLY);
    if (!become_root()) {
        error(_("error [%s could not become root (is the setuid bit set?)]\n"), get_pname());
        /*NOTREACHED*/
    }
#else
    check_running_as(RUNNING_AS_CLIENT_LOGIN);
#endif

    if (AM_GETPGRP() != getpid()) {
        error(_("error [must be the process group leader]"));
        /*NOTREACHED*/
    }

    signal(SIGTERM, term_kill_soft);

    /* Consume any extranious input */
    do {
        ch = getchar();
        /* wait until EOF */
    } while (ch != EOF);

    term_kill_soft(0);

    for(;;) {
        if (wait(&status) != -1)
            break;
        if (errno != EINTR) {
            error(_("error [wait() failed: %s]"), strerror(errno));
            /*NOTREACHED*/
        }
    }
    exitstr = str_exit_status("child", status);
    dbprintf("%s\n", exitstr);
    amfree(exitstr);

    /*@ignore@*/
    return WIFEXITED(status)?WEXITSTATUS(status):1;
    /*@end@*/
}
Example #11
0
File: bmap.c Project: brkt/fuse-xfs
static int
bmap_f(
	int		argc,
	char		**argv)
{
	int		afork = 0;
	bmap_ext_t	be;
	int		c;
	xfs_dfiloff_t	co, cosave;
	int		dfork = 0;
	xfs_dinode_t	*dip;
	xfs_dfiloff_t	eo;
	xfs_dfilblks_t	len;
	int		nex;
	char		*p;
	int		whichfork;

	if (iocur_top->ino == NULLFSINO) {
		dbprintf(_("no current inode\n"));
		return 0;
	}
	optind = 0;
	if (argc) while ((c = getopt(argc, argv, "ad")) != EOF) {
		switch (c) {
		case 'a':
			afork = 1;
			break;
		case 'd':
			dfork = 1;
			break;
		default:
			dbprintf(_("bad option for bmap command\n"));
			return 0;
		}
	}
	if (afork + dfork == 0) {
		push_cur();
		set_cur_inode(iocur_top->ino);
		dip = iocur_top->data;
		if (be32_to_cpu(dip->di_core.di_nextents))
			dfork = 1;
		if (be16_to_cpu(dip->di_core.di_anextents))
			afork = 1;
		pop_cur();
	}
	if (optind < argc) {
		co = (xfs_dfiloff_t)strtoull(argv[optind], &p, 0);
		if (*p != '\0') {
			dbprintf(_("bad block number for bmap %s\n"),
				argv[optind]);
			return 0;
		}
		optind++;
		if (optind < argc) {
			len = (xfs_dfilblks_t)strtoull(argv[optind], &p, 0);
			if (*p != '\0') {
				dbprintf(_("bad len for bmap %s\n"), argv[optind]);
				return 0;
			}
			eo = co + len - 1;
		} else
			eo = co;
	} else {
		co = 0;
		eo = -1;
	}
	cosave = co;
	for (whichfork = XFS_DATA_FORK;
	     whichfork <= XFS_ATTR_FORK;
	     whichfork++) {
		if (whichfork == XFS_DATA_FORK && !dfork)
			continue;
		if (whichfork == XFS_ATTR_FORK && !afork)
			continue;
		for (;;) {
			nex = 1;
			bmap(co, eo - co + 1, whichfork, &nex, &be);
			if (nex == 0)
				break;
			dbprintf(_("%s offset %lld startblock %llu (%u/%u) count "
				 "%llu flag %u\n"),
				whichfork == XFS_DATA_FORK ? _("data") : _("attr"),
				be.startoff, be.startblock,
				XFS_FSB_TO_AGNO(mp, be.startblock),
				XFS_FSB_TO_AGBNO(mp, be.startblock),
				be.blockcount, be.flag);
			co = be.startoff + be.blockcount;
		}
		co = cosave;
	}
	return 0;
}
Example #12
0
int
main(
    int		argc,
    char **	argv)
{
    char *line = NULL;
    char *qdisk = NULL;
    char *qamdevice = NULL;
    char *optstr = NULL;
    char *err_extra = NULL;
    char *s, *fp;
    int ch;
    dle_t *dle = NULL;
    int level;
    GSList *errlist;
    level_t *alevel;

    if (argc > 1 && argv && argv[1] && g_str_equal(argv[1], "--version")) {
	printf("selfcheck-%s\n", VERSION);
	return (0);
    }

    /* initialize */

    /*
     * 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);
    openbsd_fd_inform();
    safe_cd();

    set_pname("selfcheck");

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

    add_amanda_log_handler(amanda_log_stderr);
    add_amanda_log_handler(amanda_log_syslog);
    dbopen(DBG_SUBDIR_CLIENT);
    startclock();
    dbprintf(_("version %s\n"), VERSION);
    g_printf("OK version %s\n", VERSION);

    print_platform();
    if(argc > 2 && g_str_equal(argv[1], "amandad")) {
	amandad_auth = g_strdup(argv[2]);
    }

    config_init(CONFIG_INIT_CLIENT, NULL);
    /* (check for config errors comes later) */

    check_running_as(RUNNING_AS_CLIENT_LOGIN);

    our_features = am_init_feature_set();
    our_feature_string = am_feature_to_string(our_features);

    /* handle all service requests */

    /*@ignore@*/
    for(; (line = agets(stdin)) != NULL; free(line)) {
    /*@end@*/
	if (line[0] == '\0')
	    continue;

	if(strncmp_const(line, "OPTIONS ") == 0) {
	    if (g_options) {
		g_printf(_("ERROR [Multiple OPTIONS line in selfcheck input]\n"));
		error(_("Multiple OPTIONS line in selfcheck input\n"));
		/*NOTREACHED*/
	    }
	    g_options = parse_g_options(line+8, 1);
	    if(!g_options->hostname) {
		g_options->hostname = g_malloc(MAX_HOSTNAME_LENGTH+1);
		gethostname(g_options->hostname, MAX_HOSTNAME_LENGTH);
		g_options->hostname[MAX_HOSTNAME_LENGTH] = '\0';
	    }

	    g_printf("OPTIONS ");
	    if(am_has_feature(g_options->features, fe_rep_options_features)) {
		g_printf("features=%s;", our_feature_string);
	    }
	    if(am_has_feature(g_options->features, fe_rep_options_hostname)) {
		g_printf("hostname=%s;", g_options->hostname);
	    }
	    g_printf("\n");
	    fflush(stdout);

	    if (g_options->config) {
		/* overlay this configuration on the existing (nameless) configuration */
		config_init(CONFIG_INIT_CLIENT | CONFIG_INIT_EXPLICIT_NAME | CONFIG_INIT_OVERLAY,
			    g_options->config);

		dbrename(get_config_name(), DBG_SUBDIR_CLIENT);
	    }

	    /* check for any config errors now */
	    if (config_errors(&errlist) >= CFGERR_ERRORS) {
		char *errstr = config_errors_to_error_string(errlist);
		g_printf("%s\n", errstr);
		amfree(errstr);
		amfree(line);
		dbclose();
		return 1;
	    }

	    if (am_has_feature(g_options->features, fe_req_xml)) {
		break;
	    }
	    continue;
	}

	dle = alloc_dle();
	s = line;
	ch = *s++;

	skip_whitespace(s, ch);			/* find program name */
	if (ch == '\0') {
	    goto err;				/* no program */
	}
	dle->program = s - 1;
	skip_non_whitespace(s, ch);
	s[-1] = '\0';				/* terminate the program name */

	dle->program_is_application_api = 0;
	if(g_str_equal(dle->program, "APPLICATION")) {
	    dle->program_is_application_api = 1;
	    skip_whitespace(s, ch);		/* find dumper name */
	    if (ch == '\0') {
		goto err;			/* no program */
	    }
	    dle->program = s - 1;
	    skip_non_whitespace(s, ch);
	    s[-1] = '\0';			/* terminate the program name */
	}

	if(strncmp_const(dle->program, "CALCSIZE") == 0) {
	    skip_whitespace(s, ch);		/* find program name */
	    if (ch == '\0') {
		goto err;			/* no program */
	    }
	    dle->program = s - 1;
	    skip_non_whitespace(s, ch);
	    s[-1] = '\0';
	    dle->estimatelist = g_slist_append(dle->estimatelist,
					       GINT_TO_POINTER(ES_CALCSIZE));
	}
	else {
	    dle->estimatelist = g_slist_append(dle->estimatelist,
					       GINT_TO_POINTER(ES_CLIENT));
	}

	skip_whitespace(s, ch);			/* find disk name */
	if (ch == '\0') {
	    goto err;				/* no disk */
	}
	qdisk = s - 1;
	skip_quoted_string(s, ch);
	s[-1] = '\0';				/* terminate the disk name */
	dle->disk = unquote_string(qdisk);

	skip_whitespace(s, ch);                 /* find the device or level */
	if (ch == '\0') {
	    goto err;				/* no device or level */
	}
	if(!isdigit((int)s[-1])) {
	    fp = s - 1;
	    skip_quoted_string(s, ch);
	     s[-1] = '\0';			/* terminate the device */
	    qamdevice = g_strdup(fp);
	    dle->device = unquote_string(qamdevice);
	    skip_whitespace(s, ch);		/* find level number */
	}
	else {
	    dle->device = g_strdup(dle->disk);
	    qamdevice = g_strdup(qdisk);
	}
	amfree(qamdevice);

						/* find level number */
	if (ch == '\0' || sscanf(s - 1, "%d", &level) != 1) {
	    goto err;				/* bad level */
	}
	alevel = g_new0(level_t, 1);
	alevel->level = level;
	dle->levellist = g_slist_append(dle->levellist, alevel);
	skip_integer(s, ch);

	skip_whitespace(s, ch);
	if (ch && strncmp_const_skip(s - 1, "OPTIONS ", s, ch) == 0) {
	    skip_whitespace(s, ch);		/* find the option string */
	    if(ch == '\0') {
		goto err;			/* bad options string */
	    }
	    optstr = s - 1;
	    skip_quoted_string(s, ch);
	    s[-1] = '\0';			/* terminate the options */
	    parse_options(optstr, dle, g_options->features, 1);
	    /*@ignore@*/

	    check_options(dle);
	    check_disk(dle);

	    /*@end@*/
	} else if (ch == '\0') {
	    /* check all since no option */
	    need_samba=1;
	    need_rundump=1;
	    need_dump=1;
	    need_restore=1;
	    need_vdump=1;
	    need_vrestore=1;
	    need_xfsdump=1;
	    need_xfsrestore=1;
	    need_vxdump=1;
	    need_vxrestore=1;
	    need_runtar=1;
	    need_gnutar=1;
	    need_compress_path=1;
	    need_calcsize=1;
	    need_global_check=1;
	    /*@ignore@*/
	    check_disk(dle);
	    /*@end@*/
	} else {
	    goto err;				/* bad syntax */
	}
	free_dle(dle);
	dle = NULL;
    }
    if (g_options == NULL) {
	g_printf(_("ERROR [Missing OPTIONS line in selfcheck input]\n"));
	error(_("Missing OPTIONS line in selfcheck input\n"));
	/*NOTREACHED*/
    }

    if (am_has_feature(g_options->features, fe_req_xml)) {
	char  *errmsg = NULL;
	dle_t *dles, *dle, *dle_next;

	dles = amxml_parse_node_FILE(stdin, &errmsg);
	if (errmsg) {
	    err_extra = errmsg;
	    goto err;
	}
	if (merge_dles_properties(dles, 1) == 0) {
	    goto checkoverall;
	}
	for (dle = dles; dle != NULL; dle = dle->next) {
	    run_client_scripts(EXECUTE_ON_PRE_HOST_AMCHECK, g_options, dle,
			       stdout);
	}
	for (dle = dles; dle != NULL; dle = dle->next) {
	    check_options(dle);
	    run_client_scripts(EXECUTE_ON_PRE_DLE_AMCHECK, g_options, dle,
			       stdout);
	    check_disk(dle);
	    run_client_scripts(EXECUTE_ON_POST_DLE_AMCHECK, g_options, dle,
			       stdout);
	}
	for (dle = dles; dle != NULL; dle = dle->next) {
	    run_client_scripts(EXECUTE_ON_POST_HOST_AMCHECK, g_options, dle,
			       stdout);
	}
	for (dle = dles; dle != NULL; dle = dle_next) {
	    dle_next = dle->next;
	    free_dle(dle);
	}
    }

checkoverall:
    check_overall();

    amfree(line);
    amfree(our_feature_string);
    am_release_feature_set(our_features);
    our_features = NULL;
    free_g_options(g_options);

    dbclose();
    return 0;

 err:
    if (err_extra) {
	g_printf(_("ERROR [FORMAT ERROR IN REQUEST PACKET %s]\n"), err_extra);
	dbprintf(_("REQ packet is bogus: %s\n"), err_extra);
    } else {
	g_printf(_("ERROR [FORMAT ERROR IN REQUEST PACKET]\n"));
	dbprintf(_("REQ packet is bogus\n"));
    }
    amfree(err_extra);
    amfree(line);
    if (dle)
	free_dle(dle);
    dbclose();
    return 1;
}
Example #13
0
static void
check_disk(
    dle_t *dle)
{
    char *device = NULL;
    char *err = NULL;
    char *user_and_password = NULL;
    char *domain = NULL;
    char *share = NULL, *subdir = NULL;
    size_t lpass = 0;
    int amode = R_OK;
    int access_result;
    char *access_type;
    char *extra_info = NULL;
    char *qdisk = NULL;
    char *qamdevice = NULL;
    char *qdevice = NULL;

    if (dle->disk) {
	need_global_check=1;
	qdisk = quote_string(dle->disk);
	qamdevice = quote_string(dle->device);
	device = g_strdup("nodevice");
	dbprintf(_("checking disk %s\n"), qdisk);
	if (GPOINTER_TO_INT(dle->estimatelist->data) == ES_CALCSIZE) {
	    if (dle->device[0] == '/' && dle->device[1] == '/') {
		err = g_strdup_printf(
		    _("Can't use CALCSIZE for samba estimate, use CLIENT: %s"),
		    dle->device);
		goto common_exit;
	    }
	}

	if (g_str_equal(dle->program, "GNUTAR")) {
            if(dle->device[0] == '/' && dle->device[1] == '/') {
		#ifdef SAMBA_CLIENT
		int nullfd, checkerr;
		int passwdfd;
		char *pwtext;
		size_t pwtext_len;
		pid_t checkpid;
		amwait_t retstat;
		pid_t wpid;
		int rc;
		char *line;
		char *sep;
		FILE *ferr;
		char *pw_fd_env;
		int errdos;

		parsesharename(dle->device, &share, &subdir);
		if (!share) {
		    err = g_strdup_printf(
			      _("cannot parse for share/subdir disk entry %s"),
			      dle->device);
		    goto common_exit;
		}
		if ((subdir) && (SAMBA_VERSION < 2)) {
		    err = g_strdup_printf(_("subdirectory specified for share '%s' but, samba is not v2 or better"),
				     dle->device);
		    goto common_exit;
		}
		if ((user_and_password = findpass(share, &domain)) == NULL) {
		    err = g_strdup_printf(_("cannot find password for %s"),
				     dle->device);
		    goto common_exit;
		}
		lpass = strlen(user_and_password);
		if ((pwtext = strchr(user_and_password, '%')) == NULL) {
		    err = g_strdup_printf(
				_("password field not \'user%%pass\' for %s"),
				dle->device);
		    goto common_exit;
		}
		*pwtext++ = '\0';
		pwtext_len = (size_t)strlen(pwtext);
		amfree(device);
		if ((device = makesharename(share, 0)) == NULL) {
		    err = g_strdup_printf(_("cannot make share name of %s"), share);
		    goto common_exit;
		}

		if ((nullfd = open("/dev/null", O_RDWR)) == -1) {
	            err = g_strdup_printf(_("Cannot access /dev/null : %s"),
				     strerror(errno));
		    goto common_exit;
		}

		if (pwtext_len > 0) {
		    pw_fd_env = "PASSWD_FD";
		} else {
		    pw_fd_env = "dummy_PASSWD_FD";
		}
		checkpid = pipespawn(SAMBA_CLIENT, STDERR_PIPE|PASSWD_PIPE, 0,
				     &nullfd, &nullfd, &checkerr,
				     pw_fd_env, &passwdfd,
				     "smbclient",
				     device,
				     *user_and_password ? "-U" : skip_argument,
				     *user_and_password ? user_and_password
							: skip_argument,
				     "-E",
				     domain ? "-W" : skip_argument,
				     domain ? domain : skip_argument,
#if SAMBA_VERSION >= 2
				     subdir ? "-D" : skip_argument,
				     subdir ? subdir : skip_argument,
#endif
				     "-c", "quit",
				     NULL);
		checkpid = checkpid;
		amfree(domain);
		aclose(nullfd);
		/*@ignore@*/
		if ((pwtext_len > 0) &&
		    full_write(passwdfd, pwtext, pwtext_len) < pwtext_len) {
		    err = g_strdup_printf(_("password write failed: %s: %s"),
				     dle->device, strerror(errno));
		    aclose(passwdfd);
		    goto common_exit;
		}
		/*@end@*/
		memset(user_and_password, '\0', (size_t)lpass);
		amfree(user_and_password);
		aclose(passwdfd);
		ferr = fdopen(checkerr, "r");
		if (!ferr) {
		    g_printf(_("ERROR [Can't fdopen ferr: %s]\n"), strerror(errno));
		    error(_("Can't fdopen ferr: %s"), strerror(errno));
		    /*NOTREACHED*/
		}
		sep = "";
		errdos = 0;
		for(sep = ""; (line = agets(ferr)) != NULL; free(line)) {
		    if (line[0] == '\0')
			continue;
		    strappend(extra_info, sep);
		    strappend(extra_info, line);
		    sep = ": ";
		    if(strstr(line, "ERRDOS") != NULL) {
			errdos = 1;
		    }
		}
		afclose(ferr);
		checkerr = -1;
		rc = 0;
		sep = "";
		while ((wpid = wait(&retstat)) != -1) {
		    if (!WIFEXITED(retstat) || WEXITSTATUS(retstat) != 0) {
			char *exitstr = str_exit_status("smbclient", retstat);
			strappend(err, sep);
			strappend(err, exitstr);
			sep = "\n";
			amfree(exitstr);

			rc = 1;
		    }
		}
		if (errdos != 0 || rc != 0) {
		    char *tmpbuf;
		    if (extra_info) {
                        tmpbuf = g_strdup_printf( _("samba access error: %s: %s %s"),
                            dle->device, extra_info, err);
			amfree(extra_info);
		    } else {
			tmpbuf = g_strdup_printf(_("samba access error: %s: %s"),
                            dle->device, err);
		    }
		    g_free(err);
		    err = tmpbuf;
		}
#else
		err = g_strdup_printf(
			      _("This client is not configured for samba: %s"),
			      qdisk);
#endif
		goto common_exit;
	    }
	    amode = F_OK;
	    amfree(device);
	    device = amname_to_dirname(dle->device);
	} else if (g_str_equal(dle->program, "DUMP")) {
	    if(dle->device[0] == '/' && dle->device[1] == '/') {
		err = g_strdup_printf(
		  _("The DUMP program cannot handle samba shares, use GNUTAR: %s"),
		  qdisk);
		goto common_exit;
	    }
#ifdef VDUMP								/* { */
#ifdef DUMP								/* { */
            if (g_str_equal(amname_to_fstype(dle->device), "advfs"))
#else									/* }{*/
	    if (1)
#endif									/* } */
	    {
		amfree(device);
		device = amname_to_dirname(dle->device);
		amode = F_OK;
	    } else
#endif									/* } */
	    {
		amfree(device);
		device = amname_to_devname(dle->device);
#ifdef USE_RUNDUMP
		amode = F_OK;
#else
		amode = R_OK;
#endif
	    }
	}
    }
    if (dle->program_is_application_api) {
	pid_t                    application_api_pid;
	backup_support_option_t *bsu;
	int                      app_err[2];
	GPtrArray               *errarray;

	bsu = backup_support_option(dle->program, g_options, dle->disk,
				    dle->device, &errarray);

	if (!bsu) {
	    char  *line;
	    guint  i;
	    for (i=0; i < errarray->len; i++) {
		line = g_ptr_array_index(errarray, i);
		fprintf(stdout, _("ERROR Application '%s': %s\n"),
			dle->program, line);
		amfree(line);
	    }
	    err = g_strdup_printf(_("Application '%s': can't run support command"),
			     dle->program);
	    goto common_exit;
	}

	if (dle->data_path == DATA_PATH_AMANDA &&
	    (bsu->data_path_set & DATA_PATH_AMANDA)==0) {
	    g_printf("ERROR application %s doesn't support amanda data-path\n",
		     dle->program);
	}
	if (dle->data_path == DATA_PATH_DIRECTTCP &&
	    (bsu->data_path_set & DATA_PATH_DIRECTTCP)==0) {
	    g_printf("ERROR application %s doesn't support directtcp data-path\n",
		     dle->program);
	}
	if (GPOINTER_TO_INT(dle->estimatelist->data) == ES_CALCSIZE &&
			    !bsu->calcsize) {
	    g_printf("ERROR application %s doesn't support calcsize estimate\n",
		     dle->program);
	}
	if (dle->include_file && dle->include_file->nb_element > 0 &&
	    !bsu->include_file) {
	    g_printf("ERROR application %s doesn't support include-file\n",
		   dle->program);
	}
	if (dle->include_list && dle->include_list->nb_element > 0 &&
	    !bsu->include_list) {
	    g_printf("ERROR application %s doesn't support include-list\n",
		   dle->program);
	}
	if (dle->include_optional && !bsu->include_optional) {
	    g_printf("ERROR application %s doesn't support optional include\n",
		   dle->program);
	}
	if (dle->exclude_file && dle->exclude_file->nb_element > 0 &&
	    !bsu->exclude_file) {
	    g_printf("ERROR application %s doesn't support exclude-file\n",
		   dle->program);
	}
	if (dle->exclude_list && dle->exclude_list->nb_element > 0 &&
	    !bsu->exclude_list) {
	    g_printf("ERROR application %s doesn't support exclude-list\n",
		   dle->program);
	}
	if (dle->exclude_optional && !bsu->exclude_optional) {
	    g_printf("ERROR application %s doesn't support optional exclude\n",
		   dle->program);
	}
	fflush(stdout);fflush(stderr);

	if (pipe(app_err) < 0) {
	    err = g_strdup_printf(_("Application '%s': can't create pipe"),
			     dle->program);
	    goto common_exit;
	}

	switch (application_api_pid = fork()) {
	case -1:
	    err = g_strdup_printf(_("fork failed: %s"), strerror(errno));
	    goto common_exit;

	case 0: /* child */
	    {
		GPtrArray *argv_ptr = g_ptr_array_new();
                GPtrArray *argv_quoted = g_ptr_array_new();
                gchar **args, **quoted_strings, **ptr;
		char *cmd = g_strjoin(NULL, APPLICATION_DIR, "/", dle->program, NULL);
		GSList   *scriptlist;
		script_t *script;
		estimatelist_t el;
		char *cmdline;

		aclose(app_err[0]);
		dup2(app_err[1], 2);

		g_ptr_array_add(argv_ptr, g_strdup(dle->program));
		g_ptr_array_add(argv_ptr, g_strdup("selfcheck"));
		if (bsu->message_line == 1) {
		    g_ptr_array_add(argv_ptr, g_strdup("--message"));
		    g_ptr_array_add(argv_ptr, g_strdup("line"));
		}
		if (g_options->config != NULL && bsu->config == 1) {
		    g_ptr_array_add(argv_ptr, g_strdup("--config"));
		    g_ptr_array_add(argv_ptr, g_strdup(g_options->config));
		}
		if (g_options->hostname != NULL && bsu->host == 1) {
		    g_ptr_array_add(argv_ptr, g_strdup("--host"));
		    g_ptr_array_add(argv_ptr, g_strdup(g_options->hostname));
		}
		if (dle->disk != NULL && bsu->disk == 1) {
		    g_ptr_array_add(argv_ptr, g_strdup("--disk"));
		    g_ptr_array_add(argv_ptr, g_strdup(dle->disk));
		}
		if (dle->device) {
		    g_ptr_array_add(argv_ptr, g_strdup("--device"));
		    g_ptr_array_add(argv_ptr, g_strdup(dle->device));
		}
		if (dle->create_index && bsu->index_line == 1) {
		    g_ptr_array_add(argv_ptr, g_strdup("--index"));
		    g_ptr_array_add(argv_ptr, g_strdup("line"));
		}
		if (dle->record && bsu->record == 1) {
		    g_ptr_array_add(argv_ptr, g_strdup("--record"));
		}
		
		for (el = dle->estimatelist; el != NULL; el=el->next) {
		    estimate_t estimate = (estimate_t)GPOINTER_TO_INT(el->data);
		    if (estimate == ES_CALCSIZE && bsu->calcsize == 1) {
			g_ptr_array_add(argv_ptr, g_strdup("--calcsize"));
		    }
		}
		application_property_add_to_argv(argv_ptr, dle, bsu,
						 g_options->features);

		for (scriptlist = dle->scriptlist; scriptlist != NULL;
		     scriptlist = scriptlist->next) {
		    script = (script_t *)scriptlist->data;
		    if (script->result && script->result->proplist) {
			property_add_to_argv(argv_ptr,
					     script->result->proplist);
		    }
		}

		g_ptr_array_add(argv_ptr, NULL);
                args = (gchar **)g_ptr_array_free(argv_ptr, FALSE);

                /*
                 * Build the command line to display
                 */
                g_ptr_array_add(argv_quoted, g_strdup(cmd));

                for (ptr = args; *ptr; ptr++)
                    g_ptr_array_add(argv_quoted, quote_string(*ptr));

                g_ptr_array_add(argv_quoted, NULL);

                quoted_strings = (gchar **)g_ptr_array_free(argv_quoted, FALSE);

                cmdline = g_strjoinv(" ", quoted_strings);
                g_strfreev(quoted_strings);

		dbprintf(_("Spawning \"%s\" in pipeline\n"), cmdline);
		amfree(cmdline);

		safe_fd(-1, 0);
		execve(cmd, args, safe_env());
		g_printf(_("ERROR [Can't execute %s: %s]\n"), cmd, strerror(errno));
		exit(127);
	    }
	default: /* parent */
	    {
		int   status;
		FILE *app_stderr;
		char *line;

		aclose(app_err[1]);
		app_stderr = fdopen(app_err[0], "r");
		if (!app_stderr) {
		    g_printf(_("ERROR [Can't fdopen app_stderr: %s]\n"),
			     strerror(errno));
		    error(_("Can't fdopen app_stderr: %s"), strerror(errno));
		    /*NOTREACHED*/
		}
		while((line = agets(app_stderr)) != NULL) {
		    if (strlen(line) > 0) {
			fprintf(stdout, "ERROR Application '%s': %s\n",
				dle->program, line);
			dbprintf("ERROR %s\n", line);
		    }
		    amfree(line);
		}
		fclose(app_stderr);
		if (waitpid(application_api_pid, &status, 0) < 0) {
		    err = g_strdup_printf(_("waitpid failed: %s"),
					 strerror(errno));
		    goto common_exit;
		} else if (!WIFEXITED(status)) {
		    err = g_strdup_printf(_("Application '%s': exited with signal %d"),
				     dle->program, WTERMSIG(status));
		    goto common_exit;
		} else if (WEXITSTATUS(status) != 0) {
		    err = g_strdup_printf(_("Application '%s': exited with status %d"),
				     dle->program, WEXITSTATUS(status));
		    goto common_exit;
		}
	    }
	}
	amfree(bsu);
	fflush(stdout);fflush(stderr);
	amfree(device);
	amfree(qamdevice);
	amfree(qdisk);
	return;
    }

    if (device) {
	qdevice = quote_string(device);
	dbprintf(_("device %s\n"), qdevice);

	/* skip accessability test if this is an AFS entry */
	if(strncmp_const(device, "afs:") != 0) {
#ifdef CHECK_FOR_ACCESS_WITH_OPEN
	    access_result = open(device, O_RDONLY);
	    access_type = "open";
#else
	    access_result = access(device, amode);
	    access_type = "access";
#endif
	    if(access_result == -1) {
		err = g_strdup_printf(_("Could not %s %s (%s): %s"),
				 access_type, qdevice, qdisk, strerror(errno));
	    }
#ifdef CHECK_FOR_ACCESS_WITH_OPEN
	    aclose(access_result);
#endif
	}
    }

common_exit:

    if (!qdevice)
	qdevice = quote_string(device);

    amfree(share);
    amfree(subdir);
    if(user_and_password) {
	memset(user_and_password, '\0', (size_t)lpass);
	amfree(user_and_password);
    }
    amfree(domain);

    if(err) {
	g_printf(_("ERROR %s\n"), err);
	dbprintf(_("%s\n"), err);
	amfree(err);
    } else {
	if (dle->disk) {
	    g_printf("OK %s\n", qdisk);
	    dbprintf(_("disk %s OK\n"), qdisk);
	}
	if (dle->device) {
	    g_printf("OK %s\n", qamdevice);
	    dbprintf(_("amdevice %s OK\n"), qamdevice);
	}
	if (device) {
	    g_printf("OK %s\n", qdevice);
	    dbprintf(_("device %s OK\n"), qdevice);
	}
    }
    if(extra_info) {
	dbprintf(_("extra info: %s\n"), extra_info);
	amfree(extra_info);
    }
    amfree(qdisk);
    amfree(qdevice);
    amfree(qamdevice);
    amfree(device);

    /* XXX perhaps do something with level: read dumpdates and sanity check */
}
Example #14
0
/* do this by looking for the longest mount point which matches the
   current directory */
int
guess_disk (
    char *	cwd,
    size_t	cwd_len,
    char **	dn_guess,
    char **	mpt_guess)
{
    size_t longest_match = 0;
    size_t current_length;
    size_t cwd_length;
    int local_disk = 0;
    generic_fsent_t fsent;
    char *fsname = NULL;
    char *disk_try = NULL;

    *dn_guess = NULL;
    *mpt_guess = NULL;

    if (getcwd(cwd, cwd_len) == NULL) {
	return -1;
	/*NOTREACHED*/
    }
    cwd_length = strlen(cwd);
    dbprintf(_("guess_disk: %zu: \"%s\"\n"), cwd_length, cwd);

    if (open_fstab() == 0) {
	return -1;
	/*NOTREACHED*/
    }

    while (get_fstab_nextentry(&fsent))
    {
	current_length = fsent.mntdir ? strlen(fsent.mntdir) : (size_t)0;
	dbprintf(_("guess_disk: %zu: %zu: \"%s\": \"%s\"\n"),
		  longest_match,
		  current_length,
		  fsent.mntdir ? fsent.mntdir : _("(mntdir null)"),
		  fsent.fsname ? fsent.fsname : _("(fsname null)"));
	if ((current_length > longest_match)
	    && (current_length <= cwd_length)
	    && (strncmp(fsent.mntdir, cwd, current_length) == 0))
	{
	    longest_match = current_length;
	    *mpt_guess = newstralloc(*mpt_guess, fsent.mntdir);
	    if(strncmp(fsent.fsname,DEV_PREFIX,(strlen(DEV_PREFIX))))
	    {
	        fsname = newstralloc(fsname, fsent.fsname);
            }
	    else
	    {
	        fsname = newstralloc(fsname,fsent.fsname+strlen(DEV_PREFIX));
	    }
	    local_disk = is_local_fstype(&fsent);
	    dbprintf(_("guess_disk: local_disk = %d, fsname = \"%s\"\n"),
		      local_disk,
		      fsname);
	}
    }
    close_fstab();

    if (longest_match == 0) {
	amfree(*mpt_guess);
	amfree(fsname);
	return -1;			/* ? at least / should match */
    }

    if (!local_disk) {
	amfree(*mpt_guess);
	amfree(fsname);
	return 0;
    }

    /* have mount point now */
    /* disk name may be specified by mount point (logical name) or
       device name, have to determine */
    g_printf(_("Trying disk %s ...\n"), *mpt_guess);
    disk_try = stralloc2("DISK ", *mpt_guess);		/* try logical name */
    if (exchange(disk_try) == -1)
	exit(1);
    amfree(disk_try);
    if (server_happy())
    {
	*dn_guess = stralloc(*mpt_guess);		/* logical is okay */
	amfree(fsname);
	return 1;
    }
    g_printf(_("Trying disk %s ...\n"), fsname);
    disk_try = stralloc2("DISK ", fsname);		/* try device name */
    if (exchange(disk_try) == -1)
	exit(1);
    amfree(disk_try);
    if (server_happy())
    {
	*dn_guess = stralloc(fsname);			/* dev name is okay */
	amfree(fsname);
	return 1;
    }

    /* neither is okay */
    amfree(*mpt_guess);
    amfree(fsname);
    return 2;
}
Example #15
0
void gumball_load_from_trough (void)
{
	dbprintf ("Gumball load requested\n");
	gumball_enable_from_trough = TRUE;
	autofire_add_ball ();
}
Example #16
0
File: uuid.c Project: crossmeta/sgi
static int
uuid_f(
	int		argc,
	char		**argv)
{
	char	        bp[40];
	xfs_agnumber_t	agno;
        uuid_t          uu;
        uuid_t          *uup=NULL;
        
	if (argc != 1 && argc != 2) {
	    dbprintf("invalid parameters\n");
	    return 0;
	}
        
        if (argc==2) {
            /* write uuid */
            
	    if (flag_readonly || !flag_expert_mode) {
		    dbprintf("%s not started in read-write expert mode, writing disabled\n",
			    progname);
		    return 0;
	    }
            
            if (!strcasecmp(argv[1], "generate")) {
                uuid_generate(uu);
            } else if (!strcasecmp(argv[1], "nil")) {
                uuid_clear(uu);
            } else if (!strcasecmp(argv[1], "rewrite")) {
                uup=do_uuid(0, NULL);
                if (!uup) {
                    dbprintf("failed to read UUID from AG 0\n");
                    return 0;
                }
                memcpy(&uu, *uup, sizeof(uuid_t));
	        uuid_unparse(uu, bp);
                dbprintf("old uuid = %s\n", bp);
            } else {
                if (uuid_parse(argv[1], uu)) {
                    dbprintf("invalid uuid\n");
                    return 0;
                }
            }
            
            if (mp->m_sb.sb_logstart) {
                if (xfsargs.logdev) {
                    dbprintf("external log specified for FS with internal log - aborting \n");
                    return 0;
                }
            } else {
                if (!xfsargs.logdev) {
                    dbprintf("no external log specified for FS with external log - aborting\n");
                    return 0;
                }
            }
            
            dbprintf("clearing log and setting uuid\n");
            
            /* clear log (setting uuid) */
            
            if (libxfs_log_clear(
                    (mp->m_sb.sb_logstart)?xfsargs.ddev:xfsargs.logdev,
                    XFS_FSB_TO_DADDR(mp, mp->m_sb.sb_logstart),
                    XFS_FSB_TO_BB(mp, mp->m_sb.sb_logblocks),
                    &uu,
                    XLOG_FMT)) {
                        dbprintf("error clearing log\n");
                        return 0;
                    }
                
            
            dbprintf("writing all SBs\n");
            
	    for (agno = 0; agno < mp->m_sb.sb_agcount; agno++)
                if (!do_uuid(agno, &uu)) {
                    dbprintf("failed to set uuid in AG %d\n", agno);
                    break;
                }
                
	    uuid_unparse(uu, bp);
            dbprintf("new uuid = %s\n", bp);
            
            return 0;
            
        } else {
            /* get (check) uuid */
            
	    for (agno = 0; agno < mp->m_sb.sb_agcount; agno++) {
                uup=do_uuid(agno, NULL);
                if (!uup) {
                    dbprintf("failed to read UUID from AG %d\n", agno);
                    return 0;
                }
                if (agno) {
                    if (memcmp(&uu, uup, sizeof(uuid_t))) {
                        dbprintf("warning: uuid copies differ\n");
                        break;
                    }
                } else {
                    memcpy(uu, uup, sizeof(uuid_t));
                }
            }
            if (mp->m_sb.sb_logstart) {
                if (xfsargs.logdev) 
                    dbprintf("warning: external log specified for FS with internal log\n");
            } else {
                if (!xfsargs.logdev) {
                    dbprintf("warning: no external log specified for FS with external log\n");
                }
            }            
                
	    uuid_unparse(uu, bp);
	    dbprintf("uuid = %s\n", bp);
        }

	return 0;
}
Example #17
0
zbar_symbol_type_t zbar_decode_width (zbar_decoder_t *dcode,
                                      unsigned w)
{
    zbar_symbol_type_t tmp, sym = ZBAR_NONE;

    dcode->w[dcode->idx & (DECODE_WINDOW - 1)] = w;
    dbprintf(1, "    decode[%x]: w=%d (%g)\n", dcode->idx, w, (w / 32.));

    /* update shared character width */
    dcode->s6 -= get_width(dcode, 7);
    dcode->s6 += get_width(dcode, 1);

    /* each decoder processes width stream in parallel */
#ifdef ENABLE_QRCODE
    if(TEST_CFG(dcode->qrf.config, ZBAR_CFG_ENABLE) &&
       (tmp = _zbar_find_qr(dcode)) > ZBAR_PARTIAL)
        sym = tmp;
#endif
#ifdef ENABLE_EAN
    if((dcode->ean.enable) &&
       (tmp = _zbar_decode_ean(dcode)))
        sym = tmp;
#endif
#ifdef ENABLE_CODE39
    if(TEST_CFG(dcode->code39.config, ZBAR_CFG_ENABLE) &&
       (tmp = _zbar_decode_code39(dcode)) > ZBAR_PARTIAL)
        sym = tmp;
#endif
#ifdef ENABLE_CODE93
    if(TEST_CFG(dcode->code93.config, ZBAR_CFG_ENABLE) &&
       (tmp = _zbar_decode_code93(dcode)) > ZBAR_PARTIAL)
        sym = tmp;
#endif
#ifdef ENABLE_CODE128
    if(TEST_CFG(dcode->code128.config, ZBAR_CFG_ENABLE) &&
       (tmp = _zbar_decode_code128(dcode)) > ZBAR_PARTIAL)
        sym = tmp;
#endif
#ifdef ENABLE_DATABAR
    if(TEST_CFG(dcode->databar.config | dcode->databar.config_exp,
                ZBAR_CFG_ENABLE) &&
       (tmp = _zbar_decode_databar(dcode)) > ZBAR_PARTIAL)
        sym = tmp;
#endif
#ifdef ENABLE_I25
    if(TEST_CFG(dcode->i25.config, ZBAR_CFG_ENABLE) &&
       (tmp = _zbar_decode_i25(dcode)) > ZBAR_PARTIAL)
        sym = tmp;
#endif
#ifdef ENABLE_PDF417
    if(TEST_CFG(dcode->pdf417.config, ZBAR_CFG_ENABLE) &&
       (tmp = _zbar_decode_pdf417(dcode)) > ZBAR_PARTIAL)
        sym = tmp;
#endif

    dcode->idx++;
    dcode->type = sym;
    if(sym) {
        if(dcode->lock && sym > ZBAR_PARTIAL && sym != ZBAR_QRCODE)
            release_lock(dcode, sym);
        if(dcode->handler)
            dcode->handler(dcode);
    }
    return(sym);
}
Example #18
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_overrides_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_overrides(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_override(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_override(cfg_ovr, "conf", optarg);
		break;

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

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

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

	    case 'o':
		add_config_override_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_overrides(cfg_ovr);
    config_init(CONFIG_INIT_CLIENT | CONFIG_INIT_EXPLICIT_NAME | CONFIG_INIT_OVERLAY,
		getconf_str(CNF_CONF));
    reapply_config_overrides();

    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;
}
Example #19
0
int dbstore (struct mandata *in, const char *base)
{
	datum oldkey, oldcont;

	memset (&oldkey, 0, sizeof oldkey);
	memset (&oldcont, 0, sizeof oldcont);

	/* create a simple key */
	MYDBM_SET (oldkey, name_to_key (base));
 	if (!*base) {
		dbprintf (in);
 		return 2;
 	}

	if (in->name) {
		error (0, 0, "in->name (%s) should not be set when calling "
			     "dbstore()!\n",
		       in->name);
		free (in->name);
		in->name = NULL;
	}

	/* get the content for the simple key */

	oldcont = MYDBM_FETCH (dbf, oldkey);

	if (MYDBM_DPTR (oldcont) == NULL) { 		/* situation (1) */
		if (!STREQ (base, MYDBM_DPTR (oldkey)))
			in->name = xstrdup (base);
		oldcont = make_content (in);
		if (MYDBM_REPLACE (dbf, oldkey, oldcont))
			gripe_replace_key (MYDBM_DPTR (oldkey));
		free (MYDBM_DPTR (oldcont));
		free (in->name);
		in->name = NULL;
	} else if (*MYDBM_DPTR (oldcont) == '\t') { 	/* situation (2) */
		datum newkey, newcont;

		memset (&newkey, 0, sizeof newkey);
		memset (&newcont, 0, sizeof newcont);

		newkey = make_multi_key (base, in->ext);
		newcont = make_content (in);

		/* Try to insert the new multi data */

		if (MYDBM_INSERT (dbf, newkey, newcont)) {
			datum cont;
			struct mandata info;
			int ret;

			MYDBM_FREE (MYDBM_DPTR (oldcont));
			cont = MYDBM_FETCH (dbf, newkey);
			split_content (MYDBM_DPTR (cont), &info);
			ret = replace_if_necessary (in, &info,
						    newkey, newcont);
			/* MYDBM_FREE (MYDBM_DPTR (cont)); */
			free_mandata_elements (&info);
			free (MYDBM_DPTR (newkey));
			free (MYDBM_DPTR (newcont));
			free (MYDBM_DPTR (oldkey));

			return ret;
		}

		/* Now lets add some info to the simple key's cont. */

		/* This next bit needs to be done first as we'll wipe out
		   MYDBM_DPTR (oldcont) otherwise (for NDBM only!) */

		free (MYDBM_DPTR (newkey));
		free (MYDBM_DPTR (newcont));

		MYDBM_SET (newcont, xasprintf (
			"%s\t%s\t%s", MYDBM_DPTR (oldcont), base, in->ext));
		MYDBM_FREE (MYDBM_DPTR (oldcont));

		/* Try to replace the old simple data with the new stuff */

		if (MYDBM_REPLACE (dbf, oldkey, newcont))
			gripe_replace_key (MYDBM_DPTR (oldkey));

		free (MYDBM_DPTR (newcont));
	} else { 				/* situation (3) */
		datum newkey, newcont, lastkey, lastcont;
		struct mandata old;
		char *old_name;

		memset (&newkey, 0, sizeof newkey);
		memset (&newcont, 0, sizeof newcont);
		memset (&lastkey, 0, sizeof lastkey);
		memset (&lastcont, 0, sizeof lastcont);

		/* Extract the old singular reference */

		split_content (MYDBM_DPTR (oldcont), &old);

		/* Create multi keys for both old
		   and new items, create new content */

		if (old.name)
			old_name = xstrdup (old.name);
		else
			old_name = xstrdup (MYDBM_DPTR (oldkey));

		lastkey = make_multi_key (old_name, old.ext);

		/* Check against identical multi keys before inserting
		   into db */

		if (STREQ (old_name, base) && STREQ (old.ext, in->ext)) {
			int ret;

			if (!STREQ (base, MYDBM_DPTR (oldkey)))
				in->name = xstrdup (base);
			newcont = make_content (in);
			ret = replace_if_necessary (in, &old, oldkey, newcont);
			/* MYDBM_FREE (MYDBM_DPTR (oldcont)); */
			free_mandata_elements (&old);
			free (MYDBM_DPTR (newcont));
			free (MYDBM_DPTR (lastkey));
			free (MYDBM_DPTR (oldkey));
			free (old_name);
			free (in->name);
			in->name = NULL;

			return ret;
		}

		/* Multi keys use the proper case, and so don't need a name
		 * field.
		 */
		if (old.name) {
			free (old.name);
			old.name = NULL;
		}

		lastcont = make_content (&old);

		/* We always replace here; if the multi key already exists
		 * in the database, then that indicates some kind of
		 * database corruption, but our new multi key is almost
		 * certainly better.
		 */
		if (MYDBM_REPLACE (dbf, lastkey, lastcont))
			gripe_replace_key (MYDBM_DPTR (lastkey));

		free (MYDBM_DPTR (lastkey));
		free (MYDBM_DPTR (lastcont));

		newkey = make_multi_key (base, in->ext);
		newcont = make_content (in);

		if (MYDBM_REPLACE (dbf, newkey, newcont))
			gripe_replace_key (MYDBM_DPTR (newkey));

		free (MYDBM_DPTR (newkey));
		free (MYDBM_DPTR (newcont));

		/* Now build a simple reference to the above two items */

		MYDBM_SET (newcont, xasprintf (
			"\t%s\t%s\t%s\t%s", old_name, old.ext, base, in->ext));

		if (MYDBM_REPLACE (dbf, oldkey, newcont))
			gripe_replace_key (MYDBM_DPTR (oldkey));

		/* MYDBM_FREE (MYDBM_DPTR (oldcont)); */
		free_mandata_elements (&old);
		free (MYDBM_DPTR (newcont));
		free (old_name);
	}

	free (MYDBM_DPTR (oldkey));
	return 0;
}
Example #20
0
static void
amindexd_response(
    void *datap,
    pkt_t *pkt,
    security_handle_t *sech)
{
    int ports[NSTREAMS], *response_error = datap, i;
    char *p;
    char *tok;
    char *extra = NULL;

    assert(response_error != NULL);
    assert(sech != NULL);

    if (pkt == NULL) {
	errstr = newvstrallocf(errstr, _("[request failed: %s]"),
			     security_geterror(sech));
	*response_error = 1;
	return;
    }

    if (pkt->type == P_NAK) {
#if defined(PACKET_DEBUG)
	dbprintf(_("got nak response:\n----\n%s\n----\n\n"), pkt->body);
#endif

	tok = strtok(pkt->body, " ");
	if (tok == NULL || strcmp(tok, "ERROR") != 0)
	    goto bad_nak;

	tok = strtok(NULL, "\n");
	if (tok != NULL) {
	    errstr = newvstrallocf(errstr, "NAK: %s", tok);
	    *response_error = 1;
	} else {
bad_nak:
	    errstr = newvstrallocf(errstr, _("request NAK"));
	    *response_error = 2;
	}
	return;
    }

    if (pkt->type != P_REP) {
	errstr = newvstrallocf(errstr, _("received strange packet type %s: %s"),
			      pkt_type2str(pkt->type), pkt->body);
	*response_error = 1;
	return;
    }

#if defined(PACKET_DEBUG)
    g_fprintf(stderr, _("got response:\n----\n%s\n----\n\n"), pkt->body);
#endif

    for(i = 0; i < NSTREAMS; i++) {
        ports[i] = -1;
        streams[i].fd = NULL;
    }

    p = pkt->body;
    while((tok = strtok(p, " \n")) != NULL) {
	p = NULL;

	/*
	 * Error response packets have "ERROR" followed by the error message
	 * followed by a newline.
	 */
	if (strcmp(tok, "ERROR") == 0) {
	    tok = strtok(NULL, "\n");
	    if (tok == NULL) {
	        errstr = newvstrallocf(errstr, _("[bogus error packet]"));
	    } else {
		errstr = newvstrallocf(errstr, "%s", tok);
	    }
	    *response_error = 2;
	    return;
	}


        /*
         * Regular packets have CONNECT followed by three streams
         */
        if (strcmp(tok, "CONNECT") == 0) {

	    /*
	     * Parse the three stream specifiers out of the packet.
	     */
	    for (i = 0; i < NSTREAMS; i++) {
		tok = strtok(NULL, " ");
		if (tok == NULL || strcmp(tok, streams[i].name) != 0) {
		    extra = vstrallocf(
			   _("CONNECT token is \"%s\": expected \"%s\""),
			   tok ? tok : _("(null)"), streams[i].name);
		    goto parse_error;
		}
		tok = strtok(NULL, " \n");
		if (tok == NULL || sscanf(tok, "%d", &ports[i]) != 1) {
		    extra = vstrallocf(
			   _("CONNECT %s token is \"%s\" expected a port number"),
			   streams[i].name, tok ? tok : _("(null)"));
		    goto parse_error;
		}
	    }
	    continue;
	}

	/*
	 * OPTIONS [options string] '\n'
	 */
	if (strcmp(tok, "OPTIONS") == 0) {
	    tok = strtok(NULL, "\n");
	    if (tok == NULL) {
		extra = vstrallocf(_("OPTIONS token is missing"));
		goto parse_error;
	    }
#if 0
	    tok_end = tok + strlen(tok);
	    while((p = strchr(tok, ';')) != NULL) {
		*p++ = '\0';
		if(strncmp_const(tok, "features=") == 0) {
		    tok += SIZEOF("features=") - 1;
		    am_release_feature_set(their_features);
		    if((their_features = am_string_to_feature(tok)) == NULL) {
			errstr = newvstrallocf(errstr,
				      _("OPTIONS: bad features value: %s"),
				      tok);
			goto parse_error;
		    }
		}
		tok = p;
	    }
#endif
	    continue;
	}
#if 0
	extra = vstrallocf(_("next token is \"%s\": expected \"CONNECT\", \"ERROR\" or \"OPTIONS\""), tok ? tok : _("(null)"));
	goto parse_error;
#endif
    }

    /*
     * Connect the streams to their remote ports
     */
    for (i = 0; i < NSTREAMS; i++) {
/*@i@*/	if (ports[i] == -1)
	    continue;
	streams[i].fd = security_stream_client(sech, ports[i]);
	if (streams[i].fd == NULL) {
	    errstr = newvstrallocf(errstr,
			_("[could not connect %s stream: %s]"),
			streams[i].name, security_geterror(sech));
	    goto connect_error;
	}
    }
    /*
     * Authenticate the streams
     */
    for (i = 0; i < NSTREAMS; i++) {
	if (streams[i].fd == NULL)
	    continue;
	if (security_stream_auth(streams[i].fd) < 0) {
	    errstr = newvstrallocf(errstr,
		_("[could not authenticate %s stream: %s]"),
		streams[i].name, security_stream_geterror(streams[i].fd));
	    goto connect_error;
	}
    }

    /*
     * The MESGFD and DATAFD streams are mandatory.  If we didn't get
     * them, complain.
     */
    if (streams[MESGFD].fd == NULL) {
        errstr = newvstrallocf(errstr, _("[couldn't open MESG streams]"));
        goto connect_error;
    }

    /* everything worked */
    *response_error = 0;
    amindexd_alive = 1;
    return;

parse_error:
    errstr = newvstrallocf(errstr,
			  _("[parse of reply message failed: %s]"),
			  extra ? extra : _("(no additional information)"));
    amfree(extra);
    *response_error = 2;
    return;

connect_error:
    stop_amindexd();
    *response_error = 1;
}
Example #21
0
VMware::VMware()
:	m_cGELock("VMware_ge_lock")
{
	int pciItor, chipItor;
	bool vidCardFound = false;

	/* Give safe values to all the class data members */
	InitMembers();

	for(pciItor = 0; get_pci_info(&m_cPciInfo, pciItor) == 0; pciItor++)
	{
		m_vmChipInfo.nChipId = (m_cPciInfo.nVendorID << 16) | (m_cPciInfo.nDeviceID);

		for(chipItor = 0; chipItor < numSupportedChips; chipItor++)
		{
			if(m_vmChipInfo.nChipId == supportedChips[chipItor].nChipId)
			{
				vidCardFound = true;
				m_vmChipInfo.nArchRev = supportedChips[chipItor].nArchRev;
				m_vmChipInfo.pzName = supportedChips[chipItor].pzName;
				break;
			}
		}

		if(vidCardFound)
			break;
	}

	if(!vidCardFound)
	{
		printf("VMware - Did not find any VMware video cards.\n");
		return;
	}

	dbprintf("VMware - Found match - PCI %d: Vendor 0x%04x "
				"Device 0x%04x - Rev 0x%04x\n", pciItor,
				m_cPciInfo.nVendorID, m_cPciInfo.nDeviceID,
				m_cPciInfo.nRevisionID);

	/* Initialize the hardware.  This will setup the
	 * IO ports and write to m_regId */
	if(!InitHardware())
	{
		dbprintf("VMware - Unable to initialize hardware.\n");
		vmwareWriteReg(SVGA_REG_CONFIG_DONE, 0);
		vmwareWriteReg(SVGA_REG_ENABLE, 0);
		return;
	}

	dbprintf("VMware - Host bpp is %d\n", (int) m_regHostBPP);
	dbprintf("VMware - Current Guest bpp is set to %d\n", (int) m_regBitsPerPixel);
	dbprintf("VMware - Only allowing %d bpp\n", (int) m_regBitsPerPixel);

	int bpp;
	color_space colspace;
	float rf[] = {60.0f};
	if(m_regBitsPerPixel == 16)
	{
		bpp = 2;
		colspace = CS_RGB16;
	}
	else if(m_regBitsPerPixel == 32)
	{
		bpp = 4;
		colspace = CS_RGB32;
	}
	else
	{
		dbprintf("VMware - m_regBitsPerPixel is unexpected value of %d\n",
					(int) m_regBitsPerPixel);
		return;
	}

	for(int j = 0; j < 4; j++)
	{
		m_cScreenModeList.push_back(os::screen_mode(640, 480, 640 * bpp, colspace, rf[j]));
		m_cScreenModeList.push_back(os::screen_mode(800, 600, 800 * bpp, colspace, rf[j]));
		m_cScreenModeList.push_back(os::screen_mode(1024, 768, 1024 * bpp, colspace, rf[j]));
	}

	m_bIsInitiated = true;
	return;
}
Example #22
0
void
check_running_as(running_as_flags who)
{
#ifdef CHECK_USERID
    struct passwd *pw;
    uid_t uid_me;
    uid_t uid_target;
    char *uname_me = NULL;
    char *uname_target = NULL;
    char *dumpuser;

    uid_me = getuid();
    if ((pw = getpwuid(uid_me)) == NULL) {
        error(_("current userid %ld not found in password database"), (long)uid_me);
	/* NOTREACHED */
    }
    uname_me = stralloc(pw->pw_name);

#ifndef SINGLE_USERID
    if (!(who & RUNNING_AS_UID_ONLY) && uid_me != geteuid()) {
	error(_("euid (%lld) does not match uid (%lld); is this program setuid-root when it shouldn't be?"),
		(long long int)geteuid(), (long long int)uid_me);
	/* NOTREACHED */
    }
#endif

    switch (who & RUNNING_AS_USER_MASK) {
	case RUNNING_AS_ANY:
	    uid_target = uid_me;
	    uname_target = uname_me;
	    return;

	case RUNNING_AS_ROOT:
	    uid_target = 0;
	    uname_target = "root";
	    break;

	case RUNNING_AS_DUMPUSER_PREFERRED:
	    dumpuser = getconf_str(CNF_DUMPUSER);
	    if ((pw = getpwnam(dumpuser)) != NULL &&
                    uid_me != pw->pw_uid) {
		if ((pw = getpwnam(CLIENT_LOGIN)) != NULL &&
		    uid_me == pw->pw_uid) {
		    /* uid == CLIENT_LOGIN: not ideal, but OK */
		    dbprintf(_("NOTE: running as '%s', which is the client"
			       " user, not the dumpuser ('%s'); forging"
			       " on anyway\n"),
			     CLIENT_LOGIN, dumpuser);
		    uid_target = uid_me; /* force success below */
		   break;
		}
            }
            /* FALLTHROUGH */

	case RUNNING_AS_DUMPUSER:
	    uname_target = getconf_str(CNF_DUMPUSER);
	    if ((pw = getpwnam(uname_target)) == NULL) {
		error(_("cannot look up dumpuser \"%s\""), uname_target);
		/*NOTREACHED*/
	    }
	    uid_target = pw->pw_uid;
	    break;

	case RUNNING_AS_CLIENT_LOGIN:
	    uname_target = CLIENT_LOGIN;
	    if ((pw = getpwnam(uname_target)) == NULL) {
		error(_("cannot look up client user \"%s\""), uname_target);
		/*NOTREACHED*/
	    }
	    uid_target = pw->pw_uid;
	    break;

	default:
	    error(_("Unknown check_running_as() call"));
	    /* NOTREACHED */
    }

    if (uid_me != uid_target) {
	error(_("running as user \"%s\" instead of \"%s\""), uname_me, uname_target);
	/*NOTREACHED*/
    }
    amfree(uname_me);

#else
    /* Quiet unused variable warning */
    (void)who;
#endif
}
Example #23
0
g_option_t *
parse_g_options(
    char *	str,
    int		verbose)
{
    g_option_t *g_options;
    char *p, *tok;
    int new_maxdumps;

    g_options = g_malloc(sizeof(g_option_t));
    init_g_options(g_options);
    g_options->str = g_strdup(str);

    p = g_strdup(str);
    tok = strtok(p,";");

    while (tok != NULL) {
	if(strncmp(tok,"features=", 9) == 0) {
	    char *t = tok+9;
	    char *u = strchr(t, ';');
	    if (u)
	       *u = '\0';
	    if(g_options->features != NULL) {
		dbprintf(_("multiple features option\n"));
		if(verbose) {
		    g_printf(_("ERROR [multiple features option]\n"));
		}
		amfree(g_options->features);
	    }
	    if((g_options->features = am_string_to_feature(t)) == NULL) {
		dbprintf(_("bad features value \"%s\"\n"), t);
		if(verbose) {
		    g_printf(_("ERROR [bad features value \"%s\"]\n"), t);
		}
	    }
	    if (u)
	       *u = ';';
	}
	else if(strncmp(tok,"hostname=", 9) == 0) {
	    if(g_options->hostname != NULL) {
		dbprintf(_("multiple hostname option\n"));
		if(verbose) {
		    g_printf(_("ERROR [multiple hostname option]\n"));
		}
		amfree(g_options->hostname);
	    }
	    g_options->hostname = g_strdup(tok+9);
	}
	else if(strncmp(tok,"auth=", 5) == 0) {
	    if(g_options->auth != NULL) {
		dbprintf(_("multiple auth option\n"));
		if(verbose) {
		    g_printf(_("ERROR [multiple auth option]\n"));
		}
		amfree(g_options->auth);
	    }
	    g_options->auth = g_strdup(tok+5);
	}
	else if(strncmp(tok,"maxdumps=", 9) == 0) {
	    if(g_options->maxdumps != 0) {
		dbprintf(_("multiple maxdumps option\n"));
		if(verbose) {
		    g_printf(_("ERROR [multiple maxdumps option]\n"));
		}
	    }
	    if(sscanf(tok+9, "%d;", &new_maxdumps) == 1) {
		if (new_maxdumps > MAXMAXDUMPS) {
		    g_options->maxdumps = MAXMAXDUMPS;
		}
		else if (new_maxdumps > 0) {
		    g_options->maxdumps = new_maxdumps;
		}
		else {
		    dbprintf(_("bad maxdumps value \"%s\"\n"), tok+9);
		    if(verbose) {
			g_printf(_("ERROR [bad maxdumps value \"%s\"]\n"),
			       tok+9);
		    }
		}
	    }
	    else {
		dbprintf(_("bad maxdumps value \"%s\"\n"), tok+9);
		if(verbose) {
		    g_printf(_("ERROR [bad maxdumps value \"%s\"]\n"),
			   tok+9);
		}
	    }
	}
	else if(strncmp(tok,"config=", 7) == 0) {
	    if(g_options->config != NULL) {
		dbprintf(_("multiple config option\n"));
		if(verbose) {
		    g_printf(_("ERROR [multiple config option]\n"));
		}
		amfree(g_options->config);
	    }
	    g_options->config = g_strdup(tok+7);
	    if (strchr(g_options->config, '/')) {
		amfree(g_options->config);
		dbprintf(_("invalid character in config option\n"));
		if(verbose) {
		    g_printf(_("ERROR [invalid character in config option]\n"));
		}
	    }
	}
	else {
	    dbprintf(_("unknown option \"%s\"\n"), tok);
	    if(verbose) {
		g_printf(_("ERROR [unknown option \"%s\"]\n"), tok);
	    }
	}
	tok = strtok(NULL, ";");
    }
    if(g_options->features == NULL) {
	g_options->features = am_set_default_feature_set();
    }
    if(g_options->maxdumps == 0) /* default */
	g_options->maxdumps = 1;
    amfree(p);
    return g_options;
}
Example #24
0
/* return >0: this is the connected socket */
int
connect_port(
    sockaddr_union *addrp,
    in_port_t  		port,
    char *		proto,
    sockaddr_union *svaddr,
    int			nonblock)
{
    int			save_errno;
    struct servent *	servPort;
    socklen_t_equiv	len;
    socklen_t_equiv	socklen;
    int			s;

    servPort = getservbyport((int)htons(port), proto);
    if (servPort != NULL && !strstr(servPort->s_name, "amanda")) {
	dbprintf(_("connect_port: Skip port %d: owned by %s.\n"),
		  port, servPort->s_name);
	errno = EBUSY;
	return -1;
    }

    if ((s = make_socket(SU_GET_FAMILY(addrp))) == -1) return -2;

    SU_SET_PORT(addrp, port);
    socklen = SS_LEN(addrp);
    if (bind(s, (struct sockaddr *)addrp, socklen) != 0) {
	save_errno = errno;
	aclose(s);
	if(servPort == NULL) {
	    dbprintf(_("connect_port: Try  port %d: available - %s\n"),
		     port, strerror(errno));
	} else {
	    dbprintf(_("connect_port: Try  port %d: owned by %s - %s\n"),
		     port, servPort->s_name, strerror(errno));
	}
	if (save_errno != EADDRINUSE) {
	    errno = save_errno;
	    return -2;
	}

	errno = save_errno;
	return -1;
    }
    if(servPort == NULL) {
	dbprintf(_("connect_port: Try  port %d: available - Success\n"), port);
    } else {
	dbprintf(_("connect_port: Try  port %d: owned by %s - Success\n"),
		  port, servPort->s_name);
    }

    /* find out what port was actually used */

    len = sizeof(*addrp);
    if (getsockname(s, (struct sockaddr *)addrp, &len) == -1) {
	save_errno = errno;
	dbprintf(_("connect_port: getsockname() failed: %s\n"),
		  strerror(save_errno));
	aclose(s);
	errno = save_errno;
	return -1;
    }

    if (nonblock)
	fcntl(s, F_SETFL, fcntl(s, F_GETFL, 0)|O_NONBLOCK);
    if (connect(s, (struct sockaddr *)svaddr, SS_LEN(svaddr)) == -1 && !nonblock) {
	save_errno = errno;
	dbprintf(_("connect_portrange: Connect from %s failed: %s\n"),
		  str_sockaddr(addrp),
		  strerror(save_errno));
	dbprintf(_("connect_portrange: connect to %s failed: %s\n"),
		  str_sockaddr(svaddr),
		  strerror(save_errno));
	aclose(s);
	errno = save_errno;
	if (save_errno == ECONNREFUSED ||
	    save_errno == EHOSTUNREACH ||
	    save_errno == ENETUNREACH ||
	    save_errno == ETIMEDOUT)  {
	    return -2	;
	}
	return -1;
    }

    dbprintf(_("connected to %s\n"),
              str_sockaddr(svaddr));
    dbprintf(_("our side is %s\n"),
              str_sockaddr(addrp));
    return s;
}
Example #25
0
int FileOpen(char *filename, char *mode){

	int inode_handle;
	int i;

	if(dstrlen(filename) > FILE_MAX_FILENAME_LENGTH)
	{
		printf("FileOpen -- Filename is too large!\n");
		return(FILE_FAIL);
	}

	if((dstrlen(mode) == 2) && (*mode == 'r') && (*(mode+1) == 'w'))
	{
		printf("RW MODE\n");
		// get inode_handle (create if doesn't exist)
		inode_handle = DfsInodeOpen(filename);
		if(inode_handle == -1)
		{
			printf("FileOpen -- Unable to open file in read/write mode\n");
			return(FILE_FAIL);
		}
	}
	else if((dstrlen(mode) == 1) && (*mode == 'r'))
	{
		printf("R MODE\n");
		// get inode_handle (create if doesn't exist)
		inode_handle = DfsInodeOpen(filename);
		if(inode_handle == -1)
		{
			printf("FileOpen -- Unable to open file in read mode\n");
			return(FILE_FAIL);
		}
	}
	else if((dstrlen(mode) == 1) && (*mode == 'w'))
	{
		printf("W MODE\n");

		// check if exists
		inode_handle = DfsInodeFilenameExists(filename);

		if(inode_handle != -1) // if it exists, delete
		{
			dbprintf('F', "FileOpen -- Opening in W mode and file exists... deleting inode!\n");
			if(DfsInodeDelete(inode_handle) == -1)
			{
				printf("FileOpen -- Unable to delete inode\n");
				return(FILE_FAIL);
			}
			// TODO: invalidate all file descriptors corresponding to the deleted inode.
		}

		// then open
		inode_handle = DfsInodeOpen(filename);
		if(inode_handle == -1)
		{
			printf("FileOpen -- Unable to open file in read mode\n");
			return(FILE_FAIL);
		}

	}
	else
	{
		printf("FileOpen -- Invalid mode!\n");
		return(FILE_FAIL);
	}

	// We now have an inode descriptor for a given file

	// Find an available file descriptor to hold data
	for(i=0; i<FILE_MAX_OPEN_FILES; i++)
	{
		if(fd_array[i].FD_Valid == 0)
		{
			// Populate file descriptor with appropriate data

			dstrncpy ((char*)&fd_array[i].FD_FileName, filename, FILE_MAX_FILENAME_LENGTH);
			fd_array[i].FD_InodeHandle = inode_handle;
			fd_array[i].FD_CurrentPosition = 0;
			fd_array[i].FD_EOF_Flag = 0;

			if(dstrlen(mode) == 2)
				fd_array[i].FD_Mode = FILE_READWRITE;
			else if((dstrlen(mode) == 1) && (*mode == 'r'))
				fd_array[i].FD_Mode = FILE_READ;
			else
				fd_array[i].FD_Mode = FILE_WRITE;

			fd_array[i].FD_PID = GetCurrentPid();

			// mark as valid, and return handle to file descriptor
			fd_array[i].FD_Valid = 1;
			dbprintf('F', "FileOpen -- Using file descriptor #%d for newly opened file\n", i);

			return(i);
		}
	}

	printf("FileOpen -- Unable to find an empty file descriptor!\n");
	return(FILE_FAIL);

}
Example #26
0
/*
 * Bind to a port in the given range.  Takes a begin,end pair of port numbers.
 *
 * Returns negative on error (EGAIN if all ports are in use).  Returns 0
 * on success.
 */
int
bind_portrange(
    int			s,
    sockaddr_union *addrp,
    in_port_t		first_port,
    in_port_t		last_port,
    char *		proto)
{
    in_port_t port;
    in_port_t cnt;
    socklen_t_equiv socklen;
    struct servent *servPort;
    const in_port_t num_ports = (in_port_t)(last_port - first_port + 1);
    int save_errno = EAGAIN;

    assert(first_port <= last_port);

    /*
     * We pick a different starting port based on our pid and the current
     * time to avoid always picking the same reserved port twice.
     */
    port = (in_port_t)(((getpid() + time(0)) % num_ports) + first_port);

    /*
     * Scan through the range, trying all available ports that are either 
     * not taken in /etc/services or registered for *amanda*.  Wrap around
     * if we don't happen to start at the beginning.
     */
    for (cnt = 0; cnt < num_ports; cnt++) {
	servPort = getservbyport((int)htons(port), proto);
	if ((servPort == NULL) || strstr(servPort->s_name, "amanda")) {
	    SU_SET_PORT(addrp, port);
	    socklen = SS_LEN(addrp);
	    if (bind(s, (struct sockaddr *)addrp, socklen) >= 0) {
		if (servPort == NULL) {
		    dbprintf(_("bind_portrange2: Try  port %d: Available - Success\n"), port);
		} else {
		    dbprintf(_("bind_portrange2: Try  port %d: Owned by %s - Success.\n"), port, servPort->s_name);
		}
		return 0;
	    }
	    if (errno != EAGAIN && errno != EBUSY)
		save_errno = errno;
	    if (servPort == NULL) {
		dbprintf(_("bind_portrange2: Try  port %d: Available - %s\n"),
			port, strerror(errno));
	    } else {
		dbprintf(_("bind_portrange2: Try  port %d: Owned by %s - %s\n"),
			port, servPort->s_name, strerror(errno));
	    }
	} else {
	        dbprintf(_("bind_portrange2: Skip port %d: Owned by %s.\n"),
		      port, servPort->s_name);
	}
	if (++port > last_port)
	    port = first_port;
    }
    dbprintf(_("bind_portrange: all ports between %d and %d busy\n"),
		  first_port,
		  last_port);
    errno = save_errno;
    return -1;
}
Example #27
0
/*extern "C" */void IFRit_begin_ifrs(unsigned long id,
				     unsigned long num_reads,
				     unsigned long num_writes, ... ){
#ifdef DUPLICATE_STATS
  total_begin_ifrs_calls++;
#endif

  CHECK_SAMPLE_STATE;

#ifdef SINGLE_THREADED_OPT
  if (num_threads == 1) {
    return;
  }
#endif

  unsigned int i;
  va_list ap;

#ifdef CHECK_FOR_RACES
  unsigned long all_rvargs[num_reads];
  unsigned long all_wvargs[num_writes];
  int numNewReads = 0;
  int numNewWrites = 0;
#endif

#ifdef DUPLICATE_STATS
  total += num_reads;
  total += num_writes;
#endif

  va_start(ap, num_writes);

  // Find the set of non-duplicate read IFRs.
  for (i = 0; i < num_reads; i++) {
    unsigned long varg = va_arg(ap, unsigned long);
    assert(varg);

#ifdef THREAD_LOCAL_OPT
    if (checkThreadLocal(varg)) {
      continue;
    }
#endif

#ifdef READ_SHARED_OPT
    if (checkReadShared(varg, false)) {
      continue;
    }
#endif

    if (READ_IFR_EXISTS(varg)) {
#ifdef DUPLICATE_STATS
      duplicates++;
#endif
    } else {
      READ_IFR_INSERT(varg);
#ifdef CHECK_FOR_RACES
      all_rvargs[numNewReads++] = varg;
#endif
    }
  }

  // Find the set of non-duplicate write IFRs.
  for( i = 0; i < num_writes; i++ ){
    unsigned long varg = va_arg(ap, unsigned long);
    assert(varg);

#ifdef READ_SHARED_OPT
    checkReadShared(varg, true);
#endif

#ifdef THREAD_LOCAL_OPT
    if (checkThreadLocal(varg)) {
      continue;
    }
#endif

    if (WRITE_IFR_EXISTS(varg)) {
#ifdef DUPLICATE_STATS
      duplicates++;
#endif
    } else {
      WRITE_IFR_INSERT(varg);
#ifdef CHECK_FOR_RACES
      all_wvargs[numNewWrites++] = varg;
#endif
    }
  }

#ifdef CHECK_FOR_RACES
  // No new IFRs to start.
  if (numNewReads + numNewWrites == 0) {
    return;
  }

  // Get the PC for this call and store it in an IFR struct.
  void *curProgPC = __builtin_return_address(0);
  raceCheckIFR->id = id;
  raceCheckIFR->instAddr = (unsigned long) curProgPC;

  // Check for data races.
  int v;
  for(v = 0; v < numNewReads; v++){
    unsigned long varg = all_rvargs[v];

#ifdef USE_TBB
    // Check for read/write races.
    IFRMap::const_accessor a;
    if (ActiveMustWriteIFR->find(a, varg)) {
      IFR_raceCheck(a->second, raceCheckIFR);
    }
    a.release();

    activateReadIFR(varg, curProgPC, id);
#else
    LOCK_GLOBAL_INFO(varg);

    /*Looking in a map from variable -> IFR record */
    IFR *i = (IFR *) g_hash_table_lookup(ACTIVE_MUST_WRITE_TABLE(varg), (gconstpointer) varg);
    if (i) {
      IFR_raceCheck((gpointer) varg, i, raceCheckIFR);
    }

    activateReadIFR(varg, curProgPC, id);

    UNLOCK_GLOBAL_INFO(varg);
#endif
  }

  for (v = 0; v < numNewWrites; v++) {
    unsigned long varg = all_wvargs[v];
    dbprintf(stderr, "handling write varg %p\n",varg);
    
#ifdef USE_TBB
    // Check for read/write data races.
    IFRMapMap::const_accessor b;
    if (ActiveMayWriteIFR->find(b, varg)) {
      IFRMap *map = b->second;
      IFRMap::iterator i = map->begin(), e = map->end();
      for (; i != e; i++) {
	IFR_raceCheck(i->second, raceCheckIFR);
      }
    }
    b.release();

    // Check for write/write races and activate the write IFR.
    IFRMap::accessor a;
    IFR *i = NULL;
    if (ActiveMustWriteIFR->insert(a, varg)) {
      a->second = new_ifr(pthread_self(), id, (unsigned long) curProgPC, varg);
      a.release();
    } else {
      i = a->second;
      a->second = new_ifr(pthread_self(), id, (unsigned long) curProgPC, varg);
      a.release();
      IFR_raceCheck(i, raceCheckIFR);
      delete(i);
    }
#else
    LOCK_GLOBAL_INFO(varg);

    /*Looking in a map from variable -> IFR record */
    IFR *i = (IFR *) g_hash_table_lookup(ACTIVE_MUST_WRITE_TABLE(varg), (gconstpointer)varg);
    if (i) {
      IFR_raceCheck((gpointer) varg, i, raceCheckIFR);
    }

    /*Looking in a map from variable -> (map from thread -> IFR record)*/
    GHashTable *ifrs = (GHashTable *) g_hash_table_lookup(ACTIVE_MAY_WRITE_TABLE(varg), (gconstpointer) varg);
    if (ifrs) {
      /*Foreaching in a map from thread -> IFR record*/
      g_hash_table_foreach(ifrs, IFR_raceCheck, raceCheckIFR);
    }

    activateWriteIFR(varg, curProgPC, id);

    UNLOCK_GLOBAL_INFO(varg);
#endif
  }
#endif
}
Example #28
0
/*
 * Setup and return a handle outgoing to a client
 */
static void
bsdudp_connect(
    const char *hostname,
    char *	(*conf_fn)(char *, void *),
    void	(*fn)(void *, security_handle_t *, security_status_t),
    void *	arg,
    void *	datap)
{
    struct sec_handle *bh;
    in_port_t port;
    struct timeval sequence_time;
    int sequence;
    char *handle;
    int result;
    char *canonname;
    struct addrinfo *res = NULL, *res_addr;
    int result_bind;
    char *service;

    (void)conf_fn;	/* Quiet unused parameter warning */
    (void)datap;	/* Quiet unused parameter warning */
    assert(hostname != NULL);

    bh = g_new0(struct sec_handle, 1);
    bh->proto_handle=NULL;
    bh->rc = NULL;
    security_handleinit(&bh->sech, &bsdudp_security_driver);

    result = resolve_hostname(hostname, SOCK_DGRAM, &res, &canonname);
    if(result != 0) {
	dbprintf(_("resolve_hostname(%s): %s\n"), hostname, gai_strerror(result));
	security_seterror(&bh->sech, _("resolve_hostname(%s): %s\n"), hostname,
			  gai_strerror(result));
	(*fn)(arg, &bh->sech, S_ERROR);
	return;
    }
    if (canonname == NULL) {
	dbprintf(_("resolve_hostname(%s) did not return a canonical name\n"), hostname);
	security_seterror(&bh->sech,
	        _("resolve_hostname(%s) did not return a canonical name\n"), hostname);
	(*fn)(arg, &bh->sech, S_ERROR);
       return;
    }
    if (res == NULL) {
	dbprintf(_("resolve_hostname(%s): no results\n"), hostname);
	security_seterror(&bh->sech,
	        _("resolve_hostname(%s): no results\n"), hostname);
	(*fn)(arg, &bh->sech, S_ERROR);
       amfree(canonname);
       return;
    }

    for (res_addr = res; res_addr != NULL; res_addr = res_addr->ai_next) {
#ifdef WORKING_IPV6
	/* IPv6 socket already bound */
	if (res_addr->ai_addr->sa_family == AF_INET6 && not_init6 == 0) {
	    break;
	}
	/*
	 * Only init the IPv6 socket once
	 */
	if (res_addr->ai_addr->sa_family == AF_INET6 && not_init6 == 1) {
	    uid_t euid;
	    dgram_zero(&netfd6.dgram);

	    euid = geteuid();
	    set_root_privs(1);
	    result_bind = dgram_bind(&netfd6.dgram,
				     res_addr->ai_addr->sa_family, &port);
	    set_root_privs(0);
	    if (result_bind != 0) {
		continue;
	    }
	    netfd6.handle = NULL;
	    netfd6.pkt.body = NULL;
	    netfd6.recv_security_ok = &bsd_recv_security_ok;
	    netfd6.prefix_packet = &bsd_prefix_packet;
	    /*
	     * We must have a reserved port.  Bomb if we didn't get one.
	     */
	    if (port >= IPPORT_RESERVED) {
		security_seterror(&bh->sech,
		    _("unable to bind to a reserved port (got port %u)"),
		    (unsigned int)port);
		(*fn)(arg, &bh->sech, S_ERROR);
		freeaddrinfo(res);
		amfree(canonname);
		return;
	    }
	    not_init6 = 0;
	    bh->udp = &netfd6;
	    break;
	}
#endif

	/* IPv4 socket already bound */
	if (res_addr->ai_addr->sa_family == AF_INET && not_init4 == 0) {
	    break;
	}

	/*
	 * Only init the IPv4 socket once
	 */
	if (res_addr->ai_addr->sa_family == AF_INET && not_init4 == 1) {
	    uid_t euid;
	    dgram_zero(&netfd4.dgram);

	    euid = geteuid();
	    set_root_privs(1);
	    result_bind = dgram_bind(&netfd4.dgram,
				     res_addr->ai_addr->sa_family, &port);
	    set_root_privs(0);
	    if (result_bind != 0) {
		continue;
	    }
	    netfd4.handle = NULL;
	    netfd4.pkt.body = NULL;
	    netfd4.recv_security_ok = &bsd_recv_security_ok;
	    netfd4.prefix_packet = &bsd_prefix_packet;
	    /*
	     * We must have a reserved port.  Bomb if we didn't get one.
	     */
	    if (port >= IPPORT_RESERVED) {
		security_seterror(&bh->sech,
		    "unable to bind to a reserved port (got port %u)",
		    (unsigned int)port);
		(*fn)(arg, &bh->sech, S_ERROR);
		freeaddrinfo(res);
		amfree(canonname);
		return;
	    }
	    not_init4 = 0;
	    bh->udp = &netfd4;
	    break;
	}
    }

    if (res_addr == NULL) {
	dbprintf(_("Can't bind a socket to connect to %s\n"), hostname);
	security_seterror(&bh->sech,
	        _("Can't bind a socket to connect to %s\n"), hostname);
	(*fn)(arg, &bh->sech, S_ERROR);
       amfree(canonname);
       return;
    }

#ifdef WORKING_IPV6
    if (res_addr->ai_addr->sa_family == AF_INET6)
	bh->udp = &netfd6;
    else
#endif
	bh->udp = &netfd4;

    auth_debug(1, _("Resolved hostname=%s\n"), canonname);
    if (conf_fn) {
        service = conf_fn("client_port", datap);
        if (!service || strlen(service) <= 1)
            service = "amanda";
    } else {
        service = "amanda";
    }
    port = find_port_for_service(service, "udp");
    if (port == 0) {
        security_seterror(&bh->sech, _("%s/udp unknown protocol"), service);
        (*fn)(arg, &bh->sech, S_ERROR);
        amfree(canonname);
        return;
    }

    amanda_gettimeofday(&sequence_time);
    sequence = (int)sequence_time.tv_sec ^ (int)sequence_time.tv_usec;
    handle=alloc(15);
    g_snprintf(handle,14,"000-%08x", newhandle++);
    if (udp_inithandle(bh->udp, bh, canonname,
		       (sockaddr_union *)res_addr->ai_addr, port,
		       handle, sequence) < 0) {
	(*fn)(arg, &bh->sech, S_ERROR);
	amfree(bh->hostname);
	amfree(bh);
    } else {
	(*fn)(arg, &bh->sech, S_OK);
    }
    amfree(handle);
    amfree(canonname);

    if (res) freeaddrinfo(res);
}
Example #29
0
/* bufp=>line_head and bufp->line_tail have already been updated in method parse_request_line  */
int parse_request_headers(struct buf *bufp) {

    char *p1, *p2;
    struct http_req *http_req_p;
    int tmp_size = 128;
    char tmp[tmp_size];
    int len;

    if (bufp->req_line_header_received == 1)
	return 0; // received already, just return

    http_req_p = bufp->http_req_p;

    p1 = bufp->line_head;
    if ((p2 = strstr(p1, host)) != NULL && p2 < bufp->line_tail) {
	p1 = p2 + strlen(host);
	len = bufp->line_tail - p1;
	if (len > HEADER_LEN - 1) {
	    len = HEADER_LEN - 1;
	    fprintf(stderr, "Warning! parse_request, host buffer overflow\n");
	}
	strncpy(http_req_p->host, p1, len);
	http_req_p->host[len] = '\0';
	dbprintf("http_req->host:%s\n", http_req_p->host);

	// update line_head and head_tail
	bufp->line_head = bufp->line_tail + strlen(CRLF);
	bufp->line_tail = strstr(bufp->line_head, CRLF);
    }

    p1 = bufp->line_head;
    if ((p2 = strstr(p1, user_agent)) != NULL && p2 < bufp->line_tail) {
	p1 = p2 + strlen(user_agent);
	len = bufp->line_tail - p1;
	if (len > HEADER_LEN - 1) {
	    len = HEADER_LEN - 1;
	    fprintf(stderr, "Warning! parse_reaquest, user_agent buffer overflow\n");
	}
	strncpy(http_req_p->user_agent, p1, len);
	http_req_p->user_agent[len] = '\0';
	dbprintf("http_req->user_agent:%s\n", http_req_p->user_agent);

	// update line_head and head_tail
	bufp->line_head = bufp->line_tail + strlen(CRLF);
	bufp->line_tail = strstr(bufp->line_head, CRLF);
    }

    p1 = bufp->line_head;
    if ((p2 = strstr(p1, cont_len)) != NULL && p2 < bufp->line_tail) {
	p1 = p2 + strlen(cont_len);
	len = bufp->line_tail - p1;
	if (len > tmp_size-1) {
	    len = tmp_size- 1;
	    fprintf(stderr, "Warning! parse_request, cont_len buffer overflow\n");
	}
	strncpy(tmp, p1, len);
	tmp[len] = '\0';
	http_req_p->cont_len = atoi(tmp);
	dbprintf("http_req->cont_len:%d\n", http_req_p->cont_len);

	// update line_head and head_tail
	bufp->line_head = bufp->line_tail + strlen(CRLF);
	bufp->line_tail = strstr(bufp->line_head, CRLF);
    }
    
    p1 = bufp->line_head;
    if ((p2 = strstr(p1, cont_type)) != NULL && p2 < bufp->line_tail) {
	p1 += strlen(cont_type);
	len = bufp->line_tail - p1;
	if (len >= HEADER_LEN - 1){
	    len = HEADER_LEN - 1;
	    fprintf(stderr, "Warning! parse_request, cont_type buffer overflow\n");
	}
	strncpy(http_req_p->cont_type, p1, len);
	http_req_p->cont_type[len] = '\0';
	dbprintf("http_req->cont_type:%s\n", http_req_p->cont_type);
    }

    // update line_head and head_tail
    bufp->line_head = bufp->line_tail + strlen(CRLF);
    bufp->line_tail = strstr(bufp->line_head, CRLF);
    
    return 0;
}
Example #30
0
ssize_t
dgram_recv(
    dgram_t *		dgram,
    int			timeout,
    sockaddr_union *fromaddr)
{
    SELECT_ARG_TYPE ready;
    struct timeval to;
    ssize_t size;
    int sock;
    socklen_t_equiv addrlen;
    ssize_t nfound;
    int save_errno;

    sock = dgram->socket;

    FD_ZERO(&ready);
    FD_SET(sock, &ready);
    to.tv_sec = timeout;
    to.tv_usec = 0;

    dbprintf(_("dgram_recv(dgram=%p, timeout=%u, fromaddr=%p)\n"),
		dgram, timeout, fromaddr);
    
    nfound = (ssize_t)select(sock+1, &ready, NULL, NULL, &to);
    if(nfound <= 0 || !FD_ISSET(sock, &ready)) {
	save_errno = errno;
	if(nfound < 0) {
	    dbprintf(_("dgram_recv: select() failed: %s\n"), strerror(save_errno));
	} else if(nfound == 0) {
	    dbprintf(plural(_("dgram_recv: timeout after %d second\n"),
			    _("dgram_recv: timeout after %d seconds\n"),
			    timeout),
		     timeout);
	    nfound = 0;
	} else if (!FD_ISSET(sock, &ready)) {
	    int i;

	    for(i = 0; i < sock + 1; i++) {
		if(FD_ISSET(i, &ready)) {
		    dbprintf(_("dgram_recv: got fd %d instead of %d\n"), i, sock);
		}
	    }
	    save_errno = EBADF;
	    nfound = -1;
	}
	errno = save_errno;
	return nfound;
    }

    addrlen = (socklen_t_equiv)sizeof(sockaddr_union);
    size = recvfrom(sock, dgram->data, (size_t)MAX_DGRAM, 0,
		    (struct sockaddr *)fromaddr, &addrlen);
    if(size == -1) {
	save_errno = errno;
	dbprintf(_("dgram_recv: recvfrom() failed: %s\n"), strerror(save_errno));
	errno = save_errno;
	return -1;
    }
    dump_sockaddr(fromaddr);
    dgram->len = (size_t)size;
    dgram->data[size] = '\0';
    dgram->cur = dgram->data;
    return size;
}