Exemple #1
0
void				load_obj(t_object *obj, char *filename)
{
	int				fd;
	char			*line;

	ft_exit((fd = open(filename, O_RDONLY)) < 0, "Can't read file");
	obj->vertex_buffer_size = obj->index_buffer_size = obj->normal_buffer_size
	= obj->tex_buffer_size = 0;
	while (get_next_line(fd, &line) > 0)
	{
		if (ft_strlen(line) < 3 || line[0] == '#')
			;
		else if (line[0] == 'o')
			ft_strcpy((char *)obj->name, line + 2);
		else if (line[0] == 'v' && line[1] == ' ')
			load_vertex(obj, line + 1);
		else if (line[0] == 'v' && line[1] == 'n')
			load_normal(obj, line + 2);
		else if (line[0] == 'v' && line[1] == 't')
			load_tex(obj, line + 2);
		else if (line[0] == 'f' && line[1] == ' ')
			load_index(obj, line + 1);
		ft_memdel((void **)&line);
	}
	close(fd);
	print_obj(obj);
}
void tsFreePhoneImplementation::load_speech(CONFIG *config)
{
	if(strcmp(config->diphone_file,"-")) {
		load_index(config);  /* in alphabetical order  */
		load_diphs(config);
	}
}
int build_index(UCHAR *text, ULONG length, char *build_options, void **index){
  char delimiters[] = " =;";
  char filename[256];
  int j,num_parameters;
  char ** parameters;
  int rankb_w=16,rankb_w2=128;
  int free_text=false; /* don't free text by default */
  if (build_options != NULL) {
//    printf("build_options=%s\n",build_options);
    parse_parameters(build_options,&num_parameters, &parameters, delimiters);
    for (j=0; j<num_parameters;j++) {
      if ((strcmp(parameters[j], "samplerate") == 0 ) && (j < num_parameters-1) ) {
        rankb_w=atoi(parameters[j+1]);
        j++;
      } else if  ((strcmp(parameters[j], "samplepsi") == 0 ) && (j < num_parameters-1) ) {
        rankb_w2=atoi(parameters[j+1]);
        j++;
      } else if  ((strcmp(parameters[j], "filename") == 0 ) && (j < num_parameters-1) ) {
        strcpy(filename,parameters[j+1]);
        j++;
      } else if (strcmp(parameters[j], "free_text") == 0 )
        free_text=true;
    }
    free_parameters(num_parameters, &parameters);
  }

   int n=length;
   char fname1[128],fname2[128];

   /* make the SA */
   int  i,  *x, *p;
   int  k, l;
   p= (int *)malloc((n+1)*sizeof *p);
   x= (int *)malloc((n+1)*sizeof *x);
   if (! p || ! x) {
      return 1;
   }
   for ( i=0; i<n; i++) {
     x[i]=text[i];
   }
   l=0;
   k=UCHAR_MAX+1;

   suffixsort(x, p, n, k, l);
   free(x);
   p[0] = n;
   /* End Make SA */

   /* Œ³‚Ì•¶Žš—ñ‚Í 0..n-1 ‚Å n ”Ô–Ú‚É‚Í 0 ‚ª“ü‚éB
      p[0] ‚Í•K‚¸ n ‚É‚È‚éBp[1..n]‚É0..n-1‚ª“ü‚Á‚Ä‚¢‚éB*/
   for (i=0; i<=n; ++i) p[i]++;  /* p[1..n]‚É1..n‚ª“ü‚Á‚Ä‚¢‚éBp[0]=n+1*/

   sprintf(fname1,"%s.psi",filename);
   sprintf(fname2,"%s.idx",filename);
   csa_new(n,p,text,fname1,fname2,rankb_w,rankb_w2);
   free(p);
   if (free_text) free(text);
   load_index(filename, index);
   return 0;
}
int roadmap_tile_load (int fips, int tile_index, void **base, size_t *size) {

   if (tile_index == -1) return load_index(fips, base, size);

   if (!TS) {
      if (TS_fail) return -1;

      TS = NOPH_TileStorage_new();
      if (NOPH_TileStorage_initialize(TS) != 0) {
         NOPH_delete(TS);
		 TS = 0;
         TS_fail = 1;
         return -1;
      }
   }

   int store_id = NOPH_TileStorage_findTile(TS, fips, tile_index, (int *)size);
   if (store_id == -1) return -1;

   *base = malloc (*size);

   int res = NOPH_TileStorage_loadTile(TS, fips, tile_index, store_id, *base);

   if (res == -1) {
      free (*base);
      return -1;  
   }

   return 0;
}
	void bin_index_t::dir_node::validate_index() const
	{
		if(index_valid)return;
		load_index();
		index_valid=true;

	}
Exemple #6
0
int load_speech(CONFIG *config)
{

    if (load_index(config) != 0)  /* in alphabetical order  */
	return -1;
    if (load_diphs(config) != 0)
	return -1;
    return 0;
}
Exemple #7
0
/* usage:
 * t_res_database <res database info file> */
int main(int argc, char *argv[])
{
	if(argc != 2)
		return 1;
	std::string rifo_url(argv[1]);
	if(rifo_url.rfind(".rifo") != rifo_url.length() + 1 - sizeof(".rifo")) {
		std::cerr << "incorrect parameter, expecting .rifo file" << std::endl;
		return 1;
	}
	DictInfo dict_info;
	if (!dict_info.load_from_ifo_file(rifo_url, DictInfoType_ResDb))
		return 1;

	gulong filecount = dict_info.get_filecount();
	gulong indexfilesize = dict_info.get_index_file_size();

	std::unique_ptr<rindex_file> pindex;
	std::string base_url = rifo_url.substr(0, rifo_url.length() + 1 - sizeof(".rifo"));
	std::string ridx_url = base_url + ".ridx";
	index_type_t index_type;
	if(g_file_test(ridx_url.c_str(), G_FILE_TEST_EXISTS)) {
		pindex.reset(new offset_rindex);
		index_type = itRidx;
	} else {
		ridx_url = base_url + ".ridx.gz";
		if(g_file_test(ridx_url.c_str(), G_FILE_TEST_EXISTS)) {
			pindex.reset(new compressed_rindex);
			index_type = itRidxGz;
		} else {
			std::cerr << "index file not found" << std::endl;
			return 1;
		}
	}
	if(!pindex->load(ridx_url, filecount, indexfilesize, false)) {
		std::cerr << "unable to load index: " << ridx_url << std::endl;
		return 1;
	}
	index_vect_t index_vect;
	if(!load_index(ridx_url, index_vect, indexfilesize, filecount, index_type)) {
		std::cerr << "unable to read index: " << ridx_url << std::endl;
		return 1;
	}
	if(!lookup_test(index_vect, pindex.get())) {
		std::cerr << "test failed" << std::endl;
		return 1;
	}
	std::cout << "test passed" << std::endl;
	return 0;
}
Exemple #8
0
void load_dump(wp_dump *d, char *dump, char *loc, char *ploc, char *blocks) {
  d->fp = xfopen(dump, "r");
  d->block_map = load_block_map(blocks);

  load_index(&d->index, loc, ploc);
}
Exemple #9
0
int MAIN(int argc, char **argv)
	{
	int add_user = 0;
	int list_user= 0;
	int delete_user= 0;
	int modify_user= 0;
	char * user = NULL;

	char *passargin = NULL, *passargout = NULL;
	char *passin = NULL, *passout = NULL;
        char * gN = NULL;
	int gNindex = -1;
	char ** gNrow = NULL;
	int maxgN = -1;

	char * userinfo = NULL;

	int badops=0;
	int ret=1;
	int errors=0;
	int verbose=0;
	int doupdatedb=0;
	char *configfile=NULL;
	char *dbfile=NULL;
	CA_DB *db=NULL;
	char **pp ;
	int i;
	long errorline = -1;
	char *randfile=NULL;
#ifndef OPENSSL_NO_ENGINE
	char *engine = NULL;
#endif
	char *tofree=NULL;
	DB_ATTR db_attr;

#ifdef EFENCE
EF_PROTECT_FREE=1;
EF_PROTECT_BELOW=1;
EF_ALIGNMENT=0;
#endif

	apps_startup();

	conf = NULL;
	section = NULL;

	if (bio_err == NULL)
		if ((bio_err=BIO_new(BIO_s_file())) != NULL)
			BIO_set_fp(bio_err,stderr,BIO_NOCLOSE|BIO_FP_TEXT);

	argc--;
	argv++;
	while (argc >= 1 && badops == 0)
		{
		if	(strcmp(*argv,"-verbose") == 0)
			verbose++;
		else if	(strcmp(*argv,"-config") == 0)
			{
			if (--argc < 1) goto bad;
			configfile= *(++argv);
			}
		else if (strcmp(*argv,"-name") == 0)
			{
			if (--argc < 1) goto bad;
			section= *(++argv);
			}
		else if	(strcmp(*argv,"-srpvfile") == 0)
			{
			if (--argc < 1) goto bad;
			dbfile= *(++argv);
			}
		else if (strcmp(*argv,"-add") == 0)
			add_user=1;
		else if (strcmp(*argv,"-delete") == 0)
			delete_user=1;
		else if (strcmp(*argv,"-modify") == 0)
			modify_user=1;
		else if (strcmp(*argv,"-list") == 0)
			list_user=1;
		else if (strcmp(*argv,"-gn") == 0)
			{
			if (--argc < 1) goto bad;
			gN= *(++argv);
			}
		else if (strcmp(*argv,"-userinfo") == 0)
			{
			if (--argc < 1) goto bad;
			userinfo= *(++argv);
			}
		else if (strcmp(*argv,"-passin") == 0)
			{
			if (--argc < 1) goto bad;
			passargin= *(++argv);
			}
		else if (strcmp(*argv,"-passout") == 0)
			{
			if (--argc < 1) goto bad;
			passargout= *(++argv);
			}
#ifndef OPENSSL_NO_ENGINE
		else if (strcmp(*argv,"-engine") == 0)
			{
			if (--argc < 1) goto bad;
			engine= *(++argv);
			}
#endif

		else if (**argv == '-')
			{
bad:
			BIO_printf(bio_err,"unknown option %s\n",*argv);
			badops=1;
			break;
			}
		else 
			break;
	
		argc--;
		argv++;
		}

	if (dbfile && configfile)
		{
		BIO_printf(bio_err,"-dbfile and -configfile cannot be specified together.\n");
		badops = 1;
		}
	if (add_user+delete_user+modify_user+list_user != 1)
		{
		BIO_printf(bio_err,"Exactly one of the options -add, -delete, -modify -list must be specified.\n");
		badops = 1;
		}
	if (delete_user+modify_user+delete_user== 1 && argc <= 0)
		{
		BIO_printf(bio_err,"Need at least one user for options -add, -delete, -modify. \n");
		badops = 1;
		}
	if ((passin || passout) && argc != 1 )
		{
		BIO_printf(bio_err,"-passin, -passout arguments only valid with one user.\n");
		badops = 1;
		}

	if (badops)
		{
		for (pp=srp_usage; (*pp != NULL); pp++)
			BIO_printf(bio_err,"%s",*pp);

		BIO_printf(bio_err," -rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR);
		BIO_printf(bio_err,"                 load the file (or the files in the directory) into\n");
		BIO_printf(bio_err,"                 the random number generator\n");
		goto err;
		}

	ERR_load_crypto_strings();

#ifndef OPENSSL_NO_ENGINE
	setup_engine(bio_err, engine, 0);
#endif

	if(!app_passwd(bio_err, passargin, passargout, &passin, &passout))
		{
		BIO_printf(bio_err, "Error getting passwords\n");
		goto err;
		}

        if (!dbfile)
		{


	/*****************************************************************/
		tofree=NULL;
		if (configfile == NULL) configfile = getenv("OPENSSL_CONF");
		if (configfile == NULL) configfile = getenv("SSLEAY_CONF");
		if (configfile == NULL)
			{
			const char *s=X509_get_default_cert_area();
			size_t len;

#ifdef OPENSSL_SYS_VMS
			len = strlen(s)+sizeof(CONFIG_FILE);
			tofree=OPENSSL_malloc(len);
			strcpy(tofree,s);
#else
			len = strlen(s)+sizeof(CONFIG_FILE)+1;
			tofree=OPENSSL_malloc(len);
			BUF_strlcpy(tofree,s,len);
			BUF_strlcat(tofree,"/",len);
#endif
			BUF_strlcat(tofree,CONFIG_FILE,len);
			configfile=tofree;
			}

		VERBOSE BIO_printf(bio_err,"Using configuration from %s\n",configfile);
		conf = NCONF_new(NULL);
		if (NCONF_load(conf,configfile,&errorline) <= 0)
			{
			if (errorline <= 0)
				BIO_printf(bio_err,"error loading the config file '%s'\n",
					configfile);
			else
				BIO_printf(bio_err,"error on line %ld of config file '%s'\n"
					,errorline,configfile);
			goto err;
			}
		if(tofree)
			{
			OPENSSL_free(tofree);
			tofree = NULL;
			}

		if (!load_config(bio_err, conf))
			goto err;

	/* Lets get the config section we are using */
		if (section == NULL)
			{
			VERBOSE BIO_printf(bio_err,"trying to read " ENV_DEFAULT_SRP " in \" BASE_SECTION \"\n");

			section=NCONF_get_string(conf,BASE_SECTION,ENV_DEFAULT_SRP);
			if (section == NULL)
				{
				lookup_fail(BASE_SECTION,ENV_DEFAULT_SRP);
				goto err;
				}
			}
         
		if (randfile == NULL && conf)
	        	randfile = NCONF_get_string(conf, BASE_SECTION, "RANDFILE");

	
		VERBOSE BIO_printf(bio_err,"trying to read " ENV_DATABASE " in section \"%s\"\n",section);

		if ((dbfile=NCONF_get_string(conf,section,ENV_DATABASE)) == NULL)
			{
			lookup_fail(section,ENV_DATABASE);
			goto err;
			}

        	}
	if (randfile == NULL)
		ERR_clear_error();
       	else 
		app_RAND_load_file(randfile, bio_err, 0);

	VERBOSE BIO_printf(bio_err,"Trying to read SRP verifier file \"%s\"\n",dbfile);

	db = load_index(dbfile, &db_attr);
	if (db == NULL) goto err;

	/* Lets check some fields */
	for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++)
		{
		pp = sk_OPENSSL_PSTRING_value(db->db->data, i);
	
		if (pp[DB_srptype][0] == DB_SRP_INDEX)
			{
			maxgN = i;
			if (gNindex < 0 && gN != NULL && !strcmp(gN, pp[DB_srpid]))
				gNindex = i;

			print_index(db, bio_err, i, verbose > 1);
			}
		}
	
	VERBOSE BIO_printf(bio_err, "Database initialised\n");

	if (gNindex >= 0)
		{
		gNrow = sk_OPENSSL_PSTRING_value(db->db->data,gNindex);
		print_entry(db, bio_err, gNindex, verbose > 1, "Default g and N");
		}
	else if (maxgN > 0 && !SRP_get_default_gN(gN))
		{
		BIO_printf(bio_err, "No g and N value for index \"%s\"\n", gN);
		goto err;
		}
	else
		{
		VERBOSE BIO_printf(bio_err, "Database has no g N information.\n");
		gNrow = NULL;
		}
	

	VVERBOSE BIO_printf(bio_err,"Starting user processing\n");

	if (argc > 0)
		user = *(argv++) ;

	while (list_user || user)
		{
		int userindex = -1;
		if (user) 
			VVERBOSE BIO_printf(bio_err, "Processing user \"%s\"\n", user);
		if ((userindex = get_index(db, user, 'U')) >= 0)
			{
			print_user(db, bio_err, userindex, (verbose > 0) || list_user);
			}
		
		if (list_user)
			{
			if (user == NULL)
				{
				BIO_printf(bio_err,"List all users\n");

				for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++)
					{
					print_user(db,bio_err, i, 1);
					}
				list_user = 0;
				}
			else if (userindex < 0)
				{
				BIO_printf(bio_err, "user \"%s\" does not exist, ignored. t\n",
					   user);
				errors++;
				}
			}
		else if (add_user)
			{
			if (userindex >= 0)
				{
				/* reactivation of a new user */
				char **row = sk_OPENSSL_PSTRING_value(db->db->data, userindex);
				BIO_printf(bio_err, "user \"%s\" reactivated.\n", user);
				row[DB_srptype][0] = 'V';

				doupdatedb = 1;
				}
			else
				{
				char *row[DB_NUMBER] ; char *gNid;
				row[DB_srpverifier] = NULL;
				row[DB_srpsalt] = NULL;
				row[DB_srpinfo] = NULL;
				if (!(gNid = srp_create_user(user,&(row[DB_srpverifier]), &(row[DB_srpsalt]),gNrow?gNrow[DB_srpsalt]:gN,gNrow?gNrow[DB_srpverifier]:NULL, passout, bio_err,verbose)))
					{
						BIO_printf(bio_err, "Cannot create srp verifier for user \"%s\", operation abandoned .\n", user);
						errors++;
						goto err;
					}
				row[DB_srpid] = BUF_strdup(user);
				row[DB_srptype] = BUF_strdup("v");
				row[DB_srpgN] = BUF_strdup(gNid);

				if (!row[DB_srpid] || !row[DB_srpgN] || !row[DB_srptype] || !row[DB_srpverifier] || !row[DB_srpsalt] ||
					(userinfo && (!(row[DB_srpinfo] = BUF_strdup(userinfo)))) || 
					!update_index(db, bio_err, row))
					{
					if (row[DB_srpid]) OPENSSL_free(row[DB_srpid]);
					if (row[DB_srpgN]) OPENSSL_free(row[DB_srpgN]);
					if (row[DB_srpinfo]) OPENSSL_free(row[DB_srpinfo]);
					if (row[DB_srptype]) OPENSSL_free(row[DB_srptype]);
					if (row[DB_srpverifier]) OPENSSL_free(row[DB_srpverifier]);
					if (row[DB_srpsalt]) OPENSSL_free(row[DB_srpsalt]);
					goto err;
					}
				doupdatedb = 1;
				}
			}
		else if (modify_user)
			{
			if (userindex < 0)
				{
				BIO_printf(bio_err,"user \"%s\" does not exist, operation ignored.\n",user);
				errors++;
				}
			else
				{

				char **row = sk_OPENSSL_PSTRING_value(db->db->data, userindex);
				char type = row[DB_srptype][0];
				if (type == 'v')
					{
					BIO_printf(bio_err,"user \"%s\" already updated, operation ignored.\n",user);
					errors++;
					}
				else
					{
					char *gNid;

					if (row[DB_srptype][0] == 'V')
						{
						int user_gN;
						char **irow = NULL;
						VERBOSE BIO_printf(bio_err,"Verifying password for user \"%s\"\n",user);
						if ( (user_gN = get_index(db, row[DB_srpgN], DB_SRP_INDEX)) >= 0)
							irow = (char **)sk_OPENSSL_PSTRING_value(db->db->data, userindex);

 						if (!srp_verify_user(user, row[DB_srpverifier], row[DB_srpsalt], irow ? irow[DB_srpsalt] : row[DB_srpgN], irow ? irow[DB_srpverifier] : NULL, passin, bio_err, verbose))
							{
							BIO_printf(bio_err, "Invalid password for user \"%s\", operation abandoned.\n", user);
							errors++;
							goto err;
							}
						} 
					VERBOSE BIO_printf(bio_err,"Password for user \"%s\" ok.\n",user);

					if (!(gNid=srp_create_user(user,&(row[DB_srpverifier]), &(row[DB_srpsalt]),gNrow?gNrow[DB_srpsalt]:NULL, gNrow?gNrow[DB_srpverifier]:NULL, passout, bio_err,verbose)))
						{
						BIO_printf(bio_err, "Cannot create srp verifier for user \"%s\", operation abandoned.\n", user);
						errors++;
						goto err;
						}

					row[DB_srptype][0] = 'v';
					row[DB_srpgN] = BUF_strdup(gNid);
 
					if (!row[DB_srpid] || !row[DB_srpgN] || !row[DB_srptype] || !row[DB_srpverifier] || !row[DB_srpsalt] ||
						(userinfo && (!(row[DB_srpinfo] = BUF_strdup(userinfo)))))  
						goto err;

					doupdatedb = 1;
					}
				}
			}
		else if (delete_user)
			{
			if (userindex < 0)
				{
				BIO_printf(bio_err, "user \"%s\" does not exist, operation ignored. t\n", user);
				errors++;
				}
			else
				{
				char **xpp = sk_OPENSSL_PSTRING_value(db->db->data,userindex);
				BIO_printf(bio_err, "user \"%s\" revoked. t\n", user);

				xpp[DB_srptype][0] = 'R';
				
				doupdatedb = 1;
				}
			}
		if (--argc > 0)
			user = *(argv++) ;
		else
			{
			user = NULL;
			list_user = 0;
			}
		}

	VERBOSE BIO_printf(bio_err,"User procession done.\n");


	if (doupdatedb)
		{
		/* Lets check some fields */
		for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++)
			{
			pp = sk_OPENSSL_PSTRING_value(db->db->data,i);
	
			if (pp[DB_srptype][0] == 'v')
				{
				pp[DB_srptype][0] = 'V';
				print_user(db, bio_err, i, verbose);
				}
			}

		VERBOSE BIO_printf(bio_err, "Trying to update srpvfile.\n");
		if (!save_index(dbfile, "new", db)) goto err;
				
		VERBOSE BIO_printf(bio_err, "Temporary srpvfile created.\n");
		if (!rotate_index(dbfile, "new", "old")) goto err;

		VERBOSE BIO_printf(bio_err, "srpvfile updated.\n");
		}

	ret = (errors != 0);
err:
	if (errors != 0)
	VERBOSE BIO_printf(bio_err,"User errors %d.\n",errors);

	VERBOSE BIO_printf(bio_err,"SRP terminating with code %d.\n",ret);
	if(tofree)
		OPENSSL_free(tofree);
	if (ret) ERR_print_errors(bio_err);
	if (randfile) app_RAND_write_file(randfile, bio_err);
	if (conf) NCONF_free(conf);
	if (db) free_index(db);

	OBJ_cleanup();
	apps_shutdown();
	OPENSSL_EXIT(ret);
	}
Exemple #10
0
static struct args *parse_args(unsigned int argc, char **argv, FILE *output) {
    struct args *args;
    int err = 0,
        quiet = 0,
        id;
    long int num;                /* temporary space for numeric conversion */
    char *tmp;                   /* temporary space */
    unsigned int ind;
    const char *arg;
    struct getlongopt *parser;
    enum getlongopt_ret ret = GETLONGOPT_OK;

    struct getlongopt_opt opts[] = {
        {"file", 'f', GETLONGOPT_ARG_REQUIRED, OPT_FILE},
        {"file-list", 'F', GETLONGOPT_ARG_REQUIRED, OPT_FILELIST},
        {"number-results", 'n', GETLONGOPT_ARG_REQUIRED, OPT_NUMRESULTS},
        {"runid", 'r', GETLONGOPT_ARG_REQUIRED, OPT_RUNID},
        {"print-queries", '\0', GETLONGOPT_ARG_NONE, OPT_PRINTQUERIES},
        {"timing", '\0', GETLONGOPT_ARG_NONE, OPT_TIMING},

        {"okapi", 'o', GETLONGOPT_ARG_NONE, OPT_OKAPI},
        {"dirichlet", '\0', GETLONGOPT_ARG_REQUIRED, OPT_DIRICHLET},
        {"hawkapi", '\0', GETLONGOPT_ARG_REQUIRED, OPT_HAWKAPI},
        {"k1", '1', GETLONGOPT_ARG_REQUIRED, OPT_K1},
        {"k3", '3', GETLONGOPT_ARG_REQUIRED, OPT_K3},
        {"b", 'b', GETLONGOPT_ARG_REQUIRED, OPT_B},
        {"pivoted-cosine", 'p', GETLONGOPT_ARG_REQUIRED, OPT_PIVOTED_COSINE},
        {"cosine", 'c', GETLONGOPT_ARG_NONE, OPT_COSINE},
        {"anh-impact", '\0', GETLONGOPT_ARG_NONE, OPT_ANH_IMPACT},

        {"title", 't', GETLONGOPT_ARG_NONE, OPT_TITLE},
        {"description", 'd', GETLONGOPT_ARG_NONE, OPT_DESCRIPTION},
        {"narrative", 'a', GETLONGOPT_ARG_NONE, OPT_NARRATIVE},
        {"qrels", 'q', GETLONGOPT_ARG_REQUIRED, OPT_QRELS},
        {"accumulator-limit", 'A', GETLONGOPT_ARG_REQUIRED, 
            OPT_ACCUMULATOR_LIMIT},
        {"ignore-version", '\0', GETLONGOPT_ARG_NONE, OPT_IGNORE_VERSION},

        {"help", 'h', GETLONGOPT_ARG_NONE, OPT_HELP},
        {"version", 'v', GETLONGOPT_ARG_NONE, OPT_VERSION},
        {"memory", 'm', GETLONGOPT_ARG_REQUIRED, OPT_MEMORY},
        {"parse-buffer", 'm', GETLONGOPT_ARG_REQUIRED, OPT_PARSEBUF},
        {"tablesize", 'm', GETLONGOPT_ARG_REQUIRED, OPT_TABLESIZE},
        {"big-and-fast", 'm', GETLONGOPT_ARG_NONE, OPT_BIG_AND_FAST},
        {"phrase", '\0', GETLONGOPT_ARG_OPTIONAL, OPT_PHRASE},
        {"term-cutoff", '\0', GETLONGOPT_ARG_REQUIRED, OPT_CUTOFF},
        {"dummy", '\0', GETLONGOPT_ARG_NONE, OPT_DUMMY},
        {"non-stop", '\0', GETLONGOPT_ARG_NONE, OPT_NONSTOP},
        {"query-stop", '\0', GETLONGOPT_ARG_OPTIONAL, OPT_STOP},
        {NULL, 'V', GETLONGOPT_ARG_NONE, OPT_VERSION}
    };

    if ((args = malloc(sizeof(*args))) 
      && (parser = getlongopt_new(argc - 1, (const char **) &argv[1], opts, 
          sizeof(opts) / sizeof(*opts)))) {
        /* succeeded, do nothing */
    } else {
        if (args) {
            free(args);
        }
        fprintf(output, "failed to initialise option parsing\n");
        return NULL;
    }

    args->stoplist = NULL;
    args->topic_files = 0;
    args->topic_file = NULL;
    args->run_id = NULL;
    args->idx = NULL;
    args->numresults = 0;
    args->numaccumulators = 0;
    args->sopts = INDEX_SEARCH_NOOPT;
    args->lopts = INDEX_LOAD_NOOPT;
    args->title = 0;
    args->descr = 0;
    args->narr = 0;
    args->qrels = NULL;
    args->sopt.u.okapi_k3.k1 = 1.2F;
    args->sopt.u.okapi_k3.k3 = 1e10;
    args->sopt.u.okapi_k3.b = 0.75;
    args->lopt.docmap_cache = DOCMAP_CACHE_TRECNO;
    args->print_queries = args->timing = 0;
    args->memory = MEMORY_DEFAULT;
    args->phrase = 0;
    args->cutoff = 0;
    args->dummy = 0;
    args->cont = 0;

    /* parse arguments */
    while (!err 
      && ((ret = getlongopt(parser, &id, &arg)) == GETLONGOPT_OK)) {
        switch (id) {
        case OPT_RUNID:
            /* set run_id */
            if (!args->run_id) {
                if (!(args->run_id = str_dup(arg))) {
                    fprintf(output, "couldn't set run_id '%s': %s\n", arg, 
                      strerror(errno));
                    err = quiet = 1;
                }
            } else if (args->run_id) {
                fprintf(output, "run_id already set to '%s'\n", args->run_id);
                err = 1;
                quiet = 0;
            }
            break;

        case OPT_STOP:
            if (args->stoplist) {
                err = 1;
                fprintf(output, "query stoplist specified multiple times\n");
                quiet = 0;
            } else if (!arg || (args->stoplist = str_dup(arg))) {
                args->lopts |= INDEX_LOAD_QSTOP;
                args->lopt.qstop_file = args->stoplist;
            } else {
                err = quiet = 1;
                fprintf(output, "can't copy query stoplist name\n");
            } 
            break;

        case OPT_MEMORY:
            /* set memory */
            args->memory = atoi(arg);
            break;

        case OPT_PARSEBUF:
            errno = 0;
            num = strtol(arg, &tmp, 10);
            if (!errno && (num > 0) && (num <= UINT_MAX) && !*tmp) {
                args->lopts |= INDEX_LOAD_PARSEBUF;
                args->lopt.parsebuf = num;
            } else {
                fprintf(output, "error converting parsebuf value '%s'\n", 
                  arg);
                err = 1;
            }
            break;

        case OPT_TABLESIZE:
            errno = 0;
            num = strtol(arg, &tmp, 10);
            if (!errno && (num > 0) && (num <= UINT_MAX) && !*tmp) {
                args->lopts |= INDEX_LOAD_TABLESIZE;
                args->lopt.tablesize = num;
            } else {
                fprintf(output, "error converting tablesize value '%s'\n", 
                  arg);
                err = 1;
            }
            break;

        case OPT_BIG_AND_FAST:
            /* use big memory options */
            if (args->memory == MEMORY_DEFAULT) {
                args->memory = BIG_MEMORY_DEFAULT;
            }
            if (!(args->lopts & INDEX_NEW_PARSEBUF)) {
                args->lopts |= INDEX_LOAD_PARSEBUF;
                args->lopt.parsebuf = BIG_PARSE_BUFFER;
            }
            if (!(args->lopts & INDEX_NEW_TABLESIZE)) {
                args->lopts |= INDEX_LOAD_TABLESIZE;
                args->lopt.tablesize = BIG_TABLESIZE;
            }
            break;

        case OPT_QRELS:
            /* they want it evaluated against some qrels */
            if (!args->qrels) {
                if ((args->qrels = treceval_qrels_new(arg))) {
                    /* succeeded, do nothing */
                } else {
                    fprintf(output, "failed to load qrels from '%s'\n", arg);
                    err = 1;
                }
            } else {
                fprintf(output, "qrels specified multiple times\n");
                err = 1;
            }
            break;

        case OPT_IGNORE_VERSION:
            args->lopts |= INDEX_LOAD_IGNORE_VERSION;
            break;

        case OPT_ACCUMULATOR_LIMIT:
            /* set number of accumulators to use. */
            errno = 0;
            num = strtol(arg, &tmp, 10);
            if (!errno && !*tmp) {
                args->sopt.accumulator_limit = num;
                args->sopts |= INDEX_SEARCH_ACCUMULATOR_LIMIT;
            } else {
                fprintf(output, 
                  "error converting accumulator limit value '%s'\n", arg);
                err = 1;
            }
            break;

        case OPT_NONSTOP:
            args->cont = 1;
            break;

        case OPT_DUMMY:
            args->dummy = 1;
            break;

        case OPT_CUTOFF:
            args->cutoff = atoi(arg);
            break;

        case OPT_PHRASE:
            /* they want to run it as a phrase, optionally sloppy */
            args->phrase = 1;
            if (arg) {
                char *end;
                long int tmpnum = strtol(arg, &end, 0);

                if (!*end && (tmpnum <= UINT_MAX)) {
                    args->sloppiness = tmpnum;
                } else {
                    fprintf(output, "couldn't convert '%s' to number\n", 
                      arg);
                }
            } else {
                args->sloppiness = 0;
            }
            break;

        case OPT_NUMRESULTS:
            /* set number of results per topic */
            if (!args->numresults) {
                char *end;
                long int tmpnum = strtol(arg, &end, 0);

                if (!*end && (tmpnum <= UINT_MAX)) {
                    args->numresults = tmpnum;
                } else {
                    fprintf(output, "couldn't convert '%s' to number\n", 
                      arg);
                }
            } else {
                fprintf(output, "number of results is already set to %u\n", 
                  args->numresults);
                err = 1;
            }
            break;

        case OPT_FILE:
            /* add topic file */
            if (!(add_topic_file(args, arg))) {
                fprintf(output, "couldn't add file '%s': %s\n", arg, 
                  strerror(errno));
                err = quiet = 1;
            }
            break;

        case OPT_FILELIST:
            /* add topic file file */
            if (!(add_topic_file_file(args, arg))) {
                fprintf(output, "couldn't add list '%s': %s\n", arg, 
                  strerror(errno));
                err = quiet = 1;
            }
            break;

        case OPT_HELP:
            /* they want help */
            err = 1;
            output = stdout;
            break;

        case OPT_VERSION:
            /* they want version info */
            printf("version %s\n", PACKAGE_VERSION);
            err = quiet = 1;
            output = stdout;
            break;

        case OPT_ANH_IMPACT:
            args->sopts |= INDEX_SEARCH_ANH_IMPACT_RANK;
            break;

        case OPT_HAWKAPI:
            /* they want to use hawkapi */
            args->sopts |= INDEX_SEARCH_HAWKAPI_RANK;
            if (!sscanf(arg, "%f", &args->sopt.u.hawkapi.alpha)) {
                fprintf(stderr, "failed to read alpha parameter\n");
                err = 1;
            }
            break;

        case OPT_DIRICHLET:
            /* they want to use dirichlet */
            args->sopts |= INDEX_SEARCH_DIRICHLET_RANK;
            if (!sscanf(arg, "%f", &args->sopt.u.dirichlet.mu)) {
                fprintf(stderr, "failed to read mu parameter\n");
                err = 1;
            }
            break;

        case OPT_OKAPI:
            /* they want to use okapi */
            args->sopts |= INDEX_SEARCH_OKAPI_RANK;
            break;

        case OPT_K1:
            /* set okapi k1 parameter */
            if (sscanf(arg, "%f", &args->sopt.u.okapi_k3.k1)) {
                /* do nothing */
            } else {
                fprintf(output, "can't read k1 value '%s'\n", arg);
                err = 1;
            }
            break;

        case OPT_K3:
            /* set okapi k3 parameter */
            if (sscanf(arg, "%f", &args->sopt.u.okapi_k3.k3)) {
                /* do nothing */
            } else {
                fprintf(output, "can't read k3 value '%s'\n", arg);
                err = 1;
            }
            break;

        case OPT_B:
            /* set okapi b parameter */
            if (sscanf(arg, "%f", &args->sopt.u.okapi_k3.b)) {
                /* do nothing */
            } else {
                fprintf(output, "can't read b value '%s'\n", arg);
                err = 1;
            }
            break;

        case OPT_TIMING:
            /* print queries */
            args->timing = 1;
            break;

        case OPT_PRINTQUERIES:
            /* print queries */
            args->print_queries = 1;
            break;

        case OPT_TITLE:
            /* use title in query */
            args->title = 1;
            break;

        case OPT_DESCRIPTION:
            /* use description in query */
            args->descr = 1;
            break;

        case OPT_NARRATIVE:
            /* use narrative in query */
            args->narr = 1;
            break;

        case OPT_PIVOTED_COSINE:
            /* they want to use pivoted cosine */
            if (sscanf(arg, "%f", &args->sopt.u.pcosine.pivot)) {
                args->sopts |= INDEX_SEARCH_PCOSINE_RANK;

                /* arrange for weights to be loaded into memory */
                args->lopts |= INDEX_LOAD_DOCMAP_CACHE;
                args->lopt.docmap_cache |= DOCMAP_CACHE_WEIGHT;

                if (args->sopt.u.pcosine.pivot < 0.0) {
                    fprintf(output, "cosine pivot can't be negative\n");
                    err = 1;
                }
            } else {
                fprintf(output, "can't read pivot value '%s'\n", arg);
                err = 1;
            }
            break;

        case OPT_COSINE:
            /* they want to use the cosine metric */
            args->sopts |= INDEX_SEARCH_COSINE_RANK;

            /* arrange for weights to be loaded into memory */
            args->lopts |= INDEX_LOAD_DOCMAP_CACHE;
            args->lopt.docmap_cache |= DOCMAP_CACHE_WEIGHT;
            break;

        default:
            /* shouldn't happen */
            assert(0);
        }
    }

    ind = getlongopt_optind(parser) + 1;
    getlongopt_delete(parser);

    if (err || ret == GETLONGOPT_END) {
        /* succeeded, do nothing */
    } else {
        if (ret == GETLONGOPT_UNKNOWN) {
            fprintf(stderr, "unknown option '%s'\n", argv[ind]);
        } else if (ret == GETLONGOPT_MISSING_ARG) {
            fprintf(stderr, "missing argument to option '%s'\n", argv[ind]);
        } else {
            fprintf(stderr, "unexpected error parsing options (around '%s')\n",
              argv[ind]);
        }
        free(args);
        return NULL;
    }
        
    /* remaining arguments should be index */
    while (!err && (ind < (unsigned int) argc)) {
        if (!args->idx) {
            if (!(args->idx = load_index(argv[ind], args->memory,
                      args->lopts, &args->lopt))) {

                fprintf(output, "couldn't load index from '%s': %s\n", 
                  argv[ind], strerror(errno));
                err = quiet = 1;
            }
        } else {
            fprintf(output, "index already loaded\n");
            err = 1;
            quiet = 0;
        }
        ind++;
    }

    /* set run_id if they haven't */
    if (!err && !args->run_id 
      && !(args->run_id = str_dup(PACKAGE))) {
        fprintf(output, "couldn't set default run_id: %s\n", strerror(errno));
        err = quiet = 1;
    }

    /* set number of results if they haven't */
    if (!err && !args->numresults) {
        args->numresults = 1000;
    }

    /* set number of accumulators if they haven't */
    if (!err && !args->numaccumulators) {
        args->numaccumulators = ACCUMULATOR_LIMIT;
    }

    /* check that they've given a topic file */
    if (!err && !args->topic_files) {
        fprintf(output, "no topic files given\n");
        err = 1;
    }

    /* check that they've given an index */
    if (!err && !args->idx) {
        fprintf(output, "no index given\n");
        err = 1;
    }

    if (!(args->title || args->descr || args->narr)) {
        /* title only run is default */
        args->title = 1;
    }

    if (err) {
        if (!quiet) {
            fprintf(output, "\n");
            print_usage(output, *argv);
        }
        free_args(args);
        return NULL;
    } else {
        return args;
    }
}
/**
 * Constructor.
 *
 * @intervals - if empty, will add the contigs found in the header files
 */
BCFSyncedStreamReader::BCFSyncedStreamReader(std::vector<std::string>& vcf_files, std::vector<GenomeInterval>& intervals, bool sync_by_pos)
:vcf_files(vcf_files), intervals(intervals), sync_by_pos(sync_by_pos)
{
    nfiles = vcf_files.size();
    vcfs.resize(nfiles, 0);
    hdrs.resize(nfiles, 0);
    idxs.resize(nfiles, 0);
    tbxs.resize(nfiles, 0);
    itrs.resize(nfiles, 0);
    ftypes.resize(nfiles, -1);

    current_interval = "";
    current_pos1 = 0;

    buffer.resize(nfiles);
    s = {0, 0, 0};

    exists_selected_intervals = (intervals.size()!=0);
    for (uint32_t i=0; i<intervals.size(); ++i)
    {
        intervals_map[intervals[i].to_string()] = i;
    }
    intervals_index = 0;

    //1. check file type validity
    //2. loads indices
    //3. adds sequences found in all indexed files, this allows us to iterate through all sequences.
    for (int32_t i = 0; i<nfiles; ++i)
    {
        ftypes[i] = hts_file_type(vcf_files[i].c_str());
        vcfs[i] = bcf_open(vcf_files[i].c_str(), "r");
        if (vcfs[i]==NULL) exit(1);
        hdrs[i] = bcf_alt_hdr_read(vcfs[i]);

        if (i==0)
        {
            if (!(ftypes[i] & (FT_VCF|FT_BCF|FT_STDIN)))
            {
                fprintf(stderr, "[E:%s:%d %s] %s not a VCF or BCF file\n", __FILE__, __LINE__, __FUNCTION__, vcf_files[i].c_str());
                exit(1);
            }

            if (!load_index(i))
            {
                fprintf(stderr, "[I:%s:%d %s] index cannot be loaded for %s\n", __FILE__, __LINE__, __FUNCTION__, vcf_files[i].c_str());
                exit(1);
            }

            if (!exists_selected_intervals)
            {
                //add sequences from file i
                add_interval(i);
            }
        }
        else
        {
            if (!(ftypes[i] & (FT_VCF_GZ|FT_BCF_GZ)))
            {
                fprintf(stderr, "[E:%s:%d %s] %s not a VCF_GZ or BCF file\n", __FILE__, __LINE__, __FUNCTION__, vcf_files[i].c_str());
                exit(1);
            }

            if (!load_index(i))
            {
                fprintf(stderr, "[E:%s:%d %s] index cannot be loaded for %s\n", __FILE__, __LINE__, __FUNCTION__, vcf_files[i].c_str());
                exit(1);
            }

            if (!exists_selected_intervals)
            {
                //add sequences from file i
                add_interval(i);
            }
        }
    }
}
Exemple #12
0
int file_select(const struct dirent *entry) {
         cert                        = X509_new();
         certsubject                 = X509_NAME_new();
	 int i                       = 0;
	 char buf[80]                = "";

  /* check for "." and ".." directory entries */
  if(entry->d_name[0]=='.') return 0;

  /* Check for <id>.pem file name extensions */
  if(strstr(entry->d_name, ".pem") == NULL) return 0;

  /* generate the full file name and path to open it */
  snprintf(certfilestr, sizeof(certfilestr), "%s/%s",
                           CACERTSTORE, entry->d_name);

  /* if we cannot open the file, we move on  to the next */
  if ((certfile = fopen(certfilestr, "r")) == NULL) return 0;

  /* now we load the certificate data */
  if (! (cert = PEM_read_X509(certfile,NULL,NULL,NULL))) return 0;

  /* if search type is dn, check if dn field contains the search value */
  if (strcmp(search, "dn") == 0) {

    /* get the subject information to compare the entries in it */
    if (! (certsubject = X509_get_subject_name(cert))) return 0;

    /* now we cycle through all entries of the subject */
    for (i = 0; i < X509_NAME_entry_count(certsubject); i++) {
      e = X509_NAME_get_entry(certsubject, i);
      OBJ_obj2txt(buf, 80, X509_NAME_ENTRY_get_object(e), 0);

      /* when the search file matches the cert subject field  */
      /* check if the field value is equal the search value   */
      if(strstr(buf, field) != NULL)
        if(strstr( (char *) X509_NAME_ENTRY_get_data(e), dnvalue) != NULL) return 1;
    }
  }

  /* if search type is exp, check expiration date is between start and end date */
  if (strcmp(search, "exp") == 0) {

    /* get the certificates expiration date */
    expiration_date = X509_get_notAfter(cert);

    /* copy the certificate expiration date into a string */
    membio = BIO_new(BIO_s_mem());
    ASN1_TIME_print(membio, expiration_date);
    BIO_gets(membio, membio_buf, sizeof(membio_buf));
    BIO_free(membio);
    //int_error(membio_buf); /* debug correct time parsing */

    /* parse the expiration date string into a time struct */
    memset (&expiration_tm, '\0', sizeof(expiration_tm));
    strptime(membio_buf, "%h %d %T %Y %z", &expiration_tm);
    // int_error(asctime(&expiration_tm)); /* debug correct time parsing */

    /* parse the CGI start date string into the start_tm struct */
    memset (&start_tm, '\0', sizeof(start_tm));
    strptime(exp_startstr, "%d.%m.%Y %R", &start_tm);
    // int_error(asctime(&start_tm)); /* debug correct time parsing */

    /* parse the CGI end date string into the end_tm struct */
    memset (&end_tm, '\0', sizeof(end_tm));
    strptime(exp_endstr, "%d.%m.%Y %R", &end_tm);
    // int_error(asctime(&end_tm)); /* debug correct time parsing */

    /* check if expiration date >= start date and <= end date */
    if ( difftime(mktime(&start_tm), mktime(&expiration_tm)) <=0 &&
         difftime(mktime(&end_tm), mktime(&expiration_tm)) >= 0 ) return 1;
  }
  /* if search type is ena, check enable date is between start and end date */
  if (strcmp(search, "ena") == 0) {

    /* get the certificates enable date */
    start_date = X509_get_notBefore(cert);

    /* copy the certificate expiration date into a string */
    membio = BIO_new(BIO_s_mem());
    ASN1_TIME_print(membio, start_date);
    BIO_gets(membio, membio_buf, sizeof(membio_buf));
    BIO_free(membio);

    /* parse the expiration date string into a time struct */
    memset (&enable_tm, '\0', sizeof(enable_tm));
    strptime(membio_buf, "%h %d %T %Y %z", &enable_tm);
    // int_error(asctime(&enable_tm)); /* debug correct time parsing */

    /* parse the CGI start date string into the start_tm struct */
    memset (&start_tm, '\0', sizeof(start_tm));
    strptime(ena_startstr, "%d.%m.%Y %R", &start_tm);
    // int_error(asctime(&start_tm)); /* debug correct time parsing */

    /* parse the CGI end date string into the end_tm struct */
    memset (&end_tm, '\0', sizeof(end_tm));
    strptime(ena_endstr, "%d.%m.%Y %R", &end_tm);
    // int_error(asctime(&end_tm)); /* debug correct time parsing */

    /* check if expiration date >= start date and <= end date */
    if ( difftime(mktime(&start_tm), mktime(&enable_tm)) <=0 &&
         difftime(mktime(&end_tm), mktime(&enable_tm)) >= 0 ) return 1;
  }
  /* if search type is rev, check if cert was revoked between start and end date */
  if (strcmp(search, "rev") == 0) {
    /* ---------------------------------------------------------- *
     * Parse the CGI start date string into the start_tm struct   *
     * ---------------------------------------------------------- */
    memset (&start_tm, '\0', sizeof(start_tm));
    strptime(rev_startstr, "%d.%m.%Y %R", &start_tm);
    /* ---------------------------------------------------------- *
     * Parse the CGI end date string into the end_tm struct       *
     * ---------------------------------------------------------- */
    memset (&end_tm, '\0', sizeof(end_tm));
    strptime(rev_endstr, "%d.%m.%Y %R", &end_tm);
    /* ---------------------------------------------------------- *
     * Get all revoked certificates from revocation DB index.txt  *
     * ---------------------------------------------------------- */
    CA_DB *db = NULL;
    DB_ATTR db_attr;

    if((db = load_index(INDEXFILE, &db_attr)) == NULL)
      int_error("Error cannot load CRL certificate database file");

    /* ---------------------------------------------------------- *
     * Get the certs serial number, convert it into a hex string  *
     * -----------------------------------------------------------*/
    BIGNUM *bn = NULL;
    bn = ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), NULL);
    if (!bn)
     int_error("Cannot extract serial number from cert into BIGNUM");
    char *serialstr = BN_bn2hex(bn);

    /* ---------------------------------------------------------- *
     * Check if the cert is revoked, looking up its serial in DB  *
     * -----------------------------------------------------------*/
    char *const *pp;
    int i;
    for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
      pp = sk_OPENSSL_PSTRING_value(db->db->data, i);

      if ( (strcmp(pp[DB_serial], serialstr) == 0)
           && (pp[DB_type][0] == DB_TYPE_REV) )  {

        /* ---------------------------------------------------------- *
         * Revoked, get the certs revocation date from the database   *
         * -----------------------------------------------------------*/
        char *p = strchr(pp[DB_rev_date], ',');
        if (p) *p = '\0'; // if revocation reason is given, terminate before 
        char *revokedstr = BUF_strdup(pp[DB_rev_date]);
        revocation_date = ASN1_UTCTIME_new();
        ASN1_UTCTIME_set_string(revocation_date, revokedstr);
        //int_error(revokedstr); /* debug correct time parsing */

        /* copy the certificate revocation date into a string */
        membio = BIO_new(BIO_s_mem());
        ASN1_TIME_print(membio, revocation_date);
        BIO_gets(membio, membio_buf, sizeof(membio_buf));
        BIO_free(membio);
        //int_error(membio_buf);

        /* parse the revocation date string into a time struct */
        memset (&revoked_tm, '\0', sizeof(revoked_tm));
        strptime(membio_buf, "%h %d %T %Y %z", &revoked_tm);
        //int_error(asctime(&revoked_tm)); /* debug correct time parsing */

        /* ---------------------------------------------------------- *
         * Check if revocation date >= start date and <= end date     *
         * -----------------------------------------------------------*/
        if ( difftime(mktime(&start_tm), mktime(&revoked_tm)) <=0 &&
             difftime(mktime(&end_tm), mktime(&revoked_tm)) >= 0 ) return 1;
      }
    }
    BN_free(bn);
  }
  /* if search type is ser, check if serial is between start and end serial */
  if (strcmp(search, "ser") == 0) {

    /* convert the serial strings to BIGNUM */
    BN_dec2bn(&startserialbn, startserstr);
    BN_dec2bn(&endserialbn, endserstr);

    /* get the certificates serial number and convert it to BIGNUM */
    if ((certserial = X509_get_serialNumber(cert)) == NULL)
       int_error("Error: Getting certificate serial number in ASN1 format.");
    if ((certserialbn = ASN1_INTEGER_to_BN(certserial, NULL)) == NULL)
       int_error("Error: converting certserial number from ASN1 to BIGNUM.");

    /* debugging output to see values of BIGNUM */
    //membio = BIO_new(BIO_s_mem());
    //BN_print(membio, endserialbn);
    //BIO_gets(membio, membio_buf, sizeof(membio_buf));
    //BIO_free(membio);
    //int_error(membio_buf);

    /* check if certserial >= startserial and <= endserial */
    if ( BN_cmp(startserialbn, certserialbn) <= 0 &&
         BN_cmp(endserialbn, certserialbn) >= 0 ) return 1;
  }

  return 0;
}
Exemple #13
0
int main(int argc, void *argv) {
    load_stopwords();
    index_p index = load_index();

    int exit = 0;
    while (!exit) {
        printf(" > ");
        char *command = read_line(stdin);

        if (!strcmp(command, "exit")) {
            // exit command
            exit = 1;
            printf("Exit requested..\n");

		} else if (!strcmp(command, "rebuild index")) {
            // rebuild index command
            rebuild_index(index);
		} else if (starts_with(command, "search for ")) {
            // search for <search_query> command
            char *query = (char *) malloc(strlen(command) - 10);
            memcpy(query, command+11, strlen(command) - 10);

            index_p result = search_index(&index, query);

            printf("Results (showing no more than 10, there might be more):\n");
            if (result) {
                // print result
                int count = 0;
                indexed_word_p w = result->words;
                if (!w) {
                    printf("No documents found for search term %s\n", query);
                }

                while (w) {
                    printf("Documents containing %s:\n", w->stem);

                    int i;
                    for (i = 0; i < w->nr_docs; i++, count++) {
                        printf(" [%d] %s\n", count, result->documents[w->documents[i].id].name);
                    }

                    w = w->next;
                }

                close_index(result);
            } else {
                printf("No documents found for search term %s\n", query);
            }

            free(query);

        } else if (starts_with(command, "add file ")) {
            // add file <file> command
            char *file = (char*) malloc(strlen(command) - 8);
            memcpy(file, command+9, strlen(command) - 8);

			index = add_file(index, file);
            free(file);

        } else if (starts_with(command, "remove file ")) {
            // remove file <file> command
            char *file = (char*) malloc(strlen(command) - 11);
            memcpy(file, command+12, strlen(command) - 11);

            // obtain document id a.k.a. index in filebase
            int doc_id = find_str(&index->documents[0].name, sizeof(indexed_document_t), file, 0, index->nr_docs - 1);

            if (doc_id < 0) {
                printf("Error: %s is not in the filebase!\n", file);
            } else {
                remove_file(index, doc_id);
            }

            free(file);
        }

        free(command);
    }

    // release memory
    release_stopwords();
    close_index(index);

    return 0;
}
int command_line_function(void)
{
	int retval = 0;
	
	start_timer();

	if( flag_efficiency_debug )
		efficiency_init();

	if( input_file == NULL )
	{
		init_database();

		load_phashes();
		for( int f=0; f < flag_load_multiple_times; f++ )
			load_phashes();

		unsigned long long seed = 0x3333CCCCCCCC3333;
		master_tree = index_phashes(master_tree,&master_list,NULL,seed,0);
	}
	else
	{
		master_tree = load_index(input_file);
	}

	load_time = stop_timer();

	double total_query_time = 0;

	if( num_pthreads > num_phash_queries )
		num_pthreads = num_phash_queries;
	struct threaded_query_pkg *packages[num_phash_queries];
	pthread_t threads[num_pthreads];
	int threads_running = 0;
	int q = num_phash_queries;

	pthread_t *current_thread = threads;
	int query_num = 1;
	int join_count = 0;
	while(q--)
	{
		packages[q] = (struct threaded_query_pkg*)malloc(sizeof(struct threaded_query_pkg));
		packages[q]->done = 0;
		packages[q]->query_num = query_num;
		packages[q]->query = phash_queries[q];

		debugp( 3, "Launching thread #%d (%d running)\n", q, threads_running );
		pthread_create( &(*current_thread), NULL, &threaded_query, (void*)packages[q] );
		query_num++;

		threads_running++;
		current_thread++;

		if( (current_thread - threads) >= num_pthreads )
		{
			current_thread = threads;
		}

		if( threads_running >= num_pthreads )
		{
			pthread_join( *current_thread, NULL );
			join_count++;
			threads_running--;
		}
	}
	for( int t = 0; t < num_pthreads; t++ )
	{
		pthread_join( threads[t], NULL );
	}

	for( q=0; q < num_phash_queries; q++ )
	{

		total_query_time += packages[q]->query_time;
	
		debugp( 1, "Query #%d: phash = 0x%llX d <= %d] (%f sec) \n", q+1, packages[q]->query, query_max_distance, packages[q]->query_time );
		
		debugp( 2, "packages[%d]->matches is at %p\n", q, packages[q]->matches );
		if(packages[q]->matches != NULL)
			debugp( 2, "packages[%d]->matches->count = %d\n", q, packages[q]->matches->count );


		if( (packages[q]->matches != NULL) && (packages[q]->matches->count) )
		{
			for( int m=0; m < packages[q]->matches->count; m++ )
			{
				debugp( 1, "  Match #%d: 0x%llX (d=%d)\n", 
						m+1, 
						packages[q]->matches->matches[m].phash,
						packages[q]->matches->matches[m].dist );
				
				if( flag_php )
				{
					printf( "%llX\n", packages[q]->matches->matches[m].phash );
				}
			}
		}
		else
		{
			debugp( 1, "  ** No Matches **\n" );
		}

		debugp( 2, "packages[%d]->done = %d\n", q, packages[q]->done );

		if(packages[q]->matches != NULL)
			free(packages[q]->matches->matches);
		free(packages[q]->matches);
		free(packages[q]);
	}
		
	double avg_query_time = total_query_time / (double)num_phash_queries;
	
	if( logfile_name != NULL )
	{
		FILE *fp;
		
		if( (fp = fopen( logfile_name, "a" )) )
		{
			char buffer[512];
			sprintf( buffer, "%d,%f,%f\n", num_phash_queries,avg_query_time,total_query_time );
			fwrite( buffer, sizeof(char), strlen(buffer), fp );
		}

		fclose(fp);
	}

	if( input_file == NULL )
		deinit_database();

	if( flag_print_vp_tree )
	{
		print_vp_tree(master_tree);
		size_t size = get_recursive_node_size(master_tree);
		debugp( 1, "Total size: %d bytes\n", size );
	}
	if( output_file != NULL )
		save_index( master_tree, output_file );
	if( flag_efficiency_debug )
		print_efficiency_summary();

	free_vp_tree(master_tree);
	
	return retval;
}
Exemple #15
0
int
ocsp_main(int argc, char **argv)
{
	char **args;
	char *host = NULL, *port = NULL, *path = "/";
	char *reqin = NULL, *respin = NULL;
	char *reqout = NULL, *respout = NULL;
	char *signfile = NULL, *keyfile = NULL;
	char *rsignfile = NULL, *rkeyfile = NULL;
	char *outfile = NULL;
	int add_nonce = 1, noverify = 0, use_ssl = -1;
	STACK_OF(CONF_VALUE) * headers = NULL;
	OCSP_REQUEST *req = NULL;
	OCSP_RESPONSE *resp = NULL;
	OCSP_BASICRESP *bs = NULL;
	X509 *issuer = NULL, *cert = NULL;
	X509 *signer = NULL, *rsigner = NULL;
	EVP_PKEY *key = NULL, *rkey = NULL;
	BIO *acbio = NULL, *cbio = NULL;
	BIO *derbio = NULL;
	BIO *out = NULL;
	int req_timeout = -1;
	int req_text = 0, resp_text = 0;
	long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
	char *CAfile = NULL, *CApath = NULL;
	X509_STORE *store = NULL;
	STACK_OF(X509) * sign_other = NULL, *verify_other = NULL, *rother = NULL;
	char *sign_certfile = NULL, *verify_certfile = NULL, *rcertfile = NULL;
	unsigned long sign_flags = 0, verify_flags = 0, rflags = 0;
	int ret = 1;
	int accept_count = -1;
	int badarg = 0;
	int i;
	int ignore_err = 0;
	STACK_OF(OPENSSL_STRING) * reqnames = NULL;
	STACK_OF(OCSP_CERTID) * ids = NULL;
	X509 *rca_cert = NULL;
	char *ridx_filename = NULL;
	char *rca_filename = NULL;
	CA_DB *rdb = NULL;
	int nmin = 0, ndays = -1;
	const EVP_MD *cert_id_md = NULL;
	const char *errstr = NULL;

	args = argv + 1;
	reqnames = sk_OPENSSL_STRING_new_null();
	ids = sk_OCSP_CERTID_new_null();
	while (!badarg && *args && *args[0] == '-') {
		if (!strcmp(*args, "-out")) {
			if (args[1]) {
				args++;
				outfile = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-timeout")) {
			if (args[1]) {
				args++;
				req_timeout = strtonum(*args, 0,
				    INT_MAX, &errstr);
				if (errstr) {
					BIO_printf(bio_err,
					    "Illegal timeout value %s: %s\n",
					    *args, errstr);
					badarg = 1;
				}
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-url")) {
			if (args[1]) {
				args++;
				if (!OCSP_parse_url(*args, &host, &port, &path, &use_ssl)) {
					BIO_printf(bio_err, "Error parsing URL\n");
					badarg = 1;
				}
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-host")) {
			if (args[1]) {
				args++;
				host = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-port")) {
			if (args[1]) {
				args++;
				port = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-header")) {
			if (args[1] && args[2]) {
				if (!X509V3_add_value(args[1], args[2], &headers))
					goto end;
				args += 2;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-ignore_err"))
			ignore_err = 1;
		else if (!strcmp(*args, "-noverify"))
			noverify = 1;
		else if (!strcmp(*args, "-nonce"))
			add_nonce = 2;
		else if (!strcmp(*args, "-no_nonce"))
			add_nonce = 0;
		else if (!strcmp(*args, "-resp_no_certs"))
			rflags |= OCSP_NOCERTS;
		else if (!strcmp(*args, "-resp_key_id"))
			rflags |= OCSP_RESPID_KEY;
		else if (!strcmp(*args, "-no_certs"))
			sign_flags |= OCSP_NOCERTS;
		else if (!strcmp(*args, "-no_signature_verify"))
			verify_flags |= OCSP_NOSIGS;
		else if (!strcmp(*args, "-no_cert_verify"))
			verify_flags |= OCSP_NOVERIFY;
		else if (!strcmp(*args, "-no_chain"))
			verify_flags |= OCSP_NOCHAIN;
		else if (!strcmp(*args, "-no_cert_checks"))
			verify_flags |= OCSP_NOCHECKS;
		else if (!strcmp(*args, "-no_explicit"))
			verify_flags |= OCSP_NOEXPLICIT;
		else if (!strcmp(*args, "-trust_other"))
			verify_flags |= OCSP_TRUSTOTHER;
		else if (!strcmp(*args, "-no_intern"))
			verify_flags |= OCSP_NOINTERN;
		else if (!strcmp(*args, "-text")) {
			req_text = 1;
			resp_text = 1;
		} else if (!strcmp(*args, "-req_text"))
			req_text = 1;
		else if (!strcmp(*args, "-resp_text"))
			resp_text = 1;
		else if (!strcmp(*args, "-reqin")) {
			if (args[1]) {
				args++;
				reqin = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-respin")) {
			if (args[1]) {
				args++;
				respin = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-signer")) {
			if (args[1]) {
				args++;
				signfile = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-VAfile")) {
			if (args[1]) {
				args++;
				verify_certfile = *args;
				verify_flags |= OCSP_TRUSTOTHER;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-sign_other")) {
			if (args[1]) {
				args++;
				sign_certfile = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-verify_other")) {
			if (args[1]) {
				args++;
				verify_certfile = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-CAfile")) {
			if (args[1]) {
				args++;
				CAfile = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-CApath")) {
			if (args[1]) {
				args++;
				CApath = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-validity_period")) {
			if (args[1]) {
				args++;
				nsec = strtonum(*args, 0, LONG_MAX, &errstr);
				if (errstr) {
					BIO_printf(bio_err,
					    "Illegal validity period %s: %s\n",
					    *args, errstr);
					badarg = 1;
				}
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-status_age")) {
			if (args[1]) {
				args++;
				maxage = strtonum(*args, 0, LONG_MAX, &errstr);
				if (errstr) {
					BIO_printf(bio_err,
					    "Illegal validity age %s: %s\n",
					    *args, errstr);
					badarg = 1;
				}
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-signkey")) {
			if (args[1]) {
				args++;
				keyfile = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-reqout")) {
			if (args[1]) {
				args++;
				reqout = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-respout")) {
			if (args[1]) {
				args++;
				respout = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-path")) {
			if (args[1]) {
				args++;
				path = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-issuer")) {
			if (args[1]) {
				args++;
				X509_free(issuer);
				issuer = load_cert(bio_err, *args, FORMAT_PEM,
				    NULL, "issuer certificate");
				if (!issuer)
					goto end;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-cert")) {
			if (args[1]) {
				args++;
				X509_free(cert);
				cert = load_cert(bio_err, *args, FORMAT_PEM,
				    NULL, "certificate");
				if (!cert)
					goto end;
				if (!cert_id_md)
					cert_id_md = EVP_sha1();
				if (!add_ocsp_cert(&req, cert, cert_id_md, issuer, ids))
					goto end;
				if (!sk_OPENSSL_STRING_push(reqnames, *args))
					goto end;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-serial")) {
			if (args[1]) {
				args++;
				if (!cert_id_md)
					cert_id_md = EVP_sha1();
				if (!add_ocsp_serial(&req, *args, cert_id_md, issuer, ids))
					goto end;
				if (!sk_OPENSSL_STRING_push(reqnames, *args))
					goto end;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-index")) {
			if (args[1]) {
				args++;
				ridx_filename = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-CA")) {
			if (args[1]) {
				args++;
				rca_filename = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-nmin")) {
			if (args[1]) {
				args++;
				nmin = strtonum(*args, 0, INT_MAX, &errstr);
				if (errstr) {
					BIO_printf(bio_err,
					    "Illegal update period %s: %s\n",
					    *args, errstr);
					badarg = 1;
				}
			}
			if (ndays == -1)
				ndays = 0;
			else
				badarg = 1;
		} else if (!strcmp(*args, "-nrequest")) {
			if (args[1]) {
				args++;
				accept_count = strtonum(*args, 0, INT_MAX, &errstr);
				if (errstr) {
					BIO_printf(bio_err,
					    "Illegal accept count %s: %s\n",
					    *args, errstr);
					badarg = 1;
				}
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-ndays")) {
			if (args[1]) {
				args++;
				ndays = strtonum(*args, 0, INT_MAX, &errstr);
				if (errstr) {
					BIO_printf(bio_err,
					    "Illegal update period %s: %s\n",
					    *args, errstr);
					badarg = 1;
				}
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-rsigner")) {
			if (args[1]) {
				args++;
				rsignfile = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-rkey")) {
			if (args[1]) {
				args++;
				rkeyfile = *args;
			} else
				badarg = 1;
		} else if (!strcmp(*args, "-rother")) {
			if (args[1]) {
				args++;
				rcertfile = *args;
			} else
				badarg = 1;
		} else if ((cert_id_md = EVP_get_digestbyname((*args) + 1)) == NULL) {
			badarg = 1;
		}
		args++;
	}

	/* Have we anything to do? */
	if (!req && !reqin && !respin && !(port && ridx_filename))
		badarg = 1;

	if (badarg) {
		BIO_printf(bio_err, "OCSP utility\n");
		BIO_printf(bio_err, "Usage ocsp [options]\n");
		BIO_printf(bio_err, "where options are\n");
		BIO_printf(bio_err, "-out file          output filename\n");
		BIO_printf(bio_err, "-issuer file       issuer certificate\n");
		BIO_printf(bio_err, "-cert file         certificate to check\n");
		BIO_printf(bio_err, "-serial n          serial number to check\n");
		BIO_printf(bio_err, "-signer file       certificate to sign OCSP request with\n");
		BIO_printf(bio_err, "-signkey file      private key to sign OCSP request with\n");
		BIO_printf(bio_err, "-sign_other file   additional certificates to include in signed request\n");
		BIO_printf(bio_err, "-no_certs          don't include any certificates in signed request\n");
		BIO_printf(bio_err, "-req_text          print text form of request\n");
		BIO_printf(bio_err, "-resp_text         print text form of response\n");
		BIO_printf(bio_err, "-text              print text form of request and response\n");
		BIO_printf(bio_err, "-reqout file       write DER encoded OCSP request to \"file\"\n");
		BIO_printf(bio_err, "-respout file      write DER encoded OCSP reponse to \"file\"\n");
		BIO_printf(bio_err, "-reqin file        read DER encoded OCSP request from \"file\"\n");
		BIO_printf(bio_err, "-respin file       read DER encoded OCSP reponse from \"file\"\n");
		BIO_printf(bio_err, "-nonce             add OCSP nonce to request\n");
		BIO_printf(bio_err, "-no_nonce          don't add OCSP nonce to request\n");
		BIO_printf(bio_err, "-url URL           OCSP responder URL\n");
		BIO_printf(bio_err, "-host host:n       send OCSP request to host on port n\n");
		BIO_printf(bio_err, "-path              path to use in OCSP request\n");
		BIO_printf(bio_err, "-CApath dir        trusted certificates directory\n");
		BIO_printf(bio_err, "-CAfile file       trusted certificates file\n");
		BIO_printf(bio_err, "-VAfile file       validator certificates file\n");
		BIO_printf(bio_err, "-validity_period n maximum validity discrepancy in seconds\n");
		BIO_printf(bio_err, "-status_age n      maximum status age in seconds\n");
		BIO_printf(bio_err, "-noverify          don't verify response at all\n");
		BIO_printf(bio_err, "-verify_other file additional certificates to search for signer\n");
		BIO_printf(bio_err, "-trust_other       don't verify additional certificates\n");
		BIO_printf(bio_err, "-no_intern         don't search certificates contained in response for signer\n");
		BIO_printf(bio_err, "-no_signature_verify don't check signature on response\n");
		BIO_printf(bio_err, "-no_cert_verify    don't check signing certificate\n");
		BIO_printf(bio_err, "-no_chain          don't chain verify response\n");
		BIO_printf(bio_err, "-no_cert_checks    don't do additional checks on signing certificate\n");
		BIO_printf(bio_err, "-port num		 port to run responder on\n");
		BIO_printf(bio_err, "-index file	 certificate status index file\n");
		BIO_printf(bio_err, "-CA file		 CA certificate\n");
		BIO_printf(bio_err, "-rsigner file	 responder certificate to sign responses with\n");
		BIO_printf(bio_err, "-rkey file	 responder key to sign responses with\n");
		BIO_printf(bio_err, "-rother file	 other certificates to include in response\n");
		BIO_printf(bio_err, "-resp_no_certs     don't include any certificates in response\n");
		BIO_printf(bio_err, "-nmin n	 	 number of minutes before next update\n");
		BIO_printf(bio_err, "-ndays n	 	 number of days before next update\n");
		BIO_printf(bio_err, "-resp_key_id       identify reponse by signing certificate key ID\n");
		BIO_printf(bio_err, "-nrequest n        number of requests to accept (default unlimited)\n");
		BIO_printf(bio_err, "-<dgst alg>     use specified digest in the request\n");
		goto end;
	}
	if (outfile)
		out = BIO_new_file(outfile, "w");
	else
		out = BIO_new_fp(stdout, BIO_NOCLOSE);

	if (!out) {
		BIO_printf(bio_err, "Error opening output file\n");
		goto end;
	}
	if (!req && (add_nonce != 2))
		add_nonce = 0;

	if (!req && reqin) {
		derbio = BIO_new_file(reqin, "rb");
		if (!derbio) {
			BIO_printf(bio_err, "Error Opening OCSP request file\n");
			goto end;
		}
		req = d2i_OCSP_REQUEST_bio(derbio, NULL);
		BIO_free(derbio);
		if (!req) {
			BIO_printf(bio_err, "Error reading OCSP request\n");
			goto end;
		}
	}
	if (!req && port) {
		acbio = init_responder(port);
		if (!acbio)
			goto end;
	}
	if (rsignfile && !rdb) {
		if (!rkeyfile)
			rkeyfile = rsignfile;
		rsigner = load_cert(bio_err, rsignfile, FORMAT_PEM,
		    NULL, "responder certificate");
		if (!rsigner) {
			BIO_printf(bio_err, "Error loading responder certificate\n");
			goto end;
		}
		rca_cert = load_cert(bio_err, rca_filename, FORMAT_PEM,
		    NULL, "CA certificate");
		if (rcertfile) {
			rother = load_certs(bio_err, rcertfile, FORMAT_PEM,
			    NULL, "responder other certificates");
			if (!rother)
				goto end;
		}
		rkey = load_key(bio_err, rkeyfile, FORMAT_PEM, 0, NULL,
		    "responder private key");
		if (!rkey)
			goto end;
	}
	if (acbio)
		BIO_printf(bio_err, "Waiting for OCSP client connections...\n");

redo_accept:

	if (acbio) {
		if (!do_responder(&req, &cbio, acbio, port))
			goto end;
		if (!req) {
			resp = OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL);
			send_ocsp_response(cbio, resp);
			goto done_resp;
		}
	}
	if (!req && (signfile || reqout || host || add_nonce || ridx_filename)) {
		BIO_printf(bio_err, "Need an OCSP request for this operation!\n");
		goto end;
	}
	if (req && add_nonce)
		OCSP_request_add1_nonce(req, NULL, -1);

	if (signfile) {
		if (!keyfile)
			keyfile = signfile;
		signer = load_cert(bio_err, signfile, FORMAT_PEM,
		    NULL, "signer certificate");
		if (!signer) {
			BIO_printf(bio_err, "Error loading signer certificate\n");
			goto end;
		}
		if (sign_certfile) {
			sign_other = load_certs(bio_err, sign_certfile, FORMAT_PEM,
			    NULL, "signer certificates");
			if (!sign_other)
				goto end;
		}
		key = load_key(bio_err, keyfile, FORMAT_PEM, 0, NULL,
		    "signer private key");
		if (!key)
			goto end;

		if (!OCSP_request_sign(req, signer, key, NULL, sign_other, sign_flags)) {
			BIO_printf(bio_err, "Error signing OCSP request\n");
			goto end;
		}
	}
	if (req_text && req)
		OCSP_REQUEST_print(out, req, 0);

	if (reqout) {
		derbio = BIO_new_file(reqout, "wb");
		if (!derbio) {
			BIO_printf(bio_err, "Error opening file %s\n", reqout);
			goto end;
		}
		i2d_OCSP_REQUEST_bio(derbio, req);
		BIO_free(derbio);
	}
	if (ridx_filename && (!rkey || !rsigner || !rca_cert)) {
		BIO_printf(bio_err, "Need a responder certificate, key and CA for this operation!\n");
		goto end;
	}
	if (ridx_filename && !rdb) {
		rdb = load_index(ridx_filename, NULL);
		if (!rdb)
			goto end;
		if (!index_index(rdb))
			goto end;
	}
	if (rdb) {
		i = make_ocsp_response(&resp, req, rdb, rca_cert, rsigner, rkey, rother, rflags, nmin, ndays);
		if (cbio)
			send_ocsp_response(cbio, resp);
	} else if (host) {
		resp = process_responder(bio_err, req, host, path,
		    port, use_ssl, headers, req_timeout);
		if (!resp)
			goto end;
	} else if (respin) {
		derbio = BIO_new_file(respin, "rb");
		if (!derbio) {
			BIO_printf(bio_err, "Error Opening OCSP response file\n");
			goto end;
		}
		resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
		BIO_free(derbio);
		if (!resp) {
			BIO_printf(bio_err, "Error reading OCSP response\n");
			goto end;
		}
	} else {
		ret = 0;
		goto end;
	}

done_resp:

	if (respout) {
		derbio = BIO_new_file(respout, "wb");
		if (!derbio) {
			BIO_printf(bio_err, "Error opening file %s\n", respout);
			goto end;
		}
		i2d_OCSP_RESPONSE_bio(derbio, resp);
		BIO_free(derbio);
	}
	i = OCSP_response_status(resp);

	if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
		BIO_printf(out, "Responder Error: %s (%d)\n",
		    OCSP_response_status_str(i), i);
		if (ignore_err)
			goto redo_accept;
		ret = 0;
		goto end;
	}
	if (resp_text)
		OCSP_RESPONSE_print(out, resp, 0);

	/* If running as responder don't verify our own response */
	if (cbio) {
		if (accept_count > 0)
			accept_count--;
		/* Redo if more connections needed */
		if (accept_count) {
			BIO_free_all(cbio);
			cbio = NULL;
			OCSP_REQUEST_free(req);
			req = NULL;
			OCSP_RESPONSE_free(resp);
			resp = NULL;
			goto redo_accept;
		}
		goto end;
	}
	if (!store)
		store = setup_verify(bio_err, CAfile, CApath);
	if (!store)
		goto end;
	if (verify_certfile) {
		verify_other = load_certs(bio_err, verify_certfile, FORMAT_PEM,
		    NULL, "validator certificate");
		if (!verify_other)
			goto end;
	}
	bs = OCSP_response_get1_basic(resp);

	if (!bs) {
		BIO_printf(bio_err, "Error parsing response\n");
		goto end;
	}
	if (!noverify) {
		if (req && ((i = OCSP_check_nonce(req, bs)) <= 0)) {
			if (i == -1)
				BIO_printf(bio_err, "WARNING: no nonce in response\n");
			else {
				BIO_printf(bio_err, "Nonce Verify error\n");
				goto end;
			}
		}
		i = OCSP_basic_verify(bs, verify_other, store, verify_flags);
		if (i < 0)
			i = OCSP_basic_verify(bs, NULL, store, 0);

		if (i <= 0) {
			BIO_printf(bio_err, "Response Verify Failure\n");
			ERR_print_errors(bio_err);
		} else
			BIO_printf(bio_err, "Response verify OK\n");

	}
	if (!print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage))
		goto end;

	ret = 0;

end:
	ERR_print_errors(bio_err);
	X509_free(signer);
	X509_STORE_free(store);
	EVP_PKEY_free(key);
	EVP_PKEY_free(rkey);
	X509_free(issuer);
	X509_free(cert);
	X509_free(rsigner);
	X509_free(rca_cert);
	free_index(rdb);
	BIO_free_all(cbio);
	BIO_free_all(acbio);
	BIO_free(out);
	OCSP_REQUEST_free(req);
	OCSP_RESPONSE_free(resp);
	OCSP_BASICRESP_free(bs);
	sk_OPENSSL_STRING_free(reqnames);
	sk_OCSP_CERTID_free(ids);
	sk_X509_pop_free(sign_other, X509_free);
	sk_X509_pop_free(verify_other, X509_free);
	sk_CONF_VALUE_pop_free(headers, X509V3_conf_free);

	if (use_ssl != -1) {
		free(host);
		free(port);
		free(path);
	}
	return (ret);
}
Exemple #16
0
/* Fm-Index Search MAIN */
int main(int argc, char *argv[]) {

	char * program_name = argv[0];
	char * filename, * extfilename = NULL;
	void *index;
	uchar * pattern;
	ulong nchars, position = 0;
	int unbuild, count, locate, extract, display, error;

	nchars = 10;	
	count = locate = extract = unbuild = display = 0;
	
	int next_option;
	const char* short_options = "hlce:s:d:n:";
	const struct option long_options[] = {
		{"help" , 		0,	NULL, 	'h'},
		{"locate",		0,	NULL,	'l'},
		{"count",		0,	NULL,	'c'},
		{"extract",		1,	NULL,	'e'},
		{"display",		1,	NULL,	's'},
		{"unbuild",		1,	NULL,	'd'},
		{"numchars",	1,	NULL,	'n'},
		{NULL,			0,	NULL,	0}
	 };
 
 	if(argc<3) print_usage(program_name);
	
		do { 
		next_option = getopt_long(argc, argv, short_options,
								  long_options, NULL);
		
		switch (next_option) {
			    
			case 'l': /* report position */
         		locate = 1; 
				break;
			
			case 's': /* display len chars sourronding each occ */
         		display = 1;
			    nchars = (ulong) atol(optarg); 
				break;
			
			case 'd': /* unbuild */
         		unbuild = 1;
			    extfilename = (char *) optarg;
				break;
			
	  		case 'e': /* extract */
		 		extract = 1;
				position = (ulong) atol(optarg); 
    	 		break;
			
			case 'c': /* count */
		 		count = 1;
    	 		break;
			
	  		case 'n': /* numchars for extract function */
				extract = 1;
		 		nchars = (ulong) atol(optarg); 
	  	 		break;

			case '?': /* The user specified an invalid option. */
        		fprintf(stderr,"Unknown option.\n");
        		print_usage(program_name);
				break;	
			
			case -1: /* Done with options. */
				break;
			
			default: 
				print_usage(program_name);
    	}
	}
	while (next_option != -1);
	
	if (optind == argc)  {	
		  	fprintf(stderr,"You must supply a pattern and a .fmi filename\n\n");
			print_usage(program_name);
     		exit(1);
    }
	
	/* priorita' extract display locate count */
	if(!(extract || unbuild)) /* pattern */ 
		pattern = (uchar *) argv[optind++];
	else pattern = NULL;
		
	if (optind == argc)  {	
		  	fprintf(stderr,"You must supply a pattern and a .fmi filename\n\n");
			print_usage(program_name);
     		exit(1);
    }
			
	filename = argv[optind];
	
	error = load_index (filename, &index);
	IFERROR (error);

	if (unbuild==1) 
		do_unbuild(index, extfilename);
	if (extract==1) 
		do_extract(index, position, nchars);
	if (display==1) 
		do_display(index, pattern, nchars);
	if (locate==1) 
		do_locate(index, pattern);
	
	do_count(index, pattern);
	exit(0);
}	
Exemple #17
0
int srp_main(int argc, char **argv)
{
    CA_DB *db = NULL;
    CONF *conf = NULL;
    int gNindex = -1, maxgN = -1, ret = 1, errors = 0, verbose = 0, i;
    int doupdatedb = 0, mode = OPT_ERR;
    char *user = NULL, *passinarg = NULL, *passoutarg = NULL;
    char *passin = NULL, *passout = NULL, *gN = NULL, *userinfo = NULL;
    char *randfile = NULL, *section = NULL;
    char **gNrow = NULL, *configfile = NULL;
    char *srpvfile = NULL, **pp, *prog;
    OPTION_CHOICE o;

    prog = opt_init(argc, argv, srp_options);
    while ((o = opt_next()) != OPT_EOF) {
        switch (o) {
        case OPT_EOF:
        case OPT_ERR:
 opthelp:
            BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
            goto end;
        case OPT_HELP:
            opt_help(srp_options);
            ret = 0;
            goto end;
        case OPT_VERBOSE:
            verbose++;
            break;
        case OPT_CONFIG:
            configfile = opt_arg();
            break;
        case OPT_NAME:
            section = opt_arg();
            break;
        case OPT_SRPVFILE:
            srpvfile = opt_arg();
            break;
        case OPT_ADD:
        case OPT_DELETE:
        case OPT_MODIFY:
        case OPT_LIST:
            if (mode != OPT_ERR) {
                BIO_printf(bio_err,
                           "%s: Only one of -add/delete-modify/-list\n",
                           prog);
                goto opthelp;
            }
            mode = o;
            break;
        case OPT_GN:
            gN = opt_arg();
            break;
        case OPT_USERINFO:
            userinfo = opt_arg();
            break;
        case OPT_PASSIN:
            passinarg = opt_arg();
            break;
        case OPT_PASSOUT:
            passoutarg = opt_arg();
            break;
        case OPT_ENGINE:
            (void)setup_engine(opt_arg(), 0);
            break;
        }
    }
    argc = opt_num_rest();
    argv = opt_rest();

    if (srpvfile && configfile) {
        BIO_printf(bio_err,
                   "-srpvfile and -configfile cannot be specified together.\n");
        goto end;
    }
    if (mode == OPT_ERR) {
        BIO_printf(bio_err,
                   "Exactly one of the options -add, -delete, -modify -list must be specified.\n");
        goto opthelp;
    }
    if ((mode == OPT_DELETE || mode == OPT_MODIFY || mode == OPT_ADD)
        && argc < 1) {
        BIO_printf(bio_err,
                   "Need at least one user for options -add, -delete, -modify. \n");
        goto opthelp;
    }
    if ((passin || passout) && argc != 1) {
        BIO_printf(bio_err,
                   "-passin, -passout arguments only valid with one user.\n");
        goto opthelp;
    }

    if (!app_passwd(passinarg, passoutarg, &passin, &passout)) {
        BIO_printf(bio_err, "Error getting passwords\n");
        goto end;
    }

    if (!srpvfile) {
        if (!configfile)
            configfile = default_config_file;

        if (verbose)
            BIO_printf(bio_err, "Using configuration from %s\n",
                       configfile);
        conf = app_load_config(configfile);
        if (conf == NULL)
            goto end;
        if (configfile != default_config_file && !app_load_modules(conf))
            goto end;

        /* Lets get the config section we are using */
        if (section == NULL) {
            if (verbose)
                BIO_printf(bio_err,
                           "trying to read " ENV_DEFAULT_SRP
                           " in " BASE_SECTION "\n");

            section = lookup_conf(conf, BASE_SECTION, ENV_DEFAULT_SRP);
            if (section == NULL)
                goto end;
        }

        if (randfile == NULL)
            randfile = NCONF_get_string(conf, BASE_SECTION, "RANDFILE");

        if (verbose)
            BIO_printf(bio_err,
                       "trying to read " ENV_DATABASE " in section \"%s\"\n",
                       section);

        srpvfile = lookup_conf(conf, section, ENV_DATABASE);
        if (srpvfile == NULL)
            goto end;
    }
    if (randfile == NULL)
        ERR_clear_error();
    else
        app_RAND_load_file(randfile, 0);

    if (verbose)
        BIO_printf(bio_err, "Trying to read SRP verifier file \"%s\"\n",
                   srpvfile);

    db = load_index(srpvfile, NULL);
    if (db == NULL)
        goto end;

    /* Lets check some fields */
    for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
        pp = sk_OPENSSL_PSTRING_value(db->db->data, i);

        if (pp[DB_srptype][0] == DB_SRP_INDEX) {
            maxgN = i;
            if ((gNindex < 0) && (gN != NULL) && strcmp(gN, pp[DB_srpid]) == 0)
                gNindex = i;

            print_index(db, i, verbose > 1);
        }
    }

    if (verbose)
        BIO_printf(bio_err, "Database initialised\n");

    if (gNindex >= 0) {
        gNrow = sk_OPENSSL_PSTRING_value(db->db->data, gNindex);
        print_entry(db, gNindex, verbose > 1, "Default g and N");
    } else if (maxgN > 0 && !SRP_get_default_gN(gN)) {
        BIO_printf(bio_err, "No g and N value for index \"%s\"\n", gN);
        goto end;
    } else {
        if (verbose)
            BIO_printf(bio_err, "Database has no g N information.\n");
        gNrow = NULL;
    }

    if (verbose > 1)
        BIO_printf(bio_err, "Starting user processing\n");

    if (argc > 0)
        user = *(argv++);

    while (mode == OPT_LIST || user) {
        int userindex = -1;

        if (user != NULL && verbose > 1)
            BIO_printf(bio_err, "Processing user \"%s\"\n", user);
        if ((userindex = get_index(db, user, 'U')) >= 0) {
            print_user(db, userindex, (verbose > 0) || mode == OPT_LIST);
        }

        if (mode == OPT_LIST) {
            if (user == NULL) {
                BIO_printf(bio_err, "List all users\n");

                for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
                    print_user(db, i, 1);
                }
            } else if (userindex < 0) {
                BIO_printf(bio_err,
                           "user \"%s\" does not exist, ignored. t\n", user);
                errors++;
            }
        } else if (mode == OPT_ADD) {
            if (userindex >= 0) {
                /* reactivation of a new user */
                char **row =
                    sk_OPENSSL_PSTRING_value(db->db->data, userindex);
                BIO_printf(bio_err, "user \"%s\" reactivated.\n", user);
                row[DB_srptype][0] = 'V';

                doupdatedb = 1;
            } else {
                char *row[DB_NUMBER];
                char *gNid;
                row[DB_srpverifier] = NULL;
                row[DB_srpsalt] = NULL;
                row[DB_srpinfo] = NULL;
                if (!
                    (gNid =
                     srp_create_user(user, &(row[DB_srpverifier]),
                                     &(row[DB_srpsalt]),
                                     gNrow ? gNrow[DB_srpsalt] : gN,
                                     gNrow ? gNrow[DB_srpverifier] : NULL,
                                     passout, verbose))) {
                    BIO_printf(bio_err,
                               "Cannot create srp verifier for user \"%s\", operation abandoned .\n",
                               user);
                    errors++;
                    goto end;
                }
                row[DB_srpid] = OPENSSL_strdup(user);
                row[DB_srptype] = OPENSSL_strdup("v");
                row[DB_srpgN] = OPENSSL_strdup(gNid);

                if ((row[DB_srpid] == NULL)
                    || (row[DB_srpgN] == NULL)
                    || (row[DB_srptype] == NULL)
                    || (row[DB_srpverifier] == NULL)
                    || (row[DB_srpsalt] == NULL)
                    || (userinfo
                        && ((row[DB_srpinfo] = OPENSSL_strdup(userinfo)) == NULL))
                    || !update_index(db, row)) {
                    OPENSSL_free(row[DB_srpid]);
                    OPENSSL_free(row[DB_srpgN]);
                    OPENSSL_free(row[DB_srpinfo]);
                    OPENSSL_free(row[DB_srptype]);
                    OPENSSL_free(row[DB_srpverifier]);
                    OPENSSL_free(row[DB_srpsalt]);
                    goto end;
                }
                doupdatedb = 1;
            }
        } else if (mode == OPT_MODIFY) {
            if (userindex < 0) {
                BIO_printf(bio_err,
                           "user \"%s\" does not exist, operation ignored.\n",
                           user);
                errors++;
            } else {

                char **row =
                    sk_OPENSSL_PSTRING_value(db->db->data, userindex);
                char type = row[DB_srptype][0];
                if (type == 'v') {
                    BIO_printf(bio_err,
                               "user \"%s\" already updated, operation ignored.\n",
                               user);
                    errors++;
                } else {
                    char *gNid;

                    if (row[DB_srptype][0] == 'V') {
                        int user_gN;
                        char **irow = NULL;
                        if (verbose)
                            BIO_printf(bio_err,
                                       "Verifying password for user \"%s\"\n",
                                       user);
                        if ((user_gN =
                             get_index(db, row[DB_srpgN], DB_SRP_INDEX)) >= 0)
                            irow =
                                sk_OPENSSL_PSTRING_value(db->db->data,
                                                         userindex);

                        if (!srp_verify_user
                            (user, row[DB_srpverifier], row[DB_srpsalt],
                             irow ? irow[DB_srpsalt] : row[DB_srpgN],
                             irow ? irow[DB_srpverifier] : NULL, passin,
                             verbose)) {
                            BIO_printf(bio_err,
                                       "Invalid password for user \"%s\", operation abandoned.\n",
                                       user);
                            errors++;
                            goto end;
                        }
                    }
                    if (verbose)
                        BIO_printf(bio_err, "Password for user \"%s\" ok.\n",
                                   user);

                    if (!
                        (gNid =
                         srp_create_user(user, &(row[DB_srpverifier]),
                                         &(row[DB_srpsalt]),
                                         gNrow ? gNrow[DB_srpsalt] : NULL,
                                         gNrow ? gNrow[DB_srpverifier] : NULL,
                                         passout, verbose))) {
                        BIO_printf(bio_err,
                                   "Cannot create srp verifier for user \"%s\", operation abandoned.\n",
                                   user);
                        errors++;
                        goto end;
                    }

                    row[DB_srptype][0] = 'v';
                    row[DB_srpgN] = OPENSSL_strdup(gNid);

                    if (row[DB_srpid] == NULL
                        || row[DB_srpgN] == NULL
                        || row[DB_srptype] == NULL
                        || row[DB_srpverifier] == NULL
                        || row[DB_srpsalt] == NULL
                        || (userinfo
                            && ((row[DB_srpinfo] = OPENSSL_strdup(userinfo))
                                == NULL)))
                        goto end;

                    doupdatedb = 1;
                }
            }
        } else if (mode == OPT_DELETE) {
            if (userindex < 0) {
                BIO_printf(bio_err,
                           "user \"%s\" does not exist, operation ignored. t\n",
                           user);
                errors++;
            } else {
                char **xpp = sk_OPENSSL_PSTRING_value(db->db->data, userindex);

                BIO_printf(bio_err, "user \"%s\" revoked. t\n", user);
                xpp[DB_srptype][0] = 'R';
                doupdatedb = 1;
            }
        }
        if (--argc > 0)
            user = *(argv++);
        else {
            user = NULL;
        }
    }

    if (verbose)
        BIO_printf(bio_err, "User procession done.\n");

    if (doupdatedb) {
        /* Lets check some fields */
        for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) {
            pp = sk_OPENSSL_PSTRING_value(db->db->data, i);

            if (pp[DB_srptype][0] == 'v') {
                pp[DB_srptype][0] = 'V';
                print_user(db, i, verbose);
            }
        }

        if (verbose)
            BIO_printf(bio_err, "Trying to update srpvfile.\n");
        if (!save_index(srpvfile, "new", db))
            goto end;

        if (verbose)
            BIO_printf(bio_err, "Temporary srpvfile created.\n");
        if (!rotate_index(srpvfile, "new", "old"))
            goto end;

        if (verbose)
            BIO_printf(bio_err, "srpvfile updated.\n");
    }

    ret = (errors != 0);
 end:
    if (errors != 0)
        if (verbose)
            BIO_printf(bio_err, "User errors %d.\n", errors);

    if (verbose)
        BIO_printf(bio_err, "SRP terminating with code %d.\n", ret);

    OPENSSL_free(passin);
    OPENSSL_free(passout);
    if (ret)
        ERR_print_errors(bio_err);
    if (randfile)
        app_RAND_write_file(randfile);
    NCONF_free(conf);
    free_index(db);
    return (ret);
}
Exemple #18
0
int ocsp_main(int argc, char **argv)
{
    BIO *acbio = NULL, *cbio = NULL, *derbio = NULL, *out = NULL;
    const EVP_MD *cert_id_md = NULL, *rsign_md = NULL;
    int trailing_md = 0;
    CA_DB *rdb = NULL;
    EVP_PKEY *key = NULL, *rkey = NULL;
    OCSP_BASICRESP *bs = NULL;
    OCSP_REQUEST *req = NULL;
    OCSP_RESPONSE *resp = NULL;
    STACK_OF(CONF_VALUE) *headers = NULL;
    STACK_OF(OCSP_CERTID) *ids = NULL;
    STACK_OF(OPENSSL_STRING) *reqnames = NULL;
    STACK_OF(X509) *sign_other = NULL, *verify_other = NULL, *rother = NULL;
    STACK_OF(X509) *issuers = NULL;
    X509 *issuer = NULL, *cert = NULL;
    STACK_OF(X509) *rca_cert = NULL;
    X509 *signer = NULL, *rsigner = NULL;
    X509_STORE *store = NULL;
    X509_VERIFY_PARAM *vpm = NULL;
    const char *CAfile = NULL, *CApath = NULL;
    char *header, *value;
    char *host = NULL, *port = NULL, *path = "/", *outfile = NULL;
    char *rca_filename = NULL, *reqin = NULL, *respin = NULL;
    char *reqout = NULL, *respout = NULL, *ridx_filename = NULL;
    char *rsignfile = NULL, *rkeyfile = NULL;
    char *sign_certfile = NULL, *verify_certfile = NULL, *rcertfile = NULL;
    char *signfile = NULL, *keyfile = NULL;
    char *thost = NULL, *tport = NULL, *tpath = NULL;
    int noCAfile = 0, noCApath = 0;
    int accept_count = -1, add_nonce = 1, noverify = 0, use_ssl = -1;
    int vpmtouched = 0, badsig = 0, i, ignore_err = 0, nmin = 0, ndays = -1;
    int req_text = 0, resp_text = 0, ret = 1;
#ifndef OPENSSL_NO_SOCK
    int req_timeout = -1;
#endif
    long nsec = MAX_VALIDITY_PERIOD, maxage = -1;
    unsigned long sign_flags = 0, verify_flags = 0, rflags = 0;
    OPTION_CHOICE o;
    char *prog;

    reqnames = sk_OPENSSL_STRING_new_null();
    if (reqnames == NULL)
        goto end;
    ids = sk_OCSP_CERTID_new_null();
    if (ids == NULL)
        goto end;
    if ((vpm = X509_VERIFY_PARAM_new()) == NULL)
        return 1;

    prog = opt_init(argc, argv, ocsp_options);
    while ((o = opt_next()) != OPT_EOF) {
        switch (o) {
        case OPT_EOF:
        case OPT_ERR:
 opthelp:
            BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
            goto end;
        case OPT_HELP:
            ret = 0;
            opt_help(ocsp_options);
            goto end;
        case OPT_OUTFILE:
            outfile = opt_arg();
            break;
        case OPT_TIMEOUT:
#ifndef OPENSSL_NO_SOCK
            req_timeout = atoi(opt_arg());
#endif
            break;
        case OPT_URL:
            OPENSSL_free(thost);
            OPENSSL_free(tport);
            OPENSSL_free(tpath);
            thost = tport = tpath = NULL;
            if (!OCSP_parse_url(opt_arg(), &host, &port, &path, &use_ssl)) {
                BIO_printf(bio_err, "%s Error parsing URL\n", prog);
                goto end;
            }
            thost = host;
            tport = port;
            tpath = path;
            break;
        case OPT_HOST:
            host = opt_arg();
            break;
        case OPT_PORT:
            port = opt_arg();
            break;
        case OPT_IGNORE_ERR:
            ignore_err = 1;
            break;
        case OPT_NOVERIFY:
            noverify = 1;
            break;
        case OPT_NONCE:
            add_nonce = 2;
            break;
        case OPT_NO_NONCE:
            add_nonce = 0;
            break;
        case OPT_RESP_NO_CERTS:
            rflags |= OCSP_NOCERTS;
            break;
        case OPT_RESP_KEY_ID:
            rflags |= OCSP_RESPID_KEY;
            break;
        case OPT_NO_CERTS:
            sign_flags |= OCSP_NOCERTS;
            break;
        case OPT_NO_SIGNATURE_VERIFY:
            verify_flags |= OCSP_NOSIGS;
            break;
        case OPT_NO_CERT_VERIFY:
            verify_flags |= OCSP_NOVERIFY;
            break;
        case OPT_NO_CHAIN:
            verify_flags |= OCSP_NOCHAIN;
            break;
        case OPT_NO_CERT_CHECKS:
            verify_flags |= OCSP_NOCHECKS;
            break;
        case OPT_NO_EXPLICIT:
            verify_flags |= OCSP_NOEXPLICIT;
            break;
        case OPT_TRUST_OTHER:
            verify_flags |= OCSP_TRUSTOTHER;
            break;
        case OPT_NO_INTERN:
            verify_flags |= OCSP_NOINTERN;
            break;
        case OPT_BADSIG:
            badsig = 1;
            break;
        case OPT_TEXT:
            req_text = resp_text = 1;
            break;
        case OPT_REQ_TEXT:
            req_text = 1;
            break;
        case OPT_RESP_TEXT:
            resp_text = 1;
            break;
        case OPT_REQIN:
            reqin = opt_arg();
            break;
        case OPT_RESPIN:
            respin = opt_arg();
            break;
        case OPT_SIGNER:
            signfile = opt_arg();
            break;
        case OPT_VAFILE:
            verify_certfile = opt_arg();
            verify_flags |= OCSP_TRUSTOTHER;
            break;
        case OPT_SIGN_OTHER:
            sign_certfile = opt_arg();
            break;
        case OPT_VERIFY_OTHER:
            verify_certfile = opt_arg();
            break;
        case OPT_CAFILE:
            CAfile = opt_arg();
            break;
        case OPT_CAPATH:
            CApath = opt_arg();
            break;
        case OPT_NOCAFILE:
            noCAfile = 1;
            break;
        case OPT_NOCAPATH:
            noCApath = 1;
            break;
        case OPT_V_CASES:
            if (!opt_verify(o, vpm))
                goto end;
            vpmtouched++;
            break;
        case OPT_VALIDITY_PERIOD:
            opt_long(opt_arg(), &nsec);
            break;
        case OPT_STATUS_AGE:
            opt_long(opt_arg(), &maxage);
            break;
        case OPT_SIGNKEY:
            keyfile = opt_arg();
            break;
        case OPT_REQOUT:
            reqout = opt_arg();
            break;
        case OPT_RESPOUT:
            respout = opt_arg();
            break;
        case OPT_PATH:
            path = opt_arg();
            break;
        case OPT_ISSUER:
            issuer = load_cert(opt_arg(), FORMAT_PEM, "issuer certificate");
            if (issuer == NULL)
                goto end;
            if (issuers == NULL) {
                if ((issuers = sk_X509_new_null()) == NULL)
                    goto end;
            }
            sk_X509_push(issuers, issuer);
            break;
        case OPT_CERT:
            X509_free(cert);
            cert = load_cert(opt_arg(), FORMAT_PEM, "certificate");
            if (cert == NULL)
                goto end;
            if (cert_id_md == NULL)
                cert_id_md = EVP_sha1();
            if (!add_ocsp_cert(&req, cert, cert_id_md, issuer, ids))
                goto end;
            if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
                goto end;
            trailing_md = 0;
            break;
        case OPT_SERIAL:
            if (cert_id_md == NULL)
                cert_id_md = EVP_sha1();
            if (!add_ocsp_serial(&req, opt_arg(), cert_id_md, issuer, ids))
                goto end;
            if (!sk_OPENSSL_STRING_push(reqnames, opt_arg()))
                goto end;
            trailing_md = 0;
            break;
        case OPT_INDEX:
            ridx_filename = opt_arg();
            break;
        case OPT_CA:
            rca_filename = opt_arg();
            break;
        case OPT_NMIN:
            opt_int(opt_arg(), &nmin);
            if (ndays == -1)
                ndays = 0;
            break;
        case OPT_REQUEST:
            opt_int(opt_arg(), &accept_count);
            break;
        case OPT_NDAYS:
            ndays = atoi(opt_arg());
            break;
        case OPT_RSIGNER:
            rsignfile = opt_arg();
            break;
        case OPT_RKEY:
            rkeyfile = opt_arg();
            break;
        case OPT_ROTHER:
            rcertfile = opt_arg();
            break;
        case OPT_RMD:   /* Response MessageDigest */
            if (!opt_md(opt_arg(), &rsign_md))
                goto end;
            break;
        case OPT_HEADER:
            header = opt_arg();
            value = strchr(header, '=');
            if (value == NULL) {
                BIO_printf(bio_err, "Missing = in header key=value\n");
                goto opthelp;
            }
            *value++ = '\0';
            if (!X509V3_add_value(header, value, &headers))
                goto end;
            break;
        case OPT_MD:
            if (trailing_md) {
                BIO_printf(bio_err,
                           "%s: Digest must be before -cert or -serial\n",
                           prog);
                goto opthelp;
            }
            if (!opt_md(opt_unknown(), &cert_id_md))
                goto opthelp;
            trailing_md = 1;
            break;
        }
    }

    if (trailing_md) {
        BIO_printf(bio_err, "%s: Digest must be before -cert or -serial\n",
                   prog);
        goto opthelp;
    }
    argc = opt_num_rest();
    if (argc != 0)
        goto opthelp;

    /* Have we anything to do? */
    if (req == NULL&& reqin == NULL
        && respin == NULL && !(port != NULL && ridx_filename != NULL))
        goto opthelp;

    out = bio_open_default(outfile, 'w', FORMAT_TEXT);
    if (out == NULL)
        goto end;

    if (req == NULL && (add_nonce != 2))
        add_nonce = 0;

    if (req == NULL && reqin != NULL) {
        derbio = bio_open_default(reqin, 'r', FORMAT_ASN1);
        if (derbio == NULL)
            goto end;
        req = d2i_OCSP_REQUEST_bio(derbio, NULL);
        BIO_free(derbio);
        if (req == NULL) {
            BIO_printf(bio_err, "Error reading OCSP request\n");
            goto end;
        }
    }

    if (req == NULL && port != NULL) {
        acbio = init_responder(port);
        if (acbio == NULL)
            goto end;
    }

    if (rsignfile != NULL) {
        if (rkeyfile == NULL)
            rkeyfile = rsignfile;
        rsigner = load_cert(rsignfile, FORMAT_PEM, "responder certificate");
        if (rsigner == NULL) {
            BIO_printf(bio_err, "Error loading responder certificate\n");
            goto end;
        }
        if (!load_certs(rca_filename, &rca_cert, FORMAT_PEM,
                        NULL, "CA certificate"))
            goto end;
        if (rcertfile != NULL) {
            if (!load_certs(rcertfile, &rother, FORMAT_PEM, NULL,
                            "responder other certificates"))
                goto end;
        }
        rkey = load_key(rkeyfile, FORMAT_PEM, 0, NULL, NULL,
                        "responder private key");
        if (rkey == NULL)
            goto end;
    }
    if (acbio != NULL)
        BIO_printf(bio_err, "Waiting for OCSP client connections...\n");

redo_accept:

    if (acbio != NULL) {
        if (!do_responder(&req, &cbio, acbio))
            goto end;
        if (req == NULL) {
            resp =
                OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST,
                                     NULL);
            send_ocsp_response(cbio, resp);
            goto done_resp;
        }
    }

    if (req == NULL
        && (signfile != NULL || reqout != NULL
            || host != NULL || add_nonce || ridx_filename != NULL)) {
        BIO_printf(bio_err, "Need an OCSP request for this operation!\n");
        goto end;
    }

    if (req != NULL && add_nonce)
        OCSP_request_add1_nonce(req, NULL, -1);

    if (signfile != NULL) {
        if (keyfile == NULL)
            keyfile = signfile;
        signer = load_cert(signfile, FORMAT_PEM, "signer certificate");
        if (signer == NULL) {
            BIO_printf(bio_err, "Error loading signer certificate\n");
            goto end;
        }
        if (sign_certfile != NULL) {
            if (!load_certs(sign_certfile, &sign_other, FORMAT_PEM, NULL,
                            "signer certificates"))
                goto end;
        }
        key = load_key(keyfile, FORMAT_PEM, 0, NULL, NULL,
                       "signer private key");
        if (key == NULL)
            goto end;

        if (!OCSP_request_sign
            (req, signer, key, NULL, sign_other, sign_flags)) {
            BIO_printf(bio_err, "Error signing OCSP request\n");
            goto end;
        }
    }

    if (req_text && req != NULL)
        OCSP_REQUEST_print(out, req, 0);

    if (reqout != NULL) {
        derbio = bio_open_default(reqout, 'w', FORMAT_ASN1);
        if (derbio == NULL)
            goto end;
        i2d_OCSP_REQUEST_bio(derbio, req);
        BIO_free(derbio);
    }

    if (ridx_filename != NULL
        && (rkey == NULL || rsigner == NULL || rca_cert == NULL)) {
        BIO_printf(bio_err,
                   "Need a responder certificate, key and CA for this operation!\n");
        goto end;
    }

    if (ridx_filename != NULL && rdb == NULL) {
        rdb = load_index(ridx_filename, NULL);
        if (rdb == NULL)
            goto end;
        if (!index_index(rdb))
            goto end;
    }

    if (rdb != NULL) {
        make_ocsp_response(&resp, req, rdb, rca_cert, rsigner, rkey,
                               rsign_md, rother, rflags, nmin, ndays, badsig);
        if (cbio != NULL)
            send_ocsp_response(cbio, resp);
    } else if (host != NULL) {
# ifndef OPENSSL_NO_SOCK
        resp = process_responder(req, host, path,
                                 port, use_ssl, headers, req_timeout);
        if (resp == NULL)
            goto end;
# else
        BIO_printf(bio_err,
                   "Error creating connect BIO - sockets not supported.\n");
        goto end;
# endif
    } else if (respin != NULL) {
        derbio = bio_open_default(respin, 'r', FORMAT_ASN1);
        if (derbio == NULL)
            goto end;
        resp = d2i_OCSP_RESPONSE_bio(derbio, NULL);
        BIO_free(derbio);
        if (resp == NULL) {
            BIO_printf(bio_err, "Error reading OCSP response\n");
            goto end;
        }
    } else {
        ret = 0;
        goto end;
    }

 done_resp:

    if (respout != NULL) {
        derbio = bio_open_default(respout, 'w', FORMAT_ASN1);
        if (derbio == NULL)
            goto end;
        i2d_OCSP_RESPONSE_bio(derbio, resp);
        BIO_free(derbio);
    }

    i = OCSP_response_status(resp);
    if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
        BIO_printf(out, "Responder Error: %s (%d)\n",
                   OCSP_response_status_str(i), i);
        if (ignore_err)
            goto redo_accept;
        ret = 0;
        goto end;
    }

    if (resp_text)
        OCSP_RESPONSE_print(out, resp, 0);

    /* If running as responder don't verify our own response */
    if (cbio != NULL) {
        /* If not unlimited, see if we took all we should. */
        if (accept_count != -1 && --accept_count <= 0) {
            ret = 0;
            goto end;
        }
        BIO_free_all(cbio);
        cbio = NULL;
        OCSP_REQUEST_free(req);
        req = NULL;
        OCSP_RESPONSE_free(resp);
        resp = NULL;
        goto redo_accept;
    }
    if (ridx_filename != NULL) {
        ret = 0;
        goto end;
    }

    if (store == NULL) {
        store = setup_verify(CAfile, CApath, noCAfile, noCApath);
        if (!store)
            goto end;
    }
    if (vpmtouched)
        X509_STORE_set1_param(store, vpm);
    if (verify_certfile != NULL) {
        if (!load_certs(verify_certfile, &verify_other, FORMAT_PEM, NULL,
                        "validator certificate"))
            goto end;
    }

    bs = OCSP_response_get1_basic(resp);
    if (bs == NULL) {
        BIO_printf(bio_err, "Error parsing response\n");
        goto end;
    }

    ret = 0;

    if (!noverify) {
        if (req != NULL && ((i = OCSP_check_nonce(req, bs)) <= 0)) {
            if (i == -1)
                BIO_printf(bio_err, "WARNING: no nonce in response\n");
            else {
                BIO_printf(bio_err, "Nonce Verify error\n");
                ret = 1;
                goto end;
            }
        }

        i = OCSP_basic_verify(bs, verify_other, store, verify_flags);
        if (i <= 0 && issuers) {
            i = OCSP_basic_verify(bs, issuers, store, OCSP_TRUSTOTHER);
            if (i > 0)
                ERR_clear_error();
        }
        if (i <= 0) {
            BIO_printf(bio_err, "Response Verify Failure\n");
            ERR_print_errors(bio_err);
            ret = 1;
        } else {
            BIO_printf(bio_err, "Response verify OK\n");
        }
    }

    print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage);

 end:
    ERR_print_errors(bio_err);
    X509_free(signer);
    X509_STORE_free(store);
    X509_VERIFY_PARAM_free(vpm);
    EVP_PKEY_free(key);
    EVP_PKEY_free(rkey);
    X509_free(cert);
    sk_X509_pop_free(issuers, X509_free);
    X509_free(rsigner);
    sk_X509_pop_free(rca_cert, X509_free);
    free_index(rdb);
    BIO_free_all(cbio);
    BIO_free_all(acbio);
    BIO_free(out);
    OCSP_REQUEST_free(req);
    OCSP_RESPONSE_free(resp);
    OCSP_BASICRESP_free(bs);
    sk_OPENSSL_STRING_free(reqnames);
    sk_OCSP_CERTID_free(ids);
    sk_X509_pop_free(sign_other, X509_free);
    sk_X509_pop_free(verify_other, X509_free);
    sk_CONF_VALUE_pop_free(headers, X509V3_conf_free);
    OPENSSL_free(thost);
    OPENSSL_free(tport);
    OPENSSL_free(tpath);

    return ret;
}
Exemple #19
0
/**
 * Constructor.
 *
 * @intervals - if empty, will add the contigs found in the header files
 */
BCFSyncedReader::BCFSyncedReader(std::vector<std::string>& file_names, std::vector<GenomeInterval>& intervals, bool sync_by_pos)
:file_names(file_names), intervals(intervals), sync_by_pos(sync_by_pos)
{
    nfiles = file_names.size();
    files.resize(nfiles, 0);
    hdrs.resize(nfiles, 0);
    idxs.resize(nfiles, 0);
    tbxs.resize(nfiles, 0);
    itrs.resize(nfiles, 0);
    ftypes.resize(nfiles);

    current_interval = "";
    current_pos1 = 0;

    buffer.resize(nfiles);
    s = {0, 0, 0};

    random_access = (intervals.size()!=0);
    for (size_t i=0; i<intervals.size(); ++i)
    {
        intervals_map[intervals[i].to_string()] = i;
    }
    intervals_index = 0;

    uint32_t no_stdins = 0;

    for (size_t i = 0; i<nfiles; ++i)
    {
        if (file_names[0]=="+")
        {
            file_names[0]="-";
            ++no_stdins;
        }
        else if (file_names[0]=="-")
        {
            file_names[0]="-";
            ++no_stdins;
        }

        if (no_stdins>1)
        {
            fprintf(stderr, "[E:%s:%d %s] BCFSyncedReader does not support reading from more than one STDIN stream\n", __FILE__, __LINE__, __FUNCTION__);
            exit(1);
        }

        files[i] = hts_open(file_names[i].c_str(), "r");
        if (files[i]==NULL)
        {
            fprintf(stderr, "[%s:%d %s] Cannot open %s\n", __FILE__, __LINE__, __FUNCTION__, file_names[i].c_str());
            exit(1);
        }
        ftypes[i] = files[i]->format;

        //check format
        if (ftypes[i].format!=vcf && ftypes[i].format!=bcf)
        {
            fprintf(stderr, "[E:%s:%d %s] %s not a VCF or BCF file\n", __FILE__, __LINE__, __FUNCTION__, file_names[i].c_str());
            exit(1);
        }

        //read header
        hdrs[i] = bcf_alt_hdr_read(files[i]);
        if (!hdrs[i])
        {
            fprintf(stderr, "[E:%s:%d %s] header cannot be read for %s\n", __FILE__, __LINE__, __FUNCTION__, file_names[i].c_str());
            exit(1);
        }

        //load index if intervals are specified
        if (random_access && !load_index(i))
        {
            fprintf(stderr, "[E:%s:%d %s] index cannot be loaded for %s for random access\n", __FILE__, __LINE__, __FUNCTION__, file_names[i].c_str());
            exit(1);
        }

        //check contigs consistency
        if (i)
        {
            int32_t nseqs0;
            const char ** seqnames0 = bcf_hdr_seqnames(hdrs[i], &nseqs0);

            int32_t nseqs;
            const char ** seqnames = bcf_hdr_seqnames(hdrs[i], &nseqs);

            if (nseqs0==0 || nseqs==0 || nseqs0!=nseqs)
            {
                fprintf(stderr, "[E:%s:%d %s] contigs in header not consistent with first file for %s\n", __FILE__, __LINE__, __FUNCTION__, file_names[i].c_str());
                exit(1);
            }

            for (size_t j=0; j<nseqs; ++j)
            {
                if (strcmp(seqnames0[j], seqnames[j]))
                {
                    fprintf(stderr, "[E:%s:%d %s] contigs in header not consistent with first file for %s\n", __FILE__, __LINE__, __FUNCTION__, file_names[i].c_str());
                    exit(1);
                }
            }

            free(seqnames0);
            free(seqnames);
        }
    }
}