Пример #1
0
/// %Thread start
void CliRunnable::run()
{
    ///- Init new SQL thread for the world database (one connection call enough)
    WorldDatabase.ThreadStart();                            // let thread do safe mySQL requests

    char commandbuf[256];

    ///- Display the list of available CLI functions then beep
    sLog.outString();

    if (sConfig.GetBoolDefault("BeepAtStart", true))
        printf("\a");                                       // \a = Alert

    // print this here the first time
    // later it will be printed after command queue updates
    printf("mangos>");

    ///- As long as the World is running (no World::m_stopEvent), get the command line and handle it
    while (!World::IsStopped())
    {
        fflush(stdout);
#ifdef linux
        while (!kb_hit_return() && !World::IsStopped())
            // With this, we limit CLI to 10commands/second
            usleep(100);
        if (World::IsStopped())
            break;
#endif
        char* command_str = fgets(commandbuf, sizeof(commandbuf), stdin);
        if (command_str != NULL)
        {
            for (int x = 0; command_str[x]; ++x)
                if (command_str[x] == '\r' || command_str[x] == '\n')
                {
                    command_str[x] = 0;
                    break;
                }

            if (!*command_str)
            {
                printf("mangos>");
                continue;
            }

            std::string command;
            if (!consoleToUtf8(command_str, command))       // convert from console encoding to utf8
            {
                printf("mangos>");
                continue;
            }

            sWorld.QueueCliCommand(new CliCommandHolder(0, SEC_CONSOLE, NULL, command.c_str(), &utf8print, &commandFinished));
        }
        else if (feof(stdin))
        {
            World::StopNow(SHUTDOWN_EXIT_CODE);
        }
    }

    ///- End the database thread
    WorldDatabase.ThreadEnd();                              // free mySQL thread resources
}
Пример #2
0
void bparse_test( FILE *FH ) {
    char *s;
    size_t bd_sz = 0, i;
    struct bdeque **bd=xmalloc(bd_sz), /* Array of bdeque pointers */
                  *deque;

    while ( !feof(FH) ) {
        /* Get a line from the file */
        s=b_gets(FH,INPUT_BLOCKSIZE);
        /* Remove comments */
        strtrunc(s,comment_chars);
        /* Remove trailing new line */
        chomp(s);
        /* Tokenize line and load into a deque */
        deque = blex(s);

        if ( bdeque_count( deque ) > 0 ) {
            /* Grow the bdeque pointer array by one and append the new deque to the end */
            struct bdeque **temp = xrealloc(bd,sizeof(*bd)*(++bd_sz));
            bd = temp;
            bd[bd_sz-1] = deque;
        }
    }
    printf("<<DEQUE PRINT>>\n");
    /* Print the bdeques */
    for (i=0; i<bd_sz; i++)
        bdeque_print(bd[i]);
    printf("<<END DEQUE PRINT>>\n");
    for (i=0; i<bd_sz; i++) {
        struct bdeque *deque = bd[i], *dupdeque = bdeque_create();
        struct d_elem *node = deque->head;
        /* Keep track of operation count. If the line isn't 'done' and we can't do operations on it, we don't want to loop on it forever */
        unsigned int ops = 0;
        while ( node != NULL ) {
            struct d_elem *retnode = NULL; // Node returned by the current operation
            int def = is_def(*node->var->value);
            if ( def != -1 ) {
                if ( defs[def].operands == 2 ) {
                    retnode = defs[def].op( node->prev, node->next ); // Perform the binary operation of the current defined operator and place the result into retnode.
                    //bdeque_npush( dupdeque, defs[def].op( node->prev, node->next ) );
                // FIXME: I don't put my return value back into the deque.
                } else if ( defs[def].operands == 1 ) {
                    //struct d_elem *retval = defs[def].op( node->next );
                    retnode = defs[def].op( node->next ); // Perform the unary operation of the current defined operator and place the result into retnode.
                    //defs[def].op( node->next );
                    //if ( retval != NULL ) 
                    //    bdeque_npush( dupdeque, retval );
                } else if ( defs[def].operands == 0 ) {
                    defs[def].op( node->next );
                } else {
                    bdeque_npush( dupdeque, d_elem_copy(node) );
                }
            } //else {
                //bdeque_npush( dupdeque, d_elem_copy(node) );
            //}
            /*
            int def = is_def(*node->var->value);
            if ( def != -1 ) {
                if ( defs[def].operands == 1 )
                    b_PRINT( defs[def].op( node->next ) );
                else if ( defs[def].operands == 2 )
                    b_PRINT( defs[def].op( node->prev, node->next ) );
            }
            */
            if ( node->next == NULL )
                break;
            //else if ( node->next->prev == node )
            if ( retnode != NULL ) {
                
            }
            node = node->next;
        }
        bdeque_print( dupdeque );

    }
}
Пример #3
0
int main(int argc, char **argv)
{
	if ( argc != 2 )
	{
		printf("Usage: %s filename\n", argv[0]);
		exit(1);
	}

	int fd; /* Sound device */
	int arg; /* ioctl argument */
	int status; /* Return value of syscalls */

	/* open dsp */
	fd = open("/dev/dsp", O_RDWR);
	if (fd < 0)
	{
		perror("Failed to open /dev/dsp");
		exit(1);
	}

	/* Set sample parameters */
	arg = SIZE; /* Sample size */
	status = ioctl(fd, SOUND_PCM_WRITE_BITS, &arg);
	if ( status == -1 )
	{
		perror("SOUND_PCM_WRITE_BITS failed");
		exit(1);
	}
	if ( arg != SIZE)
	{
		perror("Unable to set sample size");
		exit(1);
	}

	arg = CHANNELS; /* Mono or stereo */
	status = ioctl(fd, SOUND_PCM_WRITE_CHANNELS, &arg);
	if ( status == -1 )
	{
		perror("SOUND_PCM_WRITE_CHANNELS failed");
		exit(1);
	}
	if (arg != CHANNELS)
	{
		perror("unable to set number of channels");
		exit(1);
	}

	arg = RATE;	   /* sampling rate */
	status = ioctl(fd, SOUND_PCM_WRITE_RATE, &arg);
	if (status == -1)
	{
		perror("SOUND_PCM_WRITE_WRITE ioctl failed");
		exit(1);
	}

	FILE *f = fopen(argv[1], "r");
	fseek(f, 44, SEEK_SET);
	size_t bytes = 0;
	while ( ! feof(f) )
	{
		memset(buf, 0, LENGTH*RATE*SIZE*CHANNELS/8); /* Zero the memory */
		bytes = fread(buf, 1, LENGTH*RATE*SIZE*CHANNELS/8, f);
		status = write(fd, buf, bytes);
	}
	fclose(f);
	close(fd);

	return 0;
}
Пример #4
0
int main(int argc, char* argv[]) {
	int result;

	int screen_width = 640;
	int screen_height = 480;

	int img_width, img_height, x, y;
	uint8_t *data;
	uint8_t *img_row;
	uint8_t *src, *dst;
	FILE* file;

	if (argc < 4) {
		printf("usage: %s width height ppmfile\n", argv[0]);
		return 1;
	}

	img_width  = screen_width  = atoi(argv[1]);
	img_height = screen_height = atoi(argv[2]);

	file = fopen(argv[3], "rb");
	if (!file) {
		printf("Can't open '%s'\n", argv[3]);
		return 1;
	}
	data    = (uint8_t*)malloc(screen_width * screen_height * 4);
	img_row = (uint8_t*)malloc(img_width * 3);
	if (!data || !img_row) {
		printf("Not enough memory\n");
		return 1;
	}

	// load file
	memset(data, 0x333333, screen_width * screen_height * 4);

	int H = (img_height < screen_height) ? img_height : screen_height;
	int W = (img_width < screen_width) ? img_width : screen_width;

	fseek(file, -img_width * img_height * 3, SEEK_END);
	for (y=0; y < H; y++) {
		fread(img_row, img_width, 3, file);
		if (feof(file))
			break;

		src = img_row;
		dst = &data[y * screen_width * 4];
		for (x=0; x < W; x++) {
			*dst++ = *(src+2);
			*dst++ = *(src+1);
			*dst++ = *(src+0);
			*dst++ = 0x00;
			src += 3;
		}
	}

	fclose(file);


	// run mainloop
	result = Xscr_mainloop(
		screen_width,
		screen_height,
		DEPTH_32bpp, False, data,
		keyboard, motion, buttons,
		"Xscr demo"
	);

	// check exit status
	if (result) {
		printf("Xscr error: %s\n", Xscr_error_str(result));
	}

	free(data);
	free(img_row);
	return 0;
}
Пример #5
0
DumpReturn PlayerDumpReader::LoadDump(const std::string& file, uint32 account, std::string name, uint32 guid)
{
    bool nameInvalidated = false;                           // set when name changed or will requested changed at next login

    // check character count
    uint32 charcount = sAccountMgr.GetCharactersCount(account);
    if (charcount >= 10)
        return DUMP_TOO_MANY_CHARS;

    FILE *fin = fopen(file.c_str(), "r");
    if (!fin)
        return DUMP_FILE_OPEN_ERROR;

    QueryResult * result = NULL;
    char newguid[20], chraccount[20], newpetid[20], currpetid[20], lastpetid[20];

    // make sure the same guid doesn't already exist and is safe to use
    bool incHighest = true;
    if (guid != 0 && guid < sObjectMgr.m_CharGuids.GetNextAfterMaxUsed())
    {
        result = CharacterDatabase.PQuery("SELECT * FROM characters WHERE guid = '%u'", guid);
        if (result)
        {
            guid = sObjectMgr.m_CharGuids.GetNextAfterMaxUsed();
            delete result;
        }
        else incHighest = false;
    }
    else
        guid = sObjectMgr.m_CharGuids.GetNextAfterMaxUsed();

    // normalize the name if specified and check if it exists
    if (!normalizePlayerName(name))
        name = "";

    if (ObjectMgr::CheckPlayerName(name,true) == CHAR_NAME_SUCCESS)
    {
        CharacterDatabase.escape_string(name);              // for safe, we use name only for sql quearies anyway
        result = CharacterDatabase.PQuery("SELECT * FROM characters WHERE name = '%s'", name.c_str());
        if (result)
        {
            name = "";                                      // use the one from the dump
            delete result;
        }
    }
    else
        name = "";

    // name encoded or empty

    snprintf(newguid, 20, "%u", guid);
    snprintf(chraccount, 20, "%u", account);
    snprintf(newpetid, 20, "%u", sObjectMgr.GeneratePetNumber());
    snprintf(lastpetid, 20, "%s", "");

    std::map<uint32,uint32> items;
    std::map<uint32,uint32> mails;
    std::map<uint32,uint32> eqsets;
    char buf[32000] = "";

    typedef std::map<uint32, uint32> PetIds;                // old->new petid relation
    typedef PetIds::value_type PetIdsPair;
    PetIds petids;

    CharacterDatabase.BeginTransaction();
    while(!feof(fin))
    {
        if (!fgets(buf, 32000, fin))
        {
            if(feof(fin)) break;
            ROLLBACK(DUMP_FILE_BROKEN);
        }

        std::string line;
        line.assign(buf);

        // skip empty strings
        size_t nw_pos = line.find_first_not_of(" \t\n\r\7");
        if (nw_pos==std::string::npos)
            continue;

        // skip NOTE
        if (line.substr(nw_pos,15)=="IMPORTANT NOTE:")
            continue;

        // add required_ check
        if (line.substr(nw_pos,41)=="UPDATE character_db_version SET required_")
        {
            if (!CharacterDatabase.Execute(line.c_str()))
                ROLLBACK(DUMP_FILE_BROKEN);

            continue;
        }

        // determine table name and load type
        std::string tn = gettablename(line);
        if (tn.empty())
        {
            sLog.outError("LoadPlayerDump: Can't extract table name from line: '%s'!", line.c_str());
            ROLLBACK(DUMP_FILE_BROKEN);
        }

        DumpTableType type = DTT_CHARACTER;                 //Fixed: Using uninitialized memory 'type'
        DumpTable* dTable = &dumpTables[0];
        for(; dTable->isValid(); ++dTable)
        {
            if (tn == dTable->name)
            {
                type = dTable->type;
                break;
            }
        }

        if (!dTable->isValid())
        {
            sLog.outError("LoadPlayerDump: Unknown table: '%s'!", tn.c_str());
            ROLLBACK(DUMP_FILE_BROKEN);
        }

        bool execute_ok = true;                             // false, if need skip soem query

        // change the data to server values
        switch(type)
        {
        case DTT_CHAR_TABLE:
            if (!changenth(line, 1, newguid))           // character_*.guid update
                ROLLBACK(DUMP_FILE_BROKEN);
            break;

        case DTT_CHAR_NAME_TABLE:
            if (nameInvalidated)                        // ignore declined names if name will changed in some way
            {
                execute_ok = false;
                break;
            }

            if (!changenth(line, 1, newguid))           // character_*.guid update
                ROLLBACK(DUMP_FILE_BROKEN);
            break;

        case DTT_CHARACTER:
        {
            if (!changenth(line, 1, newguid))           // characters.guid update
                ROLLBACK(DUMP_FILE_BROKEN);

            if (!changenth(line, 2, chraccount))        // characters.account update
                ROLLBACK(DUMP_FILE_BROKEN);

            if (name == "")
            {
                // check if the original name already exists
                name = getnth(line, 3);                 // characters.name
                CharacterDatabase.escape_string(name);

                result = CharacterDatabase.PQuery("SELECT * FROM characters WHERE name = '%s'", name.c_str());
                if (result)
                {
                    delete result;

                    if (!changenth(line, 36, "1"))      // characters.at_login set to "rename on login"
                        ROLLBACK(DUMP_FILE_BROKEN);

                    nameInvalidated = true;
                }
            }
            else
            {
                if (!changenth(line, 3, name.c_str()))  // characters.name update
                    ROLLBACK(DUMP_FILE_BROKEN);

                nameInvalidated = true;
            }

            break;
        }
        case DTT_INVENTORY:
        {
            if (!changenth(line, 1, newguid))           // character_inventory.guid update
                ROLLBACK(DUMP_FILE_BROKEN);

            if (!changeGuid(line, 2, items, sObjectMgr.m_ItemGuids.GetNextAfterMaxUsed(), true))
                ROLLBACK(DUMP_FILE_BROKEN);             // character_inventory.bag update
            if (!changeGuid(line, 4, items, sObjectMgr.m_ItemGuids.GetNextAfterMaxUsed()))
                ROLLBACK(DUMP_FILE_BROKEN);             // character_inventory.item update
            break;
        }
        case DTT_ITEM:
        {
            // item, owner, data field:item, owner guid
            if (!changeGuid(line, 1, items, sObjectMgr.m_ItemGuids.GetNextAfterMaxUsed()))
                ROLLBACK(DUMP_FILE_BROKEN);             // item_instance.guid update
            if (!changenth(line, 2, newguid))           // item_instance.owner_guid update
                ROLLBACK(DUMP_FILE_BROKEN);
            std::string vals = getnth(line,3);          // item_instance.data get
            if (!changetokGuid(vals, OBJECT_FIELD_GUID+1, items, sObjectMgr.m_ItemGuids.GetNextAfterMaxUsed()))
                ROLLBACK(DUMP_FILE_BROKEN);             // item_instance.data.OBJECT_FIELD_GUID update
            if (!changetoknth(vals, ITEM_FIELD_OWNER+1, newguid))
                ROLLBACK(DUMP_FILE_BROKEN);             // item_instance.data.ITEM_FIELD_OWNER update
            if (!changenth(line, 3, vals.c_str()))      // item_instance.data update
                ROLLBACK(DUMP_FILE_BROKEN);
            break;
        }
        case DTT_ITEM_GIFT:
        {
            if (!changenth(line, 1, newguid))           // character_gifts.guid update
                ROLLBACK(DUMP_FILE_BROKEN);
            if (!changeGuid(line, 2, items, sObjectMgr.m_ItemGuids.GetNextAfterMaxUsed()))
                ROLLBACK(DUMP_FILE_BROKEN);             // character_gifts.item_guid update
            break;
        }
        case DTT_ITEM_LOOT:
        {
            // item, owner
            if (!changeGuid(line, 1, items, sObjectMgr.m_ItemGuids.GetNextAfterMaxUsed()))
                ROLLBACK(DUMP_FILE_BROKEN);             // item_loot.guid update
            if (!changenth(line, 2, newguid))           // item_Loot.owner_guid update
                ROLLBACK(DUMP_FILE_BROKEN);
            break;
        }
        case DTT_PET:
        {
            //store a map of old pet id to new inserted pet id for use by type 5 tables
            snprintf(currpetid, 20, "%s", getnth(line, 1).c_str());
            if (strlen(lastpetid)==0)
                snprintf(lastpetid, 20, "%s", currpetid);

            if (strcmp(lastpetid,currpetid)!=0)
            {
                snprintf(newpetid, 20, "%d", sObjectMgr.GeneratePetNumber());
                snprintf(lastpetid, 20, "%s", currpetid);
            }

            std::map<uint32, uint32> :: const_iterator petids_iter = petids.find(atoi(currpetid));

            if (petids_iter == petids.end())
            {
                petids.insert(PetIdsPair(atoi(currpetid), atoi(newpetid)));
            }

            if (!changenth(line, 1, newpetid))          // character_pet.id update
                ROLLBACK(DUMP_FILE_BROKEN);
            if (!changenth(line, 3, newguid))           // character_pet.owner update
                ROLLBACK(DUMP_FILE_BROKEN);

            break;
        }
        case DTT_PET_TABLE:                             // pet_aura, pet_spell, pet_spell_cooldown
        {
            snprintf(currpetid, 20, "%s", getnth(line, 1).c_str());

            // lookup currpetid and match to new inserted pet id
            std::map<uint32, uint32> :: const_iterator petids_iter = petids.find(atoi(currpetid));
            if (petids_iter == petids.end())            // couldn't find new inserted id
                ROLLBACK(DUMP_FILE_BROKEN);

            snprintf(newpetid, 20, "%d", petids_iter->second);

            if (!changenth(line, 1, newpetid))          // pet_*.guid -> petid in fact
                ROLLBACK(DUMP_FILE_BROKEN);

            break;
        }
        case DTT_PET_DECL:                              // character_pet_declinedname
        {
            snprintf(currpetid, 20, "%s", getnth(line, 1).c_str());

            // lookup currpetid and match to new inserted pet id
            std::map<uint32, uint32> :: const_iterator petids_iter = petids.find(atoi(currpetid));
            if (petids_iter == petids.end())            // couldn't find new inserted id
                ROLLBACK(DUMP_FILE_BROKEN);

            snprintf(newpetid, 20, "%d", petids_iter->second);

            if (!changenth(line, 1, newpetid))          // character_pet_declinedname.id
                ROLLBACK(DUMP_FILE_BROKEN);

            if (!changenth(line, 2, newguid))           // character_pet_declinedname.owner update
                ROLLBACK(DUMP_FILE_BROKEN);

            break;
        }
        case DTT_MAIL:                                  // mail
        {
            if (!changeGuid(line, 1, mails, sObjectMgr.m_MailIds.GetNextAfterMaxUsed()))
                ROLLBACK(DUMP_FILE_BROKEN);             // mail.id update
            if (!changenth(line, 6, newguid))           // mail.receiver update
                ROLLBACK(DUMP_FILE_BROKEN);
            break;
        }
        case DTT_MAIL_ITEM:                             // mail_items
        {
            if (!changeGuid(line, 1, mails, sObjectMgr.m_MailIds.GetNextAfterMaxUsed()))
                ROLLBACK(DUMP_FILE_BROKEN);             // mail_items.id
            if (!changeGuid(line, 2, items, sObjectMgr.m_ItemGuids.GetNextAfterMaxUsed()))
                ROLLBACK(DUMP_FILE_BROKEN);             // mail_items.item_guid
            if (!changenth(line, 4, newguid))           // mail_items.receiver
                ROLLBACK(DUMP_FILE_BROKEN);
            break;
        }
        case DTT_EQSET_TABLE:
        {
            if (!changenth(line, 1, newguid))           // character_equipmentsets.guid update
                ROLLBACK(DUMP_FILE_BROKEN);
            if (!changeGuid(line, 2, eqsets, sObjectMgr.m_EquipmentSetIds.GetNextAfterMaxUsed()))
                ROLLBACK(DUMP_FILE_BROKEN);             // character_equipmentsets.setguid
            for(int i = 0; i < 19; ++i)                 // character_equipmentsets.item0..item18
                if(!changeGuid(line, 6+i, items, sObjectMgr.m_ItemGuids.GetNextAfterMaxUsed()))
                    ROLLBACK(DUMP_FILE_BROKEN);
            break;
        }
        default:
            sLog.outError("Unknown dump table type: %u",type);
            break;
        }

        if (execute_ok && !CharacterDatabase.Execute(line.c_str()))
            ROLLBACK(DUMP_FILE_BROKEN);
    }

    CharacterDatabase.CommitTransaction();

    //FIXME: current code with post-updating guids not safe for future per-map threads
    sObjectMgr.m_ItemGuids.Set(sObjectMgr.m_ItemGuids.GetNextAfterMaxUsed() + items.size());
    sObjectMgr.m_MailIds.Set(sObjectMgr.m_MailIds.GetNextAfterMaxUsed() +  mails.size());
    sObjectMgr.m_EquipmentSetIds.Set(sObjectMgr.m_EquipmentSetIds.GetNextAfterMaxUsed() + eqsets.size());

    if (incHighest)
        sObjectMgr.m_CharGuids.Set(sObjectMgr.m_CharGuids.GetNextAfterMaxUsed()+1);

    fclose(fin);

    return DUMP_SUCCESS;
}
Пример #6
0
int
main (int argc, char *argv[])
{
  int exit_code = EXIT_FAILURE;
  struct gengetopt_args_info args_info;
  char challenge[BUFSIZ];
  size_t chal_len;
  char response[2048];
  size_t response_len = sizeof (response);
  u2fh_devs *devs = NULL;
  u2fh_cmdflags flags = 0;
  u2fh_rc rc;

  if (cmdline_parser (argc, argv, &args_info) != 0)
    exit (EXIT_FAILURE);

  if (args_info.help_given)
    {
      cmdline_parser_print_help ();
      printf ("\nReport bugs at <https://github.com/Yubico/libu2f-host>.\n");
      exit (EXIT_SUCCESS);
    }

  chal_len = fread (challenge, 1, sizeof (challenge), stdin);
  if (!feof (stdin) || ferror (stdin))
    {
      perror ("read");
      exit (EXIT_FAILURE);
    }

  rc = u2fh_global_init (args_info.debug_flag ? U2FH_DEBUG : 0);
  if (rc != U2FH_OK)
    {
      fprintf (stderr, "error: u2fh_global_init (%d): %s\n", rc,
	       u2fh_strerror (rc));
      exit (EXIT_FAILURE);
    }

  rc = u2fh_devs_init (&devs);
  if (rc != U2FH_OK)
    {
      fprintf (stderr, "error: u2fh_devs_init (%d): %s\n", rc,
	       u2fh_strerror (rc));
      goto done;
    }

  rc = u2fh_devs_discover (devs, NULL);
  if (rc != U2FH_OK)
    {
      fprintf (stderr, "error: u2fh_devs_discover (%d): %s\n", rc,
	       u2fh_strerror (rc));
      goto done;
    }

  switch (args_info.action_arg)
    {
    case action_arg_register:
    case action_arg_authenticate:
      if (args_info.origin_arg == NULL)
	{
	  fprintf (stderr, "error: origin URL empty, use -o to specify it\n");
	  exit (EXIT_FAILURE);
	}

      if (args_info.action_arg == action_arg_register)
	{
	  rc = u2fh_register2 (devs, challenge, args_info.origin_arg,
			       response, &response_len,
			       args_info.touch_flag ? 0 :
			       U2FH_REQUEST_USER_PRESENCE);
	}
      else
	{
	  rc = u2fh_authenticate2 (devs, challenge, args_info.origin_arg,
				   response, &response_len,
				   args_info.touch_flag ? 0 :
				   U2FH_REQUEST_USER_PRESENCE);
	}
      break;
    case action_arg_sendrecv:
      {
	uint8_t command;
	unsigned char out[2048];
	size_t outlen = sizeof (out);
	if (args_info.command_arg == NULL)
	  {
	    fprintf (stderr, "error: empty sendrecv command.\n");
	    exit (EXIT_FAILURE);
	  }
	sscanf (args_info.command_arg, "%hhx", &command);
	rc =
	  u2fh_sendrecv (devs, 0, command, challenge, chal_len - 1, out,
			 &outlen);
      }
      break;
    case action__NULL:
    default:
      fprintf (stderr, "error: unknown action.\n");
      goto done;
    }
  if (rc != U2FH_OK)
    {
      fprintf (stderr, "error (%d): %s\n", rc, u2fh_strerror (rc));
      goto done;
    }

  if (strlen (response))
    {
      printf ("%s\n", response);
    }

  exit_code = EXIT_SUCCESS;

done:
  u2fh_devs_done (devs);
  u2fh_global_done ();

  exit (exit_code);
}
Пример #7
0
/*
 *@brief send线程从conf中读入全局设置
 */
int send_load_config()
{
	FILE *fp;						//打开配置文件指针
	int a[4];						//临时存储点分IP的4个部分
	int flag;						//标识IP是否合法
	char s[TEXT_LINE_LEN];	//存储从配置文件中读取的一行数据
	uint32_t i;					//for循环计数
	char c,c1;					//连续从文件的一行中读取的两个字符,用以标识变量、IP、注释行、无用行
	char *eq = NULL;			//字符串中表示"="的指针
	int len = 0;					//读取的字符串长度,如果是一个变量,其标识符的长度要大于0
	uint32_t tmpi = 0;			//临时存储读取的变量数值

	fp = fopen("conf", "rt");
	if (fp == NULL) {
		write_log("Can't open config file \"conf\":%s\n", strerror(errno));
		return -1;
	}

	net_buffer = (char*)malloc(NET_BUFFER_LEN);
	if (net_buffer == NULL) {
		write_log("net_buffer malloc failed!\n");
		return -1;
	}
	encrypt_net_buffer = (char*)malloc(NET_BUFFER_LEN);
	if (encrypt_net_buffer == NULL) {
		write_log("encrypt net_buffer malloc failed!\n");
		return -1;
	}

	while (!feof(fp)) {
		c = fgetc(fp);
		if ((int)c == -1)
			//EOF==-1
			break;
		if (c != '$') {
			while (c != '\n' && !feof(fp))
				c = fgetc(fp);
			continue;
		}
		if ((c1 = fgetc(fp)) != ':') {
			while (c != '\n' && !feof(fp))
				c = fgetc(fp);
			continue;
		}

		if ('$' == c && ':' == c1) {
			flag = 0;
			fgets(s,TEXT_LINE_LEN,fp);
			tmpi = 0;
			len = 0;
			if ((eq = strchr(s, (int)'=')) == NULL)
				continue;
			len = eq - s;
			if (len <= 0)
				continue;

			if (bcmp(s, "data_store_path", len) == 0) {
				len = strchr(eq + 1, (int)'\n') - ( eq + 1 );
				if ((len + 1) >= sizeof(data_store_path))
					continue;
				if (*( eq + 1 ) == '/')	//从根路径开始
					snprintf(data_store_path, len + 1, "%s", eq + 1 );
			}
			else if (bcmp(s, "accept_port", len) == 0) {
				sscanf(eq+1, "%d", &tmpi);
				if (tmpi > 1024 && tmpi < 65536)
					accept_port = tmpi;
			}
			else if (bcmp(s,"des_pass_phrase",len) == 0) {
				len = strchr(eq + 1,'\n') - (eq + 1);
				if ((len + 1) >= sizeof(des_pass_phrase))
					continue;
				snprintf(des_pass_phrase, len + 1, "%s", eq + 1);
			}
			else if (bcmp(s,"stop",len) == 0) {
				len = strchr(eq + 1,'\n') - (eq + 1);
				if ((len + 1) >= sizeof(stop_filename)){
					write_log("bad stop_time!\n");
					return -1;
				}
				snprintf(stop_filename, len + 1, "%s", eq + 1);
				int year,mon,day;
				sscanf(stop_filename, "META-%04d-%02d-%02d", &year, &mon, &day);
				snprintf(stop_folder, sizeof(stop_folder), "%04d-%02d-%02d", year, mon, day);
			}
			else if (bcmp(s, "accept_addr", len) == 0) {
				a[0] = a[1] = a[2] = a[3] = -1;
				sscanf(eq + 1, "%d.%d.%d.%d", &a[0], &a[1], &a[2], &a[3]);
				for (i = 0; i <= 3; i++) {
					if (a[i] > 255 || a[i] < 0) {
						write_log("[Warning]:illegal server ip in file \"conf\" [%s],ignored\n",s);
						flag = 1;	//IP有问题!则跳出并置位错误标记为真
						break;
					}
				}//for
				if (!flag)
					accept_addr = a[0]*256*256*256 + a[1]*256*256 + a[2]*256 + a[3];
			}//server
		}//if $:
	}//while
	fclose(fp);
	return 0;
}
Пример #8
0
/* If `name' has a correct extension, try to list its contents and search for
   the first file with a proper extension; if found, extract it.  If this
   succeeds, return the name of the temporary file; if the archive file is
   valid but `write_mode' is non-zero, return a zero-length string; in all
   the other cases, return NULL.  */
static char *try_uncompress_archive(const char *name, int write_mode,
                                    const char *program,
                                    const char *listopts,
                                    const char *extractopts,
                                    const char *extension,
                                    const char *search)
{
#ifdef __riscos
    return NULL;
#else
    char *tmp_name = NULL;
    int l = strlen(name), nameoffset, found = 0, len;
    int exit_status;
    char *argv[8];
    FILE *fd;
    char tmp[1024];

    /* Do we have correct extension?  */
    len = strlen(extension);
    if (l <= len || strcasecmp(name + l - len, extension) != 0)
        return NULL;

    /* First run listing and search for first recognizeable extension.  */
    argv[0] = lib_stralloc(program);
    argv[1] = lib_stralloc(listopts);
    argv[2] = archdep_filename_parameter(name);
    argv[3] = NULL;

    ZDEBUG(("try_uncompress_archive: spawning `%s %s %s'",
            program, listopts, name));
    exit_status = archdep_spawn(program, argv, &tmp_name, NULL);

    lib_free(argv[0]);
    lib_free(argv[1]);
    lib_free(argv[2]);

    /* No luck?  */
    if (exit_status != 0) {
        ZDEBUG(("try_uncompress_archive: `%s %s' failed.", program,
                listopts));
        ioutil_remove(tmp_name);
        lib_free(tmp_name);
        return NULL;
    }

    ZDEBUG(("try_uncompress_archive: `%s %s' successful.", program,
            listopts));

    fd = fopen(tmp_name, MODE_READ);
    if (!fd) {
        ZDEBUG(("try_uncompress_archive: cannot read `%s %s' output.",
                program, tmp_name));
        ioutil_remove(tmp_name);
        lib_free(tmp_name);
        return NULL;
    }

    ZDEBUG(("try_uncompress_archive: searching for the first valid file."));

    /* Search for `search' first (if any) to see the offset where
       filename begins, then search for first recognizeable file.  */
    nameoffset = search ? -1 : 0;
    len = search ? strlen(search) : 0;
    while (!feof(fd) && !found) {
        fgets(tmp, 1024, fd);
        l = strlen(tmp);
        while (l > 0) {
            tmp[--l] = 0;
            if (nameoffset < 0 && l >= len &&
                    !strcasecmp(tmp + l - len, search) != 0) {
                nameoffset = l - 4;
            }
            if (nameoffset >= 0 && is_valid_extension(tmp, l, nameoffset)) {
                ZDEBUG(("try_uncompress_archive: found `%s'.",
                        tmp + nameoffset));
                found = 1;
                break;
            }
        }
    }

    fclose(fd);
    ioutil_remove(tmp_name);
    if (!found) {
        ZDEBUG(("try_uncompress_archive: no valid file found."));
        lib_free(tmp_name);
        return NULL;
    }

    /* This would be a valid ZIP file, but we cannot handle ZIP files in
       write mode.  Return a null temporary file name to report this.  */
    if (write_mode) {
        ZDEBUG(("try_uncompress_archive: cannot open file in write mode."));
        lib_free(tmp_name);
        return "";
    }

    /* And then file inside zip.  If we have a zipcode extract all of them
       to the same file. */
    argv[0] = lib_stralloc(program);
    argv[1] = lib_stralloc(extractopts);
    argv[2] = archdep_filename_parameter(name);
    if (is_zipcode_name(tmp + nameoffset)) {
        argv[3] = lib_stralloc(tmp + nameoffset);
        argv[4] = lib_stralloc(tmp + nameoffset);
        argv[5] = lib_stralloc(tmp + nameoffset);
        argv[6] = lib_stralloc(tmp + nameoffset);
        argv[7] = NULL;
        argv[3][0] = '1';
        argv[4][0] = '2';
        argv[5][0] = '3';
        argv[6][0] = '4';
    } else {
        argv[3] = archdep_quote_parameter(tmp + nameoffset);
        argv[4] = NULL;
    }

    ZDEBUG(("try_uncompress_archive: spawning `%s %s %s %s'.",
            program, extractopts, name, tmp + nameoffset));
    exit_status = archdep_spawn(program, argv, &tmp_name, NULL);

    lib_free(argv[0]);
    lib_free(argv[1]);
    lib_free(argv[2]);
    lib_free(argv[3]);
    if (is_zipcode_name(tmp + nameoffset)) {
        lib_free(argv[4]);
        lib_free(argv[5]);
        lib_free(argv[6]);
    }

    if (exit_status != 0) {
        ZDEBUG(("try_uncompress_archive: `%s %s' failed.",
                program, extractopts));
        ioutil_remove(tmp_name);
        lib_free(tmp_name);
        return NULL;
    }

    ZDEBUG(("try_uncompress_archive: `%s %s' successful.", program,
            tmp_name));
    return tmp_name;
#endif
}
Пример #9
0
/*
 *	Warning list 를 화일로 부터 읽어들인다.
 */
int import_list(char *filename)
{
	FILE	*fp;
	char	*cp0, *cp1, *cp2, *cpp[3];
	int		i, n, sw_type;
	int		len1, len2;
	int		nQuotes, nItems;

	/*	Build filter configuration strings		*/
	nItems = 0;
	while (warn_fmts[nItems].sw_type < 0)
	{
		nItems++;
		for (i = 0; i < 3; i++)
		{
	    	warn_fmts[nItems].sw_len[i] = strlen(warn_fmts[nItems].sw_str[i]);
		}
	}

	if (nVerbose > 1)
	{
		fprintf(OUTPUT_FILE, "Data File  = %s\n", filename);
		fprintf(OUTPUT_FILE, "nSupItems1 = %d\n", nItems);
	}

	if ( (fp = fopen(filename, "r")) != NULL)
	{
		(void) fgets(warn_buf, 512, fp);

		while (!feof(fp))
		{
			nQuotes = 0;
			sw_type = 1;
			n = sscanf(warn_buf, "%d", &sw_type);

			if (n == 1)
			{
				cp0 = strchr(warn_buf, '"');
			}
			else
			{
				sw_type = 0;
				cp0     = &warn_buf[0];
				while (isspace(*cp0))
				{
					cp0++;
				}
			}

			if ((cp0 != NULL) && (*cp0 == '"'))
			{
				cpp[0] = cpp[1] = cpp[2] = (char *)"";

				for (nQuotes = 0; nQuotes < 3; nQuotes++)
				{
					cp1 = (cp0 ? strchr(cp0  , '"') : NULL);
					if (cp1 == NULL) break;
					cp2 = (cp1 ? strchr(cp1+1, '"') : NULL);
					if (cp2 == NULL) break;

					cpp[nQuotes] = cp1+1;
					*cp2 = '\0';
					cp0 = cp2 + 1;
				}

				if ( (cp2 != NULL) && (nQuotes >= 2) )
				{
					if (nVerbose > 1)
					{
						fprintf(OUTPUT_FILE, "%d:[%s][%s][%s]\n", sw_type, cpp[0], cpp[1], cpp[2]);
					}

		        	warn_fmts[nItems].sw_type = sw_type;
					for (i = 0; i < 3; i++)
					{
		        		snprintf(warn_fmts[nItems].sw_str[i], 40, "%s", cpp[i]);
	    				warn_fmts[nItems].sw_len[i] = strlen(warn_fmts[nItems].sw_str[i]);
					}
					nItems++;
				}
			}

			(void) fgets(warn_buf, 512, fp);
		}

		fclose(fp);
	}

	if (nVerbose > 1)
	{
		fprintf(OUTPUT_FILE, "nSupItems2 = %d\n", nItems);
	}

	return(nItems);
}
Пример #10
0
/* static sets the initial unchangeable structure */
struct tconfig_block *file_to_tconfig(const char *filename)
{
  FILE   *cfile;
  char   *fbuf   = NULL;
  char   *eip    = NULL;
  struct tconfig_block *block    = NULL;
  struct tconfig_block *head     = NULL;
  struct tconfig_block *search   = NULL;
  struct tconfig_block *tmp      = NULL;
  size_t  size   = 0;
  size_t  i      = 0;
	size_t  count  = 0;

  /* For debug purposes */
  int line       = 1;
  
  /* No memory allocated at this point, we don't need 
   * to die nicely
   */
  if ((cfile = fopen(filename,"r")) == NULL)
  {
    fprintf(stderr,"Could not open configuration file: %s\n",filename);
    return NULL;
  }

  fbuf = tmalloc0(BUFFER_SIZE);

  /* Read the entire file into memory */
  for(i=0;(count = fread(&fbuf[i],1,1024,cfile)) == 1024;i+=1024)
  {
    if ((fbuf = realloc(fbuf,i+1024+1024)) == NULL)
    {
      troll_debug(LOG_FATAL,"Could not allocate memory for config file, barfing.\n");
      exit(EXIT_FAILURE);
    }
  }

	/* Terminate it with a NULL */
	fbuf[i+count] = '\0';


  /* If NOT the end-of-file, we must have had an error of some sort, barf and die */
  if (!feof(cfile))
  {
    troll_debug(LOG_ERROR,"An error occurred while reading the config file");
    free(fbuf);
    return NULL;
  }
  fclose(cfile);

  block = tmalloc(sizeof(*block));

  block->parent = NULL;
  block->child  = NULL;
  block->prev   = NULL;
  block->next   = NULL;

  block->key    = NULL;
  block->value  = NULL;

  head = block;
    
  eip = fbuf;

  while(*eip)
  {
    switch (*eip)
    {
      case '{':
        if (block->child != NULL)
        {
          block = block->child;
          break;
        }
        block->child = tmalloc(sizeof(struct tconfig_block));

        block->child->parent = block;
        block                = block->child;
        block->child         = NULL;
        block->prev          = NULL;
        block->next          = NULL;
        block->key           = NULL;
        block->value         = NULL;

        break;
      
      /* The very left element in tree should have the parent */
      case '}':
        /* Rewind the list the very left */
        while (block->prev != NULL)
          block = block->prev;    
   
        if (block->parent == NULL)
        {
          fprintf(stderr, "Mismatched } around line: %d\n",line);
          exit(EXIT_FAILURE);
        }
  
        block              = block->parent;
        break;

      /* Ugly comment parsing routines */
      case '/':
        if (*(eip+1) != '*' && *(eip+1) != '/')
        {
          fprintf(stderr,"Stray / on line: %d\n",line);
          exit(EXIT_FAILURE);
        }

        /* If comment takes C form */
        if (*(eip+1) == '*')
        {
          /* Skip over / and * */
          eip+=2;

          /* Go until terminating -> */
          while (*eip != '\0') 
          {
            if (*(eip+1) == '\0')
            {
              fprintf(stderr,"Reached end of file while looking for */\n");
              exit(EXIT_FAILURE);
            }

            if (*eip == '*' && *(eip+1) == '/')
            {
              /* loop increases eip, so only add 1 */
              eip++;
              break; /* Found end of comment */
            } 

            if (*eip == '\r' && *(eip+1) == '\n')
            {
              eip++;
              line++;
            }
            else if (*eip == '\n')
            {
              line++;
            }
            else if (*eip == '\r')
            {
              line++;
            }

            eip++;
          }

          if (eip == '\0')
          {
            return head;
          }   
        }
        else /* // comment, go until \r\n, \n, or \r */
        {
          eip+=2; /* Skip over // */
         
          while (*eip != '\0')
          {
            if (*eip == '\r')
            {
              /* This just means the file is over, not an error */
              if (*(eip+1) == '\0')
                return head;

              if (*(eip+1) != '\n')
              {
                eip++;
                line++;
                break;
              }
              else
              {
                line++;
                break;
              }
            }
            else if (*eip == '\n')
            {
              line++;
              break;
            }

            eip++;  
          }

          if (*eip == '\0')
            return head;                
        }

        break;
      case '\r':
        if (*(eip+1) == '\n')
        {
          eip++;
          line++;
        }
        else
          line++;

        if (eip == '\0')
          return head;


        break;
      case '\n':
        line++;
          
        break;
      case '\t':
        break;
      case ' ':
        break;
      default:
        tmp        = tmalloc(sizeof(*tmp));

        /* Do a wasteful scan so I don't have to deal with realloc */
        if (*eip == '"')
        {
          eip++; /* Skip the first " */
          for (i=0;*(eip+i) != '\0' && *(eip+i) != '\n' && *(eip+i) != '\r' &&
                   *(eip+i) != '"';i++);

          if (*(eip+i) != '"')
          {
            fprintf(stderr, "Unmatched \" on line %d\n",line);
            exit(EXIT_FAILURE);
          }
        }
        else
        { 
          for (i=0;*(eip+i) != '\0' && *(eip+i) != ' ' && *(eip+i) != '\t';i++);
            
          if (*(eip+i) != ' ' && *(eip+i) != '\t')
          {
            fprintf(stderr, "Unmatched key on line %d\n",line);
            exit(EXIT_FAILURE);
          }
        }

        size = i;
  
        tmp->key = tmalloc0(size+1);

        for (i=0;i<size;i++)
        {
          *(tmp->key+i) = *(eip++);
        }
   
        /* Skip over trailing " if exists, this could be a problem if key is next to value */
        if (*eip == '"')
          eip++;

        /* Skip over whitespace, print error if EOF or there's a newline reached before text */
        while(*eip == '\t' || *eip == ' ' || *eip == '\r' || *eip == '\n' || *eip == '\0')
        {
          if (*eip == '\0')
          {
            fprintf(stderr, "Reached end of file looking for %s's value on line %d\n",block->key,line);
            exit(EXIT_FAILURE);
          }

          if (*eip == '\r' || *eip == '\n')
          {
            fprintf(stderr, "Reached end of line looking for %s's value on line %d\n",block->key,line);
            exit(EXIT_FAILURE);
          }
    
          eip++;
        }

        /* Now to scan the value */
        /* Do a wasteful scan so I don't have to deal with realloc */
        if (*eip == '"')
        {
          eip++; /* Skip the first " */
          for (i=0;*(eip+i) != '\0' && *(eip+i) != '\n' && *(eip+i) != '\r' &&
                   *(eip+i) != '"';i++);

          if (*(eip+i) != '"')
          {
            fprintf(stderr, "Unmatched \" on line %d\n",line);
            exit(EXIT_FAILURE);
          }
        }
        else
        {
          for (i=0;*(eip+i) != '\0' && *(eip+i) != ' ' && *(eip+i) != '\t' &&
                   *(eip+i) != '\r' && *(eip+i) != '\n';i++);

          if (*(eip+i) != ' ' && *(eip+i) != '\t' && *(eip+i) != '\r' && *(eip+i) != '\n')
          {
            fprintf(stderr, "Unmatched key on line %d\n",line);
            exit(EXIT_FAILURE);
          }
        }

        size = i;

        tmp->value = tmalloc0(size+1);

        for (i=0;i<size;i++)
        {
          *(tmp->value+i) = *(eip++);
        }

        tmp->value[size] = '\0';
 
        /* Rewind list */
        search = block;

        while (search->prev != NULL)
          search = search->prev;

        while (search != NULL)
        {
          if (search->key != NULL && search->value != NULL)
          {
            if (!strcmp(search->key,tmp->key) && !strcmp(search->value,tmp->value))
            {
              /* Same block and key, if previous block was a block with children,
               * jump into that block, elsewise, put in a dupe 
               */
              free(tmp->key);
              free(tmp->value);
              free(tmp);
              tmp = NULL;
              block = search;
              break;
            } 
          }

          block  = search;

          search = search->next;
        }

        if (tmp != NULL)
        {
          if (block->key == NULL && block->value == NULL)
          {
            block->key   = tmp->key;
            block->value = tmp->value;
 
            /* Keeping above memory */
            free(tmp);            
          } 
          else
          {
            /* Make a new block */
            block->next = tmp;
            tmp->prev   = block;
            tmp->next   = NULL;
            tmp->parent = NULL;
            tmp->child  = NULL;
            block       = block->next;
          }
        }

        break;          
    }   

    eip++; /* While loop increase */
  }

  free(fbuf);
  return head;
}
Пример #11
0
int main(int argc,char *argv[]){
  vqgen v;

  int entries=-1,dim=-1;
  int start=0,num=-1;
  float desired=.05f,mindist=0.f;
  int iter=1000;
  int biasp=1;
  int centroid=0;

  FILE *out=NULL;
  char *line;
  long i,j,k;
  int init=0;
  q.quant=-1;

  argv++;
  if(!*argv){
    usage();
    exit(0);
  }

  /* get the book name, a preexisting book to continue training */
  {
    FILE *in=NULL;
    char *filename=alloca(strlen(*argv)+30),*ptr;

    strcpy(filename,*argv);
    in=fopen(filename,"r");
    ptr=strrchr(filename,'-');
    if(ptr){
      int num;
      ptr++;
      num=atoi(ptr);
      sprintf(ptr,"%d.vqi",num+1);
    }else
      strcat(filename,"-0.vqi");
    
    out=fopen(filename,"w");
    if(out==NULL){
      fprintf(stderr,"Unable to open %s for writing\n",filename);
      exit(1);
    }
    
    if(in){
      /* we wish to suck in a preexisting book and continue to train it */
      float a;
      
      line=rline(in,out,1);
      if(strcmp(line,vqext_booktype)){
        fprintf(stderr,"wrong book type; %s!=%s\n",line,vqext_booktype);
        exit(1);
      } 
      
      line=rline(in,out,1);
      if(sscanf(line,"%d %d %d",&entries,&dim,&vqext_aux)!=3){
        fprintf(stderr,"Syntax error reading book file\n");
        exit(1);
      }
      
      vqgen_init(&v,dim,vqext_aux,entries,mindist,
                 vqext_metric,vqext_weight,centroid);
      init=1;
      
      /* quant setup */
      line=rline(in,out,1);
      if(sscanf(line,"%ld %ld %d %d",&q.min,&q.delta,
                &q.quant,&q.sequencep)!=4){
        fprintf(stderr,"Syntax error reading book file\n");
        exit(1);
      }
      
      /* quantized entries */
      i=0;
      for(j=0;j<entries;j++){
        for(k=0;k<dim;k++){
          line=rline(in,out,0);
          sscanf(line,"%f",&a);
          v.entrylist[i++]=a;
        }
      }      
      vqgen_unquantize(&v,&q);

      /* bias */
      i=0;
      for(j=0;j<entries;j++){
        line=rline(in,out,0);
        sscanf(line,"%f",&a);
        v.bias[i++]=a;
      }
      
      v.seeded=1;
      {
        float *b=alloca((dim+vqext_aux)*sizeof(float));
        i=0;
        while(1){
          for(k=0;k<dim+vqext_aux;k++){
            line=rline(in,out,0);
            if(!line)break;
            sscanf(line,"%f",b+k);
          }
          if(feof(in))break;
          vqgen_addpoint(&v,b,b+dim);
        }
      }
      
      fclose(in);
    }
  }
  
  /* get the rest... */
  argv=argv++;
  while(*argv){
    if(argv[0][0]=='-'){
      /* it's an option */
      if(!argv[1]){
        fprintf(stderr,"Option %s missing argument.\n",argv[0]);
        exit(1);
      }
      switch(argv[0][1]){
      case 'p':
        if(sscanf(argv[1],"%d,%d,%d",&entries,&dim,&q.quant)!=3)
          goto syner;
        break;
      case 's':
        if(sscanf(argv[1],"%d,%d",&start,&num)!=2){
          num= -1;
          if(sscanf(argv[1],"%d",&start)!=1)
            goto syner;
        }
        break;
      case 'e':
        if(sscanf(argv[1],"%f",&desired)!=1)
          goto syner;
        break;
      case 'd':
        if(sscanf(argv[1],"%f",&mindist)!=1)
          goto syner;
        if(init)v.mindist=mindist;
        break;
      case 'i':
        if(sscanf(argv[1],"%d",&iter)!=1)
          goto syner;
        break;
      case 'b':
        biasp=0;
        break;
      case 'c':
        centroid=1;
        break;
      default:
        fprintf(stderr,"Unknown option %s\n",argv[0]);
        exit(1);
      }
      argv+=2;
    }else{
      /* it's an input file */
      char *file=strdup(*argv++);
      FILE *in;
      int cols=-1;

      if(!init){
        if(dim==-1 || entries==-1 || q.quant==-1){
          fprintf(stderr,"-p required when training a new set\n");
          exit(1);
        }
        vqgen_init(&v,dim,vqext_aux,entries,mindist,
                   vqext_metric,vqext_weight,centroid);
        init=1;
      }

      in=fopen(file,"r");
      if(in==NULL){
        fprintf(stderr,"Could not open input file %s\n",file);
        exit(1);
      }
      fprintf(out,"# training file entry: %s\n",file);

      while((line=rline(in,out,0))){
        if(cols==-1){
          char *temp=line;
          while(*temp==' ')temp++;
          for(cols=0;*temp;cols++){
            while(*temp>32)temp++;
            while(*temp==' ')temp++;
          }

          fprintf(stderr,"%d colums per line in file %s\n",cols,file);

        }
        {
          int i;
          float b[cols];
          if(start+num*dim>cols){
            fprintf(stderr,"ran out of columns reading %s\n",file);
            exit(1);
          }
          while(*line==' ')line++;
          for(i=0;i<cols;i++){

            /* static length buffer bug workaround */
            char *temp=line;
            char old;
            while(*temp>32)temp++;

            old=temp[0];
            temp[0]='\0';
            b[i]=atof(line);
            temp[0]=old;
            
            while(*line>32)line++;
            while(*line==' ')line++;
          }
          if(num<=0)num=(cols-start)/dim;
          for(i=0;i<num;i++)
            vqext_addpoint_adj(&v,b,start+i*dim,dim,cols,num);

        }
      }
      fclose(in);
    }
  }

  if(!init){
    fprintf(stderr,"No input files!\n");
    exit(1);
  }

  vqext_preprocess(&v);

  /* train the book */
  signal(SIGTERM,setexit);
  signal(SIGINT,setexit);

  for(i=0;i<iter && !exiting;i++){
    float result;
    if(i!=0){
      vqgen_unquantize(&v,&q);
      vqgen_cellmetric(&v);
    }
    result=vqgen_iterate(&v,biasp);
    vqext_quantize(&v,&q);
    if(result<desired)break;
  }

  /* save the book */

  fprintf(out,"# OggVorbis VQ codebook trainer, intermediate file\n");
  fprintf(out,"%s\n",vqext_booktype);
  fprintf(out,"%d %d %d\n",entries,dim,vqext_aux);
  fprintf(out,"%ld %ld %d %d\n",
          q.min,q.delta,q.quant,q.sequencep);

  /* quantized entries */
  fprintf(out,"# quantized entries---\n");
  i=0;
  for(j=0;j<entries;j++)
    for(k=0;k<dim;k++)
      fprintf(out,"%d\n",(int)(rint(v.entrylist[i++])));
  
  fprintf(out,"# biases---\n");
  i=0;
  for(j=0;j<entries;j++)
    fprintf(out,"%f\n",v.bias[i++]);

  /* we may have done the density limiting mesh trick; refetch the
     training points from the temp file */

  rewind(v.asciipoints);
  fprintf(out,"# points---\n");
  {
    /* sloppy, no error handling */
    long bytes;
    char buff[4096];
    while((bytes=fread(buff,1,4096,v.asciipoints)))
      while(bytes)bytes-=fwrite(buff,1,bytes,out);
  }

  fclose(out);
  fclose(v.asciipoints);

  vqgen_unquantize(&v,&q);
  vqgen_cellmetric(&v);
  exit(0);

  syner:
    fprintf(stderr,"Syntax error in argument '%s'\n",*argv);
    exit(1);
}
Пример #12
0
int FMT_decrypt_stream(char *id, byte_string_t key,
	FILE *infp, FILE *outfp, params_t params)
{
    byte_string_t U;
    byte_string_t K, V;
    crypto_ctx_t ctx;
    unsigned char in[crypt_buf_size];
    unsigned char out[200]; //TODO: what should this be?
    int inl, outl;
    unsigned char data[1024];
    int count;
    EVP_ENCODE_CTX mime;
    int result = 0;
    char *s, slen;
    int status;

    advance_to("-----BEGIN IBE-----", infp);

    advance_to("U:", infp);
    mime_get(U, infp);

    slen = strlen(id) + 2;
    s = (char *) alloca(sizeof(char) * slen);
    for(;;) {
	advance_to("ID:", infp);
	if (feof(infp)) {
	    //ID not found
	    return 0;
	}
	fgets(s, slen, infp);
	if (s[strlen(id)] == '\n') { //correct length?
	    if (!strncmp(s, id, strlen(id))) { //compares?
		break; //email has ID for us
	    }
	}
    }

    advance_to("V:", infp);
    mime_get(V, infp);

    status = IBE_reveal_key(K, U, V, key, params);

    if (status != 1) {
	fprintf(outfp, "WARNING: KMAC MISMATCH. INVALID CIPHERTEXT!\n");
	byte_string_clear(V);
	byte_string_clear(K);
	return result;
    }

    advance_to("W:", infp);

    crypto_ctx_init(ctx);
    crypto_decrypt_init(ctx, K);
    EVP_DecodeInit(&mime);
    for (;;) {
	fgets(in, crypt_buf_size, infp);
	inl = strlen(in);
	if (inl < 0) {
	    fprintf(stderr, "read error\n");
	    exit(1);
	}
	if (inl < 2) break;
	EVP_DecodeUpdate(&mime, data, &count, in, inl);
	crypto_decrypt_update(ctx, out, &outl, data, count);
	fwrite(out, 1, outl, outfp);
    }
    EVP_DecodeFinal(&mime, data, &count);
    crypto_decrypt_update(ctx, out, &outl, data, count);
    fwrite(out, 1, outl, outfp);
    if (1 != crypto_decrypt_final(ctx, out, &outl)) {
	fprintf(outfp, "crypto_decrypt_final() failed!\n");
    } else {
	result = 1;
    }
    fwrite(out, 1, outl, outfp);
    crypto_ctx_clear(ctx);

    byte_string_clear(K);
    byte_string_clear(U);
    byte_string_clear(V);

    return result;
}
Пример #13
0
void FMT_encrypt_stream_array(char **id, int idcount,
	FILE *infp, FILE *outfp, params_t params)
{
    byte_string_t U, K;
    byte_string_t *V;
    unsigned char in[crypt_buf_size];
    unsigned char *out;
    int inl, outl;
    crypto_ctx_t ctx;
    EVP_ENCODE_CTX mime;
    unsigned char data[1024];
    int i;
    int count;

    out = (unsigned char *) alloca(crypt_buf_size + crypto_block_size());

    V = (byte_string_t *) alloca(sizeof(byte_string_t) * idcount);

    fprintf(outfp, "\n-----BEGIN IBE-----\n");

    crypto_generate_key(K);

    IBE_hide_key_array(U, V, id, idcount, K, params);
    fprintf(outfp, "\nU:\n");
    mime_put(U, outfp);
    fprintf(outfp, "\n");

    for (i=0; i<idcount; i++) {
	fprintf(outfp, "\nID:\n");
	fprintf(outfp, "%s\n", id[i]);

	fprintf(outfp, "\nV:\n");
	mime_put(V[i], outfp);
	fprintf(outfp, "\n");

	byte_string_clear(V[i]);
    }

    fprintf(outfp, "\nW:\n");
    crypto_ctx_init(ctx);
    crypto_encrypt_init(ctx, K);
    EVP_EncodeInit(&mime);
    for (;;) {
	inl = fread(in, 1, crypt_buf_size, infp);
	if (inl < 0) {
	    fprintf(stderr, "read error\n");
	    exit(1);
	}
	crypto_encrypt_update(ctx, out, &outl, in, inl);
	EVP_EncodeUpdate(&mime, data, &count, out, outl);
	fwrite(data, 1, count, outfp);
	if (feof(infp)) break;
    }
    crypto_encrypt_final(ctx, out, &outl);
    crypto_ctx_clear(ctx);
    EVP_EncodeUpdate(&mime, data, &count, out, outl);
    fwrite(data, 1, count, outfp);
    EVP_EncodeFinal(&mime, data, &count);
    fwrite(data, 1, count, outfp);

    fprintf(outfp, "\n-----END IBE-----\n");

    byte_string_clear(K);
    byte_string_clear(U);
}
Пример #14
0
// application main method
int main(int argc, char *argv[]) {
    // check if the output is a tty so we can use colors

#ifdef WIN32
    usecolor = 0;
#else
    usecolor = isatty(1);
#endif

    static struct option long_options[] = {
        {"color", no_argument, 0, 'c'},
        {0, 0, 0, 0}
    };

    while (1) {
        int c = getopt_long(argc, argv, "c", long_options, 0);

        if (c == -1) {
            break;
        }

        switch (c) {
            case 'c':
                usecolor = true;
                break;
            default:
                exit(1);
        }
    }

    // check for proper command line args
    if (optind != argc-1) {
        err("usage: %s [--color] file.osm.pbf", argv[0]);
    }

    // open specified file
    FILE *fp = fopen(argv[optind], "rb");

    if (!fp) {
        err("can't open file '%s'", argv[optind]);
    }

    // read while the file has not reached its end
    while (!feof(fp)) {
        // storage of size, used multiple times
        int32_t sz;

        // read the first 4 bytes of the file, this is the size of the blob-header
        if (fread(&sz, sizeof(sz), 1, fp) != 1) {
            break; // end of file reached
        }

        // convert the size from network byte-order to host byte-order
        sz = ntohl(sz);

        // ensure the blob-header is smaller then MAX_BLOB_HEADER_SIZE
        if (sz > OSMPBF::max_blob_header_size) {
            err("blob-header-size is bigger then allowed (%u > %u)", sz, OSMPBF::max_blob_header_size);
        }

        // read the blob-header from the file
        if (fread(buffer, sz, 1, fp) != 1) {
            err("unable to read blob-header from file");
        }

        // parse the blob-header from the read-buffer
        if (!blobheader.ParseFromArray(buffer, sz)) {
            err("unable to parse blob header");
        }

        // tell about the blob-header
        info("\nBlobHeader (%d bytes)", sz);
        debug("  type = %s", blobheader.type().c_str());

        // size of the following blob
        sz = blobheader.datasize();
        debug("  datasize = %u", sz);

        // optional indexdata
        if (blobheader.has_indexdata()) {
            debug("  indexdata = %u bytes", blobheader.indexdata().size());
        }

        // ensure the blob is smaller then MAX_BLOB_SIZE
        if (sz > OSMPBF::max_uncompressed_blob_size) {
            err("blob-size is bigger then allowed (%u > %u)", sz, OSMPBF::max_uncompressed_blob_size);
        }

        // read the blob from the file
        if (fread(buffer, sz, 1, fp) != 1) {
            err("unable to read blob from file");
        }

        // parse the blob from the read-buffer
        if (!blob.ParseFromArray(buffer, sz)) {
            err("unable to parse blob");
        }

        // tell about the blob-header
        info("Blob (%d bytes)", sz);

        // set when we find at least one data stream
        bool found_data = false;

        // if the blob has uncompressed data
        if (blob.has_raw()) {
            // we have at least one datastream
            found_data = true;

            // size of the blob-data
            sz = blob.raw().size();

            // check that raw_size is set correctly
            if (sz != blob.raw_size()) {
                warn("  reports wrong raw_size: %u bytes", blob.raw_size());
            }

            // tell about the blob-data
            debug("  contains uncompressed data: %u bytes", sz);

            // copy the uncompressed data over to the unpack_buffer
            memcpy(unpack_buffer, buffer, sz);
        }

        // if the blob has zlib-compressed data
        if (blob.has_zlib_data()) {
            // issue a warning if there is more than one data steam, a blob may only contain one data stream
            if (found_data) {
                warn("  contains several data streams");
            }

            // we have at least one datastream
            found_data = true;

            // the size of the compressesd data
            sz = blob.zlib_data().size();

            // tell about the compressed data
            debug("  contains zlib-compressed data: %u bytes", sz);
            debug("  uncompressed size: %u bytes", blob.raw_size());

            // zlib information
            z_stream z;

            // next byte to decompress
            z.next_in   = (unsigned char*) blob.zlib_data().c_str();

            // number of bytes to decompress
            z.avail_in  = sz;

            // place of next decompressed byte
            z.next_out  = (unsigned char*) unpack_buffer;

            // space for decompressed data
            z.avail_out = blob.raw_size();

            // misc
            z.zalloc    = Z_NULL;
            z.zfree     = Z_NULL;
            z.opaque    = Z_NULL;

            if (inflateInit(&z) != Z_OK) {
                err("  failed to init zlib stream");
            }
            if (inflate(&z, Z_FINISH) != Z_STREAM_END) {
                err("  failed to inflate zlib stream");
            }
            if (inflateEnd(&z) != Z_OK) {
                err("  failed to deinit zlib stream");
            }

            // unpacked size
            sz = z.total_out;
        }

        // if the blob has lzma-compressed data
        if (blob.has_lzma_data()) {
            // issue a warning if there is more than one data steam, a blob may only contain one data stream
            if (found_data) {
                warn("  contains several data streams");
            }

            // we have at least one datastream
            found_data = true;

            // tell about the compressed data
            debug("  contains lzma-compressed data: %u bytes", blob.lzma_data().size());
            debug("  uncompressed size: %u bytes", blob.raw_size());

            // issue a warning, lzma compression is not yet supported
            err("  lzma-decompression is not supported");
        }

        // check we have at least one data-stream
        if (!found_data) {
            err("  does not contain any known data stream");
        }

        // switch between different blob-types
        if (blobheader.type() == "OSMHeader") {
            // tell about the OSMHeader blob
            info("  OSMHeader");

            // parse the HeaderBlock from the blob
            if (!headerblock.ParseFromArray(unpack_buffer, sz)) {
                err("unable to parse header block");
            }

            // tell about the bbox
            if (headerblock.has_bbox()) {
                OSMPBF::HeaderBBox bbox = headerblock.bbox();
                debug("    bbox: %.7f,%.7f,%.7f,%.7f",
                    (double)bbox.left() / OSMPBF::lonlat_resolution,
                    (double)bbox.bottom() / OSMPBF::lonlat_resolution,
                    (double)bbox.right() / OSMPBF::lonlat_resolution,
                    (double)bbox.top() / OSMPBF::lonlat_resolution);
            }

            // tell about the required features
            for (int i = 0, l = headerblock.required_features_size(); i < l; i++) {
                debug("    required_feature: %s", headerblock.required_features(i).c_str());
            }

            // tell about the optional features
            for (int i = 0, l = headerblock.optional_features_size(); i < l; i++) {
                debug("    optional_feature: %s", headerblock.optional_features(i).c_str());
            }

            // tell about the writing program
            if (headerblock.has_writingprogram()) {
                debug("    writingprogram: %s", headerblock.writingprogram().c_str());
            }

            // tell about the source
            if (headerblock.has_source()) {
                debug("    source: %s", headerblock.source().c_str());
            }
        } else if (blobheader.type() == "OSMData") {
            // tell about the OSMData blob
            info("  OSMData");

            // parse the PrimitiveBlock from the blob
            if (!primblock.ParseFromArray(unpack_buffer, sz)) {
                err("unable to parse primitive block");
            }

            // tell about the block's meta info
            debug("    granularity: %u", primblock.granularity());
            debug("    lat_offset: %u", primblock.lat_offset());
            debug("    lon_offset: %u", primblock.lon_offset());
            debug("    date_granularity: %u", primblock.date_granularity());

            // tell about the stringtable
            debug("    stringtable: %u items", primblock.stringtable().s_size());

            // number of PrimitiveGroups
            debug("    primitivegroups: %u groups", primblock.primitivegroup_size());

            // iterate over all PrimitiveGroups
            for (int i = 0, l = primblock.primitivegroup_size(); i < l; i++) {
                // one PrimitiveGroup from the the Block
                OSMPBF::PrimitiveGroup pg = primblock.primitivegroup(i);

                bool found_items=false;

                // tell about nodes
                if (pg.nodes_size() > 0) {
                    found_items = true;

                    debug("      nodes: %d", pg.nodes_size());
                    if (pg.nodes(0).has_info()) {
                        debug("        with meta-info");
                    }
                }

                // tell about dense nodes
                if (pg.has_dense()) {
                    found_items = true;

                    debug("      dense nodes: %d", pg.dense().id_size());
                    if (pg.dense().has_denseinfo()) {
                        debug("        with meta-info");
                    }
                }

                // tell about ways
                if (pg.ways_size() > 0) {
                    found_items = true;

                    debug("      ways: %d", pg.ways_size());
                    if (pg.ways(0).has_info()) {
                        debug("        with meta-info");
                    }
                }

                // tell about relations
                if (pg.relations_size() > 0) {
                    found_items = true;

                    debug("      relations: %d", pg.relations_size());
                    if (pg.relations(0).has_info()) {
                        debug("        with meta-info");
                    }
                }

                if (!found_items) {
                    warn("      contains no items");
                }
            }
        }

        else {
            // unknown blob type
            warn("  unknown blob type: %s", blobheader.type().c_str());
        }
    }

    // close the file pointer
    fclose(fp);

    // clean up the protobuf lib
    google::protobuf::ShutdownProtobufLibrary();
}
Пример #15
0
int main(void)
{
    // ensure read in file can be opened
    FILE* rawfile = fopen("card.raw", "r");
    if (rawfile == NULL)
    {
        printf("Could not open file to recover.\n");
        perror("fopen");
        return 1;
    }

    // buffer size of jpg blocks
    uint8_t data[512] = {};

    // file num counter for naming files
    int outFileNum = 0;
   
   // ensure file pointer is at beginning of file
   fseek(rawfile, 0, SEEK_SET);

   // find start of jpgs 
    while (!(data[0] == 0xff && data[1] == 0xd8 && data[2] == 0xff && (data[3] == 0xe1 || data[3] == 0xe0))) 
        fread(&data, sizeof(512), 1, rawfile);   
    
    while (1)
    {
        // create string and read filename in to it
        char buf[8];
        sprintf(buf, "%03d.jpg", outFileNum);

        // open new file to write found jpgs
        FILE* output = fopen(buf, "w");
        if (output == NULL)
        {
            printf("Could not open file to write.\n");
            return 1;
        }
   
        // write in jpgs until start of next file is found    
        do
        {
           // read from raw file and write to new image file
            fwrite(&data, sizeof(512), 1, output);           
            fread(&data, sizeof(512), 1, rawfile);
            
            // check for EOF
            if (feof(rawfile))
            {
                // close files and end program if EOF found
                fclose(output);
                fclose(rawfile);
                return 0;
            } 
        }
        while (!(data[0] == 0xff && data[1] == 0xd8 && data[2] == 0xff && (data[3] == 0xe1 || data[3] == 0xe0)));

      
        // close write file and advance file counter
        fclose(output);
        outFileNum++;

    }

    return 0;
}
Пример #16
0
ptri2d
read_tri2d(const char *name)
{

  FILE     *in;
  ptri2d    t2;
  real(*x)[2];
  uint(*e)[2];
  uint(*t)[3];
  uint     *xb;
  uint     *eb;
  uint      i;

  uint      vertices, edges, triangles;
  uint      items;
  char      buf[80], *res;

  in = fopen(name, "r");
  if (!in) {
    (void) fprintf(stderr, "Could not open file \"%s\" for reading\n", name);
    return 0;
  }

  res = fgets(buf, BUFSIZE, in);
  assert(res != NULL);
  while (!feof(in) && buf[0] == '#') {
    res = fgets(buf, 80, in);
    assert(res != NULL);
  }
  items = sscanf(buf, "%u %u %u", &vertices, &edges, &triangles);
  if (items != 3) {
    (void) fprintf(stderr, "Could not get sizes from file \"%s\"\n", name);
    (void) fclose(in);
    return 0;
  }

  t2 = new_tri2d(vertices, edges, triangles);
  x = t2->x;
  e = t2->e;
  t = t2->t;
  xb = t2->xb;
  eb = t2->eb;

  /*vertices */
  for (i = 0; i < vertices; i++) {
    res = fgets(buf, 80, in);
    assert(res != NULL);
    while (!feof(in) && buf[0] == '#') {
      res = fgets(buf, 80, in);
      assert(res != NULL);
    }
    items = sscanf(buf, "%" SCANF_PREFIX "f %" SCANF_PREFIX "f %u", x[i],
		   x[i] + 1, xb + i);
    if (items != 3) {
      (void) fprintf(stderr, "Could not read vertex %u from file \"%s\"\n", i,
		     name);
      del_tri2d(t2);
      (void) fclose(in);
      return 0;
    }
  }
  /*edges */
  for (i = 0; i < edges; i++) {
    res = fgets(buf, 80, in);
    assert(res != NULL);
    while (!feof(in) && buf[0] == '#') {
      res = fgets(buf, 80, in);
      assert(res != NULL);
    }
    items = sscanf(buf, "%u %u %u", e[i], e[i] + 1, eb + i);
    if (items != 3) {
      (void) fprintf(stderr, "Could not read edge %u from file \"%s\"\n", i,
		     name);
      del_tri2d(t2);
      (void) fclose(in);
      return 0;
    }
  }
  /*triangles */
  for (i = 0; i < triangles; i++) {
    res = fgets(buf, 80, in);
    assert(res != NULL);
    while (!feof(in) && buf[0] == '#') {
      res = fgets(buf, 80, in);
      assert(res != NULL);
    }
    items = sscanf(buf, "%u %u %u", t[i], t[i] + 1, t[i] + 2);
    if (items != 3) {
      (void) fprintf(stderr, "Could not read triangle %u from file \"%s\"\n",
		     i, name);
      del_tri2d(t2);
      (void) fclose(in);
      return 0;
    }
  }

  (void) fclose(in);

  return t2;
}
Пример #17
0
unsigned int HSPParseFASTAToPacked(const char* FASTAFileName, const char* annotationFileName, const char* packedDNAFileName, const char* ambiguityFileName, const unsigned int FASTARandomSeed, const int maskLowerCase) {

	FILE *FASTAFile, *annotationFile, *packedDNAFile, *ambiguityFile;

	NewAnnotation *chrAnnotation;
	int chrAnnAllocated = 256;
	int blockAllocated = 256;

	char c;
	int chrNum, blockNum;
	unsigned int i, l;
	int nCount;
	unsigned int chrLen, usefulCharNum, numCharInBuffer, totalNumChar;
	unsigned char charMap[255];
	char *chrSeq, *p;
	unsigned int chrAllocated = 65536;
	unsigned char buffer[PACKED_BUFFER_SIZE];
	unsigned char packedBuffer[PACKED_BUFFER_SIZE / 4];
	chrLen = usefulCharNum = numCharInBuffer = totalNumChar = chrNum = blockNum = i = l = nCount = 0;
	FASTAFile = (FILE*)fopen64(FASTAFileName, "r");
	if (FASTAFile == NULL) {
		fprintf(stderr, "ParseFASTToPacked() : Cannot open FASTAFileName!\n");
		exit(1);
	}

	annotationFile = (FILE*)fopen64(annotationFileName, "w");
	if (annotationFile == NULL) {
		fprintf(stderr, "ParseFASTToPacked() : Cannot open annotationFileName!\n");
		exit(1);
	}

	packedDNAFile = (FILE*)fopen64(packedDNAFileName, "wb");
	if (packedDNAFile == NULL) {
		fprintf(stderr, "ParseFASTToPacked() : Cannot open packedDNAFileName!\n");
		exit(1);
	}

	ambiguityFile = (FILE*)fopen64(ambiguityFileName, "w");
	if (ambiguityFile == NULL) {
		fprintf(stderr, "ParseFASTToPacked() : Cannot open ambiguityFileName!\n");
		exit(1);
	}

	HSPFillCharMap(charMap);

	c = (char)getc(FASTAFile);
	if (c != '>') {
		fprintf(stderr, "ParseFASTToPacked() : FASTA file does not begin with '>'!\n");
		exit(1);
	}
	chrAnnotation = (NewAnnotation *)malloc(sizeof(NewAnnotation)*chrAnnAllocated);
	chrSeq = (char*)malloc(sizeof(char)*chrAllocated);
	chrNum = blockNum = usefulCharNum = numCharInBuffer = 0;
	while(!feof(FASTAFile)){
		if (feof(FASTAFile)) break;
		if (chrNum == chrAnnAllocated){
			chrAnnAllocated <<= 1;
			chrAnnotation = (NewAnnotation *)realloc(chrAnnotation, sizeof(NewAnnotation)*chrAnnAllocated);
//			printf("%d\n", chrNum);
		}

		l=0;
		c = (char)getc(FASTAFile);
		while(!feof(FASTAFile) && c!='\t' && c!=' ' && c!='\n' && l<MAX_SEQ_NAME_LENGTH){
			chrAnnotation[chrNum].chrName[l]=c;
			l++;
			c=(char)getc(FASTAFile);
		}
		chrAnnotation[chrNum].chrName[l]='\0';
		while(c!='\n'){
			c=(char)getc(FASTAFile);
		}
		chrLen = 0;
		while(c!='>' && !feof(FASTAFile)){
			if (c!='\n'){
				if (c>='a' && c<='z'){
					c+='A'-'a';
				}
				if (chrLen >= chrAllocated){
					chrAllocated <<= 1;
					chrSeq = (char*)realloc(chrSeq, sizeof(char)*chrAllocated);
				}
				*(chrSeq+chrLen) = c;
				chrLen += 1;
			}
			c=(char)getc(FASTAFile);
		}
		if (chrLen < 75) continue;
		//*
		i=0;
		p=chrSeq;
		while (ambiguityCount[charMap[(int)*p]] == 1 && i++ != chrLen) p++;
		if (i == chrLen) {
			blockNum = 1;
			chrAnnotation[chrNum].blockInChr = (ChrBlock *)malloc(sizeof(ChrBlock)*blockNum);
			chrAnnotation[chrNum].chrStart = usefulCharNum;
			chrAnnotation[chrNum].blockNum = blockNum;
			chrAnnotation[chrNum].blockInChr[0].blockStart = usefulCharNum;
			chrAnnotation[chrNum].blockInChr[0].ori = 0;
			usefulCharNum += chrLen;
			chrAnnotation[chrNum].chrEnd = usefulCharNum-1;
			chrAnnotation[chrNum].blockInChr[0].blockEnd = usefulCharNum-1;
			i=0;
			while(i<chrLen){
				if (numCharInBuffer >= PACKED_BUFFER_SIZE) {
					ConvertTextToBytePacked(buffer, packedBuffer, charMap, 4, PACKED_BUFFER_SIZE);
					fwrite(packedBuffer, 1, PACKED_BUFFER_SIZE / 4, packedDNAFile);
					numCharInBuffer = 0;
				}
				buffer[numCharInBuffer++] = chrSeq[i++];
			}
		} else {
			i=0;
			p = chrSeq;
			while (ambiguityCount[charMap[(int)*p]]!=1 && ++i!=chrLen) p++;
			if (i<10) { i = 0; p = chrSeq;}
			blockNum = 1;
			chrAnnotation[chrNum].blockInChr = (ChrBlock *)malloc(sizeof(ChrBlock)*blockAllocated);
			chrAnnotation[chrNum].chrStart = usefulCharNum;
			chrAnnotation[chrNum].blockInChr[blockNum-1].ori = i;
			chrAnnotation[chrNum].blockInChr[blockNum-1].blockStart = usefulCharNum;
			int len=0;
			while (i<chrLen) {
				if(ambiguityCount[charMap[(int)*p]] == 1){
					if (numCharInBuffer >= PACKED_BUFFER_SIZE) {
						ConvertTextToBytePacked(buffer, packedBuffer, charMap, 4, PACKED_BUFFER_SIZE);
						fwrite(packedBuffer, 1, PACKED_BUFFER_SIZE / 4, packedDNAFile);
						numCharInBuffer = 0;
					}
					buffer[numCharInBuffer++] = *p++;
					i++;
					usefulCharNum++;
					len++;
				}else{
					nCount = 0;
					while((ambiguityCount[charMap[(int)*p]]!=1) && i<chrLen){
						nCount++;
						i++;
						p++;
					}
					if (nCount<10) {
						do {
							if (numCharInBuffer >= PACKED_BUFFER_SIZE) {
								ConvertTextToBytePacked(buffer, packedBuffer, charMap, 4, PACKED_BUFFER_SIZE);
								fwrite(packedBuffer, 1, PACKED_BUFFER_SIZE / 4, packedDNAFile);
								numCharInBuffer = 0;
							}
							buffer[numCharInBuffer++] = 'G';
							usefulCharNum++;
							len++;
						} while(--nCount>0);
					} else {
						if (i<chrLen) {
							chrAnnotation[chrNum].blockInChr[blockNum-1].blockEnd = usefulCharNum -1;
							chrAnnotation[chrNum].blockInChr[blockNum-1].ori = i-nCount-len;
							if (blockNum == blockAllocated){
								blockAllocated <<= 1;
								chrAnnotation[chrNum].blockInChr = (ChrBlock *)realloc(chrAnnotation[chrNum].blockInChr, sizeof(ChrBlock)*blockAllocated);
							}
							blockNum++;
							len=0;
							chrAnnotation[chrNum].blockInChr[blockNum-1].blockStart = usefulCharNum;
						} else {
							i-=nCount;
							break;
						}
					}
				}
			}
			chrAnnotation[chrNum].blockInChr[blockNum-1].blockEnd = usefulCharNum-1;
			chrAnnotation[chrNum].blockInChr[blockNum-1].ori = i-len;
			chrAnnotation[chrNum].blockNum = blockNum;
			chrAnnotation[chrNum].chrEnd = usefulCharNum-1;
		}
//*/
		chrNum++;
		totalNumChar += chrLen;
	}
	if (numCharInBuffer > 0) {
		ConvertTextToBytePacked(buffer, packedBuffer, charMap, 4, numCharInBuffer);
		fwrite(packedBuffer, 1, (numCharInBuffer + 3) / 4, packedDNAFile);
		numCharInBuffer = 0;
	}
	if (totalNumChar % 4 == 0) {
		c = 0;
		fwrite(&c, 1, 1, packedDNAFile);
	}
	c = (char)(totalNumChar % 4);
	fwrite(&c, 1, 1, packedDNAFile);
	fclose(packedDNAFile);
	fprintf(annotationFile, "%u\t%d\t%d\n", totalNumChar, chrNum, FASTARandomSeed);
	int j=0;
	int total = 0;
	for (i=0;i<chrNum;i++) {
		fprintf(annotationFile, "%d\t%s\n", (int)strlen(chrAnnotation[i].chrName), chrAnnotation[i].chrName);
		total += chrAnnotation[i].blockNum;
	}
	fprintf(annotationFile, "%d\n", total);
//	fprintf(stderr, "total block, %d, %d, %d\n",i,chrNum, total);
	for(i=0;i<chrNum;i++){
		for(j=0;j<chrAnnotation[i].blockNum;j++){
			fprintf(annotationFile,"%d\t%u\t%u\t%u\n",i, chrAnnotation[i].blockInChr[j].blockStart, chrAnnotation[i].blockInChr[j].blockEnd, chrAnnotation[i].blockInChr[j].ori);
		}
		free(chrAnnotation[i].blockInChr);
	}
	free(chrAnnotation);
	fclose(annotationFile);
	return chrNum;
}
Пример #18
0
static void
set_input(struct runinfo *rip)
{
  if (rip->from == i_stdin)
    {
      rip->more_sources = 0;
      rip->source = stdin;
      curr_fname = rip->fname = xstrdup("<stdin>");
    }
  else if (rip->from == i_names)
    {
      rip->source = NULL;
      while (rip->more_sources)
	{
	  static char fname_buf[_MAX_PATH + 1];
	  char *fp = fgets(fname_buf,_MAX_PATH,stdin);
	  if (fp)
	    {
	      fp = fname_buf + strlen(fname_buf);
	      if ('\n' == fp[-1])
		fp[-1] = '\0';
	      if (NULL == (rip->source = fopen(fname_buf,"r")) && verbose)
		fprintf(stderr,"runexpat: open failed on %s\n",fname_buf);
	      else if (verbose)
		fprintf(stderr,"runexpat: inputting %s\n",fname_buf);
	      rip->more_sources = feof(stdin);
	      curr_fname = rip->fname = xstrdup(fname_buf);
	    }
	  else
	    {
	      rip->source = NULL;
	      rip->more_sources = 0;
	    }
	  if (rip->source)
	    break;
	}
    }
  else if (rip->from == i_list)
    {
      if (rip->todo == NULL)
	{
	  rip->todo = rip->list;
	  if (NULL == rip->todo || NULL == *rip->todo)
	    {
	      rip->source = NULL;
	      rip->more_sources = 0;
	      rip->todo = NULL;
	      return;
	    }
	}
      rip->more_sources = 1;
      while (rip->more_sources)
	{
	  if (NULL == (rip->source = fopen(*rip->todo,"r")) && verbose)
	    fprintf(stderr,"runexpat: open failed on %s\n",*rip->todo);
	  else
	    {
	      if (verbose)
		fprintf(stderr,"runexpat: inputting %s\n",*rip->todo);
	      curr_fname = *rip->todo;
	      rip->fname = xstrdup(curr_fname);
	      progress("xmlinput: %s\n",curr_fname);
	    }
	  rip->more_sources = (NULL != *++rip->todo);
	  if (!rip->more_sources)
	    rip->todo = NULL;
	  if (rip->source)
	    break;
	}
    }
}
Пример #19
0
int
main(int argc, char *argv[])
{
	fz_context *ctx;
	FILE *script = NULL;
	int c;

	while ((c = fz_getopt(argc, argv, "o:p:v")) != -1)
	{
		switch(c)
		{
		case 'o': output = fz_optarg; break;
		case 'p': prefix = fz_optarg; break;
		case 'v': verbosity ^= 1; break;
		default: usage(); break;
		}
	}

	if (fz_optind == argc)
		usage();

	ctx = fz_new_context(NULL, NULL, FZ_STORE_DEFAULT);
	if (!ctx)
	{
		fprintf(stderr, "cannot initialise context\n");
		exit(1);
	}
	pdfapp_init(ctx, &gapp);
	gapp.scrw = 640;
	gapp.scrh = 480;
	gapp.colorspace = fz_device_rgb(ctx);

	fz_try(ctx)
	{
		while (fz_optind < argc)
		{
			scriptname = argv[fz_optind++];
			script = fopen(scriptname, "rb");
			if (script == NULL)
				fz_throw(ctx, FZ_ERROR_GENERIC, "cannot open script: %s", scriptname);

			do
			{
				char *line = my_getline(script);
				if (line == NULL)
					continue;
				if (verbosity)
					fprintf(stderr, "'%s'\n", line);
				if (match(&line, "%"))
				{
					/* Comment */
				}
				else if (match(&line, "PASSWORD"))
				{
					strcpy(pd_password, line);
				}
				else if (match(&line, "OPEN"))
				{
					char path[1024];
					if (file_open)
						pdfapp_close(&gapp);
					strcpy(filename, line);
					if (prefix)
					{
						sprintf(path, "%s%s", prefix, line);
					}
					else
					{
						strcpy(path, line);
					}
					pdfapp_open(&gapp, path, 0);
					file_open = 1;
				}
				else if (match(&line, "GOTO"))
				{
					pdfapp_gotopage(&gapp, atoi(line)-1);
				}
				else if (match(&line, "SCREENSHOT"))
				{
					char text[1024];

					sprintf(text, output, ++shotcount);
					if (strstr(text, ".pgm") || strstr(text, ".ppm") || strstr(text, ".pnm"))
						fz_save_pixmap_as_pnm(ctx, gapp.image, text);
					else
						fz_save_pixmap_as_png(ctx, gapp.image, text, 0);
				}
				else if (match(&line, "RESIZE"))
				{
					int w, h;
					sscanf(line, "%d %d", &w, &h);
					pdfapp_onresize(&gapp, w, h);
				}
				else if (match(&line, "CLICK"))
				{
					float x, y, b;
					int n;
					n = sscanf(line, "%f %f %f", &x, &y, &b);
					if (n < 1)
						x = 0.0f;
					if (n < 2)
						y = 0.0f;
					if (n < 3)
						b = 1;
					/* state = 1 = transition down */
					pdfapp_onmouse(&gapp, (int)x, (int)y, b, 0, 1);
					/* state = -1 = transition up */
					pdfapp_onmouse(&gapp, (int)x, (int)y, b, 0, -1);
				}
				else if (match(&line, "TEXT"))
				{
					unescape_string(td_textinput, line);
				}
				else
				{
					fprintf(stderr, "Unmatched: %s\n", line);
				}
			}
			while (!feof(script));

			fclose(script);
		}
	}
	fz_catch(ctx)
	{
		fprintf(stderr, "error: cannot execute '%s'\n", scriptname);
	}

	if (file_open)
		pdfapp_close(&gapp);

	fz_drop_context(ctx);

	return 0;
}
Пример #20
0
R_API int r_core_patch (RCore *core, const char *patch) {
	char *p, *p2, *q, str[200], tmp[64];
	ut64 noff = 0LL;
	FILE *fd = r_sandbox_fopen (patch, "r");
	if (fd==NULL) {
		eprintf ("Cannot open patch file\n");
		return 1;
	}

	while (!feof (fd)) {
		fgets (str, sizeof (str), fd);
		if (*str=='#' || *str=='\n' || *str=='\r')
			continue;
		if (*str==':') {
			r_core_cmd0 (core, str+1);
			continue;
		}
		if (*str=='.' || *str=='!') {
			r_core_cmd0 (core, str);
			continue;
		}
		p = strchr (str+1, ' ');
		if (p) {
			*p = 0;
			for (++p; *p==' '; p++); // XXX: skipsspaces here
			switch (*p) {
			case '{': {
				char *s, *off = strdup (str);
				RBuffer *b = r_buf_new ();
				
				while (!feof (fd)) {
					fgets (str, sizeof (str), fd);
					if (*str=='}')
						break;
					if ((q=strstr (str, "${"))) {
						char *end = strchr (q+2,'}');
						if (end) {
							*q = *end = 0;
							noff = r_num_math (core->num, q+2);
							r_buf_append_bytes (b, (const ut8*)str, strlen (str));
							snprintf (tmp, sizeof (tmp), "0x%08"PFMT64x, noff);
							r_buf_append_bytes (b, (const ut8*)tmp, strlen (tmp));
							r_buf_append_bytes (b, (const ut8*)end+1, strlen (end+1));
						}
					} else r_buf_append_bytes (b, (const ut8*)str, strlen (str));
				}

				s = r_buf_to_string (b);
				r_egg_load (core->egg, s, 0);
				free (s);
			
				r_egg_compile (core->egg);
				r_egg_assemble (core->egg);

				r_buf_free (b);
				b = r_egg_get_bin (core->egg);

				if (strcmp (off, "+"))
					noff = r_num_math (core->num, off);
				r_core_write_at (core, noff, b->buf, b->length);
				noff += b->length;
				r_buf_free (b);
				free (off);
				}
				break;
			case '"':
				p2 = strchr (p+1,'"');
				if (p2) *p2=0;
				r_core_cmdf (core, "s %s", str);
				r_core_cmdf (core, "\"w %s\"", p+1);
				break;
			case ':':
				r_core_cmdf (core, "s %s", str);
				r_core_cmdf (core, "wa %s", p);
				break;
			default:
				r_core_cmdf (core, "s %s", str);
				r_core_cmdf (core, "wx %s", p);
				break;
			}
		}
	}
	fclose (fd);
	return 0;
}
Пример #21
0
static Boolean Get_Params (void)

{
  FILE  *f;
  FILE  *g;
  Int4  i;
  Int2  j;
  Int4  len;
  Int4  num_nuc;
  Int4  num_prt;

  if (GetArgs ("suggest", NUMARG, myargs)) {
    if (NUMARG == TOTARG && myargs [8].intvalue) {
      suggestRec.lookForStop = (Boolean) (myargs [6].intvalue);
      StringNCpy (inputFile, myargs [0].strvalue, sizeof (inputFile));
      if (inputFile [0] == '\0') {
        StringCpy (inputFile, "stdin");
      }
      StringNCpy (outputFile, myargs [1].strvalue, sizeof (outputFile));
      if (outputFile [0] == '\0') {
        StringCpy (outputFile, "stdout");
      }
      f = FileOpen (inputFile, "r");
      if (f != NULL) {
        Get_DNA (f, &suggestRec);
        FileClose (f);
        dna_seq = suggestRec.nucleotide.sequence;
        dna_len = StringLen (dna_seq);
        if (dna_len > 3 && dna_seq != NULL) {
          dna_len -= 3;
          dna_seq [dna_len] = '\0';
        }
        rev_seq = MemNew(dna_len+1);
        if (rev_seq != NULL) {
          reverse (dna_len);
          f = FileOpen (outputFile, "w");
          if (f != NULL) {
            j = 0;
            for (i = 0; i < dna_len; i++) {
              fputc ((int) (rev_seq [i]), f);
              j++;
              if (j >= 50) {
                fputc ((int) '\n', f);
                j = 0;
              }
            }
            if (j > 0) {
              fputc ((int) '\n', f);
            }
            FileClose (f);
          }
        }
      }
    } else {
      suggestRec.lookForStop = (Boolean) (myargs [6].intvalue);
      StringNCpy (inputFile, myargs [0].strvalue, sizeof (inputFile));
      if (inputFile [0] == '\0') {
        StringCpy (inputFile, "stdin");
      }
      StringNCpy (outputFile, myargs [1].strvalue, sizeof (outputFile));
      if (outputFile [0] == '\0') {
        StringCpy (outputFile, "stdout");
      }
      f = FileOpen (inputFile, "r");
      if (f != NULL) {
        g = FileOpen (outputFile, "w");
        if (g != NULL) {
	  suggestOut.out.fileOut = g;
          while (! feof (f)) {
            if ((Boolean) (myargs [7].intvalue)) {
              Get_DNA (f, &suggestRec);
              Get_Protein (f, &suggestRec);
            } else {
              Get_Protein (f, &suggestRec);
              Get_DNA (f, &suggestRec);
            }
            Get_Genetic_Code (myargs [2].intvalue, &suggestRec);
            suggestRec.minVal = (myargs [3].intvalue);
            suggestRec.maxVal = (myargs [4].intvalue);
            suggestRec.minExon = (myargs [5].intvalue);

	    ProcessData(&suggestOut);
          }
          FileClose (g);
        }
        FileClose (f);
      }
    }
    return TRUE;
  } else {
    return FALSE;
  }
}
Пример #22
0
void Set_Menu_Container() {
    GdkBitmap *mask ; 
    GdkPixmap *pixmap;
    GtkStyle *style ;
    FILE *fp, *detail ;
    char data[400] ;
    char temp[100] ;
    char detail_filename[100] ;
    int x = 0 ;

    memset( data, '\0', 400 ) ;
    memset( temp, '\0', 100 ) ;
    memset( detail_filename, '\0', 100 ) ;


    menu_Container = gtk_notebook_new() ;
    gtk_notebook_set_tab_pos( GTK_NOTEBOOK( menu_Container ), GTK_POS_LEFT ) ;
     
    z_Monster_Tag = gtk_label_new( "Monster" ) ;
    gtk_widget_set_usize( z_Monster_Tag, 85, 75 ) ;
    z_Information_Tag = gtk_label_new( "Monster Detail" ) ;
    gtk_widget_set_usize( z_Information_Tag, 85, 75 ) ;
    z_Battle_Log_Tag = gtk_label_new( "Battle Log" ) ;
    gtk_widget_set_usize( z_Battle_Log_Tag, 85, 75 ) ;
    z_Battle_Tag = gtk_label_new( "Battle!!" ) ;
    gtk_widget_set_usize( z_Battle_Tag, 85, 75 ) ;

 
    
    style = gtk_widget_get_style(main_Window ) ;
    

    // for dektop linux
    // z_Monster_Page = gtk_image_new_from_file( "DataBase/resource/123.jpg" ) ;
     
    fp = fopen( gAccount, "r" ) ;   
    //*********************************
    fscanf( fp, "%s", temp ) ;
    strcat( data, temp ) ;

    memset( temp, '\0', 100 ) ;
    fscanf( fp, "%s", temp ) ;

    
    strcpy( detail_filename, "DataBase/monster_detail/" ) ;
    if ( temp[0] == '1' ) {
       strcat( detail_filename, "a_monster" ) ;
       pixmap = gdk_pixmap_create_from_xpm_d( main_Window->window,
                     &mask,&style->bg[GTK_STATE_NORMAL], (gchar **)a_XPM);
    } // else if
    else if ( temp[0] == '2' ) {
       strcat( detail_filename, "b_monster" ) ;
       pixmap = gdk_pixmap_create_from_xpm_d( main_Window->window,
                     &mask,&style->bg[GTK_STATE_NORMAL], (gchar **)b_XPM);
    } // else if
    else if ( temp[0] == '3' ) {
       strcat( detail_filename, "c_monster" ) ;
       pixmap = gdk_pixmap_create_from_xpm_d( main_Window->window,
                     &mask,&style->bg[GTK_STATE_NORMAL], (gchar **)c_XPM);
    } // else if

    z_Monster_Page = gtk_pixmap_new(pixmap,mask);
    gProperty[0] = temp[0] ;
  
    strcat( data, "\n\n" ) ;   
    detail = fopen( detail_filename, "r" ) ; 
    for ( x = strlen(data) ; !feof(detail); x++ ) fscanf( detail, "%c", &data[x] ) ;
   
    z_Information_Page = gtk_label_new( data ) ;
    //**********************************

    memset( data, '\0', 400 ) ;
    strcat( data, "Battle History\nRecord:   " ) ;

    memset( temp, '\0', 100 ) ;
    fscanf( fp, "%s", temp ) ;
    strcat( data, temp ) ;
    strcat( data, "   " ) ;
    memset( temp, '\0', 100 ) ;
    fscanf( fp, "%s", temp ) ;
    strcat( data, temp ) ;    
    strcat( data, "\n\nMonster\t\tResult\n" ) ;
    for ( x = strlen(data) ; !feof(fp) ; x++ ) fscanf( fp, "%c", &data[x] ) ; 
    z_Battle_Log_Page = gtk_label_new( data ) ;
    // **********************************
    
    z_Battle_Page = gtk_fixed_new() ;

    fclose(fp) ;
    fclose(detail) ;

    z_Battle_IP_Entry = gtk_entry_new() ;
    gtk_fixed_put( GTK_FIXED(z_Battle_Page), z_Battle_IP_Entry, 100, 150 ) ;
    gtk_widget_set_usize( z_Battle_IP_Entry, 170,50 ) ;
    gtk_entry_set_text( z_Battle_IP_Entry , "192.168.0.50" ) ;
    z_Battle_Button = gtk_button_new_with_label( "Send!!" ) ;
    gtk_widget_set_usize( z_Battle_Button, 70,50 ) ;
    gtk_fixed_put( GTK_FIXED(z_Battle_Page), z_Battle_Button, 270, 150 ) ;    

    gtk_notebook_append_page( GTK_NOTEBOOK( menu_Container ), 
                              z_Monster_Page, z_Monster_Tag ) ;
    gtk_notebook_append_page( GTK_NOTEBOOK( menu_Container ), 
                              z_Information_Page, z_Information_Tag ) ; 
    gtk_notebook_append_page( GTK_NOTEBOOK( menu_Container ), 
                              z_Battle_Log_Page, z_Battle_Log_Tag ) ;
    gtk_notebook_append_page( GTK_NOTEBOOK( menu_Container ),
                              z_Battle_Page, z_Battle_Tag ) ;

    gtk_container_add( GTK_WINDOW( main_Window ), menu_Container ) ;

} // Set_Menu_Container() 
Пример #23
0
int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        printf("Usage: %s file\n", argv[0]);
        exit(1);
    }

    FILE* file;
    file = fopen(argv[1], "r");

    if (file)
    {
        // Get the filesize. Note: We still want to generate an empty bytecode
        // file when reading an empty input file.
        size_t filesize;
        fseek(file, 0L, SEEK_END);
        filesize = ftell(file);
        // Reset filehandle to the beginning of the file.
        fseek(file, 0L, SEEK_SET);

        // Allocate file buffer
        char* file_buffer = (char*)malloc(filesize);
        if (file_buffer)
        {
            size_t bytes_read = 0;

            while (!feof(file))
            {
                size_t count = fread(file_buffer, sizeof(char), filesize, file);

                if (ferror(file))
                {
                    printf("Error while reading the file.\n");
                }
                else
                {
                    bytes_read += count;
                }
            }

            if (bytes_read == filesize)
            {
                int result = generate_bytecode(file_buffer, bytes_read);
                if (!result)
                {
                    printf("Error during bytecode generation.\n");
                    exit(1);
                }
            }
            else if (filesize == 0)
            {
                // Create empty output file
            }
            else
            {
                printf("Error while reading the file: %d\n", bytes_read);
            }

            free(file_buffer);
        }
        else
        {
            printf("Memory allocation failure.\nCould not allocate %d bytes.\n", filesize);
        }

        // Close the filehandle.
        fclose(file);
    }
    else
    {
        printf("Could not open file %s.\n", argv[1]);
        exit(1);
    }
}
Пример #24
0
int main(int argc,char **argv)
{
  int m;
  int n;
  int num_files;
  int *ixs;
  FILE *fptr;
  long tot_lines;
  long lines;
  int chara;
  int svchara;
  int curr_arg;
  bool bTotalOnly;
  bool bStdinIsList;
  bool bStdin;
  bool bNoSort;
  bool bModulo;
  int modulo;

  bTotalOnly = false;
  bStdinIsList = false;
  bNoSort = false;
  bModulo = false;

  for (curr_arg = 1; curr_arg < argc; curr_arg++) {
    if (!strcmp(argv[curr_arg],"-totalonly"))
      bTotalOnly = true;
    else if (!strcmp(argv[curr_arg],"-stdinislist"))
      bStdinIsList = true;
    else if (!strcmp(argv[curr_arg],"-no_sort"))
      bNoSort = true;
    else if (!strncmp(argv[curr_arg],"-modulomodulo",7)) {
      bModulo = true;
      sscanf(&argv[curr_arg][7],"%d",&modulo);
    }
    else
      break;
  }

  if (curr_arg == argc)
    bStdin = 1;
  else {
    bStdin = 0;

    num_files = argc - curr_arg;

    finfo = (struct file_info *)malloc(num_files * sizeof (struct file_info));

    if (finfo == NULL) {
      printf("couldn't malloc %d bytes\n",
        num_files * sizeof (struct file_info));
      return 1;
    }

    ixs = (int *)malloc(num_files * sizeof (int));

    if (ixs == NULL) {
      printf("couldn't malloc %d bytes\n",num_files * sizeof (int));
      return 2;
    }
  }

  tot_lines = 0;
  m = 0;

  /* start of argument loop: */
  for ( ; ; ) {

  if (bStdin)
    fptr = stdin;
  else if ((fptr = fopen(argv[curr_arg],"r")) == NULL) {
    printf(couldnt_open,argv[curr_arg]);
    curr_arg++;

    if (curr_arg == argc)
      break;

    continue;
  }

  lines = 0;
  svchara = NEWLINE;

  for ( ; ; ) {
    chara = fgetc(fptr);

    if (feof(fptr))
      break;

    svchara = chara;

    if (svchara == NEWLINE)
      lines++;
  }

  fclose(fptr);

  if (svchara != NEWLINE)
    lines++;

  if (bStdin)
    break;

  strcpy(finfo[m].name,argv[curr_arg]);
  finfo[m].lines = lines;
  m++;

  if (!bModulo || !(lines % modulo))
    tot_lines += lines;

  curr_arg++;

  if (curr_arg == argc)
    break;

  /* end of argument loop: */
  }

  if (!bTotalOnly) {
    if (bStdin)
      printf(fmt_str,lines,"stdin");
    else {
      num_files = m;

      for (n = 0; n < num_files; n++)
        ixs[n] = n;

      if (!bNoSort)
        qsort(ixs,num_files,sizeof (int),compare);

      for (n = 0; n < num_files; n++) {
        if (!bModulo || !(finfo[ixs[n]].lines % modulo)) {
          printf(fmt_str,
            finfo[ixs[n]].lines,
            finfo[ixs[n]].name);
        }
      }

      putchar(NEWLINE);
    }
  }

  if (!bStdin)
    printf(fmt_str,tot_lines,total_str);

  free(finfo);
  free(ixs);

  return 0;
}
Пример #25
0
void fillbuffer (char *filename) {
   FILE *fp;      /* FILE pointer for filename                    */
   int count;     /* how many chars were read into buffer2        */
   char *p1;      /* points to current char in buffer2            */
   char *p2;      /* points to last char (of interest) in buffer2 */
   char *p3;      /* points to current char in buffer             */
   char *p6;      /* scratch */
   short found;   /* some flags */
   short in_comment;
   short in_format_BR;
   short in_format_f;
   short foo;

   /*
    * Set p4 and p5 to the ends of buffer and titlebuf, respectively.
    * These are used for error checking, so that we don't overflow the
    * buffers.  Using pointers will speed things up a bit at the cost
    * of four bytes of local storage.  They are not global for the sake
    * of speed.
    */

   char *p4 = buffer   + BUFFERSIZE;
   char *p5 = titlebuf + BUFFERSIZE;

   /*
    * open the file
    */

   if ((fp = fopen(filename,"r")) == NULL) {
      buffer[0] = '\0';
      if (v_flag) fprintf (error_fp,"Open failed for file \"%s\"\n",filename);
      return;
   }

   /*
    * see if it includes another man page
    */
   if ((fgets(buffer2,4,fp) == NULL) || (strncmp(buffer2,".so",3)==0)) {
      buffer[0] = '\0';
      titlebuf[0] = '\0';
      fclose(fp);
      return;
   }
   fseek(fp,0L,SEEK_SET);

   /*
    * Make fp point to the first newline following NAME so that the
    * next block read will pick it up as the first character.  This is
    * needed for the next section of code following this one.
    */

   for(;;) {

      /*
       * read in buffer2 in a line-oriented fashion at first so that we
       * can more easily ignore .\" and .TH lines
       */

      if (fgets(buffer2,BUFFERSIZE,fp)==NULL) {
         /*
          * eof or error, and we haven't found "NAME" yet ... return
          * an empty string
          */
          buffer[0] = '\0';
          titlebuf[0] = '\0';
          fclose(fp);
          if (v_flag) fprintf (error_fp,
               "EOF or error on %s, NAME not found.\n",filename);
          return;
      }

      /* ignore comment lines and any .TH line(s) */
      if ((strncmp(buffer2,".\\\"",3)==0) || (strncmp(buffer2,".TH",3)==0))
         continue;

      /* check the various versions of "NAME" */
      if (strstr(buffer2,NAME1) != NULL) break;
      if (strstr(buffer2,NAME2) != NULL) break;
      if (strstr(buffer2,NAME3) != NULL) break;
   }                             


   /* we need the previous newline for the next algorithm to work */
   ungetc('\n', fp);

   /*
    * Make p1 point to spot in buffer2 where there occurs the first
    * character following '-' which in turn follows "NAME".
    * Note that if "NAME" or '-' are within a comment line
    * (nroff source), it will still be picked up.
    *
    * Also copy selected chars to titlebuf until the first '-' is found.
    */

   p3 = titlebuf;
   found = 0;        /* set this when we find '-'        */
   in_format_BR = 0; /* in the middle of a .BR format    */
   in_format_f = 0;  /* in the middle of a \fI format    */
   in_comment = 0;   /* in the middle of a .\" comment   */
   foo = 0;          /* haven't found the printable character after NAME */
   for(;;) {                             

      /* read another block into buffer2. */    

      count = fread(buffer2,sizeof(char),BUFFERSIZE-1,fp);
      if (count == 0) {
         /* eof or error; empty buffer and titlebuf then return */
         buffer[0] = '\0';
         titlebuf[0] = '\0';
         fclose(fp);
         if (v_flag) fprintf (error_fp,
               "EOF or error on %s, command name not found.\n",filename);
         return;
      }
      buffer2[count] = '\0';
      p1 = buffer2;

      /* mark the "end" of buffer2 with p2 */
      if ((p2 = strchr(p1,'-')) != NULL) {
         found = 1;
      } else {
         p2 = buffer + count;
      }

      /*
       * If this is not our first iteration, dump any formatting information
       * or comments left over from the last interation.
       */

      if (in_comment) {
         while((p1<p2) && (*p1 != '\n')) p1++;
         in_comment = 0;
      }

      if (in_format_BR) {
         while ((p1<p2) && !isspace(*p1)) p1++;
         in_format_BR = 0;
      }
      
      if (in_format_f) {
         p1 = p1 + 3 - in_format_f;
         in_format_f = 0;
      }

      /*
       * At this time, p1 points to the start of the key words, p2
       * to either the end of the key words or the end of buffer2,
       * and p3 into the spot in titlebuf where the next character should
       * be put.
       *
       * Copy *p1 to *p3 while p1<p2 (not at end of titlebuf or key words),
       * skipping comments, formatting info, and control chars
       */

      for (; p1<p2; p1++) {

         /* skip .\" comments */
         if (strncmp(p1,"\n.\\\"",4) == 0) {
            while ((p1<p2) && (*p1!='\n')) p1++;
            if (p1==p2) in_comment = 1;
            continue;
         }

         /* skip .BR-type formatting */
         if ((p1<p2) && (*p1=='\n') && (*(p1+1)=='.')) {
            p1++;
            while ((p1<p2) && !isspace(*p1)) p1++;
            if (p1==p2) in_format_BR = 1;
            else --p1;
            continue;
         }

         /* skip \fI-type formatting */
         if ((p1<p2) && (*p1=='\\') && (*(p1+1)=='f')) {
            if ((p1 + 3) < p2) {
               p1 += 3;
            } else {
               in_format_f = p2 - p1;
               p1 = p2;
            }
            continue;
         }

         /*
          * skip whitespace if we haven't got the beginning of the
          * description yet.
          */

#ifdef ISGRAPH_FIX
         if (isgraph(*p1) && (*p1!=' ')) foo=1;
         if (!foo) {
            while ((p1<p2) && !(isgraph(*p1) && (*p1!=' '))) p1++;
            if ((*p1=='.') && (*(p1-1)=='\n')) p1 -=2;
            else --p1;
            continue;
         }
#else 
         if (isgraph(*p1)) foo=1;
         if (!foo) {
            while ((p1<p2) && !isgraph(*p1)) p1++;
            if ((*p1=='.') && (*(p1-1)=='\n')) p1 -=2;
            else --p1;
            continue;
         }
#endif

         /*
          * at this point, *p1 is either a control char or something that
          * we want in titlebuf, assuming that p1<p2.
          */

         if ((p1<p2) && !iscntrl(*p1)) {

            /*
             * The conditional below means:
             * Copy it so that:  1. There is only one space between words; and
             *                   2. The buffer doesn't begin with a space.
             */

            if (  !((p3>titlebuf) && (*p1 == ' ') && (*(p3-1) == ' ')) &&
                  !((p3==titlebuf) && (*p3 == ' '))
               ) {

               /* don't let a space precede a comma */
               if ((*p1==',') && (*(p3-1)==' ')) {
                  *(p3-1) = ',';
                  continue;
               } else *p3++ = *p1;
               if (p3>=p5) {  /* titlebuf overflow? */
                  if (v_flag)
                     fprintf(error_fp,"command name buffer overflow on %s\n",
                             filename);
                  buffer[0] = '\0';
                  titlebuf[0] = '\0';
                  fclose(fp);
                  return;
               }
            }
         }
      }
   
      if (found) {      /* we've got all of the key words */
         p3--;          /* p3 now points to last char, not terminator */
         if (*p3=='\\') p3--;
         while(isspace(*p3)) p3--;
         *(p3+1) = '\0';
         break;   
      }

   }
   p1 = p2 + 1;
#ifdef ISGRAPH_FIX
   while ( (p1 < buffer2 + BUFFERSIZE) &&!(isgraph(*p1) && (*p1 != ' '))) p1++;
#else 
   while ((p1 < buffer2 + BUFFERSIZE) && !isgraph(*p1)) p1++;
#endif

   /*
    * now copy selected chars to buffer until the next subheading is found
    */

   p3 = buffer;
   found = 0;        /* set this when we find one of the above strings  */
   in_format_BR = 0; /* in the middle of a .BR format                   */
   in_format_f = 0;  /* in the middle of a \fI format                   */
   in_comment = 0;   /* in the middle of a .\" comment                  */
   for(;;) {

      /* mark the "end" of buffer2 with p2 */
      if ( ((p2 = strstr(p1,".SH"))         != NULL) ||
           ((p2 = strstr(p1,SYNOPSIS1))     != NULL) ||
           ((p2 = strstr(p1,SYNOPSIS2))     != NULL) ||
           ((p2 = strstr(p1,SYNOPSIS3))     != NULL) ||
           ((p2 = strstr(p1,DESCRIPTION1))  != NULL) ||
           ((p2 = strstr(p1,DESCRIPTION2))  != NULL) ||
           ((p2 = strstr(p1,DESCRIPTION3))  != NULL)
         ) {
         *p2 = '\0';
         /*
          * this conditional is to cover the wierd case of having the word
          * "SYNOPSIS" appearing in the description (or elsewhere), as
          * it does for the GNO Intro(1) man page.  Blech.  Only in
          * aroff source or a preformatted page would this matter.
          */
         if (((p6 = strstr(p1,SYNOPSIS1))     != NULL) ||
             ((p6 = strstr(p1,DESCRIPTION1))  != NULL)) {
            p2 = p6;
         }
         found = 1;
      } else {
         p2 = buffer + count;
      }

      /*
       * If this is not our first iteration, dump any formatting information
       * or comments left over from the last interation.
       */

      if (in_comment) {
         while((p1<p2) && (*p1 != '\n')) p1++;
         in_comment = 0;
      }

      if (in_format_BR) {
         while ((p1<p2) && !isspace(*p1)) p1++;
         in_format_BR = 0;
      }
      
      if (in_format_f) {
         p1 = p1 + 3 - in_format_f;
         in_format_f = 0;
      }

      /*
       * At this time, p1 points to the start of the description, p2
       * to either the end of the description or the end of buffer2,
       * and p3 into the spot in buffer where the next character should
       * be put.
       *
       * Copy *p1 to *p3 while p1<p2 (not at end of buffer or description),
       * skipping comments, formatting info, and control chars
       */

      for (; p1<p2; p1++) {

         /* skip .\" comments */
         if (strncmp(p1,"\n.\\\"",4) == 0) {
            while ((p1<p2) && (*p1!='\n')) p1++;
            if (p1==p2) in_comment = 1;
         }
      
         /* skip .BR-type formatting */
         if ((p1<p2) && (*p1=='\n') && (*(p1+1)=='.')) {
            p1++;
            while ((p1<p2) && !isspace(*p1)) p1++;
            if (p1==p2) in_format_BR = 1;
         }

         /* skip \fI-type formatting */
         if ((p1<p2) && (*p1=='\\') && (*(p1+1)=='f')) {
            if ((p1 + 3) < p2) {
               p1 += 3;
            } else {
               in_format_f = p2 - p1;
               p1 = p2;
            }
         }

         /*
          * at this point, *p1 is either a control char or something that
          * we want in buffer, assuming that p1<p2.
          */

         if ((p1<p2) && !iscntrl(*p1)) {

            /*
             * The conditional below means:
             * Copy it so that:  1. There is only one space between words; and
             *                   2. The buffer doesn't begin with a space.
             */

            if (  !((p3>buffer) && (*p1 == ' ') && (*(p3-1) == ' ')) &&
                  !((p3==buffer) && (*p3 == ' '))
               ) {
               *p3++ = *p1;
               if (p3>=p4) {  /* buffer overflow? */
                  if (v_flag)
                     fprintf(error_fp,"command description buffer overflow on %s\n",
                             filename);
                  buffer[0] = '\0';
                  titlebuf[0] = '\0';
                  fclose(fp);
                  return;
               }
            }
         }   
      }
   
      if (found) {      /* we've got the entire description */
         *p3 = '\0';
         break;   
      }

      /*
       * We're part way through the description; read another block
       * into buffer2.
       */   

      count = fread(buffer2,sizeof(char),BUFFERSIZE-1,fp);
      if (count == 0) {
         /* eof or error; terminate buffer and return */
         *p3 = '\0';
         if (v_flag) {
#define NO_DESCRIPTION "description not found"
           if (feof(fp)) {
             warnx("EOF on %s, %s", filename, NO_DESCRIPTION);
           } else if (ferror(fp)) {
             warn("error on %s, %s", filename, NO_DESCRIPTION);
           } else {
             errx(1, "fread above line %d returned zero", __LINE__);
           }
         }
         fclose(fp);
         return;
      }
      buffer2[count] = '\0';
      p1 = buffer2;
      
   }

   /*
    * close the file
    */

    fclose(fp);

    return;
}
Пример #26
0
void
dumpHiveFromFile(
    HANDLE hFile
    )

/*++

Routine Description:

    Takes a list of the registry hives and pages from a file and
    checks to see how many of the pages are in memory.

    The format of the file is as follows
       hivename stablelength volatilelength
       stable page address
       stable page address
            .
            .
            .
       volatile page address
       volatile page address
            .
            .
            .
       hivename stablelength volatilelength
            .
            .
            .


Arguments:

    File - Supplies a file.

Return Value:

    None.

--*/

{
#if 0
    CHAR Hivename[33];
    ULONG StableLength;
    ULONG VolatileLength;
    ULONG Page;
    ULONG NumFields;
    ULONG Garbage;
    ULONG Present;
    ULONG Total;
    ULONG BytesRead;
    BYTE  buf[512]

    while (!feof(File)) {
        NumFields = fscanf(File,"%s %d %d\n",
                            Hivename,
                            &StableLength,
                            &VolatileLength);
        if (NumFields != 3) {
            dprintf("fscanf returned %d\n",NumFields);
            return;
        }

        dprintf("\ndumping hive %s\n",Hivename);
        dprintf("  Stable Length = %lx\n",StableLength);
        Present = 0;
        Total = 0;
        while (StableLength > 0) {
            fscanf(File, "%lx\n",&Page);
            ReadMemory((DWORD)Page,
                        &Garbage,
                        sizeof(ULONG),
                        &BytesRead);
            if (BytesRead > 0) {
                ++Present;
            }
            ++Total;
            StableLength -= HBLOCK_SIZE;
        }
        if (Total > 0) {
            dprintf("  %d/%d stable pages present\n",
                      Present,Total);
        }
        TotalPages += Total;
        TotalPresentPages += Present;

        dprintf("  Volatile Length = %lx\n",VolatileLength);
        Present = 0;
        Total = 0;
        while (VolatileLength > 0) {
            fscanf(File, "%lx\n",&Page);
            ReadMemory((DWORD)Page,
                        &Garbage,
                        sizeof(ULONG),
                        &BytesRead);
            if (BytesRead > 0) {
                ++Present;
            }
            ++Total;
            VolatileLength -= HBLOCK_SIZE;
        }
        if (Total > 0) {
            dprintf("  %d/%d volatile pages present\n",
                      Present,Total);
        }

        TotalPages += Total;
        TotalPresentPages += Present;
    }
#endif
}
Пример #27
0
GAE_File_t* GAE_File_read(GAE_File_t* file, const unsigned long amount, GAE_FILE_READ_STATUS* status) {
	GAE_PlatformFile_t* platform = (GAE_PlatformFile_t*)file->platformFile;
	unsigned long readAmount = amount;
	long read = 0;

	if (file->openMode != GAE_FILE_OPEN_READ) {
		if (0 != status)
			*status = GAE_FILE_READ_ERROR;
		return file;
	}
	
	if (file->fileStatus != GAE_FILE_OPEN) {
		if (0 != status)
			*status = GAE_FILE_READ_ERROR;
		return file;
	}
	
	if (0 == platform->file) {
		if (0 != status)
			*status = GAE_FILE_READ_ERROR;
		return file;
	}
	
	if (GAE_FALSE == file->owned) {
		if (0 != status)
			*status = GAE_FILE_READ_ERROR;
		return file;
	}
	
	if (readAmount < file->fileSize)
		file->bufferSize = readAmount;
	else {
		file->bufferSize = file->fileSize;
		readAmount = file->fileSize;
	}
	
	if (0 != file->buffer)
		free(file->buffer);
	
	file->buffer = (GAE_BYTE*)malloc(file->bufferSize + 1U);
	memset(file->buffer, '\0', file->bufferSize);
	if (0 == file->buffer) {
		if (0 != status)
			*status = GAE_FILE_READ_ERROR;
		return file;
	}
	
	file->owned = GAE_TRUE;
	read = fread(file->buffer, 1, file->bufferSize, platform->file);
	file->readPosition += (unsigned long)read;
	
	if ((unsigned long)(read) == readAmount) {
		if (0 != status)
			*status = GAE_FILE_READ_OK;
		return file;
	}
	else if (feof(platform->file)) {
		if (0 != status)
			*status = GAE_FILE_READ_EOF;
		return file;
	}
	else {
		if (0 != status)
			*status = GAE_FILE_READ_ERROR;
		return file;
	}
}
Пример #28
0
static char *image_int64_descpt(const char *image_path)
{
    FILE *fp = fopen(image_path, "rb");
    assert(fp);
    
    char *result = NULL;
    int8_t buf[kReadByteBlock];

	//contro iavr
	int32_t bytes_read = 0;
    int32_t times_write = 1; //count from 1(data length)
    int8_t new_line = 0;

    long filelen = length_file(fp);
       
    result = string_append(NULL, kInt64BeginDesc);
    
    char len_buf[128];  sprintf(len_buf, kTab""kTab"0x%016llx, ", (int64_t)filelen);
    char *temp = string_append(result, len_buf);
    
    free(result); result = temp;
    
    while ( ! feof(fp) )
    {        
        int32_t i = 0;
        
		size_t read_count = 0;
        size_t int64_count = 0;
        int64_t *pbuf = NULL;
        
		memset(buf, 0, kReadByteBlock);
		
		read_count = fread(buf, 1, kReadByteBlock, fp);
		int64_count = (read_count%8) ? (read_count/8 + 1) : (read_count/8);
		pbuf = (int64_t*)buf;
        
		for(i=0; i<int64_count; i++)
        {
            char bitDesc[128];
                        
            if(bytes_read + 8 < filelen)
            {                
                if((++times_write % 3) == 0)
                {
                    sprintf(bitDesc, "0x%016llx,\n", *(pbuf+i));
                    new_line = 1;
                }
                else
                {
                    sprintf(bitDesc, "%s0x%016llx, ", new_line ? kTab""kTab : "",  *(pbuf+i));

					if(new_line) new_line = 0;
                }
            }
            else
            {
                sprintf(bitDesc, "%s0x%016llx", new_line ? kTab""kTab : "", *(pbuf+i));
				if(new_line) new_line = 0;
            }
            
            char *tmp = string_append(result, bitDesc);
            free(result);
            result = tmp;

			bytes_read += 8;
        }
    }
    
    char *new_result = string_append(result, kInt64EndDesc);
    free(result);
    result = new_result;
    
    fclose(fp);
    
    return result;
}
Пример #29
0
static int read_string_inner(UI *ui, UI_STRING *uis, int echo, int strip_nl)
	{
	static int ps;
	int ok;
	char result[BUFSIZ];
	int maxsize = BUFSIZ-1;
#if !defined(OPENSSL_SYS_WIN16) && !defined(OPENSSL_SYS_WINCE)
	char *p;

	intr_signal=0;
	ok=0;
	ps=0;

	pushsig();
	ps=1;

	if (!echo && !noecho_console(ui))
		goto error;
	ps=2;

	result[0]='\0';
#ifdef OPENSSL_SYS_MSDOS
	if (!echo)
		{
		noecho_fgets(result,maxsize,tty_in);
		p=result; /* FIXME: noecho_fgets doesn't return errors */
		}
	else
		p=fgets(result,maxsize,tty_in);
#else
	p=fgets(result,maxsize,tty_in);
#endif
	if(!p)
		goto error;
	if (feof(tty_in)) goto error;
	if (ferror(tty_in)) goto error;
	if ((p=(char *)strchr(result,'\n')) != NULL)
		{
		if (strip_nl)
			*p='\0';
		}
	else
		if (!read_till_nl(tty_in))
			goto error;
	if (UI_set_result(ui, uis, result) >= 0)
		ok=1;

error:
	if (intr_signal == SIGINT)
		ok=-1;
	if (!echo) fprintf(tty_out,"\n");
	if (ps >= 2 && !echo && !echo_console(ui))
		ok=0;

	if (ps >= 1)
		popsig();
#else
	ok=1;
#endif

	OPENSSL_cleanse(result,BUFSIZ);
	return ok;
	}
Пример #30
0
/*
 * main - The shell's main routine 
 */
int main(int argc, char **argv) 
{
    char c;
    char cmdline[MAXLINE];    /* cmdline for fgets */
    int emit_prompt = 1; /* emit prompt (default) */

    /* Redirect stderr to stdout (so that driver will get all output
     * on the pipe connected to stdout) */
    dup2(1, 2);

    /* Parse the command line */
    while ((c = getopt(argc, argv, "hvp")) != EOF) {
        switch (c) {
        case 'h':             /* print help message */
            usage();
            break;
        case 'v':             /* emit additional diagnostic info */
            verbose = 1;
            break;
        case 'p':             /* don't print a prompt */
            emit_prompt = 0;  /* handy for automatic testing */
            break;
        default:
            usage();
        }
    }

    /* Install the signal handlers */

    /* These are the ones you will need to implement */
    Signal(SIGINT,  sigint_handler);   /* ctrl-c */
    Signal(SIGTSTP, sigtstp_handler);  /* ctrl-z */
    Signal(SIGCHLD, sigchld_handler);  /* Terminated or stopped child */
    Signal(SIGTTIN, SIG_IGN);
    Signal(SIGTTOU, SIG_IGN);

    /* This one provides a clean way to kill the shell */
    Signal(SIGQUIT, sigquit_handler); 

    /* Initialize the job list */
    initjobs(job_list);


    /* Execute the shell's read/eval loop */
    while (1) {

        if (emit_prompt) {
            printf("%s", prompt);
            fflush(stdout);
        }
        if ((fgets(cmdline, MAXLINE, stdin) == NULL) && ferror(stdin))
            app_error("fgets error");
        if (feof(stdin)) { 
            /* End of file (ctrl-d) */
            printf ("\n");
            fflush(stdout);
            fflush(stderr);
            exit(0);
        }
        
        /* Remove the trailing newline */
        cmdline[strlen(cmdline)-1] = '\0';
        
        /* Evaluate the command line */
		//fprintf(stderr, "got cmd:%s\n", cmdline);
        eval(cmdline);
        
        fflush(stdout);
        fflush(stdout);
    } 
    
    exit(0); /* control never reaches here */
}