Ejemplo n.º 1
0
/***************************************************************************
 *
 *N  point_in_face_table
 *
 *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
 *
 *   Purpose:
 *P
 *    Test whether a point is inside a face or not.  Must have a valid path-
 *   name to a valid VPF Face file, or else be in graphics mode for the error
 *   message that will result.  Filename must have all directory seperators
 *   escapes; eg. c:\\vpf    NOT c:\vpf
 *E
 *::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
 *   Parameters:
 *A
 *    x        <input> == (float) given point x coordinate.
 *    y        <input> == (float) given point y coordinate.
 *    face_id  <input> == (rspf_int32) face.
 *    fname    <input> == (char *) pathname to VPF face file.
 *    point_in_face_table <output> == VPF_BOOLEAN:
 *                                            1 --> point is inside
 *                                            0 --> point is not inside
 *E
 **************************************************************************/
int point_in_face_table( float x, float y,
			 rspf_int32 face_id,
			 char *fname )
{
   vpf_table_type facetable, ringtable, edgetable;
   char *name;
   int result;

   name = (char *)vpfmalloc( 255*sizeof(char) );

   facetable = vpf_open_table(fname,disk, "rb", NULL );

   strupr(fname);

   strcpy( name, fname );
   dirpath( name );
   strcat( name, "RNG" );
   ringtable = vpf_open_table( name, disk , "rb", NULL );

   strcpy( name, fname );
   dirpath( name );
   strcat( name, "EDG" );
   edgetable = vpf_open_table( name, disk , "rb", NULL );

   free( name );

   result = point_in_face( x, y, face_id, facetable, ringtable, edgetable );

   vpf_close_table(&facetable);
   vpf_close_table(&ringtable);
   vpf_close_table(&edgetable);

   return result;
}
Ejemplo n.º 2
0
/****************************************************************************
 * CreateSubfolder
 *
 * Create recursive all subfolders to the given path
 ***************************************************************************/
bool CreateSubfolder(const char * fullpath)
{
    if(!fullpath)
        return false;

    if(CheckFile(fullpath))
        return true;

    string dirpath(fullpath);

    int length = dirpath.size()-1;
    while(dirpath[length] == '/')
    {
        dirpath.erase(length);
        --length;
    }

    string subpath(dirpath);
    size_t pos = subpath.rfind('/');
    if(pos == string::npos)
        return false;

    if(subpath.size()-1 > pos)
        subpath.erase(pos+1);

    bool result = CreateSubfolder(subpath.c_str());
    if(!result)
        return false;

    return (mkdir(dirpath.c_str(), 0777) != -1);
}
Ejemplo n.º 3
0
/// Returns the absolute pathnames of all lyx local sockets in
/// file system encoding.
/// Parts stolen from lyx::support::DirList().
FileNameList lyxSockets(string const & dir, string const & pid)
{
	FileNameList dirlist;

	FileName dirpath(dir + "/");

	if (!dirpath.exists() || !dirpath.isDirectory()) {
		lyxerr << dir << " does not exist or is not a directory."
		       << endl;
		return dirlist;
	}

	FileNameList dirs = dirpath.dirList("");
	FileNameList::const_iterator it = dirs.begin();
	FileNameList::const_iterator end = dirs.end();

	for (; it != end; ++it) {
		if (!it->isDirectory())
			continue;
		string const tmpdir = it->absFileName();
		if (!contains(tmpdir, "lyx_tmpdir" + pid))
			continue;

		FileName lyxsocket(tmpdir + "/lyxsocket");
		if (lyxsocket.exists())
			dirlist.push_back(lyxsocket);
	}

	return dirlist;
}
Ejemplo n.º 4
0
BRect
LibraryWindow::ScanFolder(BPoint location, const char *path, float *maxwidth)
{
	BDirectory dir(path);
	if (dir.InitCheck() != B_OK)
		return BRect(0,0,-1,-1);
	
	float width = 0.0;
	dir.Rewind();
	entry_ref ref;
	BRect r(location.x,location.y,location.x + 1,location.y + 1);
	
	while (dir.GetNextRef(&ref) == B_OK)
	{
		BString str(ref.name);
		
		int32 soPos = str.FindLast(".so");
		int32 aPos = str.FindLast(".a");
		
		if (soPos < 0 && aPos < 0)
			continue;
		
		if (soPos >= 0 && soPos < str.CountChars() - 3)
			continue;
		
		if (aPos >= 0 && aPos < str.CountChars() - 2)
			continue;
		
		Lock();	
		BMessage *msg = new BMessage(M_TOGGLE_LIB);
		msg->AddRef("ref",&ref);
		msg->AddString("path",path);
		BCheckBox *box = new BCheckBox(r,ref.name,ref.name,msg);
		box->ResizeToPreferred();
		r = box->Frame();
		fCheckList->AddChild(box);
		fSystemLibs.AddItem(box);
		
		// Make sure that there isn't any shortcut normalization
		BPath dirpath(path);
		dirpath.Append(ref.name);
		
		if (fProject && fProject->HasLibrary(dirpath.Path()))
			box->SetValue(B_CONTROL_ON);
		else
			box->SetValue(B_CONTROL_OFF);
		Unlock();
		
		
		width = MAX(r.right,width);
		r.OffsetBy(0,r.Height());
	}
	
	if (r.Height() == 1)
		r.Set(0, 0, -1, -1);
	
	*maxwidth = width;
	return r;
}
Ejemplo n.º 5
0
/* Declares which program we'll run, and what we'll be doing with it.
 * This function should return ElvTrue if successful.  If there is an error,
 * it should issue an error message via msg(), and return ElvFalse.
 */
ELVBOOL prgopen(char *command, ELVBOOL willwrite, ELVBOOL willread)
{
	/* remember the command we're supposed to run */
	cmd = command;

	/* if we're going to be reading, then choose a tempread name now */
	if (willread)
	{
		strcpy(tempread, o_directory ? dirpath(tochar8(o_directory), "rdXXXXXX") : "rdXXXXXX");
		mktemp(tempread);

		/* open it and close it, just to make sure it exists */
		fd = open(tempread, O_WRONLY|O_CREAT|O_EXCL, 0600);
		if (fd < 0)
		{
			msg(MSG_ERROR, "[s]can't create temp file $1", tempread);
			return ElvFalse;
		}
		close(fd);
	}
	else
		tempread[0] = '\0';

	/* if we'll be writing, then choose a tempwrite name and open it */
	if (willwrite)
	{
		strcpy(tempwrite, o_directory ? dirpath(tochar8(o_directory), "wrXXXXXX") : "wrXXXXXX");
		mktemp(tempwrite);
		fd = open(tempwrite, O_WRONLY|O_CREAT|O_EXCL, 0600);
		if (fd < 0)
		{
			msg(MSG_ERROR, "[s]can't create temp file $1", tempwrite);
			if (tempread[0])
				remove(tempread);
			return ElvFalse;
		}
	}
	else
		tempwrite[0] = '\0';

	return ElvTrue;
}
Ejemplo n.º 6
0
/**
 * @brief find files
 * @param dirpath path in which to start looking
 * @param pattern pattern to search for
 * @param recurse whether or not to recursively search
 * @param include_dirs whether or not to include directory names in the result
 * @return vector of std::strings
 *
 * Will search for a file given a particular pattern.
 * Starts from dirpath, descending down if recurse is true.
 */
std::vector<std::string> FileSystemHandler::FindFiles(const std::string& dir, const std::string &pattern, bool recurse, bool include_dirs) const
{
	std::vector<std::string> matches;
	boost::filesystem::path dirpath(dir, boost::filesystem::no_check);
	if (boost::filesystem::exists(dirpath) && boost::filesystem::is_directory(dirpath)) {
		boost::regex regexpattern(filesystem.glob_to_regex(pattern));
		matches = ::FindFiles(dirpath, regexpattern, recurse, include_dirs);
	} else {
#ifdef DEBUG
		fprintf(stderr,"find_files warning: search path %s is not a directory\n",dirpath.string().c_str());
#endif
	}
	return matches;
}
Ejemplo n.º 7
0
///////////////////////////////////////////////////////////////////////////////
//  Find an include file by traversing the list of include directories
inline
bool include_paths::find_include_file (std::string &s, std::string &dir, 
    include_list_type const &pathes, char const *current_file) const
{
    namespace fs = boost::filesystem;
    typedef include_list_type::const_iterator const_include_list_iter_t;

    const_include_list_iter_t it = pathes.begin();
    const_include_list_iter_t include_paths_end = pathes.end();

#if BOOST_WAVE_SUPPORT_INCLUDE_NEXT != 0    
    if (0 != current_file) {
    // re-locate the directory of the current file (#include_next handling)

    // #include_next does not distinguish between <file> and "file"
    // inclusion, nor does it check that the file you specify has the same
    // name as the current file.  It simply looks for the file named, starting
    // with the directory in the search path after the one where the current
    // file was found.

        fs::path file_path (current_file, fs::native);
        for (/**/; it != include_paths_end; ++it) {
            fs::path currpath ((*it).first.string(), fs::native);
            if (std::equal(currpath.begin(), currpath.end(), file_path.begin())) 
            {
                ++it;     // start searching with the next directory
                break;
            }
        }
    }
#endif

    for (/**/; it != include_paths_end; ++it) {
        fs::path currpath ((*it).first.string(), fs::native);
        currpath /= fs::path(s, fs::native);      // append filename

        if (fs::exists(currpath)) {
            fs::path dirpath ((*it).second, fs::native);
            dirpath /= fs::path(s, fs::native);
            
            dir = dirpath.string();
            s = currpath.normalize().string();    // found the required file
            return true;
        }
    }
    return false;
}
Ejemplo n.º 8
0
///////////////////////////////////////////////////////////////////////////////
//  Find an include file by searching the user and system includes in the 
//  correct sequence (as it was configured by the user of the driver program)
inline bool 
include_paths::find_include_file (std::string &s, std::string &dir, 
    bool is_system, char const *current_file) const
{
    namespace fs = boost::filesystem;
    
// if not system include (<...>), then search current directory first
    if (!is_system) {
        if (!was_sys_include_path) {  // set_sys_include_delimiter() not called
        // first have a look at the current directory
            fs::path currpath (current_dir.string(), fs::native);
            currpath /= fs::path(s, fs::native);
            
            if (fs::exists(currpath) && 0 == current_file) {
            // if 0 != current_path (#include_next handling) it can't be
            // the file in the current directory
                fs::path dirpath (current_rel_dir.string(), fs::native);
                dirpath /= fs::path(s, fs::native);

                dir = dirpath.string();
                s = currpath.normalize().string();    // found in local directory
                return true;
            }   

        // iterate all user include file directories to find the file
            if (find_include_file(s, dir, user_include_paths, current_file))
                return true;

        // ... fall through
        }
        else {
        //  if set_sys_include_delimiter() was called, then user include files
        //  are searched in the user search path only
            return find_include_file(s, dir, user_include_paths, current_file);
        }
        
    // if nothing found, fall through
    // ...
    }

// iterate all system include file directories to find the file
    return find_include_file (s, dir, system_include_paths, current_file);
}
Ejemplo n.º 9
0
/*
** Factory of directory iterators
*/
int dir_iter_factory (lua_State *L) {
	const char *path = luaL_checkstring (L, 1);
	dir_data *d;
	lua_pushcfunction (L, dir_iter);
	d = (dir_data *) lua_newuserdata (L, sizeof(dir_data));
	d->closed = 0;
#ifdef _WIN32
	d->hFile = 0L;
	luaL_getmetatable (L, DIR_METATABLE);
	lua_setmetatable (L, -2);
	if (strlen(path) > PATH_MAX - 2)
	  luaL_error (L, "path too long: %s", path);
	else
	  sprintf (d->pattern, "%s/*", path);
#else
	luaL_getmetatable (L, DIR_METATABLE);
	lua_setmetatable (L, -2);
	d->dir = opendir (dirpath(path));
	if (d->dir == NULL)
		luaL_error (L, "cannot open %s.", path);
#endif
	return 2;
}
DirectoryImageSource::DirectoryImageSource(const string& directory) : ImageSource(directory), files(), index(-1) {
	path dirpath(directory);
	if (!exists(dirpath))
		throw runtime_error("DirectoryImageSource: Directory '" + directory + "' does not exist.");
	if (!is_directory(dirpath))
		throw runtime_error("DirectoryImageSource: '" + directory + "' is not a directory.");
	copy(directory_iterator(dirpath), directory_iterator(), back_inserter(files));
	/* TODO: Only copy valid images that opencv can handle. Those are:
		Built-in: bmp, portable image formats (pbm, pgm, ppm), Sun raster (sr, ras).
		With plugins, present by default: JPEG (jpeg, jpg, jpe), JPEG 2000 (jp2 (=Jasper)), 
										  TIFF files (tiff, tif), png.
		If specified: OpenEXR.
		Parameter for list of valid file extensions?
		Parameter for predicate (used by remove_if)?
		Parameter for single file extension?
		Unify the different image sources that work with file lists (DirectoryImageSource,
		FileImageSource, FileListImageSource, RepeatingFileImageSourcec), so the filtering
		does not have to be repeated in each of them. But not all of them need the filtering
		anyway (for example if a file list is given explicitly).

		First prototype version of file filtering by extension:
	*/
	vector<string> imageExtensions = { "bmp", "dib", "pbm", "pgm", "ppm", "sr", "ras", "jpeg", "jpg", "jpe", "jp2", "png", "tiff", "tif" };

	auto newFilesEnd = std::remove_if(files.begin(), files.end(), [&](const path& file) {
		string extension = file.extension().string();
		if (extension.size() > 0)
			extension = extension.substr(1);
		std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower);
		return std::none_of(imageExtensions.begin(), imageExtensions.end(), [&](const string& imageExtension) {
			return imageExtension == extension;
		});
	});
	files.erase(newFilesEnd, files.end());

	sort(files.begin(), files.end());
}
Ejemplo n.º 11
0
int main(int argc, char **argv)
{
    int i, use_stdin, use_mbox;
    char *configfile = NULL;
    char **tlang, *locale_code;
    int cmd_show_variables;
    int print_usage;

    int amount_old = 0;		/* number of old mails */
    int amount_new = 0;		/* number of new mails */

#ifdef HAVE_LOCALE_H
    setlocale(LC_ALL, "");
#endif

    lockfile[0] = '\0';
    use_stdin = 0;
    print_usage = 0;
    use_mbox = 0;

    firstdatenum = lastdatenum = 0;

    configfile = strsav(CONFIGFILE);

    cmd_show_variables = 0;

    opterr = 0;

#define GETOPT_OPTSTRING ("a:Ab:c:d:gil:L:m:n:o:ps:tTuvVxX0:1M?")

    /* get pre config options here */
	while ((i = getopt(argc, argv, GETOPT_OPTSTRING)) != -1) {
		switch ((char)i) {
	case 'c':
	    configfile = strreplace(configfile, optarg);
	    break;
	case 'v':
	    cmd_show_variables = TRUE;
	    break;
	case 'V':
	    version();
		 /*NOTREACHED*/ case 'a':
	case 'A':
	case 'b':
	case 'd':
	case 'g':
	case 'i':
	case 'l':
	case 'L':
	case 'm':
	case 'n':
	case 'o':
	case 'p':
	case 's':
	case 't':
	case 'T':
	case 'u':
	case 'x':
	case 'X':
	case '0':
	case '1':
	case 'M':
	    break;
	case '?':
	default:
	    /* 
	     * Because we need to setup the language support, 
	     * printing of the usage message must be deferred 
	     * until the proper language is determined.
	     */
	    print_usage = 1;
	    break;
	}
    }

    /* 
     * ...then read the configuration file.
     */

    readconfigs(configfile, cmd_show_variables);

    /* reset the getopt() index variable */
    optind = 1;

    /* now get the post-config options! */

	while ((i = getopt(argc, argv, GETOPT_OPTSTRING)) != -1) {
		switch ((char)i) {
	case 'A':
	    set_append = 1;
	    break;
	case 'a':
	    set_archives = strreplace(set_archives, optarg);
	    break;
	case 'b':
	    set_about = strreplace(set_about, optarg);
	    break;
	case 'c':
	    /* config file from pre-config options */
	    break;
	case 'd':
	    set_dir = strreplace(set_dir, optarg);
	    break;
	case 'g':
	    set_usegdbm = 1;
	    break;
	case 'i':
	    use_stdin = TRUE;
	    break;
	case 'l':
	    set_label = strreplace(set_label, optarg);
	    break;
	case 'L':
	    set_language = strreplace(set_language, optarg);
	    break;
	case 'm':
	    set_mbox = strreplace(set_mbox, optarg);
	    break;
	case 'n':
	    set_hmail = strreplace(set_hmail, optarg);
	    break;
	case 'o':
	    ConfigAddItem(optarg);
	    break;
	case 'p':
	    set_showprogress = TRUE;
	    break;
	case 's':
	    set_htmlsuffix = strreplace(set_htmlsuffix, optarg);
	    break;
	case 't':
	    set_usetable = TRUE;
	    break;
	case 'T':
	    set_indextable = TRUE;
	    break;
	case 'u':
	    set_increment = TRUE;
	    break;
	case 'v':
	    cmd_show_variables = TRUE;
	    break;
	case 'x':
	    set_overwrite = TRUE;
	    break;
	case 'X':
	    set_writehaof = TRUE;
	    break;
	case '0':
	    set_delete_msgnum = add_list(set_delete_msgnum, optarg);
	    break;
	case '1':
	    set_readone = TRUE;
	    break;
	case 'M':
	    set_usemeta = TRUE;
	    break;
	case 'N':
 	    set_nonsequential = TRUE;
	    break;
	case '?':
	default:
	    break;
	}
    }

#ifdef DEBUG
    dump_config();
    exit(0);
#endif

    /*
     * Now override the configuration file variables with any explicitly
     * passed on the command line. This way you need not change the
     * configuration file settings for a minor change in a single run.
     */

    /* 
     * Check and make sure that the supplied language is a
     * valid language. Otherwise strange things happen quickly.
     */

    if (strlen(set_language) > 2) {
	locale_code = strsav(set_language);
	set_language[2] = 0;	/* shorten to 2-letter code */
    }
    else
	locale_code = NULL;

    if ((tlang = valid_language(set_language, &locale_code)) == NULL) {
	snprintf(errmsg, sizeof(errmsg), "\"%s\" %s.", set_language, lang[MSG_LANGUAGE_NOT_SUPPORTED]);
	cmderr(errmsg);
    }

#ifdef HAVE_LOCALE_H
	if (!setlocale(LC_ALL, locale_code)) {
	    snprintf(errmsg, sizeof(errmsg), "WARNING: locale \"%s\", not supported.\n", locale_code);
	    fprintf(stderr, "%s", errmsg);/* AUDIT biege: avoid format-bug warning */
    }
#endif
	
    lang = tlang;		/* A good language, make it so. */

    if (print_usage)		/* Print the usage message and terminate */
	usage();

#ifndef GDBM
    if (set_usegdbm) {
    fprintf(stderr, "%s: %s\n", PROGNAME, lang[MSG_OPTION_G_NOT_BUILD_IN]);
    usage();
    }
#endif

#ifndef HAVE_LIBFNV
    if (set_nonsequential)
      progerr("Hypermail isn't built with the libfnv hash library.\n"
	     "You cannot use the nonsequential option.\n");
#endif /* HAVE_LIBFNV */

    if (set_mbox && !strcasecmp(set_mbox, "NONE")) {
	use_stdin = TRUE;
    }

    /* the list of headers that we always show and that we want to avoid
       showing twice when printing the body */
    set_skip_headers = add_list(set_skip_headers, "from");
    set_skip_headers = add_list(set_skip_headers, "date");
    set_skip_headers = add_list(set_skip_headers, "subject");

    /*
     * Did they decide to use stdin by specifying it on the command line ?
     * If not then check and see if that is the default they wanted from
     * the options.h or environment values.
     */
    if (!use_stdin) {
	if (optind < argc && set_increment == -1 && !set_mbox) {
	    set_mbox = strsav(argv[optind]);
	}
	else if (!set_mbox || !strcasecmp(set_mbox, "NONE"))
	    use_stdin = TRUE;
	else
	    use_stdin = FALSE;
    }
    else {
	if (set_mbox)
	    free(set_mbox);
	set_mbox = NULL;
    }

    /*
    ** Deprecated options 
    */
    if (set_showhr) {
      fprintf (stderr, "The \"showhr\" option has been deprecated. Ignoring it.\n");
      set_showhr = FALSE;
    }

    if (set_usetable) {
      fprintf (stderr, "The \"usetable\" option has been deprecated. Ignoring it.\n");
      set_usetable = FALSE;
    }

    /*
     * Read the contents of the file into the variables to be used
     * in printing out the pages.
     */

    ihtmlheaderfile = expand_contents(set_ihtmlheader);
    ihtmlfooterfile = expand_contents(set_ihtmlfooter);
    ihtmlheadfile = expand_contents(set_ihtmlhead);
    ihtmlhelpupfile = expand_contents(set_ihtmlhelpup);
    ihtmlhelplowfile = expand_contents(set_ihtmlhelplow);
    ihtmlnavbar2upfile = expand_contents(set_ihtmlnavbar2up);
    mhtmlheaderfile = expand_contents(set_mhtmlheader);
    mhtmlfooterfile = expand_contents(set_mhtmlfooter);

    if (set_dir)
	set_dir = strreplace(set_dir, dirpath(set_dir));

    /*
     * Default names for directories and labels need to be figured out.
     */

    if (use_stdin && (!set_dir || !strcasecmp(set_dir, "NONE")))
	set_dir = strreplace(set_dir, DIRNAME);

    if (!set_dir || !strcasecmp(set_dir, "NONE"))
	set_dir = strreplace(set_dir, (strrchr(set_mbox, '/')) ? strrchr(set_mbox, '/') + 1 : set_mbox);

    if (set_dir[strlen(set_dir) - 1] != PATH_SEPARATOR)
	trio_asprintf(&set_dir, "%s%c", set_dir, PATH_SEPARATOR);

    if (!set_label || !strcasecmp(set_label, "NONE"))
	set_label = set_mbox ? (strreplace(set_label, (strrchr(set_mbox, '/')) ? strrchr(set_mbox, '/') + 1 : set_mbox)) : "stdin";

    /*
     * Which index file will be called "index.html"?
     */

    index_name[1][DATE_INDEX] = setindex(set_defaultindex, "date", set_htmlsuffix);
    index_name[1][THREAD_INDEX] = setindex(set_defaultindex, "thread", set_htmlsuffix);
    index_name[1][SUBJECT_INDEX] = setindex(set_defaultindex, "subject", set_htmlsuffix);
    index_name[1][AUTHOR_INDEX] = setindex(set_defaultindex, "author", set_htmlsuffix);
    if (set_attachmentsindex) {
	index_name[1][ATTACHMENT_INDEX]
	    = setindex(set_defaultindex, "attachment", set_htmlsuffix);
    }
    if (set_folder_by_date || set_msgsperfolder) {
	index_name[0][DATE_INDEX] = setindex(set_default_top_index, "date", set_htmlsuffix);
	index_name[0][THREAD_INDEX] = setindex(set_default_top_index, "thread", set_htmlsuffix);
	index_name[0][SUBJECT_INDEX] = setindex(set_default_top_index, "subject", set_htmlsuffix);
	index_name[0][AUTHOR_INDEX] = setindex(set_default_top_index, "author", set_htmlsuffix);
	if (set_attachmentsindex) {
	    index_name[0][ATTACHMENT_INDEX] = setindex(set_default_top_index, "attachment", set_htmlsuffix);
	}
	index_name[0][FOLDERS_INDEX] = setindex(set_default_top_index, "folders", set_htmlsuffix);
    }
    else {
	index_name[0][DATE_INDEX] = index_name[1][DATE_INDEX];
	index_name[0][THREAD_INDEX] = index_name[1][THREAD_INDEX];
	index_name[0][AUTHOR_INDEX] = index_name[1][AUTHOR_INDEX];
	index_name[0][SUBJECT_INDEX] = index_name[1][SUBJECT_INDEX];
	index_name[0][ATTACHMENT_INDEX] = index_name[1][ATTACHMENT_INDEX];
    }

    init_index_names();

    if (set_msgsperfolder && set_folder_by_date) {
	progerr("msgsperfolder and folder_by_date may not be used at the same time!");
    }

    /*
     * General settings for mail command and rewriting.
     */

    if (!set_domainaddr || !strcasecmp(set_domainaddr, "NONE"))
	use_domainaddr = 0;
    else
	use_domainaddr = 1;

    if (!set_mailto || !strcasecmp(set_mailto, "NONE"))
	use_mailto = 0;
    else
	use_mailto = 1;

    if (!set_mailcommand || !strcasecmp(set_mailcommand, "NONE"))
	use_mailcommand = 0;
    else
	use_mailcommand = 1;

#ifndef HAVE_LIBFNV
    /* the nonsequential mode won't work unless we compiled the FNV hash library
       (./configure --enable-libfnv) */
    if (set_nonsequential)
		progerr("the nonsequential mode is only available if you enabled the\n compilation" "of the fnv hash library. Try doing a\n\t./configure --enable-libfnv\n" "and recompile if you want to use this option.");
#endif /* HAVE_LIBFNV */

    /* 
     * A little performance speed up.  The following was being done
     * over and over in the write functions. This way it is done once.
     * A bigger win on larger archives.
     */

    if (set_hmail && !strcasecmp(set_hmail, "NONE")) {
	free(set_hmail);
	set_hmail = NULL;
    }

    if (set_archives && !strcasecmp(set_archives, "NONE")) {
	free(set_archives);
	set_archives = NULL;
    }

    if (set_custom_archives && !strcasecmp(set_custom_archives, "NONE")) {
	free(set_custom_archives);
	set_custom_archives = NULL;
    }

    if (set_about && !strcasecmp(set_about, "NONE")) {
	free(set_about);
	set_about = NULL;
    }

    /* Simply show what the values of the variables are and exit */

    if (cmd_show_variables) {
	if (!set_mbox)
	    set_mbox = "NONE";
	MakeConfig(TRUE); 
	free(configfile);
	return (0);
    }

    /* Injecting a little sanity... */

    if (use_mbox && use_stdin) {
	cmderr(lang[MSG_CANNOT_READ_FROM_BOTH_FILE_AND_STDIN]);
    }
    if (set_append && use_mbox) {
        cmderr(lang[MSG_CANNOT_BOTH_READ_AND_WRITE_TO_MBOX]);
    }

    gettimezone();
    getthisyear();

    /*
     * MIME processing requires the files be created as they
     * are read in loadheaders() so assure the directories are 
     * there first...
     */

    checkdir(set_dir);

    /*
     * Let's do it.
     */

    if (set_uselock)
	lock_archive(set_dir);

    if (set_increment == -1) {
	int save_append = set_append;
	set_append = 0;
	if (set_mbox_shortened)
	    progerr("can not use increment = -1 option with mbox_shortened option\n");
	amount_new = parsemail(set_mbox, use_stdin, 1, -1, set_dir, set_inlinehtml, 0);
	set_increment = !matches_existing(set_startmsgnum);
	if (set_increment && set_folder_by_date && !set_usegdbm)
	    progerr("folder_by_date with incremental update requires usegdbm option");
	reinit_structs();
	set_append = save_append;
    }
    if (set_increment) {
	int num_displayable;
	if (set_linkquotes)
	    replylist = NULL;
	/* we have to start with the msgnum - 1 so that the rest of the
	   code works ok when there are no old headers. */
	max_msgnum = set_startmsgnum - 1;
	num_displayable = loadoldheaders(set_dir);
	amount_old = max_msgnum + 1; /* counts gaps as messages */

	/* start numbering at this number */
	amount_new = num_displayable + parsemail(set_mbox, use_stdin, set_readone, set_increment, set_dir, set_inlinehtml, amount_old);
	if (set_linkquotes)
	    analyze_headers(max_msgnum + 1);

	/* write the index of msgno/msgid_hash filenames */
	if (set_nonsequential)
		write_messageindex(0, max_msgnum + 1);

	writearticles(amount_old, max_msgnum + 1);

	/* JK: in function of other hypermail configuration options, 
	   delete_incremental will continuous escape and add more markup
	   to non-deleted messages that are replies to deleted messages.
	   Thus, a setup option to disable it */
	if (set_delete_incremental && deletedlist)
	    update_deletions(amount_old);

	if (set_show_msg_links) {
	    fixnextheader(set_dir, amount_old, -1);
	    for (i = amount_old; i <= max_msgnum; ++i) {
		if (set_showreplies)
		    fixreplyheader(set_dir, i, 0, amount_old);
		fixthreadheader(set_dir, i, amount_old);
	    }
	}
    }
    else {
	if (set_mbox_shortened) {
	    if (!set_usegdbm) progerr("mbox_shortened option requires that the usegdbm option be on");
	    max_msgnum = set_startmsgnum - 1;
	    loadoldheaders(set_dir);
	}
	amount_new = parsemail(set_mbox, use_stdin, set_readone, set_increment, set_dir, 
			       set_inlinehtml, set_startmsgnum);	/* number from 0 */
	if (!set_mbox_shortened && !matches_existing(0)) {
	    progerr("First message in mailbox does not "
		    "match first message in archive\n"
		    "or obsolete gdbm file present.\n"
		    "Maybe you want to enable the mbox_shortened option?\n");
	}
	if (set_linkquotes)
	    analyze_headers(max_msgnum + 1);

	/* write the index of msgno/msgid_hash filenames */
	if (set_nonsequential)
		write_messageindex(0, max_msgnum + 1);

	writearticles(0, max_msgnum + 1);
    }

    if (amount_new) {		/* Always write the index files */
	if (set_linkquotes) {
	    threadlist = NULL;
	    threadlist_end = NULL;
	    printedthreadlist = NULL;
	    for (i = 0; i <= max_msgnum; ++i) {
	        struct emailinfo *ep;
		if (hashnumlookup(i, &ep)) {
		    ep->flags &= ~USED_THREAD;
#ifdef FASTREPLYCODE
		    ep->isreply = 0;
#endif
		}
		threadlist_by_msgnum[i] = NULL;
	    } /* redo threading with more complete info than in 1st pass */
	    crossindexthread1(datelist);
	    for (i = 0; i <= max_msgnum; ++i) {
	        struct emailinfo *ep, *etmp;
		hashnumlookup(i, &ep);
		etmp = nextinthread(i);
		if (etmp && ep->initial_next_in_thread != etmp->msgnum)
		    fixthreadheader(set_dir, etmp->msgnum, amount_new);
		/* if (ep->flags & THREADING_ALTERED) */
	    }
	}
	count_deleted(max_msgnum + 1);
	if (show_index[0][DATE_INDEX])
	    writedates(amount_new, NULL);
	if (show_index[0][THREAD_INDEX])
	    writethreads(amount_new, NULL);
	if (show_index[0][SUBJECT_INDEX])
	    writesubjects(amount_new, NULL);
	if (show_index[0][AUTHOR_INDEX])
	    writeauthors(amount_new, NULL);
	if (set_attachmentsindex) {
	    writeattachments(amount_new, NULL);
	}
	if (set_writehaof) 
            writehaof(amount_new, NULL);
	if (set_folder_by_date || set_msgsperfolder)
	    write_toplevel_indices(amount_new);
	if (set_monthly_index || set_yearly_index)
	    write_summary_indices(amount_new);
	if (set_latest_folder)
	    symlink_latest();
    }
    else {
	printf("No mails to output!\n");
    }

    if (set_uselock)
	unlock_archive();

    if (configfile)
	free(configfile);
    if (ihtmlheaderfile)
	free(ihtmlheaderfile);
    if (ihtmlfooterfile)
	free(ihtmlfooterfile);
    if (ihtmlheadfile)
	free(ihtmlheadfile);
    if (ihtmlhelpupfile)
	free(ihtmlhelpupfile);
    if (ihtmlhelplowfile)
	free(ihtmlhelplowfile);
    if (ihtmlnavbar2upfile)
	free(ihtmlnavbar2upfile);
    if (mhtmlheaderfile)
	free(mhtmlheaderfile);
    if (mhtmlfooterfile)
	free(mhtmlfooterfile);

    return (0);
}
Ejemplo n.º 12
0
int main(int argc, char *argv[])
{
#ifdef _USE_UNPACK
	int clean_tmp = 0;
#endif
	int err = 0;
	int i;
#ifdef __APPLE__
	macosx_init();
#endif
#ifndef S60
	putenv("SDL_MOUSE_RELATIVE=0"); /* test this! */
#endif

#ifdef _WIN32_WCE
	libwince_init(argv[0], 1);
	wince_init(argv[0]);
#else
#ifdef S60
	extern char s60_data[];
	strcpy(game_cwd, s60_data);
#else
#ifdef _WIN32
	strcpy(game_cwd, dirname(argv[0]));
#else
	if (!getcwd(game_cwd, sizeof(game_cwd)))
		fprintf(stderr,"Warning: can not get current dir\n.");
#endif
#endif
#endif
	unix_path(game_cwd);
	setdir(game_cwd);

	for (i = 1; i < argc; i++) {
		if (!strcmp(argv[i], "-vsync"))
			vsync_sw = 1;
		else if (!strcmp(argv[i], "-nosound"))
			nosound_sw = 1;
		else if (!strcmp(argv[i], "-fullscreen"))
			fullscreen_sw = 1;
		else if (!strcmp(argv[i], "-mode")) {	
			if ((i + 1) < argc)
				mode_sw = argv[++i];
			else
				mode_sw = "-1x-1";
		} else if (!strcmp(argv[i], "-window"))
			window_sw = 1;
		else if (!strcmp(argv[i], "-debug")) {
			if (!debug_sw)
				debug_init();
			debug_sw = 1;
		} else if (!strcmp(argv[i], "-owntheme"))
			owntheme_sw = 1;
		else if (!strcmp(argv[i], "-noautosave"))
			noauto_sw = 1;
		else if (!strcmp(argv[i], "-game")) {
			if ((i + 1) < argc)
				game_sw = argv[++i];
			else
				game_sw = "";
		} else if (!strcmp(argv[i], "-theme")) {
			if ((i + 1) < argc)
				theme_sw = argv[++i];
			else
				theme_sw = "";
		} else if (!strcmp(argv[i], "-nostdgames")) {
			nostdgames_sw = 1;
#ifdef _LOCAL_APPDATA
		} else if (!strcmp(argv[i], "-appdata")) {
			if ((i + 1) < argc)
				appdata_sw = argv[++i];
			else
				appdata_sw = "";
#endif
		} else if (!strcmp(argv[i], "-chunksize")) {
			if ((i + 1) < argc)
				chunksize_sw = atoi(argv[++i]);
			else
				chunksize_sw = DEFAULT_CHUNKSIZE;
		} else if (!strcmp(argv[i], "-gamespath")) {
			if ((i + 1) < argc)
				games_sw = argv[++i];
			else
				games_sw = "";
		} else if (!strcmp(argv[i], "-themespath")) {
			if ((i + 1) < argc)
				themes_sw = argv[++i];
			else
				themes_sw = "";
		} else if (!strcmp(argv[i], "-idf")) {	
			if ((i + 1) < argc)
				idf_sw = argv[++i];
			else {
				fprintf(stderr,"No data directory specified.\n");
				err = 1;
				goto out;
			}
		} else if (!strcmp(argv[i], "-encode")) {	
			if ((i + 1) < argc)
				encode_sw = argv[++i];
			else {
				fprintf(stderr,"No lua file specified.\n");
				err = 1;
				goto out;
			}
			if ((i + 1) < argc)
				encode_output = argv[++i];
			else
				encode_output = "lua.enc";
		} else if (!strcmp(argv[i], "-version")) {
			version_sw = 1;
		} else if (!strcmp(argv[i], "-nopause")) {
			nopause_sw = 1;
		} else if (!strcmp(argv[i], "-software")) {
			software_sw = 1;
#ifdef _USE_UNPACK
		} else if (!strcmp(argv[i], "-install")) {
			if ((i + 1) < argc) {
				char *file = argv[++i];
				char *p;
				if (games_sw)
					p = games_sw;
				else
					p = game_local_games_path(1);
				if (setup_zip(file, p)) {
					err = 1;
					goto out;
				}
			}
#endif
		} else if (!strcmp(argv[i], "-quit")) {
			exit(0);
		} else if (!strcmp(argv[i], "-hinting")) {
			if ((i + 1) < argc)
				hinting_sw = atoi(argv[++i]);
			else
				hinting_sw = 1;
		} else if (!strcmp(argv[i], "-lua") || !strcmp(argv[i], "-luac")) {
			if ((i + 1) < argc) {
				lua_exec = !strcmp(argv[i], "-lua");
				lua_sw = argv[++ i];
				opt_index = i + 1;
				break;
			} else {
				fprintf(stderr, "No lua script.\n");
				err = 1;
				goto out;
			}
		} else if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "-help")
			|| !strcmp(argv[i], "--help")) {
			usage();
			goto out;
		} else if (argv[i][0] == '-') {
			fprintf(stderr,"Unknown option: %s\n", argv[i]);
			usage();
			err = 1;
			goto out;
		} else if (!start_idf(argv[i])) {
			fprintf(stderr, "Adding idf: %s\n", argv[i]);
		} else if (!run_game(argv[i])) {
			fprintf(stderr, "Opening game: %s\n", argv[i]);
		}
#ifdef _USE_UNPACK
		else {
			char *p;
			if (games_sw)
				p = games_sw;
			else
				p = game_tmp_path();
			if (setup_zip(argv[i], p)) {
				err = 1;
				goto out;
			}
			clean_tmp = 1;
		}
#endif
	}
	cfg_load();

	if (opt_debug == 1 && debug_sw == 0) {
		debug_sw = 1;
		debug_init();
	}

	if (opt_vsync == 1 && vsync_sw == 0)
		vsync_sw = 1;

	if (version_sw) {
		fprintf(stdout, VERSION"\n");
		goto out;
	}

	if (lua_sw) {
		err = instead_init_lua(dirname(lua_sw));
		if (err)
			goto out;
		if (!err)
			err = instead_loadscript(lua_sw,
				argc - opt_index,
				argv + opt_index,
				lua_exec);
		instead_done();
		goto out;
	}

	if (encode_sw) {
		err = instead_encode(encode_sw, encode_output);
		goto out;
	}

	if (idf_sw) {
		char *p = malloc(strlen(idf_sw) + 5);
		if (p) {
			char *b;
			strcpy(p, idf_sw);
			b = basename(p);
			strcat(b, ".idf");
			idf_create(b, idf_sw);
			free(p);
		} else
			idf_create("data.idf", idf_sw);
		goto out;
	}
	menu_langs_lookup(dirpath(LANG_PATH));
	
	if (!langs_nr) {
		fprintf(stderr, "No languages found in: %s.\n", dirpath(LANG_PATH));
		err = 1;
		goto out;
	}
	if (!opt_lang || !opt_lang[0])
		opt_lang = game_locale();
	
	if (menu_lang_select(opt_lang) && menu_lang_select(LANG_DEF)) {
		fprintf(stderr, "Can not load default language.\n");
		err = 1;
		goto out;
	}
	
	if (games_sw)
		games_lookup(games_sw);

	if (owntheme_sw && !opt_owntheme) {
		opt_owntheme = 2;
	}

	if (!nostdgames_sw && games_lookup(dirpath(GAMES_PATH)))
		fprintf(stderr, "No games found in: %s.\n", GAMES_PATH);

	if (themes_sw)
		themes_lookup(themes_sw);

	if (!nostdthemes_sw) {
		themes_lookup(dirpath(THEMES_PATH));
		themes_lookup(game_local_themes_path());
	}
	
	if (!nostdgames_sw)
		games_lookup(game_local_games_path(0));

	if (start_idf_sw) {
		char *d, *b;
		char *dd, *bb;
		static char idf_game[255];
		d = strdup(start_idf_sw);
		b = strdup(start_idf_sw);
		if (d && b) {
			dd = dirname(d);
			bb = basename(b);
			if (!games_replace(dirpath(dd), bb)) {
				game_sw = idf_game;
				strncpy(idf_game, bb, sizeof(idf_game) - 1);
				idf_game[sizeof(idf_game) - 1] = 0;
			}
		}
		if (d)
			free(d); 
		if (b)
			free(b);
	}

	if (noauto_sw && opt_autosave)
		opt_autosave = 2;
	if (window_sw)
		opt_fs = 0;
	if (fullscreen_sw)
		opt_fs = 1;
	
	if (mode_sw)
		parse_mode(mode_sw, opt_mode);
	
	if (game_sw) {
		FREE(opt_game);
		opt_game = game_sw;
	}	

	if (theme_sw) {
		FREE(opt_theme);
		opt_theme = theme_sw;
	}	
	
	if (opt_theme)
		game_theme_select(opt_theme);
	if (!curtheme_dir)
		game_theme_select(DEFAULT_THEME);
	
	/* Initialize SDL */
	if (gfx_init() < 0)
		return -1;
#ifdef _USE_GTK
	gtk_init(&argc, &argv); /* must be called AFTER SDL_Init when using SDL2 */
#endif
	if (gfx_video_init() || input_init())
		return -1;

	if (game_init(opt_game)) {
		game_error();
	}

	game_loop();
	cfg_save();
	game_done(0);

	gfx_video_done();

#ifndef ANDROID
	gfx_done();
#endif
out:
	if (debug_sw)
		debug_done();
#ifdef _USE_GTK
/*	gtk_main_quit (); */
#endif
#ifdef _USE_UNPACK
	if (clean_tmp)
		remove_dir(game_tmp_path());
#endif
#if defined(ANDROID) || defined(IOS)
	exit(err);
#endif
	return err;
}
Ejemplo n.º 13
0
int main(int argc, char** argv)
{

  if (argc < 5)
  {
    PCL17_INFO ("Usage %s -input_dir /dir/with/models -output_dir /output/dir [options]\n", argv[0]);
    PCL17_INFO (" * where options are:\n"
        "         -height <X>            : simulate scans with sensor mounted on height X\n"
        "         -noise_std <X>         : std of gaussian noise added to pointcloud. Default value 0.0001.\n"
        "         -distance <X>          : simulate scans with object located on a distance X. Can be used multiple times. Default value 4.\n"
        "         -tilt <X>              : tilt sensor for X degrees. X == 0 - sensor looks strait. X < 0 Sensor looks down. X > 0 Sensor looks up . Can be used multiple times. Default value -15.\n"
        "         -shift <X>             : shift object from the straight line. Can be used multiple times. Default value 0.\n"
        "         -num_views <X>         : how many times rotate the object in for every distance, tilt and shift. Default value 6.\n"

        "");
    return -1;
  }

  std::string input_dir, output_dir;
  double height = 1.5;
  double num_views = 6;
  double noise_std = 0.0001;
  std::vector<double> distances;
  std::vector<double> tilt;
  std::vector<double> shift;
  int full_model_n_points = 30000;

  pcl17::console::parse_argument(argc, argv, "-input_dir", input_dir);
  pcl17::console::parse_argument(argc, argv, "-output_dir", output_dir);
  pcl17::console::parse_argument(argc, argv, "-num_views", num_views);
  pcl17::console::parse_argument(argc, argv, "-height", height);
  pcl17::console::parse_argument(argc, argv, "-noise_std", noise_std);
  pcl17::console::parse_multiple_arguments(argc, argv, "-distance", distances);
  pcl17::console::parse_multiple_arguments(argc, argv, "-tilt", tilt);
  pcl17::console::parse_multiple_arguments(argc, argv, "-shift", shift);

  PCL17_INFO("distances size: %d\n", distances.size());
  for (size_t i = 0; i < distances.size(); i++)
  {
    PCL17_INFO("distance: %f\n", distances[i]);
  }

  // Set default values if user didn't provide any
  if (distances.size() == 0)
    distances.push_back(4);
  if (tilt.size() == 0)
    tilt.push_back(-15);
  if (shift.size() == 0)
    shift.push_back(0);

  // Check if input path exists
  boost::filesystem::path input_path(input_dir);
  if (!boost::filesystem::exists(input_path))
  {
    PCL17_ERROR("Input directory doesnt exists.");
    return -1;
  }

  // Check if input path is a directory
  if (!boost::filesystem::is_directory(input_path))
  {
    PCL17_ERROR("%s is not directory.", input_path.c_str());
    return -1;
  }

  // Check if output directory exists
  boost::filesystem::path output_path(output_dir);
  if (!boost::filesystem::exists(output_path) || !boost::filesystem::is_directory(output_path))
  {
    if (!boost::filesystem::create_directories(output_path))
    {
      PCL17_ERROR ("Error creating directory %s.\n", output_path.c_str ());
      return -1;
    }
  }

  // Find all .vtk files in the input directory
  std::vector<std::string> files_to_process;
  PCL17_INFO("Processing following files:\n");
  boost::filesystem::directory_iterator end_iter;
  for (boost::filesystem::directory_iterator iter(input_path); iter != end_iter; iter++)
  {
    boost::filesystem::path class_dir_path(*iter);
    for (boost::filesystem::directory_iterator iter2(class_dir_path); iter2 != end_iter; iter2++)
    {
      boost::filesystem::path file(*iter2);
      if (file.extension() == ".vtk")
      {
        files_to_process.push_back(file.c_str());
        PCL17_INFO("\t%s\n", file.c_str());
      }
    }

  }

  // Check if there are any .vtk files to process
  if (files_to_process.size() == 0)
  {
    PCL17_ERROR("Directory %s has no .vtk files.", input_path.c_str());
    return -1;
  }

  // Iterate over all files
  for (size_t i = 0; i < files_to_process.size(); i++)
  {
    vtkSmartPointer<vtkPolyData> model;
    vtkSmartPointer<vtkPolyDataReader> reader = vtkPolyDataReader::New();
    vtkSmartPointer<vtkTransform> transform = vtkTransform::New();
    pcl17::PointCloud<pcl17::PointXYZ>::Ptr cloud(new pcl17::PointCloud<pcl17::PointXYZ>());

    // Compute output directory for this model
    std::vector<std::string> st;
    boost::split(st, files_to_process.at(i), boost::is_any_of("/"), boost::token_compress_on);
    std::string class_dirname = st.at(st.size() - 2);
    std::string dirname = st.at(st.size() - 1);
    dirname = dirname.substr(0, dirname.size() - 4);
    dirname = output_dir + class_dirname + "/" + dirname;

    // Check if output directory for this model exists. If not create
    boost::filesystem::path dirpath(dirname);
    if (!boost::filesystem::exists(dirpath))
    {
      if (!boost::filesystem::create_directories(dirpath))
      {
        PCL17_ERROR ("Error creating directory %s.\n", dirpath.c_str ());
        return -1;
      }
    }

    // Load model from file
    reader->SetFileName(files_to_process.at(i).c_str());
    reader->Update();
    model = reader->GetOutput();
    PCL17_INFO("Number of points %d\n",model->GetNumberOfPoints());

    // Coumpute bounds and center of the model
    double bounds[6];
    model->GetBounds(bounds);
    double min_z_value = bounds[4];

    double center[3];
    model->GetCenter(center);

    createFullModelPointcloud(model, full_model_n_points, *cloud);
    pcl17::io::savePCDFile(dirname + "/full.pcd", *cloud);

    // Initialize PCLVisualizer. Add model to scene.
    pcl17::visualization::PCLVisualizer viz;
    viz.initCameraParameters();
    viz.updateCamera();
    viz.setCameraPosition(0, 0, 0, 1, 0, 0, 0, 0, 1);
    viz.addModelFromPolyData(model, transform);
    viz.setRepresentationToSurfaceForAllActors();

    // Iterate over all shifts
    for (size_t shift_index = 0; shift_index < shift.size(); shift_index++)
    {

      // Iterate over all tilts
      for (size_t tilt_index = 0; tilt_index < tilt.size(); tilt_index++)
      {

        // Iterate over all distances
        for (size_t distance_index = 0; distance_index < distances.size(); distance_index++)
        {

          // Iterate over all angles
          double angle = 0;
          double angle_step = 360.0 / num_views;
          for (int angle_index = 0; angle_index < num_views; angle_index++)
          {

            // Set transformation with distance, shift, tilt and angle parameters.
            transform->Identity();
            transform->RotateY(tilt[tilt_index]);
            transform->Translate(distances[distance_index], shift[shift_index], -(height + min_z_value));
            transform->RotateZ(angle);

		/*		

            // Render pointcloud
            viz.renderView(640, 480, cloud);

            //Add noise
            addNoise(cloud, noise_std);

            // Compute new coordinates of the model center
            double new_center[3];
            transform->TransformPoint(center, new_center);

            // Shift origin of the poincloud to the model center and align with initial coordinate system.
            pcl17::PointCloud<pcl17::PointXYZ>::Ptr cloud_transformed(new pcl17::PointCloud<pcl17::PointXYZ>());
            moveToNewCenterAndAlign(cloud, cloud_transformed, new_center, tilt[tilt_index]);

            // Compute file name for this pointcloud and save it
            std::stringstream ss;
            ss << dirname << "/rotation" << angle << "_distance" << distances[distance_index] << "_tilt"
                << tilt[tilt_index] << "_shift" << shift[shift_index] << ".pcd";
            PCL17_INFO("Writing %d points to file %s\n", cloud->points.size(), ss.str().c_str());
            pcl17::io::savePCDFile(ss.str(), *cloud_transformed);

		*/

            // increment angle by step
            angle += angle_step;
	
	

          }

        }
      }
    }

  }

  return 0;
}
Ejemplo n.º 14
0
static int detect_netkey(
	sc_pkcs15_card_t *p15card
){
	sc_card_t *card=p15card->card;
	sc_path_t p;
	sc_file_t *f;
	int keylen;
	char dir[10];
	const char *c_auth;

	/* NKS-Applikation ? */
	memset(&p, 0, sizeof(sc_path_t));
	p.type=SC_PATH_TYPE_DF_NAME;
	memcpy(p.value, "\xD2\x76\x00\x00\x03\x01\x02", p.len=7);
	if (sc_select_file(card,&p,&f)!=SC_SUCCESS) return 1;
	sprintf(dir,"%04X", f->id);
	sc_file_free(f);

	p15card->tokeninfo->manufacturer_id = strdup("TeleSec GmbH");
	p15card->tokeninfo->label = strdup(card->type==SC_CARD_TYPE_TCOS_V3 ? "NetKey V3 Card" : "NetKey Card");
	keylen= card->type==SC_CARD_TYPE_TCOS_V3 ? 2048 : 1024;
	c_auth= card->type==SC_CARD_TYPE_TCOS_V3 ? "C500" : "C100";

	insert_cert(p15card, dirpath(dir,"4331"), 0x45, 1, "Signatur Zertifikat 1");
	insert_cert(p15card, dirpath(dir,"4332"), 0x45, 1, "Signatur Zertifikat 2");
	insert_cert(p15card, dirpath(dir,"C000"), 0x45, 0, "Telesec Signatur Zertifikat");
	insert_cert(p15card, dirpath(dir,"43B1"), 0x46, 1, "Verschluesselungs Zertifikat 1");
	insert_cert(p15card, dirpath(dir,"43B2"), 0x46, 1, "Verschluesselungs Zertifikat 2");
	insert_cert(p15card, dirpath(dir,"C200"), 0x46, 0, "Telesec Verschluesselungs Zertifikat");
	insert_cert(p15card, dirpath(dir,"4371"), 0x47, 1, "Authentifizierungs Zertifikat 1");
	insert_cert(p15card, dirpath(dir,"4372"), 0x47, 1, "Authentifizierungs Zertifikat 2");
	insert_cert(p15card, dirpath(dir,c_auth), 0x47, 0, "Telesec Authentifizierungs Zertifikat");
	insert_cert(p15card, dirpath(dir,"C201"), 0x48, 0, "Telesec 1024bit Zertifikat");

	insert_key(p15card, dirpath(dir,"5331"), 0x45, 0x80, keylen, 4, "Signatur Schluessel");
	insert_key(p15card, dirpath(dir,"53B1"), 0x46, 0x81, keylen, 3, "Verschluesselungs Schluessel");
	insert_key(p15card, dirpath(dir,"5371"), 0x47, 0x82, keylen, 3, "Authentifizierungs Schluessel");
	insert_key(p15card, dirpath(dir,"0000"), 0x48, 0x83, 1024,   3, "1024bit Schluessel");

	insert_pin(p15card, "5000", 1, 2, 0x00, 6, "PIN",
		SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_INITIALIZED
	);
	insert_pin(p15card, "5001", 2, 0, 0x01, 8, "PUK",
		SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_INITIALIZED |
		SC_PKCS15_PIN_FLAG_UNBLOCKING_PIN | SC_PKCS15_PIN_FLAG_SO_PIN
	);
	if(card->type==SC_CARD_TYPE_TCOS_V3){
		insert_pin(p15card, dirpath(dir,"0000"), 3, 1, 0x83, 6, "NetKey PIN2",
			SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_LOCAL |
			SC_PKCS15_PIN_FLAG_INITIALIZED
		);
	} else {
		insert_pin(p15card, dirpath(dir,"5080"), 3, 1, 0x80, 6, "NetKey PIN0",
			SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_LOCAL |
			SC_PKCS15_PIN_FLAG_INITIALIZED
		);
	}
	insert_pin(p15card, dirpath(dir,"5081"), 4, 1, 0x81, 6, "NetKey PIN1",
		SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_LOCAL |
		SC_PKCS15_PIN_FLAG_INITIALIZED
	);

	/* SigG-Applikation */
	p.len=7; p.type=SC_PATH_TYPE_DF_NAME;
	memcpy(p.value, "\xD2\x76\x00\x00\x66\x01", p.len=6);
	if (sc_select_file(card,&p,&f)==SC_SUCCESS){
		sprintf(dir,"%04X", f->id);
		sc_file_free(f);

		insert_cert(p15card, dirpath(dir,"C000"), 0x49, 1, "SigG Zertifikat 1");
		insert_cert(p15card, dirpath(dir,"4331"), 0x49, 1, "SigG Zertifikat 2");
		insert_cert(p15card, dirpath(dir,"4332"), 0x49, 1, "SigG Zertifikat 3");
		
		if(card->type==SC_CARD_TYPE_TCOS_V3){
			insert_key(p15card, dirpath(dir,"0000"), 0x49, 0x84, 2048, 5, "SigG Schluessel");
		} else {
			insert_key(p15card, dirpath(dir,"5331"), 0x49, 0x80, 1024, 5, "SigG Schluessel");
		}

		insert_pin(p15card, dirpath(dir,"5081"), 5, 0, 0x81, 6, "SigG PIN",
			SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_LOCAL |
			SC_PKCS15_PIN_FLAG_INITIALIZED
		);
		if(card->type==SC_CARD_TYPE_TCOS_V3){
			insert_pin(p15card, dirpath(dir,"0000"), 6, 0, 0x83, 8, "SigG PIN2",
				SC_PKCS15_PIN_FLAG_CASE_SENSITIVE | SC_PKCS15_PIN_FLAG_LOCAL |
				SC_PKCS15_PIN_FLAG_INITIALIZED
			);
		}
	}

	return 0;
}
Ejemplo n.º 15
0
int main(int argc,char **argv)
{
	cout<<"dptest start..."<<endl;
	
	try {
		TOCIDatabase database;
		
		database.Connect("sett","fzsett","sett");
		
		cout<<"Connect database success"<<endl;
		system("date");
		time_t stime;
		time(&stime);
		int i,j;

	for (  j=0; j<10; j++){
		

		TOCIDirPath	dirpath(&database,"xzc_dp_test");
		
		dirpath.setSchameName("sett");
		
		cout<<"dirpath create success"<<endl;
		
		
		dirpath.prepare();
		
		cout<<"dirpath prepare ok"<<endl;
		
		char strTmp[256];
		

		for( i=0;i<100000;i++)
		{
		    /*if ( i && i%1000==0)
		        dirpath.save();
			*/
			sprintf(strTmp,"test%d",i);
			dirpath.append();
#if 1
			dirpath.setField("C1",strTmp);
			dirpath.setField("C2",(long)i);
			dirpath.setField("C3","19980601080000");
			dirpath.setField("C4",strTmp);
			dirpath.setField("C5",strTmp);
			dirpath.setField("C6",strTmp);
			dirpath.setField("C7",strTmp);
			dirpath.setField("C8",strTmp);
#else
			dirpath.setField((unsigned )0,strTmp);
			dirpath.setField((unsigned )1,i);
			dirpath.setField((unsigned )2,"19980601080000");
			dirpath.setField((unsigned )3,strTmp);
			dirpath.setField((unsigned )4,strTmp);
			dirpath.setField((unsigned )5,strTmp);
			dirpath.setField((unsigned )6,strTmp);
			dirpath.setField((unsigned )7,strTmp);

#endif
			/* */

			//dirpath.save();
	
			/*dirpath.finish();	
			dirpath.prepare();
			*/
		}
		
		cout<<"begin save"<<endl;

		dirpath.save();
		
		cout<<"begin finish"<<endl;

		dirpath.finish();	
		cout<<"finish!"<<endl;

	}
		time_t etime;
		time(&etime);

		int utime;
		utime = etime-stime;
		cout<<i*j<<" rows  loaded use time: "<<utime<<endl;

	}
	catch(TOCIException &oe)
	{
		cout<<"TOCIException catched"<<endl;
		cout<<oe.GetErrMsg()<<endl;		
		cout<<oe.GetErrSrc()<<endl;
	}
	catch(...)
	{
		cout<<"Exception occur"<<endl;
	}
	system("date");
	
	return 0;
}