Esempio n. 1
0
int clearpid_file(char *path)
{
	if (file_readable(path))
	{
		unlink(path);
		return 0;
	}
	return (-1);
}
ssize_t vfs_readv(struct file *file, const struct iovec __user *vec,
		  unsigned long vlen, loff_t *pos)
{
	if (!(file->f_mode & FMODE_READ))
		return -EBADF;
	if (!file_readable(file))
		return -EINVAL;

	return do_readv_writev(READ, file, vec, vlen, pos);
}
Esempio n. 3
0
FILE *
mediaGetCDROM(Device *dev, char *file, Boolean probe)
{
    char	buf[PATH_MAX];

    if (isDebug())
	msgDebug("Request for %s from CDROM\n", file);
    snprintf(buf, PATH_MAX, "/dist/%s", file);
    if (file_readable(buf))
	return fopen(buf, "r");
    snprintf(buf, PATH_MAX, "/dist/dists/%s", file);
    if (file_readable(buf))
	return fopen(buf, "r");
    snprintf(buf, PATH_MAX, "/dist/%s/%s", variable_get(VAR_RELNAME), file);
    if (file_readable(buf))
	return fopen(buf, "r");
    snprintf(buf, PATH_MAX, "/dist/%s/dists/%s", variable_get(VAR_RELNAME), file);
    return fopen(buf, "r");
}
Esempio n. 4
0
char *
systemHelpFile(char *file, char *buf)
{
    if (!file)
	return NULL;
    if (file[0] == '/')
	return file;
    snprintf(buf, FILENAME_MAX, "/stand/help/%s.hlp.gz", file);
    if (file_readable(buf)) 
	return expand(buf);
    snprintf(buf, FILENAME_MAX, "/stand/help/%s.hlp", file);
    if (file_readable(buf)) 
	return expand(buf);
    snprintf(buf, FILENAME_MAX, "/stand/help/%s.TXT.gz", file);
    if (file_readable(buf)) 
	return expand(buf);
    snprintf(buf, FILENAME_MAX, "/stand/help/%s.TXT", file);
    if (file_readable(buf)) 
	return expand(buf);
    snprintf(buf, FILENAME_MAX, "/usr/src/usr.sbin/%s/help/%s.hlp", ProgName,
	file);
    if (file_readable(buf))
	return buf;
    snprintf(buf, FILENAME_MAX, "/usr/src/usr.sbin/%s/help/%s.TXT", ProgName,
	file);
    if (file_readable(buf))
	return buf;
    return NULL;
}
Esempio n. 5
0
// DRUMKITS
QStringList Filesystem::drumkits_list( const QString& path )
{
	QStringList ok;
	QStringList possible = QDir( path ).entryList( QDir::Dirs | QDir::NoDotAndDotDot );
	for( int i=0; i<possible.size(); i++ ) {
		if ( file_readable( path+"/"+possible[i]+"/"+DRUMKIT_XML, true ) )
			ok << possible[i];
		else {
			ERRORLOG( QString( "drumkit %1 is not usable" ).arg( path+"/"+possible[i] ) );
		}
	}
	return ok;
}
Esempio n. 6
0
bool Filesystem::check_sys_paths()
{
	if(  !dir_readable( __sys_data_path ) ) return false;
	if(  !dir_readable( img_dir() ) ) return false;
	if(  !dir_readable( xsd_dir() ) ) return false;
	if(  !dir_readable( doc_dir() ) ) return false;
	if(  !dir_readable( i18n_dir() ) ) return false;
	if(  !dir_readable( demos_dir() ) ) return false;
	if( !file_readable( click_file() ) ) return false;
	if( !file_readable( empty_song() ) ) return false;
	if( !file_readable( empty_sample() ) ) return false;

	//@Jeremy: Please check if those files are obsolote
	//if( !file_readable( sys_gui_config() ) ) return false;
	//if( !file_readable( sys_core_config() ) ) return false;
	//if( !file_readable( pattern_xsd() ) ) return false;

	if(  !dir_readable( sys_drumkits_dir() ) ) return false;
	if( !file_readable( drumkit_xsd() ) ) return false;
	if( !file_readable( drumkit_pattern_xsd() ) ) return false;

	INFOLOG( QString( "system wide data path %1 is usable." ).arg( __sys_data_path ) );
	return true;
}
Esempio n. 7
0
const char *getLastModelFolderPath(){
	if ( g_strLastModelFolder.empty() ) {
		GlobalPreferenceSystem().registerPreference( "LastModelFolder", make_property_string( g_strLastModelFolder ) );
		if ( g_strLastModelFolder.empty() ) {
			StringOutputStream buffer( 1024 );
			buffer << g_qeglobals.m_userGamePath.c_str() << "models/";
			if ( !file_readable( buffer.c_str() ) ) {
				// just go to fsmain
				buffer.clear();
				buffer << g_qeglobals.m_userGamePath.c_str() << "/";
			}
			g_strLastModelFolder = buffer.c_str();
		}
	}
	return g_strLastModelFolder.c_str();
}
Esempio n. 8
0
bool Filesystem::file_copy( const QString& src, const QString& dst, bool overwrite )
{
	if( file_exists( dst, true ) && !overwrite ) {
		WARNINGLOG( QString( "do not overwrite %1 with %2 as it already exists" ).arg( dst ).arg( src ) );
		return true;
	}
	if ( !file_readable( src ) ) {
		ERRORLOG( QString( "unable to copy %1 to %2, %1 is not readable" ).arg( src ).arg( dst ) );
		return false;
	}
	if ( !file_writable( dst ) ) {
		ERRORLOG( QString( "unable to copy %1 to %2, %2 is not writable" ).arg( src ).arg( dst ) );
		return false;
	}
	INFOLOG( QString( "copy %1 to %2" ).arg( src ).arg( dst ) );
	return QFile::copy( src,dst );
}
Esempio n. 9
0
/* Reload the user file from disk
 */
void reload()
{
  if (!file_readable(userfile)) {
    putlog(LOG_MISC, "*", MISC_CANTRELOADUSER);
    return;
  }

  noshare = 1;
  clear_userlist(userlist);
  noshare = 0;
  userlist = NULL;
  if (!readuserfile(userfile, &userlist))
    fatal(MISC_MISSINGUSERF, 0);
  reaffirm_owners();
  check_tcl_event("userfile-loaded");
  call_hook(HOOK_READ_USERFILE);
}
Esempio n. 10
0
/* Expand a file into a convenient location, nuking it each time */
static char *
expand(char *fname)
{
    char *gunzip = "/usr/bin/gunzip";

    if (!directory_exists(DOC_TMP_DIR)) {
	Mkdir(DOC_TMP_DIR);
	if (chown(DOC_TMP_DIR, 0, 0) < 0)
	    return NULL;
	if (chmod(DOC_TMP_DIR, S_IRWXU) < 0)
	    return NULL;
    }
    else
	unlink(DOC_TMP_FILE);
    if (!file_readable(fname) || vsystem("%s < %s > %s", gunzip, fname, DOC_TMP_FILE))
	return NULL;
    return DOC_TMP_FILE;
}
Esempio n. 11
0
void init_items(void)
{
	uint32 i = 0;
	char *path;

	item_array = (item_t *)calloc(MAX_ITEMS, sizeof(item_t));

	for(i = 0; i < MAX_ITEMS; i++){
		item_array[i].name = (char *)calloc(MAX_NAME_LENGTH, sizeof(char));

		path = get_path(ITEM_PATH, i, FILE_ENDING);

		check_dir(ITEM_PATH);

		if(file_readable(path))
			read_item(path,i);
		else
			write_item(path,i);
	}
}
Esempio n. 12
0
int is_CONFIG_ind_set(CONFIG *cfg, int ind, int verbose)
{
    char **t_arr;
    int i;

    switch (cfg->rec_list[ind].value_type){
      case CFG_TGL:
	if (strcmp(cfg->rec_list[ind].value,TOGGLE_ON_CHR) == 0)
	    return(TRUE);
	break;
      case CFG_C:
	if (*(cfg->rec_list[ind].value) != NULL_CHAR){
	    if (file_readable(cfg->rec_list[ind].value))
		return(TRUE);
	    fprintf(stderr,
		    "Error: File '%s' for argument '%s' is un-readable\n",
		    cfg->rec_list[ind].value,cfg->rec_list[ind].intern_id);
	    return(FALSE);
	}
	break;
      case CFG_STR:
	if (*(cfg->rec_list[ind].value) != NULL_CHAR)
	    return(TRUE);
	break;
      case CFG_C2:
	t_arr = (char **)cfg->rec_list[ind].value;
	for (i=0; i < cfg->rec_list[ind].num_elem; i++)
	    if (*(t_arr[i]) != NULL_CHAR)
		return(TRUE);
	break;
      default:
	fprintf(stderr,"Error: Unknown CONFIG type %d\n",
		cfg->rec_list[ind].value_type);
	exit(-1);
	break;
    }
    if (verbose)
	fprintf(stderr,"Error: Argument '%s' was not used\n",
		cfg->rec_list[ind].intern_id);
    return(FALSE);
}
Esempio n. 13
0
const char* misc_model_dialog( GtkWidget* parent ){
	StringOutputStream buffer( 1024 );

	buffer << g_qeglobals.m_userGamePath.c_str() << "models/";

	if ( !file_readable( buffer.c_str() ) ) {
		// just go to fsmain
		buffer.clear();
		buffer << g_qeglobals.m_userGamePath.c_str() << "/";
	}

	const char *filename = file_dialog( parent, TRUE, "Choose Model", buffer.c_str(), ModelLoader::Name() );
	if ( filename != 0 ) {
		// use VFS to get the correct relative path
		const char* relative = path_make_relative( filename, GlobalFileSystem().findRoot( filename ) );
		if ( relative == filename ) {
			globalWarningStream() << "WARNING: could not extract the relative path, using full path instead\n";
		}
		return relative;
	}
	return 0;
}
Esempio n. 14
0
void init_shops(void)
{
	uint32 i = 0;
	char *path;

	shop_array = (shop_t *)calloc(MAX_SHOPS, sizeof(shop_t));

	for(i = 0; i < MAX_SHOPS; i++){
		shop_array[i].name = (char *)calloc(MAX_NAME_LENGTH, sizeof(char));
		shop_array[i].joinsay = (char *)calloc(MAX_SAY_LENGTH, sizeof(char));
		shop_array[i].leavesay = (char *)calloc(MAX_SAY_LENGTH, sizeof(char));
		shop_array[i].tradeitem = (trade_item_t *)calloc(MAX_TRADES, sizeof(trade_item_t));

		path = get_path(SHOP_PATH, i, FILE_ENDING);

		check_dir(SHOP_PATH);

		if(file_readable(path))
			read_shop(path,i);
		else
			write_shop(path,i);
	}
}
Esempio n. 15
0
Boolean
mediaInitNetwork(Device *dev)
{
    int i;
    char *rp;
    char *cp, ifconfig[255];
    WINDOW *w;

    if (!RunningAsInit || networkInitialized)
        return TRUE;

    if (isDebug())
        msgDebug("Init routine called for network device %s.\n", dev->name);

    if (!file_readable("/etc/resolv.conf")) {
        if (DITEM_STATUS(configResolv(NULL)) == DITEM_FAILURE) {
            msgConfirm("Can't seem to write out /etc/resolv.conf.  Net cannot be used.");
            return FALSE;
        }
    }

    w = savescr();
    dialog_clear_norefresh();

    snprintf(ifconfig, 255, "%s%s", VAR_IFCONFIG, dev->name);
    cp = variable_get(ifconfig);
    if (cp) {
        /*
         * If this interface isn't a DHCP one, bring it up.
         * If it is, then it's already up.
         */
        if (strstr(cp, "DHCP") == NULL) {
            msgDebug("Not a DHCP interface.\n");
            i = vsystem("ifconfig %s %s", dev->name, cp);
            if (i) {
                msgConfirm("Unable to configure the %s interface!\n"
                           "This installation method cannot be used.",
                           dev->name);
                return FALSE;
            }
            rp = variable_get(VAR_GATEWAY);
            if (!rp || *rp == '0') {
                msgConfirm("No gateway has been set. You will be unable to access hosts\n"
                           "not on your local network");
            }
            else {
                /*
                 * Explicitly flush all routes to get back to a known sane
                 * state. We don't need to check this exit code because if
                 * anything fails it will show up in the route add below.
                 */
                system("route -n flush");
                msgDebug("Adding default route to %s.\n", rp);
                if (vsystem("route -n add default %s", rp) != 0) {
                    msgConfirm("Failed to add a default route; please check "
                               "your network configuration");
                    return FALSE;
                }
            }
        } else {
            msgDebug("A DHCP interface.  Should already be up.\n");
        }
    } else if ((cp = variable_get(VAR_IPV6ADDR)) == NULL || *cp == '\0') {
        msgConfirm("The %s device is not configured.  You will need to do so\n"
                   "in the Networking configuration menu before proceeding.", dev->name);
        return FALSE;
    }

    if (isDebug())
        msgDebug("Network initialized successfully.\n");
    networkInitialized = TRUE;
    return TRUE;
}
Esempio n. 16
0
 virtual bool containsFile(const char* name)
 {
   UnixPath path(m_root.c_str());
   path.push_filename(name);
   return file_readable(path.c_str());
 }
Esempio n. 17
0
static void filesys_dcc_send_hostresolved(int i)
{
  char *s1, *param, prt[100], ip[100], *tempf;
  int len = dcc[i].u.dns->ibuf, j;

  sprintf(prt, "%d", dcc[i].port);
  sprintf(ip, "%lu", iptolong(htonl(dcc[i].addr)));
  if (!hostsanitycheck_dcc(dcc[i].nick, dcc[i].u.dns->host, dcc[i].addr,
                           dcc[i].u.dns->host, prt)) {
    lostdcc(i);
    return;
  }
  param = nmalloc(strlen(dcc[i].u.dns->cbuf) + 1);
  strcpy(param, dcc[i].u.dns->cbuf);

  changeover_dcc(i, &DCC_FORK_SEND, sizeof(struct xfer_info));
  if (param[0] == '.')
    param[0] = '_';
  /* Save the original filename */
  dcc[i].u.xfer->origname = get_data_ptr(strlen(param) + 1);
  strcpy(dcc[i].u.xfer->origname, param);
  tempf = mktempfile(param);
  dcc[i].u.xfer->filename = get_data_ptr(strlen(tempf) + 1);
  strcpy(dcc[i].u.xfer->filename, tempf);
  /* We don't need the temporary buffers anymore */
  my_free(tempf);
  my_free(param);

  if (upload_to_cd) {
    char *p = get_user(&USERENTRY_DCCDIR, dcc[i].user);

    if (p)
      sprintf(dcc[i].u.xfer->dir, "%s%s/", dccdir, p);
    else
      sprintf(dcc[i].u.xfer->dir, "%s", dccdir);
  } else
    strcpy(dcc[i].u.xfer->dir, dccin);
  dcc[i].u.xfer->length = len;
  s1 = nmalloc(strlen(dcc[i].u.xfer->dir) +
               strlen(dcc[i].u.xfer->origname) + 1);
  sprintf(s1, "%s%s", dcc[i].u.xfer->dir, dcc[i].u.xfer->origname);

  if (file_readable(s1)) {
    dprintf(DP_HELP, "NOTICE %s :File `%s' already exists.\n", dcc[i].nick,
            dcc[i].u.xfer->origname);
    lostdcc(i);
    my_free(s1);
  } else {
    my_free(s1);
    /* Check for dcc-sends in process with the same filename */
    for (j = 0; j < dcc_total; j++)
      if (j != i) {
        if ((dcc[j].type->flags & (DCT_FILETRAN | DCT_FILESEND)) ==
            (DCT_FILETRAN | DCT_FILESEND)) {
          if (!strcmp(dcc[i].u.xfer->origname, dcc[j].u.xfer->origname)) {
            dprintf(DP_HELP, "NOTICE %s :File `%s' is already being sent.\n",
                    dcc[i].nick, dcc[i].u.xfer->origname);
            lostdcc(i);
            return;
          }
        }
      }
    /* Put uploads in /tmp first */
    s1 = nmalloc(strlen(tempdir) + strlen(dcc[i].u.xfer->filename) + 1);
    sprintf(s1, "%s%s", tempdir, dcc[i].u.xfer->filename);
    dcc[i].u.xfer->f = fopen(s1, "w");
    my_free(s1);
    if (dcc[i].u.xfer->f == NULL) {
      dprintf(DP_HELP,
              "NOTICE %s :Can't create file `%s' (temp dir error)\n",
              dcc[i].nick, dcc[i].u.xfer->origname);
      lostdcc(i);
    } else {
      dcc[i].timeval = now;
      dcc[i].sock = getsock(SOCK_BINARY);
      if (dcc[i].sock < 0 || open_telnet_dcc(dcc[i].sock, ip, prt) < 0)
        dcc[i].type->eof(i);
    }
  }
}
Esempio n. 18
0
bool Filesystem::drumkit_valid( const QString& dk_path )
{
	return file_readable( dk_path + "/" + DRUMKIT_XML );
}
Esempio n. 19
0
QString Filesystem::usr_click_file()
{
	if( file_readable( __usr_data_path + CLICK_SAMPLE, true ) ) return __usr_data_path + CLICK_SAMPLE;
	return click_file();
}
Esempio n. 20
0
Boolean
mediaInitCDROM(Device *dev)
{
    struct iso_args	args;
    Attribs *cd_attr;
    char *cp, *mountpoint = "/dist";
    Boolean readInfo = TRUE;
    static Boolean bogusCDOK = FALSE;

    if (cdromMounted)
	return TRUE;

    bzero(&args, sizeof(args));
    args.fspec = dev->devname;
    args.flags = 0;

    cd_attr = alloca(sizeof(Attribs) * MAX_ATTRIBS);
    cp = NULL;

    Mkdir(mountpoint);

    if (mount(MOUNT_CD9660, mountpoint, MNT_RDONLY, (caddr_t) &args) == -1) {
	if (errno == EINVAL) {
	    msgConfirm("The CD in your drive looks more like an Audio CD than a FreeBSD release.");
	    return FALSE;
	}
	else if (errno != EBUSY) {
	    msgConfirm("Error mounting %s on %s: %s (%u)", dev->devname, mountpoint, strerror(errno), errno);
	    return FALSE;
	}
	cdromMounted = TRUE;
    }
    else
	cdromMounted = TRUE;

    if (!file_readable(string_concat(mountpoint, "/cdrom.inf")) && !bogusCDOK) {
	if (msgYesNo("Warning: The CD currently in the drive is either not a FreeBSD\n"
		     "CD or it is an older (pre 2.1.5) FreeBSD CD which does not\n"
		     "have a version number on it.  Do you wish to use this CD anyway?") != 0) {
	    unmount(mountpoint, MNT_FORCE);
	    cdromMounted = FALSE;
	    return FALSE;
	}
	else {
	    readInfo = FALSE;
	    bogusCDOK = TRUE;
	}
    }

    if (readInfo &&
	(DITEM_STATUS(attr_parse_file(cd_attr, string_concat(mountpoint, "/cdrom.inf"))) == DITEM_FAILURE ||
		      !(cp = attr_match(cd_attr, "CD_VERSION")) || (strcmp(cp, variable_get(VAR_RELNAME)) && strcmp("none", variable_get(VAR_RELNAME))))) {
	if (!cp) {
	    msgConfirm("Unable to find a %s/cdrom.inf file.\n"
		       "Either this is not a FreeBSD CDROM, there is a problem with\n"
		       "the CDROM driver or something is wrong with your hardware.\n"
		       "Please fix this problem (check the console logs on VTY2) and\n"
		       "try again.", mountpoint);
	}
	else if (!bogusCDOK) {
	    msgConfirm("Warning: The version of the FreeBSD CD currently in the drive\n"
		       "(%s) does not match the version of the boot floppy\n"
		       "(%s).\n\n"
		       "If this is intentional, to avoid this message in the future\n"
		       "please visit the Options editor to set the boot floppy version\n"
		       "string to match that of the CD before selecting it as your\n"
		       "installation media.", cp, variable_get(VAR_RELNAME));

	    if (msgYesNo("Would you like to try and use this CDROM anyway?") != 0) {
		unmount(mountpoint, MNT_FORCE);
		cdromMounted = FALSE;
		return FALSE;
	    }
	    else
		bogusCDOK = TRUE;
	}
    }
    msgDebug("Mounted FreeBSD CDROM from device %s\n", dev->devname);
    return TRUE;
}
Esempio n. 21
0
static int do_dcc_send(int idx, char *dir, char *fn, char *nick, int resend)
{
  char *s = NULL, *s1 = NULL;
  int x;

  if (nick && strlen(nick) > NICKMAX)
    nick[NICKMAX] = 0;
  if (dccdir[0] == 0) {
    dprintf(idx, "DCC file transfers not supported.\n");
    putlog(LOG_FILES, "*", "Refused dcc %sget %s from [%s]", resend ? "re" : "",
           fn, dcc[idx].nick);
    return 0;
  }
  if (strchr(fn, '/') != NULL) {
    dprintf(idx, "Filename cannot have '/' in it...\n");
    putlog(LOG_FILES, "*", "Refused dcc %sget %s from [%s]", resend ? "re" : "",
           fn, dcc[idx].nick);
    return 0;
  }
  if (dir[0]) {
    s = nmalloc(strlen(dccdir) + strlen(dir) + strlen(fn) + 2);
    sprintf(s, "%s%s/%s", dccdir, dir, fn);
  } else {
    s = nmalloc(strlen(dccdir) + strlen(fn) + 1);
    sprintf(s, "%s%s", dccdir, fn);
  }

  if (!file_readable(s)) {
    dprintf(idx, "No such file.\n");
    putlog(LOG_FILES, "*", "Refused dcc %sget %s from [%s]", resend ? "re" :
           "", fn, dcc[idx].nick);
    my_free(s);
    return 0;
  }

  if (!nick || !nick[0])
    nick = dcc[idx].nick;
  /* Already have too many transfers active for this user?  queue it */
  if (at_limit(nick)) {
    char xxx[1024];

    sprintf(xxx, "%d*%s%s", (int) strlen(dccdir), dccdir, dir);
    queue_file(xxx, fn, dcc[idx].nick, nick);
    dprintf(idx, "Queued: %s to %s\n", fn, nick);
    my_free(s);
    return 1;
  }
  if (copy_to_tmp) {
    char *tempfn = mktempfile(fn);

    /* Copy this file to /tmp, add a random prefix to the filename. */
    s = nrealloc(s, strlen(dccdir) + strlen(dir) + strlen(fn) + 2);
    sprintf(s, "%s%s%s%s", dccdir, dir, dir[0] ? "/" : "", fn);
    s1 = nrealloc(s1, strlen(tempdir) + strlen(tempfn) + 1);
    sprintf(s1, "%s%s", tempdir, tempfn);
    my_free(tempfn);
    if (copyfile(s, s1) != 0) {
      dprintf(idx, "Can't make temporary copy of file!\n");
      putlog(LOG_FILES | LOG_MISC, "*",
             "Refused dcc %sget %s: copy to %s FAILED!",
             resend ? "re" : "", fn, tempdir);
      my_free(s);
      my_free(s1);
      return 0;
    }
  } else {
    s1 = nrealloc(s1, strlen(dccdir) + strlen(dir) + strlen(fn) + 2);
    sprintf(s1, "%s%s%s%s", dccdir, dir, dir[0] ? "/" : "", fn);
  }
  s = nrealloc(s, strlen(dir) + strlen(fn) + 2);
  sprintf(s, "%s%s%s", dir, dir[0] ? "/" : "", fn);
  x = _dcc_send(idx, s1, nick, s, resend);
  if (x != DCCSEND_OK)
    wipe_tmp_filename(s1, -1);
  my_free(s);
  my_free(s1);
  return x;
}
Esempio n. 22
0
bool DirectoryArchive::containsFile(const std::string& name) {
	UnixPath path(_root);
	path.push_filename(name);
	return file_readable(path.c_str());
}
Esempio n. 23
0
int main (int argc, char *argv[]) {
  char databuf[BUFFER_SIZE];
  char *section, *name, *inifn;
  int nBoolValue = FALSE, bFlagBool = FALSE, bFlagDump = FALSE;
  int firstArgIndex = 1;
  char* const DEFAULT_VALUE = "";

  application_init(argc, argv, arg_c, arg_v, &databuf, BUFFER_SIZE);

  if (argc <= 1) {
    show_error(STR_ERR_NOT_ENOUGH_ARGS);
    return show_usage( THIS_APP_FILENAME );
  }

  bFlagBool = (check_arg_flag_bool(1) ? TRUE : FALSE);
  bFlagDump = (check_arg_flag(1, FLAG_DUMP) ? TRUE : FALSE);

  if (argc == 2) {
    if (bFlagBool==TRUE)
      return show_error(STR_ERR_NOT_ENOUGH_ARGS);
    if (bFlagDump)
      return show_error(STR_ERR_NO_FILE_NAME);

    if (check_arg_flag(1, FLAG_VERSION))
      return show_version(APP_TITLE, INI_TOOLS_VERSION);

    if (check_arg_flag(1, FLAG_HELP))
      return show_help( THIS_APP_FILENAME );
  }


  firstArgIndex = 1;  //first arg is index 1,
  if (bFlagBool || bFlagDump)
    firstArgIndex++;  //unless -b|-d is passed

  //--- start dump file processing ---
  if (bFlagDump) {
    inifn   = argv[firstArgIndex];
    if (strcmp(inifn, "-")==0)
      inifn = "/dev/stdin";
    if (!file_exist(inifn))
      return show_error(STR_ERR_FILE_NOT_FOUND);
    if (!file_readable(inifn))
      return show_error_fmt(STR_ERR_FMT_FILE_NOT_READABLE, basename(inifn));

    char * sectionName = NULL;
    if (argc == 4) {
      sectionName = argv[3];
      if (!ini_section_exists(inifn, sectionName))
        return show_error_fmt(STR_ERR_FMT_SECTION_NOT_FOUND, sectionName);
    }

    //dump either the entire ini file or specified [section] keys
    ini_browse(browsecb, sectionName, inifn);
    if (lastSection!="")
      free(lastSection);
    return EXIT_SUCCESS;
  }
  //--- end dump file processing ---


  // --- start error checking ---
  if (argc <= firstArgIndex)
    return show_error(STR_ERR_NO_SECTION_NAME);
  if (argc <= firstArgIndex+1)
    return show_error(STR_ERR_NO_KEY_NAME);
  if (argc <= firstArgIndex+2)
    return show_error(STR_ERR_NO_FILE_NAME);
  // --- end error checking ---

  section = argv[firstArgIndex+0];
  name    = argv[firstArgIndex+1];
  inifn   = argv[firstArgIndex+2];
  if (strcmp(inifn, "-")==0)
    inifn = "/dev/stdin";

  // -- start sanity checking --
  if (!file_exist(inifn))
    return show_error(STR_ERR_FILE_NOT_FOUND);

  if ((file_exist(inifn) && !file_readable(inifn)) )
    return show_error_fmt(STR_ERR_FMT_FILE_NOT_READABLE, basename(inifn));

  if (!valid_section_name(section))
    return show_error(STR_ERR_INVALID_SECTION_NAME);

  if (!valid_key_name(name))
    return show_error(STR_ERR_INVALID_KEY_NAME);
  // -- end sanity checking --

  ini_gets(section, name, DEFAULT_VALUE, databuf, sizeof(databuf), inifn);

  if (bFlagBool) {
    nBoolValue = FALSE; //default value
    if (is_bool_str_true(databuf))
      nBoolValue = TRUE;
    if (is_bool_str_false(databuf))
      nBoolValue = FALSE;
    sprintf(databuf,"%d", nBoolValue);
  }

  printf("%s", databuf);
  return EXIT_SUCCESS;
}
Esempio n. 24
0
int main(int argc, char** args) {
	int c;
	anbool help = FALSE;
	char* outdir = NULL;
	char* cmd;
	int i, j, f;
    int inputnum;
	int rtn;
	sl* engineargs;
	int nbeargs;
	anbool fromstdin = FALSE;
	anbool overwrite = FALSE;
	anbool cont = FALSE;
    anbool skip_solved = FALSE;
    anbool makeplots = TRUE;
	double plotscale = 1.0;
	char* inbgfn = NULL;
    char* bgfn = NULL;
    char* me;
    anbool verbose = FALSE;
    int loglvl = LOG_MSG;
    char* outbase = NULL;
	anbool usecurl = TRUE;
    bl* opts;
    augment_xylist_t theallaxy;
    augment_xylist_t* allaxy = &theallaxy;
    int nmyopts;
    char* removeopts = "ixo\x01";
    char* newfits;
    char* kmz = NULL;
    char* scamp = NULL;
    char* scampconfig = NULL;
    char* index_xyls;
	anbool just_augment = FALSE;
	anbool engine_batch = FALSE;
	bl* batchaxy = NULL;
	bl* batchsf = NULL;
	sl* outfiles;
	sl* tempfiles;
    // these are deleted after the outer loop over input files
	sl* tempfiles2;
	sl* tempdirs;
	anbool timestamp = FALSE;
    anbool tempaxy = FALSE;

    errors_print_on_exit(stderr);
    fits_use_error_system();

    me = find_executable(args[0], NULL);

	engineargs = sl_new(16);
	append_executable(engineargs, "astrometry-engine", me);

	// output filenames.
	outfiles = sl_new(16);
	tempfiles = sl_new(4);
	tempfiles2 = sl_new(4);
	tempdirs = sl_new(4);

	rtn = 0;

    nmyopts = sizeof(options)/sizeof(an_option_t);
    opts = opts_from_array(options, nmyopts, NULL);
    augment_xylist_add_options(opts);

    // remove duplicate short options.
    for (i=0; i<nmyopts; i++) {
        an_option_t* opt1 = bl_access(opts, i);
        for (j=nmyopts; j<bl_size(opts); j++) {
            an_option_t* opt2 = bl_access(opts, j);
            if (opt2->shortopt == opt1->shortopt)
                bl_remove_index(opts, j);
        }
    }

    // remove unwanted augment-xylist options.
    for (i=0; i<strlen(removeopts); i++) {
        for (j=nmyopts; j<bl_size(opts); j++) {
            an_option_t* opt2 = bl_access(opts, j);
            if (opt2->shortopt == removeopts[i])
                bl_remove_index(opts, j);
        }
    }

	// which options are left?
	/*{
		char options[256];
		memset(options, 0, 256);
		printf("options:\n");
		for (i=0; i<bl_size(opts); i++) {
			an_option_t* opt = bl_access(opts, i);
			printf("  %c (%i) %s\n", opt->shortopt, (int)opt->shortopt, opt->name);
			options[(int)((opt->shortopt + 256) % 256)] = 1;
		}
		printf("Remaining short opts:\n");
		for (i=0; i<256; i++) {
			if (!options[i])
				printf("  %c (%i, 0x%x)\n", (char)i, i, i);
		}
	 }*/

    augment_xylist_init(allaxy);

    // default output filename patterns.
    allaxy->axyfn    = "%s.axy";
    allaxy->matchfn  = "%s.match";
    allaxy->rdlsfn   = "%s.rdls";
    allaxy->solvedfn = "%s.solved";
    allaxy->wcsfn    = "%s.wcs";
    allaxy->corrfn   = "%s.corr";
    newfits          = "%s.new";
    index_xyls = "%s-indx.xyls";

	while (1) {
        int res;
		c = opts_getopt(opts, argc, args);
		//printf("option %c (%i)\n", c, (int)c);
        if (c == -1)
            break;
        switch (c) {
        case '\x91':
            allaxy->axyfn = optarg;
            break;
        case '\x90':
            tempaxy = TRUE;
            break;
		case '\x88':
			timestamp = TRUE;
			break;
		case '\x84':
			plotscale = atof(optarg);
			break;
		case '\x85':
			inbgfn = optarg;
			break;
		case '\x87':
			allaxy->assume_fits_image = TRUE;
			break;
		case '(':
			engine_batch = TRUE;
			break;
		case '@':
			just_augment = TRUE;
			break;
        case 'U':
            index_xyls = optarg;
            break;
        case 'n':
            scampconfig = optarg;
            break;
        case 'i':
            scamp = optarg;
            break;
        case 'Z':
            kmz = optarg;
            break;
        case 'N':
            newfits = optarg;
            break;
		case 'h':
			help = TRUE;
			break;
        case 'v':
            sl_append(engineargs, "--verbose");
            verbose = TRUE;
			allaxy->verbosity++;
            loglvl++;
            break;
		case 'D':
			outdir = optarg;
			break;
        case 'o':
            outbase = optarg;
            break;
		case 'b':
		case '\x89':
			sl_append(engineargs, "--config");
			append_escape(engineargs, optarg);
			break;
		case 'f':
			fromstdin = TRUE;
			break;
        case 'O':
            overwrite = TRUE;
            break;
        case 'p':
            makeplots = FALSE;
            break;
        case 'G':
            usecurl = FALSE;
            break;
        case 'K':
            cont = TRUE;
            break;
        case 'J':
            skip_solved = TRUE;
            break;
        default:
            res = augment_xylist_parse_option(c, optarg, allaxy);
            if (res) {
                rtn = -1;
                goto dohelp;
            }
        }
    }

	if ((optind == argc) && !fromstdin) {
		printf("ERROR: You didn't specify any files to process.\n");
		help = TRUE;
	}

	if (help) {
    dohelp:
		print_help(args[0], opts);
		exit(rtn);
	}
    bl_free(opts);

    // --dont-augment: advertised as just write xy file,
    // so quit after doing that.
    if (allaxy->dont_augment) {
        just_augment = TRUE;
    }

    log_init(loglvl);
	if (timestamp)
		log_set_timestamp(TRUE);

    if (kmz && starts_with(kmz, "-"))
        logmsg("Do you really want to save KMZ to the file named \"%s\" ??\n", kmz);

    if (starts_with(newfits, "-")) {
        logmsg("Do you really want to save the new FITS file to the file named \"%s\" ??\n", newfits);
    }

	if (engine_batch) {
		batchaxy = bl_new(16, sizeof(augment_xylist_t));
		batchsf  = bl_new(16, sizeof(solve_field_args_t));
	}

    // Allow (some of the) default filenames to be disabled by setting them to "none".
    allaxy->matchfn  = none_is_null(allaxy->matchfn);
    allaxy->rdlsfn   = none_is_null(allaxy->rdlsfn);
    allaxy->solvedfn = none_is_null(allaxy->solvedfn);
    allaxy->solvedinfn = none_is_null(allaxy->solvedinfn);
    allaxy->wcsfn    = none_is_null(allaxy->wcsfn);
    allaxy->corrfn   = none_is_null(allaxy->corrfn);
    newfits          = none_is_null(newfits);
    index_xyls = none_is_null(index_xyls);

	if (outdir) {
        if (mkdir_p(outdir)) {
            ERROR("Failed to create output directory %s", outdir);
            exit(-1);
        }
	}

	// number of engine args not specific to a particular file
	nbeargs = sl_size(engineargs);

	f = optind;
    inputnum = 0;
	while (1) {
		char* infile = NULL;
		anbool isxyls;
		char* reason;
		int len;
		char* base;
        char* basedir;
        char* basefile = NULL;
		char *objsfn=NULL;
		char *ppmfn=NULL;
        char* downloadfn = NULL;
        char* suffix = NULL;
		sl* cmdline;
        anbool ctrlc;
        anbool isurl;
        augment_xylist_t theaxy;
        augment_xylist_t* axy = &theaxy;
        int j;
		solve_field_args_t thesf;
		solve_field_args_t* sf = &thesf;
		anbool want_pnm = FALSE;

        // reset augment-xylist args.
        memcpy(axy, allaxy, sizeof(augment_xylist_t));

		memset(sf, 0, sizeof(solve_field_args_t));

		if (fromstdin) {
            char fnbuf[1024];
			if (!fgets(fnbuf, sizeof(fnbuf), stdin)) {
				if (ferror(stdin))
					SYSERROR("Failed to read a filename from stdin");
				break;
			}
			len = strlen(fnbuf);
			if (fnbuf[len-1] == '\n')
				fnbuf[len-1] = '\0';
			infile = fnbuf;
            logmsg("Reading input file \"%s\"...\n", infile);
		} else {
			if (f == argc)
				break;
			infile = args[f];
			f++;
            logmsg("Reading input file %i of %i: \"%s\"...\n",
                   f - optind, argc - optind, infile);
		}
        inputnum++;

        cmdline = sl_new(16);

		if (!engine_batch) {
			// Remove arguments that might have been added in previous trips through this loop
			sl_remove_from(engineargs,  nbeargs);
		}

		// Choose the base path/filename for output files.
        if (outbase)
            asprintf_safe(&basefile, outbase, inputnum, infile);
        else
			basefile = basename_safe(infile);
        //logverb("Base filename: %s\n", basefile);

        isurl = (!file_exists(infile) &&
                 (starts_with(infile, "http://") ||
                  starts_with(infile, "ftp://")));

		if (outdir)
            basedir = strdup(outdir);
		else {
            if (isurl)
                basedir = strdup(".");
            else
				basedir = dirname_safe(infile);
        }
        //logverb("Base directory: %s\n", basedir);

        asprintf_safe(&base, "%s/%s", basedir, basefile);
        //logverb("Base name for output files: %s\n", base);

        // trim .gz, .bz2
        // hmm, we drop the suffix in this case...
		len = strlen(base);
        if (ends_with(base, ".gz"))
            base[len-3] = '\0';
        else if (ends_with(base, ".bz2"))
            base[len-4] = '\0';
		len = strlen(base);
		// trim .xx / .xxx / .xxxx
		if (len >= 5) {
            for (j=3; j<=5; j++) {
                if (base[len - j] == '/')
                    break;
                if (base[len - j] == '.') {
                    base[len - j] = '\0';
                    suffix = base + len - j + 1;
                    break;
                }
            }
		}
        logverb("Base: \"%s\", basefile \"%s\", basedir \"%s\", suffix \"%s\"\n", base, basefile, basedir, suffix);

        if (tempaxy) {
            axy->axyfn = create_temp_file("axy", axy->tempdir);
            sl_append_nocopy(tempfiles2, axy->axyfn);
        } else
            axy->axyfn    = sl_appendf(outfiles, axy->axyfn,       base);
        if (axy->matchfn)
            axy->matchfn  = sl_appendf(outfiles, axy->matchfn,     base);
        if (axy->rdlsfn)
            axy->rdlsfn   = sl_appendf(outfiles, axy->rdlsfn,      base);
        if (axy->solvedfn)
            axy->solvedfn = sl_appendf(outfiles, axy->solvedfn,    base);
        if (axy->wcsfn)
            axy->wcsfn    = sl_appendf(outfiles, axy->wcsfn,       base);
        if (axy->corrfn)
            axy->corrfn   = sl_appendf(outfiles, axy->corrfn,      base);
        if (axy->cancelfn)
            axy->cancelfn  = sl_appendf(outfiles, axy->cancelfn, base);
        if (axy->keepxylsfn)
            axy->keepxylsfn  = sl_appendf(outfiles, axy->keepxylsfn, base);
        if (axy->pnmfn)
            axy->pnmfn  = sl_appendf(outfiles, axy->pnmfn, base);
        if (newfits)
            sf->newfitsfn  = sl_appendf(outfiles, newfits,  base);
		if (kmz)
			sf->kmzfn = sl_appendf(outfiles, kmz, base);
        if (index_xyls)
            sf->indxylsfn  = sl_appendf(outfiles, index_xyls, base);
		if (scamp)
			sf->scampfn = sl_appendf(outfiles, scamp, base);
		if (scampconfig)
			sf->scampconfigfn = sl_appendf(outfiles, scampconfig, base);
        if (makeplots) {
            objsfn     = sl_appendf(outfiles, "%s-objs.png",  base);
            sf->redgreenfn = sl_appendf(outfiles, "%s-indx.png",  base);
            sf->ngcfn      = sl_appendf(outfiles, "%s-ngc.png",   base);
        }
        if (isurl) {
            if (suffix)
                downloadfn = sl_appendf(outfiles, "%s.%s", base, suffix);
            else
                downloadfn = sl_appendf(outfiles, "%s", base);
        }

        if (axy->solvedinfn)
            asprintf_safe(&axy->solvedinfn, axy->solvedinfn, base);

        // Do %s replacement on --verify-wcs entries...
        if (sl_size(axy->verifywcs)) {
            sl* newlist = sl_new(4);
            for (j=0; j<sl_size(axy->verifywcs); j++)
                sl_appendf(newlist, sl_get(axy->verifywcs, j), base);
            axy->verifywcs = newlist;
        }

        // ... and plot-bg
        if (inbgfn)
            asprintf_safe(&bgfn, inbgfn, base);

        if (axy->solvedinfn && axy->solvedfn && streq(axy->solvedfn, axy->solvedinfn)) {
            // solved input and output files are the same: don't delete the input!
            sl_remove_string(outfiles, axy->solvedfn);
            free(axy->solvedfn);
            axy->solvedfn = axy->solvedinfn;
        }

        free(basedir);
        free(basefile);

        if (skip_solved) {
            char* tocheck[] = { axy->solvedinfn, axy->solvedfn };
            for (j=0; j<sizeof(tocheck)/sizeof(char*); j++) {
                if (!tocheck[j])
                    continue;
                logverb("Checking for solved file %s\n", tocheck[j]);
                if (file_exists(tocheck[j])) {
                    logmsg("Solved file exists: %s; skipping this input file.\n", tocheck[j]);
                    goto nextfile;
                } else {
                    logverb("File \"%s\" does not exist.\n", tocheck[j]);
                }
            }
        }

        // Check for overlap between input and output filenames
		for (i = 0; i < sl_size(outfiles); i++) {
			char* fn = sl_get(outfiles, i);
            if (streq(fn, infile)) {
                logmsg("Output filename \"%s\" is the same as your input file.\n"
                       "Refusing to continue.\n"
                       "You can either choose a different output filename, or\n"
                       "rename your input file to have a different extension.\n", fn);
                goto nextfile;
            }
        }

		// Check for (and possibly delete) existing output filenames.
		for (i = 0; i < sl_size(outfiles); i++) {
			char* fn = sl_get(outfiles, i);
			if (!file_exists(fn))
				continue;
            if (cont) {
            } else if (overwrite) {
				if (unlink(fn)) {
					SYSERROR("Failed to delete an already-existing output file \"%s\"", fn);
					exit(-1);
				}
			} else {
				logmsg("Output file already exists: \"%s\".\n"
				       "Use the --overwrite flag to overwrite existing files,\n"
                       " or the --continue  flag to not overwrite existing files but still try solving.\n", fn);
				logmsg("Continuing to next input file.\n");
                goto nextfile;
			}
		}

		// if we're making "redgreen" plot, we need:
		if (sf->redgreenfn) {
			// -- index xylist
			if (!sf->indxylsfn) {
				sf->indxylsfn = create_temp_file("indxyls", axy->tempdir);
				sl_append_nocopy(tempfiles, sf->indxylsfn);
			}
			// -- match file.
			if (!axy->matchfn) {
				axy->matchfn = create_temp_file("match", axy->tempdir);
				sl_append_nocopy(tempfiles, axy->matchfn);
			}
		}

		// if index xyls file is needed, we need:
		if (sf->indxylsfn) {
			// -- wcs
			if (!axy->wcsfn) {
				axy->wcsfn = create_temp_file("wcs", axy->tempdir);
				sl_append_nocopy(tempfiles, axy->wcsfn);
			}
			// -- rdls
			if (!axy->rdlsfn) {
				axy->rdlsfn = create_temp_file("rdls", axy->tempdir);
				sl_append_nocopy(tempfiles, axy->rdlsfn);
			}
		}

        // Download URL...
        if (isurl) {

            sl_append(cmdline, usecurl ? "curl" : "wget");
            if (!verbose)
                sl_append(cmdline, usecurl ? "--silent" : "--quiet");
            sl_append(cmdline, usecurl ? "--output" : "-O");
            append_escape(cmdline, downloadfn);
            append_escape(cmdline, infile);

            cmd = sl_implode(cmdline, " ");

            logmsg("Downloading...\n");
            if (run_command(cmd, &ctrlc)) {
                ERROR("%s command %s", sl_get(cmdline, 0),
                      (ctrlc ? "was cancelled" : "failed"));
                exit(-1);
            }
            sl_remove_all(cmdline);
            free(cmd);

            infile = downloadfn;
        }

		if (makeplots)
			want_pnm = TRUE;

		if (axy->assume_fits_image) {
			axy->imagefn = infile;
			if (axy->pnmfn)
				want_pnm = TRUE;
		} else {
			logverb("Checking if file \"%s\" ext %i is xylist or image: ",
                    infile, axy->extension);
			fflush(NULL);
			reason = NULL;
			isxyls = xylist_is_file_xylist(infile, axy->extension,
                                           axy->xcol, axy->ycol, &reason);
			logverb(isxyls ? "xyls\n" : "image\n");
			if (!isxyls)
				logverb("  (not xyls because: %s)\n", reason);
			free(reason);
			fflush(NULL);

			if (isxyls)
				axy->xylsfn = infile;
			else {
				axy->imagefn = infile;
				want_pnm = TRUE;
			}
		}

		if (want_pnm && !axy->pnmfn) {
            ppmfn = create_temp_file("ppm", axy->tempdir);
            sl_append_nocopy(tempfiles, ppmfn);
            axy->pnmfn = ppmfn;
            axy->force_ppm = TRUE;
		}

        axy->keep_fitsimg = (newfits || scamp);

        if (augment_xylist(axy, me)) {
            ERROR("augment-xylist failed");
            exit(-1);
        }

		if (just_augment)
			goto nextfile;

        if (makeplots) {
            // Check that the plotting executables were built...
            char* exec = find_executable("plotxy", me);
            free(exec);
            if (!exec) {
                logmsg("Couldn't find \"plotxy\" executable - maybe you didn't build the plotting programs?\n");
                logmsg("Disabling plots.\n");
                makeplots = FALSE;
            }
        }
        if (makeplots) {
            // source extraction overlay
            if (plot_source_overlay(axy, me, objsfn, plotscale, bgfn))
                makeplots = FALSE;
        }

		append_escape(engineargs, axy->axyfn);

		if (file_readable(axy->wcsfn))
			axy->wcs_last_mod = file_get_last_modified_time(axy->wcsfn);
		else
			axy->wcs_last_mod = 0;

		if (!engine_batch) {
			run_engine(engineargs);
			after_solved(axy, sf, makeplots, me, verbose,
						 axy->tempdir, tempdirs, tempfiles, plotscale, bgfn);
		} else {
			bl_append(batchaxy, axy);
			bl_append(batchsf,  sf );
		}
        fflush(NULL);

        // clean up and move on to the next file.
    nextfile:        
		free(base);
        sl_free2(cmdline);

		if (!engine_batch) {
			free(axy->fitsimgfn);
			free(axy->solvedinfn);
            free(bgfn);
			// erm.
			if (axy->verifywcs != allaxy->verifywcs)
				sl_free2(axy->verifywcs);
			sl_remove_all(outfiles);
			if (!axy->no_delete_temp)
				delete_temp_files(tempfiles, tempdirs);
		}
        errors_print_stack(stdout);
        errors_clear_stack();
        logmsg("\n");
	}

	if (engine_batch) {
		run_engine(engineargs);
		for (i=0; i<bl_size(batchaxy); i++) {
			augment_xylist_t* axy = bl_access(batchaxy, i);
			solve_field_args_t* sf = bl_access(batchsf, i);

			after_solved(axy, sf, makeplots, me, verbose,
						 axy->tempdir, tempdirs, tempfiles, plotscale, bgfn);
			errors_print_stack(stdout);
			errors_clear_stack();
			logmsg("\n");

			free(axy->fitsimgfn);
			free(axy->solvedinfn);
			// erm.
			if (axy->verifywcs != allaxy->verifywcs)
				sl_free2(axy->verifywcs);
		}
		if (!allaxy->no_delete_temp)
			delete_temp_files(tempfiles, tempdirs);
		bl_free(batchaxy);
		bl_free(batchsf);
	}

    if (!allaxy->no_delete_temp)
        delete_temp_files(tempfiles2, NULL);

	sl_free2(outfiles);
	sl_free2(tempfiles);
	sl_free2(tempfiles2);
	sl_free2(tempdirs);
	sl_free2(engineargs);
    free(me);
    augment_xylist_free_contents(allaxy);

	return 0;
}
Esempio n. 25
0
void test_hd_1(CuTest* tc) {
    hd_catalog_t* hdcat;
    int* invperm;
    int* present;
    int ind, i, N;
    double xyz[3];
    double ra, dec;
    int strangehds[] = { 40142, 40441, 40672, 40746, 40763, 40764,
                         104176, 104193, 163635, 224698, 224699,
                         129371 };

    if (!file_readable("hd.fits")) {
        printf("File \"hd.fits\" does not exist; test skipped.\n");
        return;
    }

    hdcat = henry_draper_open("hd.fits");
    CuAssertPtrNotNull(tc, hdcat);

    N = hdcat->kd->ndata;
    invperm = calloc(N, sizeof(int));
    CuAssertPtrNotNull(tc, invperm);

    CuAssertIntEquals(tc, 0, kdtree_check(hdcat->kd));

    kdtree_inverse_permutation(hdcat->kd, invperm);

    present = calloc(N, sizeof(int));
    for (i=0; i<N; i++) {
        CuAssert(tc, "invperm in range", invperm[i] < N);
        present[invperm[i]]++;
    }

    for (i=0; i<N; i++) {
        CuAssertIntEquals(tc, 1, present[i]);
    }
    free(present);

    // Where is "HD n" ?
    for (i=0; i<10; i++) {
        bl* res;
        int j;

        ind = invperm[i];
        kdtree_copy_data_double(hdcat->kd, ind, 1, xyz);
        xyzarr2radecdeg(xyz, &ra, &dec);
        printf("HD %i: RA,Dec %g, %g\n", i+1, ra, dec);

        res = henry_draper_get(hdcat, ra, dec, 10.0);
        CuAssertPtrNotNull(tc, res);
        for (j=0; j<bl_size(res); j++) {
            hd_entry_t* hd = bl_access(res, j);
            printf("res %i: HD %i, RA, Dec %g, %g\n", j, hd->hd, hd->ra, hd->dec);
        }
        bl_free(res);
    }

    for (i=0; i<sizeof(strangehds)/sizeof(int); i++) {
        ind = invperm[strangehds[i]-1];
        kdtree_copy_data_double(hdcat->kd, ind, 1, xyz);
        xyzarr2radecdeg(xyz, &ra, &dec);
        printf("HD %i: RA,Dec %g, %g\n", strangehds[i], ra, dec);
    }
    free(invperm);

    henry_draper_close(hdcat);
}
Esempio n. 26
0
int main(int argc, char* argv[]) {
  std::istream& in = std::cin;
  std::ostream& out = std::cout;

  out.setf(std::ios::unitbuf);

  unsigned time_budget = 60;

  bool debug = false;
  
  // if present, this is the path to a file where the agent is to be serialized.
  boost::optional<std::string> path_to_storage;
  if (argc > 0)
    path_to_storage = std::string(argv[1]);

  Game game;
  MCTSAgent agent(2);
  if (path_to_storage && file_readable(*path_to_storage))
    agent.load_yourself(*path_to_storage);

  boost::optional<Color> agent_color;

  boost::future<void> future_quit;
  boost::future<Move> future_decision;
  boost::future<std::string> future_command;

  auto protocol_debug = [&](std::string s) {
    if (debug)
      out << "#" << s << std::endl;
  };

  auto recv_command = [&]() {
    std::string line;
    if (!std::getline(in, line))
      future_quit = boost::make_ready_future();
    protocol_debug("<xboard> " + line);
    return line;
  };

  auto send_command = [&](std::string line) {
    protocol_debug("<engine> " + line);
    out << line << std::endl;
  };

  auto report_illegal = [&](std::string move) {
    send_command("Illegal move: " + move);
  };

  auto report_error = [&](std::string class_, std::string instance) {
    send_command("Error (" + class_ + "): " + instance);
  };

  auto protocol_assert = [&](bool condition, std::string message) {
    if (!condition)
      report_error("protocol assumption violated", message);
  };

  typedef std::vector<std::string> ARGV;

  std::function<void(std::vector<std::string>)> do_nothing = [&](ARGV argv){};
  std::function<void(std::vector<std::string>)> unsupported = [&](ARGV argv){
    report_error("unsupported", argv[0]);
  };

  std::map<std::string, std::function<void(std::vector<std::string>)> > handlers = {
    {"xboard", do_nothing},
    {"protover", [&](ARGV argv) {
        for (auto feature: features)
          send_command("feature " + feature);
      }},
    // TODO: handle these as soon as we get a use case
    {"accepted", do_nothing},
    {"rejected", unsupported},
    {"new", [&](ARGV argv) {
        protocol_assert(!agent_color, "expected \"new\" only in force mode");
        game = Game();
        agent_color = colors::black;
        agent.set_state(game.current_state());
      }},
    {"variant", unsupported},
    {"quit", [&](ARGV argv) {
        agent.abort_decision();
        agent.stop_pondering();
        future_quit = boost::make_ready_future();
      }},
    {"random", do_nothing},
    {"force", [&](ARGV argv) {
        agent_color = boost::none;
        agent.abort_decision();
        agent.stop_pondering();
      }},
    {"go", [&](ARGV argv) {
        agent_color = game.color_to_move();
        agent.set_state(game.current_state());
        agent.start_pondering();
        future_decision = agent.start_decision(time_budget);
      }},
    {"playother", [&](ARGV argv) {
        protocol_assert(!agent_color, "expected \"playother\" only in force mode");
        agent_color = colors::opposite(game.color_to_move());
      }},
    {"level", unsupported},
    {"st", unsupported},
    {"sd", unsupported},
    {"nps", unsupported},
    {"time", unsupported},
    {"otim", unsupported},
    {"usermove", [&](ARGV argv) {
        protocol_assert(!agent_color || agent_color != game.color_to_move(),
                        "usermove during engine's turn");
        Move move;
        try {
          move = notation::algebraic::parse(argv[1], game.current_state());
        } catch (notation::algebraic::OverdeterminedException& e) {
          report_illegal(argv[1]);
          return;
        } catch (notation::algebraic::UnderdeterminedException& e) {
          report_error("ambiguous move", argv[1]);
          return;
        }
        game.make_move(move);
        if (agent_color) {
          agent.advance_state(move);
          agent.start_pondering();
          future_decision = agent.start_decision(time_budget);
        }
      }},
    {"?", [&](ARGV argv) {
        agent.finalize_decision();
      }},
    {"ping", [&](ARGV argv) {
        if (future_decision.valid())
          future_decision.wait();
        send_command("pong " + argv[1]);
      }},
    {"draw", [&](ARGV argv) {
        protocol_assert(!!agent_color, "\"draw\" when engine not assigned to any color");
        agent.set_state(game.current_state());
        if (agent.accept_draw(*agent_color))
          send_command("offer draw");
      }},
    {"result", [&](ARGV argv) {
        agent.idle();
      }},
    {"setboard", [&](ARGV argv) {
        protocol_assert(!agent_color, "expected \"setboard\" only in force mode");
        std::string fen = boost::algorithm::join(ARGV(argv.begin() + 1, argv.end()), " ");
        game.setboard(fen);
        agent.set_state(game.current_state());
      }},
    {"edit", unsupported},
    {"hint", unsupported},
    {"bk", do_nothing},
    {"undo", [&](ARGV argv) {
        protocol_assert(!agent_color, "expected \"undo\" only in force mode");
        game.undo();
        agent.set_state(game.current_state());
      }},
    {"remove", [&](ARGV argv) {
        protocol_assert(!agent_color || agent_color != game.color_to_move(),
                        "expected \"remove\" only during user's turn");
        game.undo();
        game.undo();
        agent.set_state(game.current_state());
      }},
    {"hard", do_nothing},
    {"easy", do_nothing},
    {"post", do_nothing},
    {"nopost", do_nothing},
    {"analyze", unsupported},
    {"name", do_nothing},
    {"rating", do_nothing},
    {"ics", unsupported},
    {"computer", do_nothing},
    {"pause", [&](ARGV argv) {
        agent.pause();
      }},
    {"resume", [&](ARGV argv) {
        agent.resume();
      }},
    // this could prove to be useful
    {"memory", unsupported},
    {"cores", unsupported},
    {"egtpath", do_nothing},
    {"option", do_nothing},
  };

  auto handle_decision = [&](){
    Move move = future_decision.get();
    send_command("move " + notation::coordinate::format(move));
    game.make_move(move);
    agent.advance_state(move);
    if (path_to_storage)
      agent.save_yourself(*path_to_storage);
    // there has to be a better way to make sure we don't keep redetecting
    // the same future decision value, but i don't know it.  really, the
    // wait_for_any function should wait for any one of them to turn from
    // not-yet-ready to ready, but the manual says that's not how it works.
    // so, replace the ready future with one that will never be ready.
    // i considered keeping a set of futures that need waiting for, and then
    // simply removing processed futures.  but the futures have different
    // value types so we can't store them in a single container unless we use
    // something like boost::variant and then we need a boost::visitor and a
    // boost::welcome_committee and a boost::mayor to ceremonially snip a
    // ribbon with a giant pair of scissors and...  what was the question?
    future_decision = boost::async([]() -> Move {
        sleep_forever();
        throw std::runtime_error("greetings, time traveler!");
      });
  };
  
  auto handle_command = [&]() {
    std::string line = future_command.get();
    std::vector<std::string> argv;
    boost::algorithm::split(argv, line, boost::algorithm::is_any_of("\t "), boost::token_compress_on);
    std::function<void(ARGV)> handler;
    try {
      handler = handlers.at(argv[0]);
    } catch (std::out_of_range& e) {
      protocol_assert(false, "unknown command: " + line);
      goto after_handler;
    }
    handler(argv);

    after_handler:
    future_command = boost::async(recv_command);
  };
  
  future_command = boost::async(recv_command);
  while (true) {
    unsigned short ifuture;
    try {
      ifuture = boost::wait_for_any(future_quit, future_decision, future_command);
    } catch (boost::thread_interrupted&) {
    }

    switch (ifuture) {
    case 0:
      goto quit;
      break;
    case 1:
      handle_decision();
      break;
    case 2:
      handle_command();
      break;
    }

    ifuture = -1;
  }

  quit:
  ;
}
Esempio n. 27
0
// This runs after "astrometry-engine" is run on the file.
static void after_solved(augment_xylist_t* axy,
						 solve_field_args_t* sf,
						 anbool makeplots,
						 const char* me,
						 anbool verbose,
						 const char* tempdir,
						 sl* tempdirs,
						 sl* tempfiles,
						 double plotscale,
						 const char* bgfn) {
	sip_t wcs;
	double ra, dec, fieldw, fieldh;
	char rastr[32], decstr[32];
	char* fieldunits;

	// print info about the field.
	logmsg("Field: %s\n", axy->imagefn ? axy->imagefn : axy->xylsfn);
	if (file_exists(axy->wcsfn)) {
		double orient;
		if (axy->wcs_last_mod) {
			time_t t = file_get_last_modified_time(axy->wcsfn);
			if (t == axy->wcs_last_mod) {
				logmsg("Warning: there was already a WCS file, and its timestamp has not changed.\n");
			}
		}
		if (!sip_read_header_file(axy->wcsfn, &wcs)) {
			ERROR("Failed to read WCS header from file %s", axy->wcsfn);
			exit(-1);
		}
		sip_get_radec_center(&wcs, &ra, &dec);
		sip_get_radec_center_hms_string(&wcs, rastr, decstr);
		sip_get_field_size(&wcs, &fieldw, &fieldh, &fieldunits);
		orient = sip_get_orientation(&wcs);
		logmsg("Field center: (RA,Dec) = (%3.6f, %3.6f) deg.\n", ra, dec);
		logmsg("Field center: (RA H:M:S, Dec D:M:S) = (%s, %s).\n", rastr, decstr);
		logmsg("Field size: %g x %g %s\n", fieldw, fieldh, fieldunits);
		logmsg("Field rotation angle: up is %g degrees E of N\n", orient);
	} else {
		logmsg("Did not solve (or no WCS file was written).\n");
	}

	// create new FITS file...
	if (axy->fitsimgfn && sf->newfitsfn && file_exists(axy->wcsfn)) {
		logmsg("Creating new FITS file \"%s\"...\n", sf->newfitsfn);
		if (new_wcs(axy->fitsimgfn, axy->wcsfn, sf->newfitsfn, TRUE)) {
			ERROR("Failed to create FITS image with new WCS headers");
			exit(-1);
		}
	}

	// write list of index stars in image coordinates
	if (sf->indxylsfn && file_exists(axy->wcsfn) && file_exists(axy->rdlsfn)) {
		assert(axy->wcsfn);
		assert(axy->rdlsfn);
		// index rdls to xyls.
		if (wcs_rd2xy(axy->wcsfn, 0, axy->rdlsfn, sf->indxylsfn,
					  NULL, NULL, FALSE, FALSE, NULL)) {
			ERROR("Failed to project index stars into field coordinates using wcs-rd2xy");
			exit(-1);
		}
	}

	if (makeplots && file_exists(sf->indxylsfn) && file_readable(axy->matchfn) && file_readable(axy->wcsfn)) {
		logmsg("Creating index object overlay plot...\n");
		if (plot_index_overlay(axy, me, sf->indxylsfn, sf->redgreenfn, plotscale, bgfn)) {
			ERROR("Plot index overlay failed.");
		}
	}

	if (makeplots && file_readable(axy->wcsfn)) {
		logmsg("Creating annotation plot...\n");
		if (plot_annotations(axy, me, verbose, sf->ngcfn, plotscale, bgfn)) {
			ERROR("Plot annotations failed.");
		}
	}

	if (axy->imagefn && sf->kmzfn && file_exists(axy->wcsfn)) {
		logmsg("Writing kmz file...\n");
		if (write_kmz(axy, sf->kmzfn, tempdir, tempdirs, tempfiles)) {
			ERROR("Failed to write KMZ.");
			exit(-1);
		}
	}

	if (sf->scampfn && file_exists(axy->wcsfn)) {
		//char* hdrfile = NULL;
		qfits_header* imageheader = NULL;
		starxy_t* xy;
		xylist_t* xyls;

		xyls = xylist_open(axy->axyfn);
		if (!xyls) {
			ERROR("Failed to read xylist to write SCAMP catalog");
			exit(-1);
		}
		if (axy->xcol)
			xylist_set_xname(xyls, axy->xcol);
		if (axy->ycol)
			xylist_set_yname(xyls, axy->ycol);
		//xylist_set_include_flux(xyls, FALSE);
		xylist_set_include_background(xyls, FALSE);
		xy = xylist_read_field(xyls, NULL);
		xylist_close(xyls);

		if (axy->fitsimgfn) {
			//hdrfile = axy->fitsimgfn;
			imageheader = anqfits_get_header2(axy->fitsimgfn, 0);
		}
		if (axy->xylsfn) {
			char val[32];
			//hdrfile = axy->xylsfn;
			imageheader = anqfits_get_header2(axy->xylsfn, 0);
			// Set NAXIS=2, NAXIS1=IMAGEW, NAXIS2=IMAGEH
			fits_header_mod_int(imageheader, "NAXIS", 2, NULL);
			sprintf(val, "%i", axy->W);
			qfits_header_add_after(imageheader, "NAXIS",  "NAXIS1", val, "image width", NULL);
			sprintf(val, "%i", axy->H);
			qfits_header_add_after(imageheader, "NAXIS1", "NAXIS2", val, "image height", NULL);
			//fits_header_add_int(imageheader, "NAXIS1", axy->W, NULL);
			//fits_header_add_int(imageheader, "NAXIS2", axy->H, NULL);
			logverb("Using NAXIS 1,2 = %i,%i\n", axy->W, axy->H);
		}

		if (scamp_write_field(imageheader, &wcs, xy, sf->scampfn)) {
			ERROR("Failed to write SCAMP catalog");
			exit(-1);
		}
		starxy_free(xy);
		if (imageheader)
			qfits_header_destroy(imageheader);
	}

	if (sf->scampconfigfn) {
		if (scamp_write_config_file(axy->scampfn, sf->scampconfigfn)) {
			ERROR("Failed to write SCAMP config file snippet to %s", sf->scampconfigfn);
			exit(-1);
		}
	}
}