Пример #1
0
int	main(void)
{
	char	*key;
	char	*value;
	char	*tmp;
	int		read;
	t_node	*root;

	read = 1;
	root = 0;
	while (read)
	{
		get_next_line(0, &key);
		read = get_next_line(0, &value);
		if (!ft_strcmp(key, ""))
			read = 0;
		else
			add_node(&root, key, value);
	}
	if (*value)
	{
		search_key(root, value);
		while (get_next_line(0, &tmp) > 0)
			search_key(root, tmp);
	}
	destroy_tree(&root);
	return (0);
}
Пример #2
0
/*
 * connect to pgsql catalog database
 *
 * in:
 *    paramlist - list of parameters from config file
 *       required params: CATDBHOST, CATDBPORT, CATDB, CATUSER, CATPASSWD
 * out:
 *    on success: PGconn * - working catalog connection
 *    on error:   NULL
 */
PGconn * catdbconnect ( keylist * paramlist ){

   char * catdbconnstring = NULL;
   PGconn * conndb = NULL;
   ConnStatusType status;

   catdbconnstring = MALLOC ( CONNSTRLEN );
   ASSERT_NVAL_RET_NULL ( catdbconnstring );

   snprintf ( catdbconnstring, CONNSTRLEN, "host=%s port=%s dbname=%s user=%s password=%s",
         search_key ( paramlist, "CATDBHOST" ),
         search_key ( paramlist, "CATDBPORT" ),
         search_key ( paramlist, "CATDB" ),
         search_key ( paramlist, "CATUSER" ),
         search_key ( paramlist, "CATPASSWD" ));

   conndb = PQconnectdb ( catdbconnstring );
   FREE ( catdbconnstring );

   status = PQstatus ( conndb );
   if ( status == CONNECTION_BAD ){
      logprg ( LOGERROR, PQerrorMessage( conndb ) );
      PQfinish ( conndb );
      return NULL;
   }
   /* check for schema version number */
   if ( !check_schema_version ( conndb, 1 )){
      printf ( "Schema version error\n" );
   }

   return conndb;
}
Пример #3
0
node_t* search_key( node_t* node, key_type key ){
        if( node == NULL ){
                printf("Node not found\n");
                return NULL;
        }

        if( comp_key( key, node->key ) == 0 )
                return node;
        
        if( comp_key( key, node->key ) == -1 )
                search_key( node->left, key );
        else
                search_key( node->right, key);
}
Пример #4
0
int main() {
	int t, i, j, n, sr, steps;
	Treap[0].l = Treap[0].r = Treap[0].key = 0;
	scanf("%d", &t);

	while (t--) {
		//    memset(Treap,0,MAXNODES*sizeof(item));
		scanf("%d", &n);
		buildtree(1, 1, n, 0);
		i = n;
		j = 2;
		steps = 2;
		a[1] = a[2] = 1;
		while (i > 1) {
			//printf("\n\ncall erase with j=%d steps:%d\n",j,steps);
			erase_key(1, j, steps - 1);
			// print_tree(1);
			i--;
			steps++;
			j = ((j + steps - 2) % i) + 1;
		}
		a[2] = 1;
		sr = search_key(1);
		a[Treap[sr].idx] = steps - 1;
		for (i = 1; i <= n; i++)
			printf("%d ", a[i]);
		printf("\n");
		//n==2?printf("2\n"):printf("%d\n",Treap[sr].idx);

		// (Treap[1].l)? printf("%d\n",Treap[1].idx):printf("%d\n",Treap[1].idx);
	}
	return 0;
}
Пример #5
0
/*
 * searches at catdb for rowid of input data
 * 
 * in:
 *    pdata->paramlist,"ARCHCLIENT"
 *    pdata->walfilename
 * out:
 *    >= 0 - on success, status vaule for selected wal and client
 *    < 0 - value not found or error
 */
int _get_walstatus_from_catalog ( pgsqldata * pdata ){

   int pgstatus = -1;
   char * sql;
   PGresult * result;

   sql = MALLOC ( SQLLEN );
   snprintf ( sql, SQLLEN, "select status from pgsql_archivelogs where client='%s' and filename='%s'",
         search_key ( pdata->paramlist, "ARCHCLIENT" ),
         pdata->walfilename );

   result = PQexec ( pdata->catdb, sql );
   FREE ( sql );

   if ( PQresultStatus ( result ) != PGRES_TUPLES_OK ){
      return -1;
   }

   if ( PQntuples ( result ) ){
      /* we found a row and pgid will be a primary key of the row */
      pgstatus = atoi ((char *) PQgetvalue ( result, 0, PQfnumber ( result, "status") ));
   }

   return pgstatus;
}
Пример #6
0
node_t* remove_key( node_t* root, key_type key ){
        node_t* node = search_key(root,key);

        if( node == NULL ){
                printf("Node not found!\n");
                return;
        }

        if( node->right == NULL && node->left == NULL ){
                printf("node:%d\n", node->key.value);
                free_node(node);
                return;
        }

        node_t* replace = NULL;
        if( node->left != NULL ){
                replace = find_predecessor(node->left);
                copy_key( &(node->key), replace->key);
        } else if( node->right != NULL ){
                replace = find_successor(node->right);
                copy_key( &(node->key), replace->key);
        } 
        
        free_node(replace);
}
Пример #7
0
// Retrieve an entry from mEventMap and delete it.
UtlContainable* ResourceListSet::retrieveObjectBySeqNoAndDeleteMapping(int seqNo)
{
   // Serialize access to the ResourceListSet.
   OsLock lock(mSemaphore);

   // Search for and possibly delete seqNo.
   UtlInt search_key(seqNo);
   UtlContainable* value;
   UtlContainable* key = mEventMap.removeKeyAndValue(&search_key, value);

   if (key)
   {
      Os::Logger::instance().log(FAC_RLS, PRI_DEBUG,
                    "ResourceListSet::retrieveObjectBySeqNoAndDeleteMapping seqNo = %d, value = %p",
                    seqNo, value);
      delete key;
   }
   else
   {
      Os::Logger::instance().log(FAC_RLS, PRI_WARNING,
                    "ResourceListSet::retrieveObjectBySeqNoAndDeleteMapping seqNo = %d not found",
                    seqNo);
   }

   return value;
}
Пример #8
0
bool decrypt_file(FileTypesSet &fileTypes, Params &params, std::string enc_filename)
{
    //get extension:
    std::string extension = get_extension(enc_filename);
    FileType *my_type =  fileTypes.getType(extension);

    if (my_type == NULL) {
        printf("[ERROR] Not supported file type! Add a header for %s into '%s' folder!\n", extension.c_str(), HDRS_DIR);
        return false;
    }
    TypeValidator *validator = makeValidator(my_type);
    if (validator == NULL) {
        printf("[ERROR] Not suppeoted File Type: %s\n", extension.c_str());
        return false;
    }
    validator->init(enc_filename, my_type);

    printf("Extension: %s\n", extension.c_str());
    //crack it!
    bool isDecrypted = false;
    std::string key = search_key(params, validator, params.series_min, params.series_max);
    if (key.length() == DmaDecryptor::KEY_LEN ) {
        DmaDecryptor decr(enc_filename, key);
        decr.init();
        isDecrypted = decr.decrypt(DmaDecryptor::makeOutName(enc_filename.c_str()));
    }
    delete validator;
    return isDecrypted;
}
Пример #9
0
Node *search_key(int target, Node *root, int *targetpos){
  if (root == NULL)
    return NULL;
  else 
    if (linear_search(target,root,targetpos))
      return root;
    else
      return search_key(target,root->branch[*targetpos],targetpos);
}
Пример #10
0
  cudaError_t malloc(void** devPtr, size_t size, cudaStream_t stream)
  {
    std::lock_guard<std::mutex> lock(mutex);

    int device;
    cudaError_t err = cudaGetDevice(&device);
    if (err != cudaSuccess) {
      return err;
    }

    size = round_size(size);
    bool small = size <= kSmallAlloc;

    Block search_key(device, stream, size);
    auto& free_blocks = small ? large_blocks : small_blocks;

    Block* block = NULL;
    Block* remaining = NULL;

    auto it = free_blocks.lower_bound(&search_key);
    if (it != free_blocks.end() && (*it)->device == device && (*it)->stream == stream) {
      block = *it;
      free_blocks.erase(it);
    } else {
      void* ptr;
      size_t alloc_size = small ? kSmallAlloc : size;
      cudaError_t err = cuda_malloc_retry(device, &ptr, alloc_size);
      if (err != cudaSuccess) {
        return err;
      }
      block = new Block(device, stream, alloc_size, (char*)ptr);
    }

    if (block->size - size >= (small ? kRoundSmall : kSmallAlloc + 1)) {
      remaining = block;

      block = new Block(device, stream, size, block->ptr);
      block->prev = remaining->prev;
      if (block->prev) {
        block->prev->next = block;
      }
      block->next = remaining;

      remaining->prev = block;
      remaining->ptr += size;
      remaining->size -= size;
      free_blocks.insert(remaining);
    }

    block->allocated = true;
    allocated_blocks[block->ptr] = block;

    *devPtr = (void*)block->ptr;
    return cudaSuccess;
  }
Пример #11
0
void font::measure(string const &text, rectangle &bounds) const
{
   float x = 0.0f;
   float y = 0.0f;

   if (text.size() == 0)
      return;

   //y += m_common.base;
   for (size_t i = 0; i < text.size(); ++i)
   {
      char c = text[i];
      unsigned char uc = static_cast<unsigned char>(c);

      ft_char const &font_char = m_chars_256[uc];
      if (font_char.width == 0)
         continue;

      float a  = static_cast<float>(font_char.xadvance);
      float w  = static_cast<float>(font_char.width);
      float h  = static_cast<float>(font_char.height);
      float ox = static_cast<float>(font_char.xoffset);
      float oy = static_cast<float>(font_char.yoffset);

      bounds.extend_by(x +     ox, y +     oy);
      bounds.extend_by(x + w + ox, y +     oy);
      bounds.extend_by(x + w + ox, y + h + oy);
      bounds.extend_by(x +     ox, y + h + oy);

      x += a;
      x += m_spacing_delta;

      if (i + 1 < text.size() - 1)
      {
         char next = text[i + 1];
         kerning search_key(static_cast<unsigned short>(next));
         compare_kerning cmp;

         auto j = std::lower_bound(
            font_char.kernings.cbegin(),
            font_char.kernings.cend(),
            search_key,
            cmp
         );

         if (j != font_char.kernings.cend())
         {
            kerning const &k = *j;
            x += static_cast<float>(k.amount);
         }
      }
   }
}
Пример #12
0
int search_key(BTreeNode* head,char* key,struct DB* db,BTreeNode* result)
{
	unsigned int i = 0;
	while(i < head->nKeys && keys_compare(head,key,i) > 0)i++;
	if(i < head->nKeys && keys_compare(head,key,i) == 0)
	{
		*result = *head; 
		return 1;
	} 
	if(head->leaf)return 0;
	else 
	{
		disk_read_node(db,head->chld[i],result);
		search_key(result,key,db,result); 
	}
}
Пример #13
0
int     search_key(BTREE *bt, long page, KEY *key, ITEM *u)
{
PAGE_ADDRESS *p;
KEY *pk, *pkk;
long    nx;
int	l, r, k;

   if (page == BTREE_NULL)
   {
        u->next = page;
	u->address = BTREE_NULL;
	u->size = -1;
	btree_errno = NON_KEY;
        return -1;
   }

   p = (PAGE_ADDRESS *) get_page(bt, page);
   pk = (KEY *) (p + 1);

   l = 0; r = p->nkeys-1;
   do {
        k = (l + r) / 2;
        pkk = nth_key(bt, p, k);

        if (bt->compare_key((void *) key, pkk) < 0) r = k - 1;
        else

        if (bt->compare_key((void *) key, pkk) > 0) l = k + 1;
        else
           break;
   } while (r >= l);

   if (r >= l)
   {
	*u = p->s[k];
        return 0;      /* chave jah existe */
   }

   if (r < 0)
        nx = p->next0;
   else
        nx = p->s[r].next;

   return search_key(bt, nx, key, u);
}
Пример #14
0
int main(int argc, char *argv[])
{
	char word[100];
	struct key_word *key = NULL;

	/*
	 * use getword-2.c 's getword routine
	 */
	while (getword(word, 100) != EOF) {
		if (isalpha(word[0])) {
			key = search_key(keywords, word);
			if (key) 
				key->count++;
		}
	}
	keywords_print(keywords);
	exit(0);
}
Пример #15
0
int main(int argc, char *argv[]) {
	data_t alldata[MAXDATA];
	int i,l,k;
	int n;
	int c=0;
	data_t data;
	/* open a buildfile */
	FILE *buildfile;
	if((buildfile=fopen(argv[1], "r"))==NULL){
		printf("No file\n");
	}  
	n = 0;
	while(fscanf(buildfile,"%d %s\n",&data.key,&data.val)==2){
		alldata[(n)++]=data;
	}
	fclose(buildfile);
	
	int searchkey;
	int search[MAXDATA];
	int m=0;
	while(scanf("%d\n",&searchkey)==1){
		search[m]=searchkey;
		m++;
	}	
	SkipSet* set = make_skipset();    
     	for(i=0;i<n;i++){
     		c+=insert(set, alldata[i].key);
     	}
     	printf("%d Insertions %d\n",n,c);
     	for(l=0;l<m;l++){
     		if(search_key(set, search[l])) {
     			printf("%d ",search[l]);
     			for(k=0;k<n;k++){
     				if(search[l]==alldata[k].key){   	     	     
     					printf("%s %d\n",alldata[k].val,l);
     				}
     			}
     		}
     		else{
     			printf("%d NOTFOUND %d\n",search[l],l);
     		}
     	} 
     	return 0;
}
Пример #16
0
void input_function(){
  char input,blank,dump;
  int position,i,key;
  Node *node;
  root = NULL;
  printf("> ");
  
  while (fscanf(fp,"%c",&input) != EOF) { 
    switch (input) {
      case 'q' : printf("\n");
                 exit(0);
      case 'f' : fscanf(fp,"%c%d%c",&blank,&key,&dump);
                 printf("FIND: %d\n",key);
                 node=search_key(key,root,&position);
                 if(node)
                  {
                    printf("Found key %d at position %d in node ",key,position);
                    int temps=-1;
                    print_node(node,0,0,&temps,FALSE);
                    printf("\n");
                  }
                else
                  printf("Not found %d\n",key);
                 break;
      case 'i' : fscanf(fp,"%c%d%c",&blank,&key,&dump);
                 printf("INSERT: %d\n",key); 
                 root=insert_main(key,root);
                 break;     
      case 'd' : fscanf(fp,"%c%d%c",&blank,&key,&dump);
                 printf("DELETE: %d\n",key); 
                 root=delete_key(key,root);
                 break;
      case 'p' : fscanf(fp,"%c",&dump);
                   printf("B-TREE:\n"); 
                   print_allnodes(root);
                 break;
      default:
               usageinput();
               break; 
    }
    printf("> ");
  }   
}
Пример #17
0
//! Delete a mapping for a Resource's sequence number.
void ResourceListSet::deleteResourceSeqNoMapping(int seqNo)
{
   // Search for and possibly delete seqNo.
   UtlInt search_key(seqNo);
   UtlContainable* value;
   UtlContainable* key = mEventMap.removeKeyAndValue(&search_key, value);

   if (key)
   {
      Os::Logger::instance().log(FAC_RLS, PRI_DEBUG,
                    "ResourceListSet::deleteResourceSeqNoMapping seqNo = %d, instanceName = '%s'",
                    seqNo,
                    (dynamic_cast <ResourceCached*> (value))->getUri()->data());
      delete key;
   }
   else
   {
      Os::Logger::instance().log(FAC_RLS, PRI_WARNING,
                    "ResourceListSet::deleteResourceSeqNoMapping seqNo = %d not found",
                    seqNo);
   }
}
Пример #18
0
void	search_index(t_node *tree)
{
	char	*search;
	char	*tmp;
	char	*s;
	int		gnl;

	s = NULL;
	search = NULL;
	tmp = search;
	gnl = get_next_line(0, &search);
	while (gnl)
	{
		s = search_key(search, tree);
		ft_putendl(s);
		free(s);
		free(tmp);
		tmp = search;
		gnl = get_next_line(0, &search);
	}
	free(tmp);
}
Пример #19
0
/*
 * inserts a status value into a catalog
 * 
 * in:
 *    pdata->paramlist,"ARCHCLIENT"
 *    pdata->walfilename
 *    status - status number to insert into catdb
 * out:
 *    pgid - id of inserted row
 *    >= 0 - on success, vaule of id for selected wal and client
 *    < 0 - on error
 */
int _insert_status_in_catalog ( pgsqldata * pdata, int status ){

   char * sql;
   PGresult * result;
   int pgid;

   sql = MALLOC ( SQLLEN );
   /* insert status in catalog */
   snprintf ( sql, SQLLEN, "insert into pgsql_archivelogs (client, filename, status) values ('%s', '%s', '%i')",
         search_key ( pdata->paramlist, "ARCHCLIENT" ),
         pdata->walfilename, status );

   result = PQexec ( pdata->catdb, sql );
   FREE ( sql );
   
   if ( PQresultStatus ( result ) != PGRES_COMMAND_OK ){
      return -1;
   }

   pgid = _get_walid_from_catalog ( pdata );

   return pgid;
}
Пример #20
0
/*
 * message queue (IPC) initialization
 * 
 * input:
 *    pdata->paramlist[PGDATA]
 * output:
 *    msqid - on success, message queue id
 *    -1 - on error
 */
int pgsql_msg_init ( pgsqldata * pdata, int prg ){

   key_t key;     /* key to be passed to msgget() */ 
   int msgflg;    /* msgflg to be passed to msgget() */
   int msqid;     /* return value from msgget() */ 

   key = ftok ( search_key ( pdata->paramlist, "PGDATA" ), prg );
   if ( key == -1 ){
      /* TODO: change error logging */
      perror ( " msgget failed" );
      return -1;
   }

   msgflg = IPC_CREAT | 0666 ;

   if ( ( msqid = msgget ( key, msgflg ) ) == -1 ){
      /* TODO: change error logging */
      perror ( "msgget failed" );
      return -1;
   }

   return msqid;
}
Пример #21
0
int udevmonitor(int argc, char *argv[], char *envp[])
{
	struct sigaction act;
	int option;
	int env = 0;
	int kernel = 0;
	int udev = 0;
	fd_set readfds;
	int retval = 0;

	static const struct option options[] = {
		{ "environment", 0, NULL, 'e' },
		{ "kernel", 0, NULL, 'k' },
		{ "udev", 0, NULL, 'u' },
		{ "help", 0, NULL, 'h' },
		{ NULL, 0, NULL, 0 },
	};

	while (1) {
		option = getopt_long(argc, argv, "ekuh", options, NULL);
		if (option == -1)
			break;

		switch (option) {
		case 'e':
			env = 1;
			break;
		case 'k':
			kernel = 1;
			break;
		case 'u':
			udev = 1;
			break;
		case 'h':
			printf("Usage: udevadm monitor [--environment] [--kernel] [--udev] [--help]\n"
			       "  --env    print the whole event environment\n"
			       "  --kernel print kernel uevents\n"
			       "  --udev   print udev events\n"
			       "  --help   print this help text\n\n");
		default:
			goto out;
		}
	}

	if (!kernel && !udev) {
		kernel = 1;
		udev =1;
	}

	if (getuid() != 0 && kernel) {
		fprintf(stderr, "root privileges needed to subscribe to kernel events\n");
		goto out;
	}

	/* set signal handlers */
	memset(&act, 0x00, sizeof(struct sigaction));
	act.sa_handler = (void (*)(int)) sig_handler;
	sigemptyset(&act.sa_mask);
	act.sa_flags = SA_RESTART;
	sigaction(SIGINT, &act, NULL);
	sigaction(SIGTERM, &act, NULL);

	printf("udevmonitor will print the received events for:\n");
	if (udev) {
		retval = init_udev_monitor_socket();
		if (retval)
			goto out;
		printf("UDEV the event which udev sends out after rule processing\n");
	}
	if (kernel) {
		retval = init_uevent_netlink_sock();
		if (retval)
			goto out;
		printf("UEVENT the kernel uevent\n");
	}
	printf("\n");

	while (!udev_exit) {
		char buf[UEVENT_BUFFER_SIZE*2];
		ssize_t buflen;
		ssize_t bufpos;
		ssize_t keys;
		int fdcount;
		struct timeval tv;
		struct timezone tz;
		char timestr[64];
		const char *source = NULL;
		const char *devpath, *action, *subsys;

		buflen = 0;
		FD_ZERO(&readfds);
		if (uevent_netlink_sock >= 0)
			FD_SET(uevent_netlink_sock, &readfds);
		if (udev_monitor_sock >= 0)
			FD_SET(udev_monitor_sock, &readfds);

		fdcount = select(UDEV_MAX(uevent_netlink_sock, udev_monitor_sock)+1, &readfds, NULL, NULL, NULL);
		if (fdcount < 0) {
			if (errno != EINTR)
				fprintf(stderr, "error receiving uevent message: %s\n", strerror(errno));
			continue;
		}

		if (gettimeofday(&tv, &tz) == 0) {
			snprintf(timestr, sizeof(timestr), "%llu.%06u",
				 (unsigned long long) tv.tv_sec, (unsigned int) tv.tv_usec);
		} else
			timestr[0] = '\0';

		if ((uevent_netlink_sock >= 0) && FD_ISSET(uevent_netlink_sock, &readfds)) {
			buflen = recv(uevent_netlink_sock, &buf, sizeof(buf), 0);
			if (buflen <= 0) {
				fprintf(stderr, "error receiving uevent message: %s\n", strerror(errno));
				continue;
			}
			source = "UEVENT";
		}

		if ((udev_monitor_sock >= 0) && FD_ISSET(udev_monitor_sock, &readfds)) {
			buflen = recv(udev_monitor_sock, &buf, sizeof(buf), 0);
			if (buflen <= 0) {
				fprintf(stderr, "error receiving udev message: %s\n", strerror(errno));
				continue;
			}
			source = "UDEV  ";
		}

		if (buflen == 0)
			continue;

		keys = strlen(buf) + 1; /* start of payload */
		devpath = search_key("DEVPATH", &buf[keys], buflen);
		action = search_key("ACTION", &buf[keys], buflen);
		subsys = search_key("SUBSYSTEM", &buf[keys], buflen);
		printf("%s[%s] %-8s %s (%s)\n", source, timestr, action, devpath, subsys);

		/* print environment */
		bufpos = keys;
		if (env) {
			while (bufpos < buflen) {
				int keylen;
				char *key;

				key = &buf[bufpos];
				keylen = strlen(key);
				if (keylen == 0)
					break;
				printf("%s\n", key);
				bufpos += keylen + 1;
			}
			printf("\n");
		}
	}

out:
	if (uevent_netlink_sock >= 0)
		close(uevent_netlink_sock);
	if (udev_monitor_sock >= 0)
		close(udev_monitor_sock);

	if (retval)
		return 1;
	return 0;
}
Пример #22
0
/* Other operations */
Symbol get_symbol(char *name, hash_table_t table)
{
    return (Symbol)search_key(name, table);
}
Пример #23
0
/* perform an internal connection to the database in separate process and execute sql
 * statement */
bRC pg_internal_conn ( bpContext *ctx, const char * sql ){

   PGconn * db;
   ConnStatusType status;
   PGresult * result;
   int pid = 0;
   struct stat st;
   uid_t pguid;
   int err;
   char connstring[CONNSTRLEN];
   pgsqlpinst * pinst;
   bRC exitstatus = bRC_OK;

   /* check input data */
   ASSERT_ctx_p;
   pinst = (pgsqlpinst *)ctx->pContext;

   /* dynamic production database owner verification, we use it do connect to production
    * database. Required PGDATA from config file */
   ASSERT_p ( pinst->paramlist );
   err = stat ( search_key ( pinst->paramlist, "PGDATA" ) , &st );
   if ( err ){
      /* error, invalid PGDATA in config file */
//FIXME      printf ( PLUGIN_INFO "invalid 'PGDATA' variable in config file.\n" );
      return bRC_Error;
   }
   /* we will fork to the owner of PGDATA database cluster */
   pguid = st.st_uid;

   /* switch pg xlog in different process, so make a fork */
   pid = fork ();
   if ( pid == 0 ){
//      printf ( PLUGIN_INFO "forked process\n" );
      /* sleep used for debuging forked process in gdb */
      // sleep ( 60 );

      /* we are in forked process, do a real job */
      /* switch to pgcluster owner (postgres) */
      err = seteuid ( pguid );
      if ( err ){
         /* error switching uid, report a problem */
         /* TODO: add an errorlog display */
//FIXME         printf ( PLUGIN_INFO "seteuid to uid=%i failed!\n", pguid );
         exit (bRC_Error);
      }
      /* host is a socket directory, port is a socket 'port', we perform an 'internal'
       * connection through a postgresql socket, which is required by plugin */
      snprintf ( connstring, CONNSTRLEN, "host=%s port=%s",
            search_key ( pinst->paramlist, "PGHOST" ),
            search_key ( pinst->paramlist, "PGPORT" ) );

      db = PQconnectdb ( connstring );
      status = PQstatus ( db );
      if ( status == CONNECTION_BAD ){
         /* TODO: add an errorlog display */
//FIXME         printf ( PLUGIN_INFO "conndb failed!\n");
         exit (bRC_Error);
      }

      /* we have a successful production database connection, so execute sql */
      result = PQexec ( db, sql );
      if ( PQresultStatus ( result ) != PGRES_TUPLES_OK ){
         /* TODO: add an errorlog display */
//FIXME         printf ( PLUGIN_INFO "pg_internal_conn failed! (%s)\n", sql);
         exit (bRC_Error);
      }

      /* finish database connection */
      PQfinish ( db );

      /* finish forked process */
      exit (bRC_OK);
   } else {
      /* we are waiting for background process to finish */
      waitpid ( pid, (int*)&exitstatus, 0 );
   }

   /* XXX: we should check for forked process exit status */

   return exitstatus;
}
Пример #24
0
/* 
 * parse configfile, if invalid config found, setup defaults
 * 
 * in:
 *    configfile - path and name of the pgsql.conf file
 * out:
 *    keylist of parameters
 */
keylist * parse_pgsql_conf ( char * configfile ){

   keylist * paramlist;

   paramlist = parse_config_file ( configfile );

   if ( ! paramlist ){
      logprg ( LOGINFO, "Config file not found, using defaults." );
   }

   if ( ! search_key ( paramlist, "CATDB" ) )
      paramlist = add_keylist ( paramlist, "CATDB", "catdb" );
   if ( ! search_key ( paramlist, "CATDBHOST" ) )
      paramlist = add_keylist ( paramlist, "CATDBHOST", "localhost" );
   if ( ! search_key ( paramlist, "CATDBPORT" ) )
      paramlist = add_keylist ( paramlist, "CATDBPORT", "5432" );
   if ( ! search_key ( paramlist, "CATUSER" ) )
      paramlist = add_keylist ( paramlist, "CATUSER", "catdbuser" );
   if ( ! search_key ( paramlist, "CATPASSWD" ) )
      paramlist = add_keylist ( paramlist, "CATPASSWD", "catdpasswd" );
   if ( ! search_key ( paramlist, "ARCHDEST" ) )
      paramlist = add_keylist ( paramlist, "ARCHDEST", "/tmp" );
   if ( ! search_key ( paramlist, "ARCHCLIENT" ) )
      paramlist = add_keylist ( paramlist, "ARCHCLIENT", "catdb" );
   if ( ! search_key ( paramlist, "DIRNAME" ) )
      paramlist = add_keylist ( paramlist, "DIRNAME", "director" );
   if ( ! search_key ( paramlist, "DIRHOST" ) )
      paramlist = add_keylist ( paramlist, "DIRHOST", "localhost" );
   if ( ! search_key ( paramlist, "DIRPORT" ) )
      paramlist = add_keylist ( paramlist, "DIRPORT", "9101" );
   if ( ! search_key ( paramlist, "DIRPASSWD" ) )
      paramlist = add_keylist ( paramlist, "DIRPASSWD", "dirpasswd" );

   return paramlist;
}
int
main(int argc,char *argv[])
{
  int arg,ret=KEYSERVER_INTERNAL_ERROR;
  char line[MAX_LINE];
  int failed=0;
  struct keylist *keylist=NULL,*keyptr=NULL;
  char *proxy=NULL;

  console=stderr;

  /* Kludge to implement standard GNU options.  */
  if (argc > 1 && !strcmp (argv[1], "--version"))
    {
      fputs ("gpgkeys_hkp (GnuPG) " VERSION"\n", stdout);
      return 0;
    }
  else if (argc > 1 && !strcmp (argv[1], "--help"))
    {
      show_help (stdout);
      return 0;
    }

  while((arg=getopt(argc,argv,"hVo:"))!=-1)
    switch(arg)
      {
      default:
      case 'h':
        show_help (console);
	return KEYSERVER_OK;

      case 'V':
	fprintf(stdout,"%d\n%s\n",KEYSERVER_PROTO_VERSION,VERSION);
	return KEYSERVER_OK;

      case 'o':
	output=fopen(optarg,"w");
	if(output==NULL)
	  {
	    fprintf(console,"gpgkeys: Cannot open output file `%s': %s\n",
		    optarg,strerror(errno));
	    return KEYSERVER_INTERNAL_ERROR;
	  }

	break;
      }

  if(argc>optind)
    {
      input=fopen(argv[optind],"r");
      if(input==NULL)
	{
	  fprintf(console,"gpgkeys: Cannot open input file `%s': %s\n",
		  argv[optind],strerror(errno));
	  return KEYSERVER_INTERNAL_ERROR;
	}
    }

  if(input==NULL)
    input=stdin;

  if(output==NULL)
    output=stdout;

  opt=init_ks_options();
  if(!opt)
    return KEYSERVER_NO_MEMORY;

  /* Get the command and info block */

  while(fgets(line,MAX_LINE,input)!=NULL)
    {
      int err;
      char option[MAX_OPTION+1];

      if(line[0]=='\n')
	break;

      err=parse_ks_options(line,opt);
      if(err>0)
	{
	  ret=err;
	  goto fail;
	}
      else if(err==0)
	continue;

      if(sscanf(line,"OPTION %" MKSTRING(MAX_OPTION) "s\n",option)==1)
	{
	  int no=0;
	  char *start=&option[0];

	  option[MAX_OPTION]='\0';

	  if(strncasecmp(option,"no-",3)==0)
	    {
	      no=1;
	      start=&option[3];
	    }

	  if(strncasecmp(start,"http-proxy",10)==0)
	    {
	      if(no)
		{
		  free(proxy);
		  proxy=strdup("");
		}
	      else if(start[10]=='=')
		{
		  if(strlen(&start[11])<MAX_PROXY)
		    {
		      free(proxy);
		      proxy=strdup(&start[11]);
		    }
		}
	    }
#if 0
	  else if(strcasecmp(start,"try-dns-srv")==0)
	    {
	      if(no)
		http_flags&=~HTTP_FLAG_TRY_SRV;
	      else
		http_flags|=HTTP_FLAG_TRY_SRV;
	    }
#endif
	  continue;
	}
    }

  if(!opt->host)
    {
      fprintf(console,"gpgkeys: no keyserver host provided\n");
      goto fail;
    }

  if(opt->timeout && register_timeout()==-1)
    {
      fprintf(console,"gpgkeys: unable to register timeout handler\n");
      return KEYSERVER_INTERNAL_ERROR;
    }

  curl_global_init(CURL_GLOBAL_DEFAULT);
  curl=curl_easy_init();
  if(!curl)
    {
      fprintf(console,"gpgkeys: unable to initialize curl\n");
      ret=KEYSERVER_INTERNAL_ERROR;
      goto fail;
    }

  curl_easy_setopt(curl,CURLOPT_ERRORBUFFER,errorbuffer);

  if(opt->auth)
    curl_easy_setopt(curl,CURLOPT_USERPWD,opt->auth);

  if(opt->debug)
    {
      fprintf(console,"gpgkeys: curl version = %s\n",curl_version());
      curl_easy_setopt(curl,CURLOPT_STDERR,console);
      curl_easy_setopt(curl,CURLOPT_VERBOSE,1);
    }

  if(proxy)
    curl_easy_setopt(curl,CURLOPT_PROXY,proxy);

#if 0
  /* By suggested convention, if the user gives a :port, then disable
     SRV. */
  if(opt->port)
    http_flags&=~HTTP_FLAG_TRY_SRV;
#endif

  /* If it's a GET or a SEARCH, the next thing to come in is the
     keyids.  If it's a SEND, then there are no keyids. */

  if(opt->action==KS_SEND)
    while(fgets(line,MAX_LINE,input)!=NULL && line[0]!='\n');
  else if(opt->action==KS_GET
	  || opt->action==KS_GETNAME || opt->action==KS_SEARCH)
    {
      for(;;)
	{
	  struct keylist *work;

	  if(fgets(line,MAX_LINE,input)==NULL)
	    break;
	  else
	    {
	      if(line[0]=='\n' || line[0]=='\0')
		break;

	      work=malloc(sizeof(struct keylist));
	      if(work==NULL)
		{
		  fprintf(console,"gpgkeys: out of memory while "
			  "building key list\n");
		  ret=KEYSERVER_NO_MEMORY;
		  goto fail;
		}

	      strcpy(work->str,line);

	      /* Trim the trailing \n */
	      work->str[strlen(line)-1]='\0';

	      work->next=NULL;

	      /* Always attach at the end to keep the list in proper
                 order for searching */
	      if(keylist==NULL)
		keylist=work;
	      else
		keyptr->next=work;

	      keyptr=work;
	    }
	}
    }
  else
    {
      fprintf(console,"gpgkeys: no keyserver command specified\n");
      goto fail;
    }

  /* Send the response */

  fprintf(output,"VERSION %d\n",KEYSERVER_PROTO_VERSION);
  fprintf(output,"PROGRAM %s\n\n",VERSION);

  if(opt->verbose>1)
    {
      fprintf(console,"Host:\t\t%s\n",opt->host);
      if(opt->port)
	fprintf(console,"Port:\t\t%s\n",opt->port);
      if(strcmp(opt->path,"/")!=0)
	fprintf(console,"Path:\t\t%s\n",opt->path);
      fprintf(console,"Command:\t%s\n",ks_action_to_string(opt->action));
    }

  if(opt->action==KS_GET)
    {
      keyptr=keylist;

      while(keyptr!=NULL)
	{
	  set_timeout(opt->timeout);

	  if(get_key(keyptr->str)!=KEYSERVER_OK)
	    failed++;

	  keyptr=keyptr->next;
	}
    }
  else if(opt->action==KS_GETNAME)
    {
      keyptr=keylist;

      while(keyptr!=NULL)
	{
	  set_timeout(opt->timeout);

	  if(get_name(keyptr->str)!=KEYSERVER_OK)
	    failed++;

	  keyptr=keyptr->next;
	}
    }
  else if(opt->action==KS_SEND)
    {
      int eof=0;

      do
	{
	  set_timeout(opt->timeout);

	  if(send_key(&eof)!=KEYSERVER_OK)
	    failed++;
	}
      while(!eof);
    }
  else if(opt->action==KS_SEARCH)
    {
      char *searchkey=NULL;
      int len=0;

      set_timeout(opt->timeout);

      /* To search, we stick a space in between each key to search
	 for. */

      keyptr=keylist;
      while(keyptr!=NULL)
	{
	  len+=strlen(keyptr->str)+1;
	  keyptr=keyptr->next;
	}

      searchkey=malloc(len+1);
      if(searchkey==NULL)
	{
	  ret=KEYSERVER_NO_MEMORY;
	  fail_all(keylist,KEYSERVER_NO_MEMORY);
	  goto fail;
	}

      searchkey[0]='\0';

      keyptr=keylist;
      while(keyptr!=NULL)
	{
	  strcat(searchkey,keyptr->str);
	  strcat(searchkey," ");
	  keyptr=keyptr->next;
	}

      /* Nail that last space */
      if(*searchkey)
	searchkey[strlen(searchkey)-1]='\0';

      if(search_key(searchkey)!=KEYSERVER_OK)
	failed++;

      free(searchkey);
    }
  else
    abort();

  if(!failed)
    ret=KEYSERVER_OK;

 fail:
  while(keylist!=NULL)
    {
      struct keylist *current=keylist;
      keylist=keylist->next;
      free(current);
    }

  if(input!=stdin)
    fclose(input);

  if(output!=stdout)
    fclose(output);

  free_ks_options(opt);

  if(curl)
    curl_easy_cleanup(curl);

  free(proxy);

  return ret;
}
Пример #26
0
int main(int argc, char *argv[]){
	char buffer[64];
	char *c;

#if DEBUG
	printf("[DEBUG MODE]\n");
	printf("Compile: %s %s\n", __DATE__, __TIME__);
#endif

	printf("Version: %d.%d.%d\n", VER_REL, VER_MAJOR, VER_MINOR);
	printf("Database> ");
	dbfile_t *mdb = open_dbfile(get_input(buffer, 32, TRUE));
	commit_db(mdb);

	for(;;){
		printf("valca> ");

		c = get_input(buffer, 64, TRUE);
		if(!strcmp("quit", c)||!strcmp("exit", c)||!strcmp("\\q", c)){
			break;
		}
		if(!strcmp("help", c)){
			printf("COMMANDS:\n");
			printf("COMMIT        Commit file to disk\n");
			printf("COUNT         Show row count\n");
			printf("TRUNCATE      Delete all keys\n");
			printf("UPDATE        Update key value\n");
			printf("INSERT        Insert key\n");
			printf("DELETE \\\n");
			printf("  COLUMN      Delete column\n");
			printf("  ROW         Delete row\n");
			printf("ALTER \\\n");
			printf("  NAME        Change column name\n");
			printf("  LEFT        Shift column left\n");
			printf("  RIGHT       Shift column right\n");
			printf("SELECT        Select value from\n");
			printf("ADD \\\n");
			printf("  COLUMN      Add column\n");
			printf("SHOW \\\n");
			printf("  COLUMNS     Show all columns\n");
			printf("  TREE        Show storage tree\n");
			printf("  STATUS      Show database info\n");
			printf("  TABLE       Show dataset as table\n");
			printf("FREE \\\n");
			printf("  COLUMNS     Columns freelist\n");
			printf("  NODE        Node freelist\n");
			printf("  DATAFIELDS  Payload freelist\n");
			printf("EXIT          Quit the shell\n");
		}
		if(!strcmp("commit", c)){
			commit_db(mdb);
		}
		if(!strcmp("count", c)){
			printf("Total rows: %d\n", mdb->k_cnt);
		}
		if(!strcmp("truncate", c)){
			truncate_root(mdb);
		}
		if(!strcmp("update", c)){
			char tmp[32];
			printf(">psid: ");
			c = get_input(tmp, 32, FALSE);
			int key = atoi(tmp);
			char tmpcolname[32];
			printf(">column: ");
			c = get_input(tmpcolname, 32, FALSE);
			int idx = get_column_idx(mdb, tmpcolname);
			printf(">value: ");
			c = get_input(tmp, 32, FALSE);
			change(mdb, key, (void*)tmp, idx);
		}
		if(!strcmp("insert", c)){
			if(!mdb->c_cnt){
				printf("Cannot insert without column\n");
			}else{
				char tmp[32];
				printf(">psid[%d]: ", mdb->seq_cnt);
				c = get_input(tmp, 32, FALSE);
				int key;
				if(!strlen(tmp)){
					key = mdb->seq_cnt++;
				}else{
					key = atoi(tmp);
				}
				column_t col;
				read_column(mdb, mdb->data.c_root, &col);
				printf(">%s<%s(%d)>: ", col.name, get_datatype_name(col.d_type), col.maxsize);
				c = get_input(tmp, 32, FALSE);
				if(get_datatype(col.d_type).size == -1) tmp[col.maxsize] = '\0';
				if(col.usign) printf("<> %d\n", atoi(tmp));
					//if(atoi())
				if(insert_key(mdb, key, (void*)tmp) == SUCCESS){
					result_t rs = search_key(mdb, key);
					if(rs.rstat == SUCCESS){
						char tmp[32];
						int i = 1;
						while(col.c_next != EMPTY){
							read_column(mdb, col.c_next, &col);
							printf(">%s<%s(%d)>: ", col.name, get_datatype_name(col.d_type), col.maxsize);
							c = get_input(tmp, 32, FALSE);
							add_field(mdb, rs.fpos, rs.idx, (void*)tmp, i);
							i++;
						}
					}
				}
			}
		}
		if(!strcmp("delete", c)){
			printf(">");
			c = get_input(buffer, 64, TRUE);
			if(!strcmp("column", c)){
				char tmpcolname[32];
				printf(">column: ");
				c = get_input(tmpcolname, 32, FALSE);
				int idx = get_column_idx(mdb, tmpcolname);
				delete_column(mdb, idx);
			}
			if(!strcmp("row", c)){
				char tmp[32];
				printf(">psid: ");
				c = get_input(tmp, 32, FALSE);
				int key = atoi(tmp);
				result_t rs = search_key(mdb, key);
				if(rs.rstat == SUCCESS){
					int i;
					for(i=mdb->c_cnt; i>1; i--){
						delete_field(mdb, rs.fpos, rs.idx, (i-1));
					}
					delete_key(mdb, key);
				}
			}
		}
		if(!strcmp("alter", c)){
			printf(">");
			c = get_input(buffer, 64, TRUE);
			if(!strcmp("name", c)){
				printf(">column: ");
				char tmpcolname[32];
				c = get_input(tmpcolname, 32, FALSE);
				int idx = get_column_idx(mdb, tmpcolname);
				printf(">new name: ");
				c = get_input(tmpcolname, 32, FALSE);
				rename_column(mdb, tmpcolname, idx);
			}
			if(!strcmp("left", c)){
				char tmpcolname[32];
				printf(">column: ");
				c = get_input(tmpcolname, 32, FALSE);
				int idx = get_column_idx(mdb, tmpcolname);
				shift_column_left(mdb, idx);
			}
			if(!strcmp("right", c)){
				char tmpcolname[32];
				printf(">column: ");
				c = get_input(tmpcolname, 32, FALSE);
				int idx = get_column_idx(mdb, tmpcolname);
				shift_column_right(mdb, idx);
			}
		}
		if(!strcmp("select", c)){
			printf(">");
			char tmp[16];
			printf(">psid: ");
			c = get_input(tmp, 32, FALSE);
			int key = atoi(tmp);
			result_t rs = search_key(mdb, key);
			if(rs.rstat == SUCCESS){
				found(mdb, rs.fpos, rs.idx);
			}
		}
		if(!strcmp("add", c)){
			printf(">");
			c = get_input(buffer, 64, TRUE);
			if(!strcmp("column", c)){
				char colname[32];
				DTYPE type;
				int size;
				bool usign = FALSE;
				int idx;
				printf(">name: ");
				c = get_input(colname, 32, FALSE);
				printf(">type: ");
				char tmptype[32];
				c = get_input(tmptype, 32, FALSE);
				type = get_datatype_idx(tmptype);
				if(type == EMPTY){
					printf("Unkown datatype\n");
					continue;
				}
				size = get_datatype(type).size;
				if(size == EMPTY){
					printf(">size: ");
					char tmpsize[16];
					c = get_input(tmpsize, 16, FALSE);
					size = atoi(tmpsize);
				}
				if(get_datatype(type).signness){
					printf(">unsigned: ");
					char tmpsign[4];
					c = get_input(tmpsign, 4, FALSE);
					if(!strcmp("y", tmpsign)){
						usign = TRUE;
					}
				}
				printf(">before: ");
				char tmpcolname[32];
				c = get_input(tmpcolname, 32, FALSE);
				idx = get_column_idx(mdb, tmpcolname);
				add_column(mdb, colname, size, type, usign, idx);
			}
		}
		if(!strcmp("show", c)){
			printf(">");
			c = get_input(buffer, 64, TRUE);
			if(!strcmp("columns", c)){
				printf("Idx   Offset   Psid         Columnname  Size      Type    Unsigned    Next\n");
				printf("--------------------------------------------------------------------------\n");
				print_column(mdb, mdb->data.c_root, 0);
			}
			if(!strcmp("tree", c)){
				print_tree(mdb, mdb->data.n_root, 0);
			}
			if(!strcmp("status", c)){
				print_status(mdb);
			}
			if(!strcmp("table", c)){
				print_table(mdb);
			}
		}
		if(!strcmp("free", c)){
			printf(">");
			c = get_input(buffer, 64, TRUE);
			if(!strcmp("columns", c)){
				printf("Idx   Offset   Psid         Columnname  Size      Type    Unsigned    Next\n");
				printf("--------------------------------------------------------------------------\n");
				print_column(mdb, mdb->data.c_free, 0);
			}
			if(!strcmp("node", c)){
				print_tree(mdb, mdb->data.n_free, 0);
			}
			if(!strcmp("datafields", c)){
				print_datafield(mdb, mdb->data.d_free);
			}
		}
	}

	commit_db(mdb);
	close_dbfile(mdb->vfp);
	close_db(mdb);

	return 0;
}
Пример #27
0
/* decode hidim png file and write the torrent file */
int decode(const char *pngfilename) {
    FILE *fp;
    png_uint_32 height, width;
    png_bytep *row_pointers = NULL, *transpose = NULL;
    char *filename, *basefilename, *sha1sum;
    int start_row, start_column, line_length, c;
    unsigned int length, metadata_length, count, s;

    if ((fp = fopen(pngfilename, "rb")) == NULL) {
        fprintf(stderr, "%s: %s\n", pngfilename, strerror(errno));
        return 0;
    }
    if (config & CONFIG_VERBOSE) {
        printf(":: decoding %s\n", pngfilename);
    }

    if (!read_png(fp, &row_pointers, &width, &height)) {
        fclose(fp);
        fprintf(stderr, "Error: %s is not a png file.\n", pngfilename);
        return 0;
    }
    fclose(fp);

    /* rotate image */
    transpose = rotate_image(row_pointers, width, height);
    free_array(row_pointers, height);
    if (transpose == NULL) { // it can't be. already checked before
        exit(EXIT_FAILURE);
    }

    /* search for hidim key */
    if (!search_key(transpose, width, height, &start_row, &start_column)) {
        fprintf(stderr, "Error: %s is not a hidim or is corrupted.\n", pngfilename);
        free_array(transpose, width);
        return 0;
    } else if (config & CONFIG_MORE_VERBOSE) {
        printf("  hidim key found at (%d, %d)\n", start_row, (int)(height-start_column-1));
    }

    /* extract metadata */
    read_metadata(transpose, start_row, start_column, &line_length, &filename, &sha1sum, &metadata_length, &length);

    /* for security reason, only keep the basename of filename */
    basefilename = basename(filename);
    if (config & CONFIG_MORE_VERBOSE) {
        printf("==== metadata (%d bytes) ====\n", metadata_length);
        printf("  line_length: %d  sha1sum: %s  length: %d\n", line_length, sha1sum, length);
        printf("  filename   : %s\n", filename);
        printf("====\n");
        //printf(":: %d %s %s %d %d\n", line_length, basefilename, sha1sum, metadata_length, length);
    }
    /* get the torrent */
    unsigned char *torrent = calloc(length, sizeof(char));
    if (torrent == NULL) {
        fprintf(stderr, "Error: Can't allocate %d bytes.\n", length*sizeof(char));
        exit(EXIT_FAILURE);
    }

    count = c = s = 0;
    while (count < length+metadata_length) {
        if (count >= metadata_length) {
            torrent[count - metadata_length] = (unsigned char)transpose[start_row+s][3*start_column+c];
        }
        if (c == (line_length*3 -1) ) {
            c = 0;
            s++;
        } else {
            c++;
        }
        count++;
    }
    free_array(transpose, width);

    /* check the sha1sum of the torrent we extracted with sha1sum from metadata */
    unsigned char md[20];
    SHA1(torrent, length, md);
    char *sha1sum_comp = hexa_sha1sum(md);
    if (strcmp(sha1sum_comp, sha1sum) != 0) {
        if (config & CONFIG_MORE_VERBOSE) {
            printf("sha2sum: expected %s, got %s\n", sha1sum, sha1sum_comp);
        }
        fprintf(stderr, "%s: wrong sha1sum for extracted data.\n", filename);
        free(sha1sum_comp);
        free(sha1sum);
        free(torrent);
        free(filename);
        return 0;
    }
    free(sha1sum);
    free(sha1sum_comp);

    /* check if torrent file does not already exist */
    if (is_file(basefilename) && (!(config & CONFIG_OVERWRITE))) {
        fprintf(stderr, "%s already exists. nothing done.\n", basefilename);
        free(torrent);
        free(filename);
        return 0;
    }
    /* write torrent to file */
    FILE *fo = fopen(basefilename, "w");
    fwrite(torrent, sizeof(char), length, fo);
    fclose(fo);
    if (config & CONFIG_VERBOSE) {
        printf("%s has been saved.\n", basefilename);
    }

    free(torrent);
    free(filename);

    return 1;
}
Пример #28
0
int
main(int argc,char *argv[])
{
  int arg,ret=KEYSERVER_INTERNAL_ERROR,try_srv=1;
  char line[MAX_LINE];
  int failed=0;
  struct keylist *keylist=NULL,*keyptr=NULL;
  char *proxy=NULL;
  struct curl_slist *headers=NULL;

  console=stderr;

  /* Kludge to implement standard GNU options.  */
  if (argc > 1 && !strcmp (argv[1], "--version"))
    {
      printf ("gpgkeys_hkp (GnuPG) %s\n", VERSION);
      printf ("Uses: %s\n", curl_version());
      return 0;
    }
  else if (argc > 1 && !strcmp (argv[1], "--help"))
    {
      show_help (stdout);
      return 0;
    }

  while((arg=getopt(argc,argv,"hVo:"))!=-1)
    switch(arg)
      {
      default:
      case 'h':
        show_help (console);
	return KEYSERVER_OK;

      case 'V':
	fprintf(stdout,"%d\n%s\n",KEYSERVER_PROTO_VERSION,VERSION);
	return KEYSERVER_OK;

      case 'o':
	output=fopen(optarg,"w");
	if(output==NULL)
	  {
	    fprintf(console,"gpgkeys: Cannot open output file `%s': %s\n",
		    optarg,strerror(errno));
	    return KEYSERVER_INTERNAL_ERROR;
	  }

	break;
      }

  if(argc>optind)
    {
      input=fopen(argv[optind],"r");
      if(input==NULL)
	{
	  fprintf(console,"gpgkeys: Cannot open input file `%s': %s\n",
		  argv[optind],strerror(errno));
	  return KEYSERVER_INTERNAL_ERROR;
	}
    }

  if(input==NULL)
    input=stdin;

  if(output==NULL)
    output=stdout;

  opt=init_ks_options();
  if(!opt)
    return KEYSERVER_NO_MEMORY;

  /* Get the command and info block */

  while(fgets(line,MAX_LINE,input)!=NULL)
    {
      int err;
      char option[MAX_OPTION+1];

      if(line[0]=='\n')
	break;

      err=parse_ks_options(line,opt);
      if(err>0)
	{
	  ret=err;
	  goto fail;
	}
      else if(err==0)
	continue;

      if(sscanf(line,"OPTION %" MKSTRING(MAX_OPTION) "s\n",option)==1)
	{
	  int no=0;
	  char *start=&option[0];

	  option[MAX_OPTION]='\0';

	  if(ascii_strncasecmp(option,"no-",3)==0)
	    {
	      no=1;
	      start=&option[3];
	    }

	  if(ascii_strncasecmp(start,"http-proxy",10)==0)
	    {
	      if(no)
		{
		  free(proxy);
		  proxy=strdup("");
		}
	      else if(start[10]=='=')
		{
		  if(strlen(&start[11])<MAX_PROXY)
		    {
		      free(proxy);
		      proxy=strdup(&start[11]);
		    }
		}
	    }
	  else if(ascii_strcasecmp(start,"try-dns-srv")==0)
	    {
	      if(no)
		try_srv=0;
	      else
		try_srv=1;
	    }

	  continue;
	}
    }


  if(!opt->scheme)
    {
      fprintf(console,"gpgkeys: no scheme supplied!\n");
      ret=KEYSERVER_SCHEME_NOT_FOUND;
      goto fail;
    }

  if(ascii_strcasecmp(opt->scheme,"hkps")==0)
    {
      proto="https";
      port="443";
    }
  else
    {
      proto="http";
      port="11371";
    }

  if(!opt->host)
    {
      fprintf(console,"gpgkeys: no keyserver host provided\n");
      goto fail;
    }

  if(opt->timeout && register_timeout()==-1)
    {
      fprintf(console,"gpgkeys: unable to register timeout handler\n");
      return KEYSERVER_INTERNAL_ERROR;
    }

  curl_global_init(CURL_GLOBAL_DEFAULT);
  curl=curl_easy_init();
  if(!curl)
    {
      fprintf(console,"gpgkeys: unable to initialize curl\n");
      ret=KEYSERVER_INTERNAL_ERROR;
      goto fail;
    }

  /* If the user gives a :port, then disable SRV.  The semantics of a
     specified port and SRV do not play well together. */
  if(opt->port)
    port=opt->port;
  else if(try_srv)
    {
      char *srvtag;

      if(ascii_strcasecmp(opt->scheme,"hkp")==0)
	srvtag="pgpkey-http";
      else if(ascii_strcasecmp(opt->scheme,"hkps")==0)
	srvtag="pgpkey-https";
      else
	srvtag=NULL;

#ifdef HAVE_LIBCURL
      /* We're using libcurl, so fake SRV support via our wrapper.
	 This isn't as good as true SRV support, as we do not try all
	 possible targets at one particular level and work our way
	 down the list, but it's better than nothing. */
      srv_replace(srvtag);
#else
      /* We're using our internal curl shim, so we can use its (true)
	 SRV support.  Obviously, CURLOPT_SRVTAG_GPG_HACK isn't a real
	 libcurl option.  It's specific to our shim. */
      curl_easy_setopt(curl,CURLOPT_SRVTAG_GPG_HACK,srvtag);
#endif
    }

  curl_easy_setopt(curl,CURLOPT_ERRORBUFFER,errorbuffer);

  if(opt->auth)
    curl_easy_setopt(curl,CURLOPT_USERPWD,opt->auth);

  if(opt->debug)
    {
      fprintf(console,"gpgkeys: curl version = %s\n",curl_version());
      curl_easy_setopt(curl,CURLOPT_STDERR,console);
      curl_easy_setopt(curl,CURLOPT_VERBOSE,1L);
    }

  curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,(long)opt->flags.check_cert);
  curl_easy_setopt(curl,CURLOPT_CAINFO,opt->ca_cert_file);

  /* Avoid caches to get the most recent copy of the key.  This is bug
     #1061.  In pre-curl versions of the code, we didn't do it.  Then
     we did do it (as a curl default) until curl changed the default.
     Now we're doing it again, but in such a way that changing
     defaults in the future won't impact us.  We set both the Pragma
     and Cache-Control versions of the header, so we're good with both
     HTTP 1.0 and 1.1. */
  headers=curl_slist_append(headers,"Pragma: no-cache");
  if(headers)
    headers=curl_slist_append(headers,"Cache-Control: no-cache");

  if(!headers)
    {
      fprintf(console,"gpgkeys: out of memory when building HTTP headers\n");
      ret=KEYSERVER_NO_MEMORY;
      goto fail;
    }

  curl_easy_setopt(curl,CURLOPT_HTTPHEADER,headers);

  if(proxy)
    curl_easy_setopt(curl,CURLOPT_PROXY,proxy);

  /* If it's a GET or a SEARCH, the next thing to come in is the
     keyids.  If it's a SEND, then there are no keyids. */

  if(opt->action==KS_SEND)
    while(fgets(line,MAX_LINE,input)!=NULL && line[0]!='\n');
  else if(opt->action==KS_GET
	  || opt->action==KS_GETNAME || opt->action==KS_SEARCH)
    {
      for(;;)
	{
	  struct keylist *work;

	  if(fgets(line,MAX_LINE,input)==NULL)
	    break;
	  else
	    {
	      if(line[0]=='\n' || line[0]=='\0')
		break;

	      work=xtrymalloc(sizeof(struct keylist));
	      if(work==NULL)
		{
		  fprintf(console,"gpgkeys: out of memory while "
			  "building key list\n");
		  ret=KEYSERVER_NO_MEMORY;
		  goto fail;
		}

	      strcpy(work->str,line);

	      /* Trim the trailing \n */
	      work->str[strlen(line)-1]='\0';

	      work->next=NULL;

	      /* Always attach at the end to keep the list in proper
                 order for searching */
	      if(keylist==NULL)
		keylist=work;
	      else
		keyptr->next=work;

	      keyptr=work;
	    }
	}
    }
  else
    {
      fprintf(console,"gpgkeys: no keyserver command specified\n");
      goto fail;
    }

  /* Send the response */

  fprintf(output,"VERSION %d\n",KEYSERVER_PROTO_VERSION);
  fprintf(output,"PROGRAM %s %s\n\n",VERSION,curl_version());

  if(opt->verbose>1)
    {
      fprintf(console,"Host:\t\t%s\n",opt->host);
      if(opt->port)
	fprintf(console,"Port:\t\t%s\n",opt->port);
      if(strcmp(opt->path,"/")!=0)
	fprintf(console,"Path:\t\t%s\n",opt->path);
      fprintf(console,"Command:\t%s\n",ks_action_to_string(opt->action));
    }

  if(opt->action==KS_GET)
    {
      keyptr=keylist;

      while(keyptr!=NULL)
	{
	  set_timeout(opt->timeout);

	  if(get_key(keyptr->str)!=KEYSERVER_OK)
	    failed++;

	  keyptr=keyptr->next;
	}
    }
  else if(opt->action==KS_GETNAME)
    {
      keyptr=keylist;

      while(keyptr!=NULL)
	{
	  set_timeout(opt->timeout);

	  if(get_name(keyptr->str)!=KEYSERVER_OK)
	    failed++;

	  keyptr=keyptr->next;
	}
    }
  else if(opt->action==KS_SEND)
    {
      int eof=0;

      do
	{
	  set_timeout(opt->timeout);

	  if(send_key(&eof)!=KEYSERVER_OK)
	    failed++;
	}
      while(!eof);
    }
  else if(opt->action==KS_SEARCH)
    {
      char *searchkey=NULL;
      int len=0;

      set_timeout(opt->timeout);

      /* To search, we stick a space in between each key to search
	 for. */

      keyptr=keylist;
      while(keyptr!=NULL)
	{
	  len+=strlen(keyptr->str)+1;
	  keyptr=keyptr->next;
	}

      searchkey=xtrymalloc(len+1);
      if(searchkey==NULL)
	{
	  ret=KEYSERVER_NO_MEMORY;
	  fail_all(keylist,KEYSERVER_NO_MEMORY);
	  goto fail;
	}

      searchkey[0]='\0';

      keyptr=keylist;
      while(keyptr!=NULL)
	{
	  strcat(searchkey,keyptr->str);
	  strcat(searchkey," ");
	  keyptr=keyptr->next;
	}

      /* Nail that last space */
      if(*searchkey)
	searchkey[strlen(searchkey)-1]='\0';

      if(search_key(searchkey)!=KEYSERVER_OK)
	failed++;

      free(searchkey);
    }
  else
    abort();

  if(!failed)
    ret=KEYSERVER_OK;

 fail:
  while(keylist!=NULL)
    {
      struct keylist *current=keylist;
      keylist=keylist->next;
      free(current);
    }

  if(input!=stdin)
    fclose(input);

  if(output!=stdout)
    fclose(output);

  free_ks_options(opt);

  curl_slist_free_all(headers);

  if(curl)
    curl_easy_cleanup(curl);

  free(proxy);

  return ret;
}
Пример #29
0
size_t font::print(string const &text, rectangle &bounds, float *&ptr, float x, float y, std::size_t max_chars) const
{
   slog_trace("font::print(ptr = %p, text = %s, x = % 7.2, y = % 7.2)",
      ptr,
      text.c_str(),
      x,
      y);

   if (text.size() == 0)
      return 0;

   size_t chars_printed = 0;
   for (size_t i = 0; i < text.size(); ++i)
   {
      char c = text[i];
      unsigned char uc = static_cast<unsigned char>(c);

      ft_char const &font_char = m_chars_256[uc];

      float a = static_cast<float>(font_char.xadvance);

      if (font_char.width != 0)
      {
         float w  = static_cast<float>(font_char.width);
         float h  = static_cast<float>(font_char.height);
         float ox = static_cast<float>(font_char.xoffset);
         float oy = static_cast<float>(font_char.yoffset);

#if 0
         glTexCoord2f(font_char.u[0], font_char.v[0]); glVertex2f(x + ox, y + oy);
         glTexCoord2f(font_char.u[1], font_char.v[1]); glVertex2f(x + ox + w, y + oy);
         glTexCoord2f(font_char.u[2], font_char.v[2]); glVertex2f(x + ox + w, y + oy + h);
         glTexCoord2f(font_char.u[0], font_char.v[0]); glVertex2f(x + ox, y + oy);
         glTexCoord2f(font_char.u[2], font_char.v[2]); glVertex2f(x + ox + w, y + oy + h);
         glTexCoord2f(font_char.u[3], font_char.v[3]); glVertex2f(x + ox, y + oy + h);
#else
         *ptr++ = x + ox;
         *ptr++ = y + oy;
         *ptr++ = font_char.u[0];
         *ptr++ = font_char.v[0];
         *ptr++ = x + ox + w;
         *ptr++ = y + oy;
         *ptr++ = font_char.u[1];
         *ptr++ = font_char.v[1];
         *ptr++ = x + ox + w;
         *ptr++ = y + oy + h;
         *ptr++ = font_char.u[2];
         *ptr++ = font_char.v[2];
         *ptr++ = x + ox;
         *ptr++ = y + oy + h;
         *ptr++ = font_char.u[3];
         *ptr++ = font_char.v[3];
#endif

         bounds.extend_by(x + ox    , y + oy);
         bounds.extend_by(x + ox + w, y + oy);
         bounds.extend_by(x + ox + w, y + oy + h);
         bounds.extend_by(x + ox    , y + oy + h);

         ++chars_printed;
         if (chars_printed == max_chars)
            break;
      }

      x += a;
      x += m_spacing_delta;

      if (i + 1 < text.size())
      {
         char next = text[i + 1];
         kerning search_key(static_cast<unsigned short>(next));
         compare_kerning cmp;

         vector<kerning>::const_iterator j = std::lower_bound(
            font_char.kernings.cbegin(),
            font_char.kernings.cend(),
            search_key,
            cmp
         );

         if (j != font_char.kernings.cend()) {
            kerning const &k = *j;
            x += (float)(k.amount);
         }
      }
   }
   return chars_printed;
}