Beispiel #1
0
DumpReturn PlayerDumpReader::LoadDump(const std::string& file, uint32 account, std::string name, uint32 guid)
{
    // 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_AutoPtr result = QueryResult_AutoPtr(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 < objmgr.m_hiCharGuid)
    {
        result = CharacterDatabase.PQuery("SELECT 1 FROM characters WHERE guid = '%d'", guid);
        if (result)
            guid = objmgr.m_hiCharGuid;                     // use first free if exists
        else incHighest = false;
    }
    else
        guid = objmgr.m_hiCharGuid;

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

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

    // name encoded or empty

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

    std::map<uint32,uint32> items;
    std::map<uint32,uint32> mails;
    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;

        // 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;
        uint8 i;
        for (i = 0; i < DUMP_TABLE_COUNT; ++i)
        {
            if (tn == dumpTables[i].name)
            {
                type = dumpTables[i].type;
                break;
            }
        }

        if (i == DUMP_TABLE_COUNT)
        {
            sLog.outError("LoadPlayerDump: Unknown table: '%s'!", tn.c_str());
            ROLLBACK(DUMP_FILE_BROKEN);
        }

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

            case DTT_CHARACTER:                             // character t.
            {
                if (!changenth(line, 1, newguid))
                    ROLLBACK(DUMP_FILE_BROKEN);

                // guid, data field:guid, items
                if (!changenth(line, 2, chraccount))
                    ROLLBACK(DUMP_FILE_BROKEN);
                std::string vals = getnth(line, 3);
                if (!changetoknth(vals, OBJECT_FIELD_GUID+1, newguid))
                    ROLLBACK(DUMP_FILE_BROKEN);
                for (uint16 field = PLAYER_FIELD_INV_SLOT_HEAD; field < PLAYER_FARSIGHT; field++)
                    if (!changetokGuid(vals, field+1, items, objmgr.m_hiItemGuid, true))
                        ROLLBACK(DUMP_FILE_BROKEN);
                if (!changenth(line, 3, vals.c_str()))
                    ROLLBACK(DUMP_FILE_BROKEN);
                if (name == "")
                {
                    // check if the original name already exists
                    name = getnth(line, 4);
                    CharacterDatabase.escape_string(name);

                    result = CharacterDatabase.PQuery("SELECT 1 FROM characters WHERE name = '%s'", name.c_str());
                    if (result)
                    {
                        if (!changenth(line, 30, "1"))       // rename on login: `at_login` field 30 in raw field list
                            ROLLBACK(DUMP_FILE_BROKEN);
                    }
                }
                else if (!changenth(line, 4, name.c_str()))
                    ROLLBACK(DUMP_FILE_BROKEN);

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

                // bag, item
                if (!changeGuid(line, 2, items, objmgr.m_hiItemGuid, true))
                    ROLLBACK(DUMP_FILE_BROKEN);
                if (!changeGuid(line, 4, items, objmgr.m_hiItemGuid))
                    ROLLBACK(DUMP_FILE_BROKEN);
                break;
            }
            case DTT_ITEM:                                  // item_instance t.
            {
                // item, owner, data field:item, owner guid
                if (!changeGuid(line, 1, items, objmgr.m_hiItemGuid))
                    ROLLBACK(DUMP_FILE_BROKEN);
                if (!changenth(line, 2, newguid))
                    ROLLBACK(DUMP_FILE_BROKEN);
                std::string vals = getnth(line,3);
                if (!changetokGuid(vals, OBJECT_FIELD_GUID+1, items, objmgr.m_hiItemGuid))
                    ROLLBACK(DUMP_FILE_BROKEN);
                if (!changetoknth(vals, ITEM_FIELD_OWNER+1, newguid))
                    ROLLBACK(DUMP_FILE_BROKEN);
                if (!changenth(line, 3, vals.c_str()))
                    ROLLBACK(DUMP_FILE_BROKEN);
                break;
            }
            case DTT_ITEM_GIFT:                             // character_gift
            {
                // guid,item_guid,
                if (!changenth(line, 1, newguid))
                    ROLLBACK(DUMP_FILE_BROKEN);
                if (!changeGuid(line, 2, items, objmgr.m_hiItemGuid))
                    ROLLBACK(DUMP_FILE_BROKEN);
                break;
            }
            case DTT_PET:                                   // character_pet t
            {
                //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", objmgr.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)));
                }

                // item, entry, owner, ...
                if (!changenth(line, 1, newpetid))
                    ROLLBACK(DUMP_FILE_BROKEN);
                if (!changenth(line, 3, newguid))
                    ROLLBACK(DUMP_FILE_BROKEN);

                break;
            }
            case DTT_PET_TABLE:                             // pet_aura, pet_spell, pet_spell_cooldown t
            {
                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))
                    ROLLBACK(DUMP_FILE_BROKEN);

                break;
            }
            case DTT_MAIL:                                  // mail
            {
                // id,messageType,stationery,sender,receiver
                if (!changeGuid(line, 1, mails, objmgr.m_mailid))
                    ROLLBACK(DUMP_FILE_BROKEN);
                if (!changenth(line, 5, newguid))
                    ROLLBACK(DUMP_FILE_BROKEN);
                break;
            }
            case DTT_MAIL_ITEM:                             // mail_items
            {
                // mail_id,item_guid,item_template,receiver
                if (!changeGuid(line, 1, mails, objmgr.m_mailid))
                    ROLLBACK(DUMP_FILE_BROKEN);
                if (!changeGuid(line, 2, items, objmgr.m_hiItemGuid))
                    ROLLBACK(DUMP_FILE_BROKEN);
                if (!changenth(line, 4, newguid))
                    ROLLBACK(DUMP_FILE_BROKEN);
                break;
            }
            default:
                sLog.outError("Unknown dump table type: %u",type);
                break;
        }

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

    CharacterDatabase.CommitTransaction();

    objmgr.m_hiItemGuid += items.size();
    objmgr.m_mailid     += mails.size();

    if (incHighest)
        ++objmgr.m_hiCharGuid;

    fclose(fin);

    return DUMP_SUCCESS;
}
Beispiel #2
0
int parse_map(FILE *rules, Ship *ships, Grid *board, 
        unsigned int *numShips)
{
    char line[BUFF_LEN];	/* Line buffers */
    int i;
    int maths;				/* Temporary integer for performing math */

    /* All lines should be a two positive integers followed by a char */
    /* Also, we expect there to be the same number of ships described
     * here as defined by the second line of the rules file and saved
     * to numShips */ 
    /* After parsing for errors, we then check for overlap and out of bounds
     * on a line by line basis */
    /* Note: We can assume only one error possible per line */
    for(i = 0; i < *numShips; i++) {
        /* Check if we reached EOF prematurely */
        if(fgets(line, BUFF_LEN, rules) == NULL) {
            return map_invalid();
        }
        /* Check the length of the line */
        if(!check_length(line)) {
            return map_invalid();
        }
        if(sscanf(line, "%u %u %c", &ships[i].xPos, &ships[i].yPos, 
                    &ships[i].direction) != 3) {
            return map_invalid();
        }

        /* ship.direction must be 'N', 'S', 'E', or 'W' */
        if(ships[i].direction != 'N' && ships[i].direction != 'S' && 
                ships[i].direction != 'E' && ships[i].direction != 'W') {
            return map_invalid();
        }

        /* Out of Bounds check */
        /* First check anchor point */
        if(ships[i].xPos > board->width ||
                ships[i].xPos > board->height) {
            return map_oob(); 
        }
        /* Next, check no section of ship is out of bounds */
        switch(ships[i].direction) {
            case 'N':
                maths = ships[i].yPos - (ships[i].length - 1);
                if(maths < 0) {
                    return map_oob();
                }
                break;
            case 'S':
                maths = ships[i].yPos + (ships[i].length - 1);
                if(maths >=	board->height) {
                    return map_oob();
                }
                break;
            case 'E':
                maths = ships[i].xPos + (ships[i].length - 1);
                if(maths >=	board->width) {
                    return map_oob();
                }
                break;
            case 'W':
                maths = ships[i].xPos - (ships[i].length - 1);
                if(maths < 0) {
                    return map_oob();
                }
                break;
            default:
                return map_invalid();
        }

    }
    return 0;
}
Beispiel #3
0
int load_files(char *argv[], int argc, int have_flags) {

  struct label *l;
  int st = STATE_NONE, i, x, line, bank, slot, base, bank_defined, slot_defined, base_defined, n;
  char tmp[1024], ou[1024];
  FILE *fop;

  if (no_std_libraries == OFF) {
    char* stdlibs[] = {
#define LIBDIR PREFIX "/lib"
      LIBDIR "/crt0_snes.obj",
      LIBDIR "/libm.obj",
      LIBDIR "/libtcc.obj",
      LIBDIR "/libc.obj",
      NULL
    };
    char** sl;
    for (sl = stdlibs; *sl; sl++) {
      if (load_file(*sl, STATE_OBJECT, 0, 0, 0, OFF) == FAILED) return FAILED;
    }
  }
  if (object_file_parameters == ON) {
    for (i = (have_flags ? 2 : 1); i < argc - 1 ; i++) {
      if (load_file(argv[i], STATE_OBJECT, 0, 0, 0, OFF) == FAILED) return FAILED;
    }
  }
  else {
    fop = fopen(argv[argc - 2], "rb");
    if (fop == NULL) {
      fprintf(stderr, "LOAD_FILES: Could not open file \"%s\".\n", argv[argc - 2]);
      return FAILED;
    }

    line = 0;
    while (fgets(tmp, 255, fop) != NULL) {
      line++;
      x = 0;

      if (tmp[0] == ';' || tmp[0] == '*' || tmp[0] == '#' || tmp[0] == 0x0D || tmp[0] == 0x0A)
        continue;

      /* remove garbage from the end */
      for (i = 0; !(tmp[i] == 0x0D || tmp[i] == 0x0A); i++);
      tmp[i] = 0;

      /* empty line check */
      if (get_next_token(tmp, ou, &x) == FAILED)
        continue;

      /* first checks */
      if (ou[0] == '[') {
        if (strcmp("[objects]", ou) == 0) {
                                  st = STATE_OBJECT;
                                  continue;
        }
        else if (strcmp("[libraries]", ou) == 0) {
                                  st = STATE_LIBRARY;
                                  continue;
        }
        else if (strcmp("[header]", ou) == 0) {
                                  st = STATE_HEADER;
                                  continue;
        }
        else if (strcmp("[footer]", ou) == 0) {
                                  st = STATE_FOOTER;
                                  continue;
        }
        else if (strcmp("[definitions]", ou) == 0) {
                                  st = STATE_DEFINITION;
                                  continue;
        }
        else {
                                  fprintf(stderr, "%s:%d LOAD_FILES: Unknown group \"%s\".\n", argv[argc - 2], line, ou);
                                  fclose(fop);
                                  return FAILED;
        }
      }

      if (st == STATE_NONE) {
        fprintf(stderr, "%s:%d: LOAD_FILES: Before file \"%s\" can be loaded you must define a group for it.\n", argv[argc - 2], line, ou);
        fclose(fop);
        return FAILED;
      }

      bank_defined = OFF;
      slot_defined = OFF;
      base_defined = OFF;
      bank = 0;
      slot = 0;
      base = 0;

      /* definition loading? */
      if (st == STATE_DEFINITION) {
        l = malloc(sizeof(struct label));
        if (l == NULL) {
                                  fprintf(stderr, "LOAD_FILES: Out of memory.\n");
                                  return FAILED;
        }
        strcpy(l->name, ou);
        l->status = LABEL_STATUS_DEFINE;
        l->bank = 0;
        l->slot = 0;
        l->base = 0;

        if (get_next_number(&tmp[x], &n, &x) == FAILED) {
                                  fprintf(stderr, "%s:%d: LOAD_FILES: Error in DEFINITION value.\n", argv[argc - 2], line);
                                  fclose(fop);
                                  return FAILED;
        }

        l->address = n;
        add_label(l);
        continue;
      }
      /* header loading? */
      else if (st == STATE_HEADER) {
        if (file_header != NULL) {
                                  fprintf(stderr, "%s:%d: LOAD_FILES: There can be only one header file.\n", argv[argc - 2], line);
                                  fclose(fop);
                                  return FAILED;
        }

        if (load_file_data(ou, &file_header, &file_header_size) == FAILED) {
                                  fclose(fop);
                                  return FAILED;
        }
        if (get_next_token(&tmp[x], ou, &x) == FAILED)
                                  continue;

        fprintf(stderr, "%s:%d: LOAD_FILES: Syntax error.\n", argv[argc - 2], line);
        fclose(fop);
        return FAILED;
      }
      /* footer loading? */
      else if (st == STATE_FOOTER) {
        if (file_footer != NULL) {
                                  fprintf(stderr, "%s:%d: LOAD_FILES: There can be only one footer file.\n", argv[argc - 2], line);
                                  fclose(fop);
                                  return FAILED;
        }

        if (load_file_data(ou, &file_footer, &file_footer_size) == FAILED) {
                                  fclose(fop);
                                  return FAILED;
        }
        if (get_next_token(&tmp[x], ou, &x) == FAILED)
                                  continue;

        fprintf(stderr, "%s:%d: LOAD_FILES: Syntax error.\n", argv[argc - 2], line);
        fclose(fop);
        return FAILED;
      }
      /* library loading? */
      else if (st == STATE_LIBRARY) {
        i = SUCCEEDED;
        while (i == SUCCEEDED) {
                                  if (strcmp(ou, "bank") == 0 || strcmp(ou, "BANK") == 0) {
                                          if (bank_defined == ON) {
                                                  fprintf(stderr, "%s:%d: LOAD_FILES: BANK defined for the second time for a library file.\n", argv[argc - 2], line);
                                                  fclose(fop);
                                                  return FAILED;
                                          }
                                          bank_defined = ON;

                                          if (get_next_number(&tmp[x], &bank, &x) == FAILED) {
                                                  fprintf(stderr, "%s:%d: LOAD_FILES: Error in BANK number.\n", argv[argc - 2], line);
                                                  fclose(fop);
                                                  return FAILED;
                                          }
                                  }
                                  else if (strcmp(ou, "slot") == 0 || strcmp(ou, "SLOT") == 0) {
                                          if (slot_defined == ON) {
                                                  fprintf(stderr, "%s:%d: LOAD_FILES: SLOT defined for the second time for a library file.\n", argv[argc - 2], line);
                                                  fclose(fop);
                                                  return FAILED;
                                          }
                                          slot_defined = ON;

                                          if (get_next_number(&tmp[x], &slot, &x) == FAILED) {
                                                  fprintf(stderr, "%s:%d: LOAD_FILES: Error in SLOT number.\n", argv[argc - 2], line);
                                                  fclose(fop);
                                                  return FAILED;
                                          }
                                  }
                                  else if (strcmp(ou, "base") == 0 || strcmp(ou, "BASE") == 0) {
                                          if (base_defined == ON) {
                                                  fprintf(stderr, "%s:%d: LOAD_FILES: BASE defined for the second time for a library file.\n", argv[argc - 2], line);
                                                  fclose(fop);
                                                  return FAILED;
                                          }
                                          base_defined = ON;

                                          if (get_next_number(&tmp[x], &base, &x) == FAILED) {
                                                  fprintf(stderr, "%s:%d: LOAD_FILES: Error in BASE number.\n", argv[argc - 2], line);
                                                  fclose(fop);
                                                  return FAILED;
                                          }
                                  }
                                  else
                                          break;

                                  i = get_next_token(&tmp[x], ou, &x);
        }

        if (i == FAILED) {
                                  fprintf(stderr, "%s:%d: LOAD_FILES: No library to load.\n", argv[argc - 2], line);
                                  fclose(fop);
                                  return FAILED;
        }
        if (slot_defined == OFF) {
                                  fprintf(stderr, "%s:%d: LOAD_FILES: Library file requires a SLOT.\n", argv[argc - 2], line);
                                  fclose(fop);
                                  return FAILED;
        }
        if (bank_defined == OFF) {
                                  fprintf(stderr, "%s:%d: LOAD_FILES: Library file requires a BANK.\n", argv[argc - 2], line);
                                  fclose(fop);
                                  return FAILED;
        }

        if (load_file(ou, STATE_LIBRARY, bank, slot, base, base_defined) == FAILED) {
                                  fclose(fop);
                                  return FAILED;
        }

        if (get_next_token(&tmp[x], ou, &x) == SUCCEEDED) {
                                  fprintf(stderr, "%s:%d: LOAD_FILES: Syntax error.\n", argv[argc - 2], line);
                                  fclose(fop);
                                  return FAILED;
        }

        continue;
      }
      /* object file loading */
      else if (load_file(ou, STATE_OBJECT, 0, 0, 0, OFF) == FAILED) {
        fclose(fop);
        return FAILED;
      }
      if (get_next_token(&tmp[x], ou, &x) == FAILED)
        continue;

      fprintf(stderr, "%s:%d: LOAD_FILES: Syntax error.\n", argv[argc - 2], line);
      fclose(fop);
      return FAILED;
    }

    fclose(fop);
  }

  return SUCCEEDED;
}
Beispiel #4
0
int I_PickIWad (WadStuff *wads, int numwads, bool showwin, int defaultiwad)
{
	int i;

	if (!showwin)
	{
		return defaultiwad;
	}

#if !defined(__APPLE__)
	const char *str;
	if((str=getenv("KDE_FULL_SESSION")) && strcmp(str, "true") == 0)
	{
		FString cmd("kdialog --title \""GAMESIG" "DOTVERSIONSTR": Select an IWAD to use\""
		            " --menu \"ZDoom found more than one IWAD\n"
		            "Select from the list below to determine which one to use:\"");

		for(i = 0; i < numwads; ++i)
		{
			const char *filepart = strrchr(wads[i].Path, '/');
			if(filepart == NULL)
				filepart = wads[i].Path;
			else
				filepart++;
			// Menu entries are specified in "tag" "item" pairs, where when a
			// particular item is selected (and the Okay button clicked), its
			// corresponding tag is printed to stdout for identification.
			cmd.AppendFormat(" \"%d\" \"%s (%s)\"", i, wads[i].Name.GetChars(), filepart);
		}

		if(defaultiwad >= 0 && defaultiwad < numwads)
		{
			const char *filepart = strrchr(wads[defaultiwad].Path, '/');
			if(filepart == NULL)
				filepart = wads[defaultiwad].Path;
			else
				filepart++;
			cmd.AppendFormat(" --default \"%s (%s)\"", wads[defaultiwad].Name.GetChars(), filepart);
		}

		FILE *f = popen(cmd, "r");
		if(f != NULL)
		{
			char gotstr[16];

			if(fgets(gotstr, sizeof(gotstr), f) == NULL ||
			   sscanf(gotstr, "%d", &i) != 1)
				i = -1;

			// Exit status = 1 means the selection was canceled (either by
			// Cancel/Esc or the X button), not that there was an error running
			// the program. In that case, nothing was printed so fgets will
			// have failed. Other values can indicate an error running the app,
			// so fall back to whatever else can be used.
			int status = pclose(f);
			if(WIFEXITED(status) && (WEXITSTATUS(status) == 0 || WEXITSTATUS(status) == 1))
				return i;
		}
	}
#endif
#ifndef NO_GTK
	if (GtkAvailable)
	{
		return I_PickIWad_Gtk (wads, numwads, showwin, defaultiwad);
	}
#elif defined(__APPLE__)
	return I_PickIWad_Cocoa (wads, numwads, showwin, defaultiwad);
#endif
	
	printf ("Please select a game wad (or 0 to exit):\n");
	for (i = 0; i < numwads; ++i)
	{
		const char *filepart = strrchr (wads[i].Path, '/');
		if (filepart == NULL)
			filepart = wads[i].Path;
		else
			filepart++;
		printf ("%d. %s (%s)\n", i+1, wads[i].Name.GetChars(), filepart);
	}
	printf ("Which one? ");
	scanf ("%d", &i);
	if (i > numwads)
		return -1;
	return i-1;
}
Beispiel #5
0
DumpReturn PlayerDumpReader::LoadDump(const std::string& file, uint32 account,
                                      std::string name, uint32 guid) {
    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 = QueryResult(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_hiCharGuid)
    {
        result = CharacterDatabase.PQuery("SELECT 1 FROM characters WHERE guid = '%d'", guid);
        if (result)
            guid = sObjectMgr->m_hiCharGuid; // use first free if exists
        else incHighest = false;
    }
    else
        guid = sObjectMgr->m_hiCharGuid;

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

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

    // name encoded or empty

    snprintf(newguid, 20, "%d", guid);
    snprintf(chraccount, 20, "%d", account);
    snprintf(newpetid, 20, "%d", sObjectMgr->GeneratePetNumber());
    snprintf(lastpetid, 20, "%s", "");

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

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

    SQLTransaction trans = 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 logfile-side dump start notice, the important notes and dump end notices
        if ((line.substr(nw_pos, 16) == "== START DUMP ==") ||
                (line.substr(nw_pos, 15) == "IMPORTANT NOTE:") ||
                (line.substr(nw_pos, 14) == "== END DUMP =="))
            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 = DumpTableType(0);
        uint8 i;
        for (i = 0; i < DUMP_TABLE_COUNT; ++i)
        {
            if (tn == dumpTables[i].name)
            {
                type = dumpTables[i].type;
                break;
            }
        }

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

        // change the data to server values
        switch(type)
        {
        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);
                CharacterDatabase.EscapeString(name);

                result = CharacterDatabase.PQuery("SELECT 1 FROM characters WHERE name = '%s'", name.c_str());
                if (result)
                {
                    if (!changenth(line, 37, "1")) // characters.at_login set to "rename on login"
                        ROLLBACK(DUMP_FILE_BROKEN);
                }
            }
            else if (!changenth(line, 3, name.c_str())) // characters.name
                ROLLBACK(DUMP_FILE_BROKEN);

            const char null[5] = "NULL";
            if (!changenth(line, 68, null))// characters.deleteInfos_Account
                ROLLBACK(DUMP_FILE_BROKEN);
            if (!changenth(line, 69, null))// characters.deleteInfos_Name
                ROLLBACK(DUMP_FILE_BROKEN);
            if (!changenth(line, 70, null))// characters.deleteDate
                ROLLBACK(DUMP_FILE_BROKEN);
            break;
        }
        case DTT_CHAR_TABLE:
        {
            if (!changenth(line, 1, newguid)) // character_*.guid update
                ROLLBACK(DUMP_FILE_BROKEN);
            break;
        }
        case DTT_EQSET_TABLE:
        {
            if (!changenth(line, 1, newguid))
                ROLLBACK(DUMP_FILE_BROKEN); // character_equipmentsets.guid

            char newSetGuid[24];
            snprintf(newSetGuid, 24, UI64FMTD, sObjectMgr->GenerateEquipmentSetGuid());
            if (!changenth(line, 2, newSetGuid))
                ROLLBACK(DUMP_FILE_BROKEN);// character_equipmentsets.setguid
            break;
        }
        case DTT_INVENTORY:
        {
            if (!changenth(line, 1, newguid)) // character_inventory.guid update
                ROLLBACK(DUMP_FILE_BROKEN);

            if (!changeGuid(line, 2, items, sObjectMgr->m_hiItemGuid, true))
                ROLLBACK(DUMP_FILE_BROKEN);// character_inventory.bag update
            if (!changeGuid(line, 4, items, sObjectMgr->m_hiItemGuid))
                ROLLBACK(DUMP_FILE_BROKEN);// character_inventory.item update
            break;
        }
        case DTT_MAIL: // mail
        {
            if (!changeGuid(line, 1, mails, sObjectMgr->m_mailid))
                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_mailid))
                ROLLBACK(DUMP_FILE_BROKEN); // mail_items.id
            if (!changeGuid(line, 2, items, sObjectMgr->m_hiItemGuid))
                ROLLBACK(DUMP_FILE_BROKEN);// mail_items.item_guid
            if (!changenth(line, 3, newguid))// mail_items.receiver
                ROLLBACK(DUMP_FILE_BROKEN);
            break;
        }
        case DTT_ITEM:
        {
            // item, owner, data field:item, owner guid
            if (!changeGuid(line, 1, items, sObjectMgr->m_hiItemGuid))
                ROLLBACK(DUMP_FILE_BROKEN);// item_instance.guid update
            if (!changenth(line, 3, newguid))// item_instance.owner_guid 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_hiItemGuid))
                ROLLBACK(DUMP_FILE_BROKEN);// character_gifts.item_guid update
            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 (*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))
                ROLLBACK(DUMP_FILE_BROKEN);

            break;
        }
        default:
            sLog->outError("Unknown dump table type: %u", type);
            break;
        }

        fixNULLfields(line);

        trans->Append(line.c_str());
    }

    CharacterDatabase.CommitTransaction(trans);

    sObjectMgr->m_hiItemGuid += items.size();
    sObjectMgr->m_mailid += mails.size();

    if (incHighest)
        ++sObjectMgr->m_hiCharGuid;

    fclose(fin);

    return DUMP_SUCCESS;
}
Beispiel #6
0
int start_stunnel(int stunnel_port, int x11vnc_port, int hport, int x11vnc_hport) {
#ifdef SSLCMDS
	char extra[] = ":/usr/sbin:/usr/local/sbin:/dist/sbin";
	char *path, *p, *exe;
	char *stunnel_path = NULL;
	struct stat verify_buf;
	struct stat crl_buf;
	int status, tmp_pem = 0;

	if (stunnel_pid) {
		stop_stunnel();
	}
	stunnel_pid = 0;

	path = getenv("PATH");
	if (! path) {
		path = strdup(extra+1);
	} else {
		char *pt = path;
		path = (char *) malloc(strlen(path)+strlen(extra)+1);
		if (! path) {
			return 0;
		}
		strcpy(path, pt);
		strcat(path, extra);
	}

	exe = (char *) malloc(strlen(path) + 1 + strlen("stunnel4") + 1);

	p = strtok(path, ":");

	exe[0] = '\0';

	while (p) {
		struct stat sbuf;

		sprintf(exe, "%s/%s", p, "stunnel4");
		if (! stunnel_path && stat(exe, &sbuf) == 0) {
			if (! S_ISDIR(sbuf.st_mode)) {
				stunnel_path = exe;
				break;
			}
		}

		sprintf(exe, "%s/%s", p, "stunnel");
		if (! stunnel_path && stat(exe, &sbuf) == 0) {
			if (! S_ISDIR(sbuf.st_mode)) {
				stunnel_path = exe;
				break;
			}
		}

		p = strtok(NULL, ":");
	}
	if (path) {
		free(path);
	}

	if (getenv("STUNNEL_PROG")) {
		free(exe);
		exe = strdup(getenv("STUNNEL_PROG"));
		stunnel_path = exe;
	}

	if (! stunnel_path) {
		free(exe);
		return 0;
	}
	if (stunnel_path[0] == '\0') {
		free(exe);
		return 0;
	}

	/* stunnel */
	if (no_external_cmds || !cmd_ok("stunnel")) {
		rfbLogEnable(1);
		rfbLog("start_stunnel: cannot run external commands in -nocmds mode:\n");
		rfbLog("   \"%s\"\n", stunnel_path);
		rfbLog("   exiting.\n");
		clean_up_exit(1);
	}

	if (! quiet) {
		rfbLog("\n");
		rfbLog("starting ssl tunnel: %s  %d -> %d\n", stunnel_path,
		    stunnel_port, x11vnc_port);
	}

	if (stunnel_pem && strstr(stunnel_pem, "SAVE") == stunnel_pem) {
		stunnel_pem = get_saved_pem(stunnel_pem, 1);
		if (! stunnel_pem) {
			rfbLog("start_stunnel: could not create or open"
			    " saved PEM.\n");	
			clean_up_exit(1);
		}
	} else if (!stunnel_pem) {
		stunnel_pem = create_tmp_pem(NULL, 0);
		if (! stunnel_pem) {
			rfbLog("start_stunnel: could not create temporary,"
			    " self-signed PEM.\n");	
			clean_up_exit(1);
		}
		tmp_pem = 1;
		if (getenv("X11VNC_SHOW_TMP_PEM")) {
			FILE *in = fopen(stunnel_pem, "r");
			if (in != NULL) {
				char line[128];
				fprintf(stderr, "\n");
				while (fgets(line, 128, in) != NULL) {
					fprintf(stderr, "%s", line);
				}
				fprintf(stderr, "\n");
				fclose(in);
			}
		}
	}

	if (ssl_verify) {
		char *file = get_ssl_verify_file(ssl_verify);
		if (file) {
			ssl_verify = file;
		}
		if (stat(ssl_verify, &verify_buf) != 0) {
			rfbLog("stunnel: %s does not exist.\n", ssl_verify);
			clean_up_exit(1);
		}
	}
	if (ssl_crl) {
		if (stat(ssl_crl, &crl_buf) != 0) {
			rfbLog("stunnel: %s does not exist.\n", ssl_crl);
			clean_up_exit(1);
		}
	}

	stunnel_pid = fork();

	if (stunnel_pid < 0) {
		stunnel_pid = 0;
		free(exe);
		return 0;
	}

	if (stunnel_pid == 0) {
		FILE *in;
		char fd[20];
		int i;
		char *st_if = getenv("STUNNEL_LISTEN");

		if (st_if == NULL) {
			st_if = "";
		} else {
			st_if = (char *) malloc(strlen(st_if) + 2);
			sprintf(st_if, "%s:", getenv("STUNNEL_LISTEN"));
		}


		for (i=3; i<256; i++) {
			close(i);
		}

		if (use_stunnel == 3) {
			char sp[30], xp[30], *a = NULL;
			char *st = stunnel_path;
			char *pm = stunnel_pem;
			char *sv = ssl_verify;

			sprintf(sp, "%d", stunnel_port);
			sprintf(xp, "%d", x11vnc_port);

			if (ssl_verify) {
				if(S_ISDIR(verify_buf.st_mode)) {
					a = "-a";
				} else {
					a = "-A";
				}
			}

			if (ssl_crl) {
				rfbLog("stunnel: stunnel3 does not support CRL. %s\n", ssl_crl);
				clean_up_exit(1);
			}
			
			if (stunnel_pem && ssl_verify) {
				/* XXX double check -v 2 */
				execlp(st, st, "-f", "-d", sp, "-r", xp, "-P",
				    "none", "-p", pm, a, sv, "-v", "2",
				    (char *) NULL);
			} else if (stunnel_pem && !ssl_verify) {
				execlp(st, st, "-f", "-d", sp, "-r", xp, "-P",
				    "none", "-p", pm,
				    (char *) NULL);
			} else if (!stunnel_pem && ssl_verify) {
				execlp(st, st, "-f", "-d", sp, "-r", xp, "-P",
				    "none", a, sv, "-v", "2",
				    (char *) NULL);
			} else {
				execlp(st, st, "-f", "-d", sp, "-r", xp, "-P",
				    "none", (char *) NULL);
			}
			exit(1);
		}

		in = tmpfile();
		if (! in) {
			exit(1);
		}

		fprintf(in, "foreground = yes\n");
		fprintf(in, "pid =\n");
		if (stunnel_pem) {
			fprintf(in, "cert = %s\n", stunnel_pem);
		}
		if (ssl_crl) {
			if(S_ISDIR(crl_buf.st_mode)) {
				fprintf(in, "CRLpath = %s\n", ssl_crl);
			} else {
				fprintf(in, "CRLfile = %s\n", ssl_crl);
			}
		}
		if (ssl_verify) {
			if(S_ISDIR(verify_buf.st_mode)) {
				fprintf(in, "CApath = %s\n", ssl_verify);
			} else {
				fprintf(in, "CAfile = %s\n", ssl_verify);
			}
			fprintf(in, "verify = 2\n");
		}
		fprintf(in, ";debug = 7\n\n");
		fprintf(in, "[x11vnc_stunnel]\n");
		fprintf(in, "accept = %s%d\n", st_if, stunnel_port);
		fprintf(in, "connect = %d\n", x11vnc_port);

		if (hport > 0 && x11vnc_hport > 0) {
			fprintf(in, "\n[x11vnc_http]\n");
			fprintf(in, "accept = %s%d\n", st_if, hport);
			fprintf(in, "connect = %d\n", x11vnc_hport);
		}

		fflush(in);
		rewind(in);

		if (getenv("STUNNEL_DEBUG")) {
			char line[1000];
			fprintf(stderr, "\nstunnel config contents:\n\n");
			while (fgets(line, sizeof(line), in) != NULL) {
				fprintf(stderr, "%s", line);
			}
			fprintf(stderr, "\n");
			rewind(in);
		}
		
		sprintf(fd, "%d", fileno(in));
		execlp(stunnel_path, stunnel_path, "-fd", fd, (char *) NULL);
		exit(1);
	}

	free(exe);
	usleep(750 * 1000);

	waitpid(stunnel_pid, &status, WNOHANG); 

	if (ssl_verify && strstr(ssl_verify, "/sslverify-tmp-load-")) {
		/* temporary file */
		usleep(1000 * 1000);
		unlink(ssl_verify);
	}
	if (tmp_pem) {
		/* temporary cert */
		usleep(1500 * 1000);
		unlink(stunnel_pem);
	}

	if (kill(stunnel_pid, 0) != 0) {
		waitpid(stunnel_pid, &status, WNOHANG); 
		stunnel_pid = 0;
		return 0;
	}

	if (! quiet) {
		rfbLog("stunnel pid is: %d\n", (int) stunnel_pid);
	}

	return 1;
#else
	return 0;
#endif
}
Beispiel #7
0
void AsciiOpenDlg::updateTable(const QString &separator)
{
	tableWidget->setEnabled(false);
	extractSFNamesFrom1stLineCheckBox->setEnabled(false);
	m_headerLine.clear();

	if (m_filename.isEmpty())
	{
		tableWidget->clear();
        return;
	}

    if (separator.length()<1)
    {
        asciiCodeLabel->setText("Enter a valid character!");
        buttonBox->setEnabled(false);
		tableWidget->clear();
		m_invalidColumns = true;
        return;
    }

	//we open the file in ASCII mode
	FILE* pFile = fopen(qPrintable(m_filename),"rt");
	if (!pFile)
	{
		tableWidget->clear();
		m_invalidColumns = true;
        return;
	}

    //buffer
	char line[MAX_ASCII_FILE_LINE_LENGTH];      //last read line

    //we skip first lines (if needed)
	unsigned i;
    for (i=0;i<m_skippedLines;++i)
	{
        if (fgets(line, MAX_ASCII_FILE_LINE_LENGTH, pFile))
		{
			//we keep track of the first line
			if (i==0)
				m_headerLine = QString(line);
		}
		else
		{
			fclose(pFile);
			tableWidget->clear();
			m_invalidColumns = true;
            return;
		}
	}

    //new separator
    m_separator = separator[0];
    asciiCodeLabel->setText(QString("(ASCII code: %1)").arg(m_separator.unicode()));
	//if the old setup has less than 3 columns, we forget it
	if (m_columnsCount<3)
	{
		tableWidget->clear();
		m_columnsCount=0;
	}
    tableWidget->setRowCount(DISPLAYED_LINES+1);    //+1 for first line shifting

	unsigned lineCount = 0;			//number of lines read
	unsigned totalChars = 0;        //total read characters (for stats)
	unsigned columnsCount = 0;		//max columns count per line

	std::vector<bool> valueIsNumber;	//identifies columns with numbers only [mandatory]
	std::vector<bool> valueIsBelowOne;	//identifies columns with values between -1 and 1 only
	std::vector<bool> valueIsInteger;	//identifies columns with integer values only
	std::vector<bool> valueIsBelow255;	//identifies columns with integer values between 0 and 255 only

	while ((lineCount<LINES_READ_FOR_STATS) && fgets(line, MAX_ASCII_FILE_LINE_LENGTH, pFile))
	{
        //we convert char buffer to a QString object
		QString str(line);

        //we recognize "//" as comment
		if (line[0]!='/' || line[1]!='/')
		{
			QStringList parts = str.trimmed().split(m_separator,QString::SkipEmptyParts);
            unsigned partsCount = (unsigned)parts.size();
            if (partsCount>MAX_COLUMNS)
                partsCount=MAX_COLUMNS;

            if (lineCount<DISPLAYED_LINES)
            {
                //do we need to add one or several new columns?
                if (partsCount>columnsCount)
                {
					//we also extend vectors
					for (i=columnsCount;i<partsCount;++i)
					{
						valueIsNumber.push_back(true);
						valueIsBelowOne.push_back(true);
						valueIsBelow255.push_back(true);
						valueIsInteger.push_back(true);
					}

					tableWidget->setColumnCount(partsCount);
                    columnsCount=partsCount;
                }

                //we fill row with extracted parts
                for (i=0;i<partsCount;++i)
                {
                    QTableWidgetItem *newItem = new QTableWidgetItem(parts[i]);

					//test values
					bool isANumber = false;
					double value = parts[i].toDouble(&isANumber);
					if (!isANumber)
					{
						valueIsNumber[i]	= false;
						valueIsBelowOne[i]	= false;
						valueIsInteger[i]	= false;
						valueIsBelow255[i]	= false;
						newItem->setBackground(QBrush(QColor(255,160,160)));
					}
					else
					{
						double intPart, fracPart;
						fracPart = modf(value,&intPart);

						valueIsBelowOne[i]	= valueIsBelowOne[i] && (fabs(value)<=1.0);
						valueIsInteger[i]	= valueIsInteger[i] && (fracPart == 0.0);
						valueIsBelow255[i]	= valueIsBelow255[i] && (valueIsInteger[i] && (intPart >= 0.0 && value<=255.0));
					}

					tableWidget->setItem(lineCount+1, i, newItem); //+1 for first line shifting
                }
            }

            totalChars += (str.size()+1); //+1 for return char at eol

            ++lineCount;
		}
	}

	fclose(pFile);
	pFile=0;

	if (lineCount==0 || columnsCount==0)
	{
		m_averageLineSize = -1.0;
		tableWidget->clear();
		m_invalidColumns = true;
        return;
	}

	//average line size
	m_averageLineSize = double(totalChars)/double(lineCount);

    //we add a type selector for each column
	QStringList propsText;
	for (i=0; i<ASCII_OPEN_DLG_TYPES_NUMBER; i++)
        propsText << QString(ASCII_OPEN_DLG_TYPES_NAMES[i]);

	//remove unnecessary columns
	while (columnsCount<m_columnsCount)
		tableWidget->removeColumn(--m_columnsCount);
	for (i=lineCount+1;i<=DISPLAYED_LINES;++i)
		tableWidget->removeRow(i);

    int columnWidth = (tableWidget->width()*9) / (columnsCount*10);
    columnWidth = std::max(columnWidth,80);

	//Icons
	const QIcon xIcon(QString::fromUtf8(":/CC/Types/images/types/x_coordinate.png"));
	const QIcon yIcon(QString::fromUtf8(":/CC/Types/images/types/y_coordinate.png"));
	const QIcon zIcon(QString::fromUtf8(":/CC/Types/images/types/z_coordinate.png"));
	const QIcon NormIcon(QString::fromUtf8(":/CC/Types/images/types/normal.png"));
	const QIcon RGBIcon(QString::fromUtf8(":/CC/Types/images/types/rgb_color.png"));
	const QIcon GreyIcon(QString::fromUtf8(":/CC/Types/images/types/gray_color.png"));
	const QIcon ScalarIcon(QString::fromUtf8(":/CC/Types/images/types/scalar_field.png"));
	const QIcon PositiveScalarIcon(QString::fromUtf8(":/CC/Types/images/types/positive_scalar_field.png"));

	unsigned assignedXYZ = 0;
	unsigned assignedNorm = 0;
	unsigned assignedRGB = 0;
	for (i=0;i<columnsCount;i++)
	{
		QComboBox* columnHeader = static_cast<QComboBox*>(tableWidget->cellWidget(0,i));
		QComboBox* _columnHeader = columnHeader;
		if (!columnHeader)
		{
			columnHeader = new QComboBox();
			columnHeader->addItems(propsText);
			columnHeader->setMaxVisibleItems(ASCII_OPEN_DLG_TYPES_NUMBER);
			columnHeader->setCurrentIndex(0);
			columnHeader->setItemIcon(ASCII_OPEN_DLG_X,xIcon);
			columnHeader->setItemIcon(ASCII_OPEN_DLG_Y,yIcon);
			columnHeader->setItemIcon(ASCII_OPEN_DLG_Z,zIcon);
			columnHeader->setItemIcon(ASCII_OPEN_DLG_NX,NormIcon);
			columnHeader->setItemIcon(ASCII_OPEN_DLG_NY,NormIcon);
			columnHeader->setItemIcon(ASCII_OPEN_DLG_NZ,NormIcon);
			columnHeader->setItemIcon(ASCII_OPEN_DLG_R,RGBIcon);
			columnHeader->setItemIcon(ASCII_OPEN_DLG_G,RGBIcon);
			columnHeader->setItemIcon(ASCII_OPEN_DLG_B,RGBIcon);
			columnHeader->setItemIcon(ASCII_OPEN_DLG_Grey,GreyIcon);
			columnHeader->setItemIcon(ASCII_OPEN_DLG_Scalar,ScalarIcon);
			columnHeader->setItemIcon(ASCII_OPEN_DLG_Positive_Scalar,PositiveScalarIcon);
			columnHeader->setItemIcon(ASCII_OPEN_DLG_RGB32i,RGBIcon);
			columnHeader->setItemIcon(ASCII_OPEN_DLG_RGB32f,RGBIcon);

			connect(columnHeader, SIGNAL(currentIndexChanged(int)), this, SLOT(columnsTypeHasChanged(int)));
		}

		if (valueIsNumber[i])
		{
			//first time? let's try to assign each column a type
			if ((m_invalidColumns || m_columnsCount==0) && columnsCount>1)
			{
				columnHeader->blockSignals(true);
				//by default, we assume that the first columns are always X,Y and Z
				if (assignedXYZ<3)
				{
					//in rare cases, the first column is an index
					if (assignedXYZ==0 && valueIsInteger[i] && (i+1<columnsCount) && !valueIsInteger[i+1])
					{
						//we skip it
					}
					else
					{
						++assignedXYZ;
						columnHeader->setCurrentIndex(assignedXYZ);
					}
				}
				else
				{
					//looks like RGB?
					if (valueIsBelow255[i] && assignedRGB<3 && (i+2-assignedRGB < columnsCount)
						&& (assignedRGB > 0 || (valueIsBelow255[i+1] && valueIsBelow255[i+2]))) //make sure that next values are also ok!
					{
						columnHeader->setCurrentIndex(ASCII_OPEN_DLG_R+assignedRGB);
						++assignedRGB;
					}
					else if (valueIsBelowOne[i] && assignedNorm<3 && (i+2-assignedNorm < columnsCount)
						&& (assignedNorm > 0 || (valueIsBelowOne[i+1] && valueIsBelowOne[i+2]))) //make sure that next values are also ok!
					{
						columnHeader->setCurrentIndex(ASCII_OPEN_DLG_NX+assignedNorm);
						++assignedNorm;
					}
					else
					{
						//maybe it's a scalar?
						columnHeader->setCurrentIndex(ASCII_OPEN_DLG_Scalar);
					}
				}
				columnHeader->blockSignals(false);
			}
		}

		if (!_columnHeader)
			tableWidget->setCellWidget(0,i,columnHeader);
		tableWidget->setColumnWidth(i,columnWidth);
	}
Beispiel #8
0
/**
 * Load an OBJ model from file -- first pass.
 * This time, read model data and feed buffers.
 */
int
SecondPass (FILE *fp, struct obj_model_t *mdl)
{
  struct obj_vertex_t *pvert = mdl->vertices;
  struct obj_texCoord_t *puvw = mdl->texCoords;
  struct obj_normal_t *pnorm = mdl->normals;
  struct obj_face_t *pface = mdl->faces;
  char buf[128], *pbuf;
  int i;
  int index=0;

  while (!feof (fp))
    {
      /* Read whole line */
      fgets (buf, sizeof (buf), fp);

      switch (buf[0])
	{
	case 'v':
	  {
	    if (buf[1] == ' ')
	      {
		/* Vertex */
		if (sscanf (buf + 2, "%f %f %f %f",
			    &pvert->xyzw[0], &pvert->xyzw[1],
			    &pvert->xyzw[2], &pvert->xyzw[3]) != 4)
		  {
		    if (sscanf (buf + 2, "%f %f %f", &pvert->xyzw[0],
				&pvert->xyzw[1], &pvert->xyzw[2] ) != 3)
		      {
			fprintf (stderr, "Error reading vertex data!\n");
			return 0;
		      }
		    else
		      {
			pvert->xyzw[3] = 1.0;
		      }
		  }

		pvert++;
	      }
	    else if (buf[1] == 't')
	      {
		/* Texture coords. */
		if (sscanf (buf + 2, "%f %f %f", &puvw->uvw[0],
			    &puvw->uvw[1], &puvw->uvw[2]) != 3)
		  {
		    if (sscanf (buf + 2, "%f %f", &puvw->uvw[0],
				&puvw->uvw[1]) != 2)
		      {
			if (sscanf (buf + 2, "%f", &puvw->uvw[0]) != 1)
			  {
			    fprintf (stderr, "Error reading texture coordinates!\n");
			    return 0;
			  }
			else
			  {
			    puvw->uvw[1] = 0.0;
			    puvw->uvw[2] = 0.0;
			  }
		      }
		    else
		      {
			puvw->uvw[2] = 0.0;
		      }
		  }

		puvw++;
	      }
	    else if (buf[1] == 'n')
	      {
		/* Normal vector */
		if (sscanf (buf + 2, "%f %f %f", &pnorm->ijk[0],
			    &pnorm->ijk[1], &pnorm->ijk[2]) != 3)
		  {
		    fprintf (stderr, "Error reading normal vectors!\n");
		    return 0;
		  }

		pnorm++;
	      }

	    break;
	  }
	case 'u':
		{
			//pface->matindex = &pface;//((&mdl->faces) - (&pface));//(sizeof mdl->faces); 
			sscanf(buf, "%*s %s", &pface->mat);
		
			break;
		}
	case 'f':
	  {
	    pbuf = buf;
	    pface->num_elems = 0;

	    /* Count number of vertices for this face */
	    while (*pbuf)
	      {
			if (*pbuf == ' ')
			if(isalnum(*(pbuf+1))) {
				pface->num_elems++;
			}

			pbuf++;
	      }

	    /* Select primitive type */
	    if (pface->num_elems < 3)
	      {
		fprintf (stderr, "Error: a face must have at least 3 vertices!\n");
		return 0;
	      }
	    else if (pface->num_elems == 3)
	      {
		pface->type = GL_TRIANGLES;
	      }
	    else if (pface->num_elems == 4)
	      {
		pface->type = GL_QUADS;
	      }
	    else
	      {
		pface->type = GL_POLYGON;
	      }

	    /* Memory allocation for vertices */
	    pface->vert_indices = (int *)malloc (sizeof (int) * pface->num_elems);

	    if (1/*mdl->has_texCoords*/)
	      pface->uvw_indices = (int *)malloc (sizeof (int) * pface->num_elems);

	    if (1/*mdl->has_normals*/)
	      pface->norm_indices = (int *)malloc (sizeof (int) * pface->num_elems);

	    /* Read face data */
	    pbuf = buf;
	    i = 0;

	    for (i = 0; i < pface->num_elems; ++i)
	      {
		pbuf = strchr (pbuf, ' ');
		pbuf++; /* Skip space */

	//	pface->vert_indices[i]=2;
	//	pface->uvw_indices[i]=2;
	//	pface->norm_indices[i]=2;

		/* Try reading vertices */
		if (sscanf_s (pbuf, "%d/%d/%d",
			    &pface->vert_indices[i],
			    &pface->uvw_indices[i],
			    &pface->norm_indices[i]) != 3)
		  {
		    if (sscanf_s (pbuf, "%d//%d", &pface->vert_indices[i],
				&pface->norm_indices[i]) != 2)
		      {
			if (sscanf_s (pbuf, "%d/%d", &pface->vert_indices[i],
				&pface->uvw_indices[i]) != 2)
			  {
			    sscanf (pbuf, "%d", &pface->vert_indices[i]);
			  }
		      }
		  }

		/* Indices must start at 0 */
		pface->vert_indices[i]--;

		if (mdl->has_texCoords)
		  pface->uvw_indices[i]--;

		if (mdl->has_normals)
		  pface->norm_indices[i]--;
	      }

	    pface++;
	    break;
	  }
	}
    }

  printf ("second pass results: read\n");
  printf ("   * %i vertices\n", pvert - mdl->vertices);
  printf ("   * %i texture coords.\n", puvw - mdl->texCoords);
  printf ("   * %i normal vectors\n", pnorm - mdl->normals);
  printf ("   * %i faces\n", pface - mdl->faces);
  //printf ("   * %s test name\n", mdl->faces[0].mat);
  //printf("wtf %d\n", mdl->num_faces);

  return 1;
}
Beispiel #9
0
int mtlLoad (const char *filename, struct mtl_file *mtlfile, int materials) {
  FILE *fp;
  char buf[256];
  int i=-1;

  mtlfile->mtl = (struct mtl*)malloc(sizeof(struct mtl)*materials);
  mtlfile->materials = materials;

  fp = fopen (filename, "r");
  if (!fp)
    {
      fprintf (stderr, "Error: couldn't open \"%s\"!\n", filename);
      return 0;
    }

  while (!feof (fp))
    {
      /* Read whole line */
      fgets (buf, sizeof (buf), fp);

      switch (buf[0])
	  {
	  case 'N':
		  if (buf[1] == 's') {
			  sscanf(buf+2, "%f", &mtlfile->mtl[i].ns);
		  }
		  if (buf[1] == 'i') {
			  sscanf(buf+2, "%f", &(mtlfile->mtl[i].ni));
		  }
		  break;
	  case 'n':
		  if (buf[1] == 'e') {
			  if (i<materials) {
				  i++;
			  }
			  sscanf(buf, "%*s %s", &mtlfile->mtl[i].name);
			  //sscanf(buf, "%s", &mtlfile->mtl[i].name);

		  }
		  break;
	  case 'K':
		  if (buf[1] == 'a') {
			  sscanf(buf+2, "%f %f %f", &mtlfile->mtl[i].ka[0], &mtlfile->mtl[i].ka[1], &mtlfile->mtl[i].ka[2]);
		  }
		  if (buf[1] == 's') {
			  sscanf(buf+2, "%f %f %f", &mtlfile->mtl[i].ks[0], &mtlfile->mtl[i].ks[1], &mtlfile->mtl[i].ks[2]);
		  }
		  if (buf[1] == 'd') {
			  sscanf(buf+2, "%f %f %f", &mtlfile->mtl[i].kd, &mtlfile->mtl[i].kd[1], &mtlfile->mtl[i].kd[2]);
		  }
		  break;
	  case 'i':
		  if (buf[1] == 'l') {
			  //sscanf(buf+2, "%*s %d", mtlfile->mtl[i].illum);
			  sscanf(buf+2, "%d", mtlfile->mtl[i].illum);
		  }
		  break;
	  case 'd':
		  if (buf[1] == 'l') {
			  sscanf(buf+2, "%f", mtlfile->mtl[i].d);
		  }
		  break;
	  }
  }
  /*printf ("mtl results: read\n");
  printf ("   * %s name\n", mtlfile->mtl[0].name);
  printf ("   * %f ns\n", mtlfile->mtl[0].ns);
  printf ("   * %f %f %f ka\n", mtlfile->mtl[3].ka[0], mtlfile->mtl[3].ka[1], mtlfile->mtl[3].ka[2]);
  printf ("   * %f %f %f kd\n", mtlfile->mtl[3].kd[0], mtlfile->mtl[3].kd[1], mtlfile->mtl[3].kd[2]);
  printf ("   * %f %f %f ks\n", mtlfile->mtl[3].ks[0], mtlfile->mtl[3].ks[1], mtlfile->mtl[3].ks[2]);
  printf ("   * %f ni\n", mtlfile->mtl[0].ni);*/
  //printf ("   * %i faces\n", pface - mdl->faces);

}
int main(int argc, char* argv[] ) {

	FILE* fp;
	/* Remove all existing log files */

	remove(FIFO_PIPE);
	
	
	int pid;		//Initialize first process to ID 1
	
	int msgId, namedPipe;	
	if (access(FIFO_PIPE, F_OK) == -1) {
		printf("Creating named pipe...\n");
		namedPipe = mkfifo(FIFO_PIPE, 0777); 
		if (namedPipe != 0) {
			/* the fifo name */
			/* check if fifo already /* if not then, create the fifo*/
			printf("Could not create fifo %s\n", FIFO_PIPE);
			exit(EXIT_FAILURE); 
		}
		printf("Named pipe created successfully: %s\n",FIFO_PIPE);
	}

	pid = (int)fork();

	if(pid == 0) {
		/* Child 1 section */

		

		printf("Opening FIFO named pipe..\n");
		/* Open the named pipe for read only on child process 2 */
		namedPipe = open(FIFO_PIPE, O_RDONLY);
		printf("Opening success..\n");
		
		//fclose(fp);
		
		fp = fopen("TESTLOG.txt", "a+");					/* Open a log file */
		printf("Parent Process 1: reading from Child 3..\n");
		while(read(namedPipe, tmpBuffer, sizeof(tmpBuffer))) {	/* Read all the buffers from pipe */
			
			sscanf(tmpBuffer, "%d%[^\n]",&msgId, buffer);				/* Break the message into the ID and message */
			printf("MSG: %d, %s\n", msgId, buffer);
			if(msgId == 1) {											/* Message is belongs to the child */
				strcat(buffer, KEEP_MSG);								/* Append message will "keep" word*/
			} else {													/* Message is NOT belongs to the child */
				//write(pipeFd[1], tmpBuffer, sizeof(tmpBuffer));			/* Forward the message to next child */
				strcat(buffer, FWD_MSG);								/* Append message will "forward" word*/
			}
			fprintf(fp, "%d%s\n",msgId,buffer);				/* Write the messages into the log file */
		}
		printf("Close file PP LOG\n");
		fclose(fp);

		return 0;

	}
	else {
		/* Parent or root section */
		
		printf("PARENT: Opening FIFO named pipe..\n");
		/* Open the named pipe for read only on child process 2 */
		namedPipe = open(FIFO_PIPE, O_WRONLY);
		
		printf("PARENT: Opened FIFO successfully.\n");
		
		/* Write to Childs from Message File*/
		fp = fopen(C2_TXT, "r");	/* Open Message File */
		while(fgets(tmpBuffer, (sizeof(tmpBuffer) + 2), fp)) {			/* Read all the messages from the file */
			printf("%s\n", tmpBuffer );
			write(namedPipe, tmpBuffer, sizeof(tmpBuffer));
		}	
		//c2Status = 1;		/* File is logged */
		printf("PARENT: Close file\n");
		fclose(fp);
		
	}
        	
	return EXIT_SUCCESS;
}
Beispiel #11
0
/**
 * Load an OBJ model from file -- first pass.
 * Get the number of triangles/vertices/texture coords for
 * allocating buffers.
 */
int
FirstPass (FILE *fp, struct obj_model_t *mdl)
{
  int v, t, n, i;
  char buf[256];

  while (!feof (fp))
    {
      /* Read whole line */
      fgets (buf, sizeof (buf), fp);

      switch (buf[0])
	{
	case 'm':
	  {
		  /*i=0;
		  while(buf[i] != ' '){
		    i++;
			  
		  }*/
		  sscanf(buf/*+i*/, "%*s %s", test);//mdl->name->name); 
		  hasname=1;
		  break;
	  }
	case 'v':
	  {
	    if (buf[1] == ' ')
	      {
		/* Vertex */
		mdl->num_verts++;
	      }
	    else if (buf[1] == 't')
	      {
		/* Texture coords. */
		mdl->num_texCoords++;
	      }
	    else if (buf[1] == 'n')
	      {
		/* Normal vector */
		mdl->num_normals++;
	      }
	    else
	      {
		printf ("Warning: unknown token \"%s\"! (ignoring)\n", buf);
	      }

	    break;
	  }

	case 'f':
	  {
	    /* Face */
	    if (sscanf (buf + 2, "%d/%d/%d", &v, &n, &t) == 3)
	      {
		mdl->num_faces++;
		mdl->has_texCoords = 1;
		mdl->has_normals = 1;
	      }
	    else if (sscanf (buf + 2, "%d//%d", &v, &n) == 2)
	      {
		mdl->num_faces++;
		mdl->has_texCoords = 0;
		mdl->has_normals = 1;
	      }
	    else if (sscanf (buf + 2, "%d/%d", &v, &t) == 2)
	      {
		mdl->num_faces++;
		mdl->has_texCoords = 1;
		mdl->has_normals = 0;
	      }
	    else if (sscanf (buf + 2, "%d", &v) == 1)
	      {
			  //printf("huh\n");
		mdl->num_faces++;
		mdl->has_texCoords = 0;
		mdl->has_normals = 0;
	      }
	    else
	      {
		/* Should never be there or the model is very crappy */
		fprintf (stderr, "Error: found face with no vertex!\n");
	      }

	    break;
	  }

	case 'g':
	  {
	    /* Group */
	    /*	fscanf (fp, "%s", buf); */
	    break;
	  }

	default:
	  break;
	}
    }

  /* Check if informations are valid */
  if ((mdl->has_texCoords && !mdl->num_texCoords) ||
      (mdl->has_normals && !mdl->num_normals))
    {
      fprintf (stderr, "error: contradiction between collected info!\n");
      return 0;
    }

  if (!mdl->num_verts)
    {
      fprintf (stderr, "error: no vertex found!\n");
      return 0;
    }

  printf ("first pass results: found\n");
  printf ("   * %i vertices\n", mdl->num_verts);
  printf ("   * %i texture coords.\n", mdl->num_texCoords);
  printf ("   * %i normal vectors\n", mdl->num_normals);
  printf ("   * %i faces\n", mdl->num_faces);
  printf ("   * has texture coords.: %s\n", mdl->has_texCoords ? "yes" : "no");
  printf ("   * has normals: %s\n", mdl->has_normals ? "yes" : "no"); 
  if (hasname){
	  printf ("   * has mtl file named: %s\n", test);
  }
  //mdl->name->name

  return 1;
}
Beispiel #12
0
void Read_Mapinfo(
    /* [in] */ FILE* fp,
    /* [in] */ stats_t* stats)
{
    char line[1024];
    int len, nameLen;
    bool skip, done = false;

    unsigned size = 0, resident = 0, pss = 0;
    unsigned shared_clean = 0, shared_dirty = 0;
    unsigned private_clean = 0, private_dirty = 0;
    unsigned referenced = 0;
    unsigned temp;

    unsigned long int start;
    unsigned long int end = 0;
    unsigned long int prevEnd = 0;
    char* name;
    int name_pos;

    int whichHeap = HEAP_UNKNOWN;
    int prevHeap = HEAP_UNKNOWN;

    if(fgets(line, sizeof(line), fp) == 0) return;

    while (!done) {
        prevHeap = whichHeap;
        prevEnd = end;
        whichHeap = HEAP_UNKNOWN;
        skip = FALSE;

        len = strlen(line);
        if (len < 1) return;
        line[--len] = 0;

        if (sscanf(line, "%lx-%lx %*s %*x %*x:%*x %*d%n", &start, &end, &name_pos) != 2) {
            skip = TRUE;
        } else {
            while (isspace(line[name_pos])) {
                name_pos += 1;
            }
            name = line + name_pos;
            nameLen = strlen(name);

            if (strstr(name, "[heap]") == name) {
                whichHeap = HEAP_NATIVE;
            } else if (strstr(name, "/dev/ashmem/dalvik-") == name) {
                whichHeap = HEAP_DALVIK;
            } else if (strstr(name, "/dev/ashmem/CursorWindow") == name) {
                whichHeap = HEAP_CURSOR;
            } else if (strstr(name, "/dev/ashmem/") == name) {
                whichHeap = HEAP_ASHMEM;
            } else if (strstr(name, "/dev/") == name) {
                whichHeap = HEAP_UNKNOWN_DEV;
            } else if (nameLen > 3 && strcmp(name+nameLen-3, ".so") == 0) {
                whichHeap = HEAP_SO;
            } else if (nameLen > 4 && strcmp(name+nameLen-4, ".jar") == 0) {
                whichHeap = HEAP_JAR;
            } else if (nameLen > 4 && strcmp(name+nameLen-4, ".apk") == 0) {
                whichHeap = HEAP_APK;
            } else if (nameLen > 4 && strcmp(name+nameLen-4, ".ttf") == 0) {
                whichHeap = HEAP_TTF;
            } else if (nameLen > 4 && strcmp(name+nameLen-4, ".dex") == 0) {
                whichHeap = HEAP_DEX;
            } else if (nameLen > 0) {
                whichHeap = HEAP_UNKNOWN_MAP;
            } else if (start == prevEnd && prevHeap == HEAP_SO) {
                // bss section of a shared library.
                whichHeap = HEAP_SO;
            }
        }

        //ALOGI("native=%d dalvik=%d sqlite=%d: %s\n", isNativeHeap, isDalvikHeap,
        //    isSqliteHeap, line);

        while (TRUE) {
            if (fgets(line, 1024, fp) == 0) {
                done = TRUE;
                break;
            }

            if (sscanf(line, "Size: %d kB", &temp) == 1) {
                size = temp;
            } else if (sscanf(line, "Rss: %d kB", &temp) == 1) {
                resident = temp;
            } else if (sscanf(line, "Pss: %d kB", &temp) == 1) {
                pss = temp;
            } else if (sscanf(line, "Shared_Clean: %d kB", &temp) == 1) {
                shared_clean = temp;
            } else if (sscanf(line, "Shared_Dirty: %d kB", &temp) == 1) {
                shared_dirty = temp;
            } else if (sscanf(line, "Private_Clean: %d kB", &temp) == 1) {
                private_clean = temp;
            } else if (sscanf(line, "Private_Dirty: %d kB", &temp) == 1) {
                private_dirty = temp;
            } else if (sscanf(line, "Referenced: %d kB", &temp) == 1) {
                referenced = temp;
            } else if (strlen(line) > 30 && line[8] == '-' && line[17] == ' ') {
                // looks like a new mapping
                // example: "10000000-10001000 ---p 10000000 00:00 0"
                break;
            }
        }

        if (!skip) {
            stats[whichHeap].pss += pss;
            stats[whichHeap].privateDirty += private_dirty;
            stats[whichHeap].sharedDirty += shared_dirty;
        }
    }
    return;
}
Beispiel #13
0
int RFG_Groups_readDefFile( RFG_Groups* groups )
{
    FILE*    f;
    char*    line;
    uint32_t lineno = 0;
    uint8_t  parse_err = 0;

    if( !groups )
        return 0;

    if( !groups->file_name )
        return 1;

    /* open group definition file */

    f = fopen( groups->file_name, "r" );
    if( !f )
    {
        fprintf( stderr,
                 "RFG_Groups_readDefFile(): Error: Could not open file '%s'\n",
                 groups->file_name );
        return 0;
    }

    line = ( char* )malloc( MAX_LINE_LEN * sizeof( char ) );
    if( !line )
    {
        fclose( f );
        return 0;
    }

    /* read lines */

    while( !parse_err && fgets( line, MAX_LINE_LEN, f ) )
    {
        char* group;
        char* p;

        /* increment line number */
        lineno++;

        /* remove newline */
        if( strlen( line ) > 0 && line[strlen(line)-1] == '\n' )
            line[strlen(line)-1] = '\0';

        /* remove leading and trailing spaces from line */
        vt_strtrim( line );

        /* cut possible comment from line */

        p = strchr( line, '#' );
        if( p )
            *p = '\0';

        /* continue if line is empty */
        if( strlen( line ) == 0 )
            continue;

        /* search for '='
           e.g. "GROUP=func1;func2;func3"
                      p
        */

        p = strchr( line, '=' );
        if( !p )
        {
            parse_err = 1;
            break;
        }

        /* cut group name from line
           e.g.   "GROUP=func1;func2;func3"
               => "GROUP"
        */

        *p = '\0';

        group = strdup( line );
        vt_strtrim( group );

        /* split remaining line at ';' to get pattern */

        p = strtok( p+1, ";" );
        do
        {
            char* pattern;

            if( !p )
            {
                parse_err = 1;
                break;
            }

            pattern = strdup( p );
            vt_strtrim( pattern );

            /* add group assignment */

            if( strlen( pattern ) > 0 )
                RFG_Groups_addAssign( groups, group, pattern );

            free( pattern );

        } while( ( p = strtok( 0, ";" ) ) );

        free( group );
    }

    if( parse_err )
    {
        fprintf( stderr, "%s:%u: Could not be parsed\n",
                 groups->file_name, lineno );
    }

    free( line );

    fclose( f );

    return parse_err ? 0 : 1;
}
Beispiel #14
0
int 
main(int argc, char **argv)
{

	if (argc < 2) {
		printf("usage: ./multisort inputfile > outfile \n");
		exit(1);
	}

	char **words = (char **)malloc(sizeof(char *)*MAXLINE);
	int n_words = readwords(words, argv[1]);

	int len = n_words;
    
    // parent should wait for child to exit

    pid_t pid;
    if ((pid = fork() == 0))
    {
        // split input file into two halves
        int halflen = len / 2;
        FILE *firsthalf = fopen("first-half-exec.txt", "w");
        FILE *secondhalf = fopen("second-half-exec.txt", "w");
        for (int i = 0; i < halflen; i++)
        {
            fprintf(firsthalf, "%s", words[i]);
        }
        for (int i = halflen; i < len; i++)
        {
            fprintf(secondhalf, "%s", words[i]);
        }
        //fclose(firsthalf);
        //fclose(secondhalf);

        // clean up memory
        for (int i = 0; i < len; i++)
        {
            free(words[i]);
        }
        free(words);

        // the program "sort" outputs to standard output
        // we should change our programs to redirect standard output to the two files
        fclose(firsthalf);
        fclose(secondhalf);

	    pid_t cpid;
	    if ((cpid = fork()) != 0) {
            FILE *sortedfirsthalf = fopen("first-half-exec-sorted.txt", "w");
            dup2(fileno(sortedfirsthalf), STDOUT_FILENO);
            fclose(sortedfirsthalf);            
            char *sortargs[] = { "sort", "-n", "first-half-exec.txt", NULL };
            execvp("sort", sortargs);
		    //parent sort the first half of the [start, start + len] section of words
	    	//len = len/2;
		    //qsort(words + start, len, sizeof(char *), qsort_cmp);
	    	//fprintf(stderr, "pid-%d has sorted [%d, %d)\n", getpid(), start, start + len);
            // write out first half of array to disk
	    } else {
            FILE *sortedsecondhalf = fopen("second-half-exec-sorted.txt", "w");
            dup2(fileno(sortedsecondhalf), STDOUT_FILENO);
            fclose(sortedsecondhalf);            
            char *sortargs[] = { "sort" , "-n", "second-half-exec.txt", NULL };
            execvp("sort", sortargs);
	    	//start = start + len/2;
	    	//len = len - len/2;
	    	//qsort(words + start, len, sizeof(char *), qsort_cmp);
	    	//fprintf(stderr, "pid-%d has sorted [%d, %d)\n", getpid(), start, start + len);
            // write out second half of array to disk
	    	exit(0);
	    }
        // wait for child's child to exit
        int status;
        waitpid(cpid, &status, 0);
        exit(0);
    }
    else
    {
    }

    
    // wait for all child processes
    wait(NULL);

	fprintf(stderr, "both sorting has finished\n");
	fprintf(stderr, "merging both lists\n\n\n");

    for (int i = 0; i < len; i++)
    {
        free(words[i]);
    }

    int halflen = len / 2;
    FILE *firsthalf = fopen("first-half-exec-sorted.txt", "r");
    FILE *secondhalf = fopen("second-half-exec-sorted.txt", "r");
    for (int i = 0; i < halflen; i++)
    {
        char *word = (char *)malloc(MAXWORDSZ);
        fgets(word, MAXWORDSZ, firsthalf);
        words[i] = word; 
    }
    for (int i = halflen; i < len; i++)
    {
        char *word = (char *)malloc(MAXWORDSZ);
        fgets(word, MAXWORDSZ, secondhalf);
        words[i] = word;
    }
    fclose(firsthalf);
    fclose(secondhalf);

    //merge the two sorted list into one
	mergewords(words, n_words/2, words+(n_words/2), n_words-(n_words/2), argv[1]);

    for (int i = 0; i < len; i++)
    {
        free(words[i]);
    }
    free(words);
    return 0;
}
Beispiel #15
0
static int tss2_get_socket (FILE **ret_read_fh, FILE **ret_write_fh)
{
	/*
	 * Returns connected file objects or establishes the connection
	 * if it's not already present
	 */
	struct addrinfo ai_hints;
	struct addrinfo *ai_head;
	struct addrinfo *ai_ptr;
	int sd = -1;
	int status;

	/* Check if we already got opened connections */
	if ((global_read_fh != NULL) && (global_write_fh != NULL))
	{
		/* If so, use them */
		if (ret_read_fh != NULL)
			*ret_read_fh = global_read_fh;
		if (ret_write_fh != NULL)
			*ret_write_fh = global_write_fh;
		return (0);
	}

	/* Get all addrs for this hostname */
	memset (&ai_hints, 0, sizeof (ai_hints));
#ifdef AI_ADDRCONFIG
	ai_hints.ai_flags |= AI_ADDRCONFIG;
#endif
	ai_hints.ai_family = AF_UNSPEC;
	ai_hints.ai_socktype = SOCK_STREAM;

	status = getaddrinfo ((config_host != NULL) ? config_host : DEFAULT_HOST,
			(config_port != NULL) ? config_port : DEFAULT_PORT,
			&ai_hints,
			&ai_head);
	if (status != 0)
	{
		ERROR ("teamspeak2 plugin: getaddrinfo failed: %s",
				gai_strerror (status));
		return (-1);
	}

	/* Try all given hosts until we can connect to one */
	for (ai_ptr = ai_head; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
	{
		/* Create socket */
		sd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype,
				ai_ptr->ai_protocol);
		if (sd < 0)
		{
			char errbuf[1024];
			WARNING ("teamspeak2 plugin: socket failed: %s",
					sstrerror (errno, errbuf, sizeof (errbuf)));
			continue;
		}

		/* Try to connect */
		status = connect (sd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
		if (status != 0)
		{
			char errbuf[1024];
			WARNING ("teamspeak2 plugin: connect failed: %s",
					sstrerror (errno, errbuf, sizeof (errbuf)));
			close (sd);
			continue;
		}

		/*
		 * Success, we can break. Don't need more than one connection
		 */
		break;
	} /* for (ai_ptr) */

	freeaddrinfo (ai_head);

	/* Check if we really got connected */
	if (sd < 0)
		return (-1);

	/* Create file objects from sockets */
	global_read_fh = fdopen (sd, "r");
	if (global_read_fh == NULL)
	{
		char errbuf[1024];
		ERROR ("teamspeak2 plugin: fdopen failed: %s",
				sstrerror (errno, errbuf, sizeof (errbuf)));
		close (sd);
		return (-1);
	}

	global_write_fh = fdopen (sd, "w");
	if (global_write_fh == NULL)
	{
		char errbuf[1024];
		ERROR ("teamspeak2 plugin: fdopen failed: %s",
				sstrerror (errno, errbuf, sizeof (errbuf)));
		tss2_close_socket ();
		return (-1);
	}

	{ /* Check that the server correctly identifies itself. */
		char buffer[4096];
		char *buffer_ptr;

		buffer_ptr = fgets (buffer, sizeof (buffer), global_read_fh);
		buffer[sizeof (buffer) - 1] = 0;

		if (memcmp ("[TS]\r\n", buffer, 6) != 0)
		{
			ERROR ("teamspeak2 plugin: Unexpected response when connecting "
					"to server. Expected ``[TS]'', got ``%s''.",
					buffer);
			tss2_close_socket ();
			return (-1);
		}
		DEBUG ("teamspeak2 plugin: Server send correct banner, connected!");
	}

	/* Copy the new filehandles to the given pointers */
	if (ret_read_fh != NULL)
		*ret_read_fh = global_read_fh;
	if (ret_write_fh != NULL)
		*ret_write_fh = global_write_fh;
	return (0);
} /* int tss2_get_socket */
Beispiel #16
0
int main(int argc, char **argv){
  if(argc <= 0){
    return -1;
  }
  /*
  char* filename = argv[1];
  char* ssss;
  ssss = filename;


  */
  FILE *pInputFile;
  //pInputFile = fopen(filename, "r");
  pInputFile = fopen("input/test.bfc", "r");
  //fp = fopen("/etc/vim/vimrc", "r");
  if (pInputFile == NULL){
    exit(EXIT_FAILURE);
  }

  FILE *pOutputFile;
  pOutputFile = fopen("output/out.asm", "w");

  cstring* data;
  data = (cstring*) malloc(sizeof(cstring) * 1000);
  int dataIdx = 0;
  cstring* text;
  text = (cstring*) malloc(sizeof(cstring) * 1000);
  int textIdx = 0;

  int levelsDeep = 0;

  char* line = (char*) malloc(sizeof(char) * MAX_LINE_LENGTH);
  //array of 15 pointers
  //char** tokens = (char**) malloc(15);
  tokens = (token*) malloc(sizeof(token) * 15);
  currToken = 0;

  //char** functionStack = (char**) malloc(50);
  //char* pNull = "NULL";
  cstring* functionStack = (cstring*) malloc(sizeof(cstring) * 50);

  functionStack = new_cstring(10);
  functionStack->i = "NULL";
  functionStack++;

  //TODO no point in going line by line anymore, just grab tokens...
  while(fgets(line, MAX_LINE_LENGTH, pInputFile)){
    token* token = getNextToken(&line);
    while(token != NULL){
      printf("%s\n", token->str.i);
      //handle token
      //remove brackets, semicolons, etc
      //clean(&(token->str));
      tokens[currToken++] = *token;

      token = getNextToken(&line);
    }
  }

  determineTokenType();

  //should combine tokens into expressions, ex
  //char* my_str; is four tokens but one 'expression'
  //printf("hello world");
  //is two expressions, expression has return value
  //but still need expression tree

  //this is so messy my god help
  tree* expTrees = new (tree*) malloc(sizeof(tree) * MAX_NUM_LINES);
  tree* currTree = expTrees;

  token* currLine = *tokenLines;
  int i;
  for(i = 0; i < currLine; i++){
    if(currTree == NULL){
      expression* root = new_expression();
      root->type = ROOT;
      currTree = new_tree(root);
    }
    token curr = *currLine;
    
    if(curr.type == TYPE){
      //this and next are expression
      //recursive procedure to attach next tokens as expression to current tree
      //this way we can have func( x+y, func2(y*z) )
      //if we need to attach root expression node, perhaps each line should root
      //node
    }
  }

  fclose(pInputFile);
  exit(EXIT_SUCCESS);
}
Beispiel #17
0
void sslEncKey(char *path, int mode) {
	char *openssl = find_openssl_bin();
	char *scr, *cert = NULL, *tca, *cdir = NULL;
	char line[1024], tmp[] = "/tmp/x11vnc-tmp.XXXXXX";
	int tmp_fd, incert, info_only = 0, delete_only = 0, listlong = 0;
	struct stat sbuf;
	FILE *file;
	static int depth = 0;

	if (depth > 0) {
		/* get_saved_pem may call us back. */
		return;
	}

	if (! path) {
		return;
	}

	depth++;

	if (mode == 1) {
		info_only = 1;
	} else if (mode == 2) {
		delete_only = 1;
	}

	if (! openssl) {
		exit(1);
	}

	cdir = get_Cert_dir(NULL, &tca);
	if (! cdir || ! tca) {
		fprintf(stderr, "could not find Cert dir\n");
		exit(1);
	}

	if (!strcasecmp(path, "LL") || !strcasecmp(path, "LISTL")) {
		listlong = 1;
		path = "LIST";
	}

	if (strstr(path, "SAVE") == path) {
		char *p = get_saved_pem(path, 0);
		if (p == NULL) {
			fprintf(stderr, "could not find saved pem "
			    "matching: %s\n", path);
			exit(1);
		}
		path = p;

	} else if (!strcmp(path, "CA")) {
		tca = (char *) malloc(strlen(cdir)+strlen("/CA/cacert.pem")+1);
		sprintf(tca, "%s/CA/cacert.pem", cdir);
		path = tca;

	} else if (info_only && (!strcasecmp(path, "LIST") ||
	    !strcasecmp(path, "LS") || !strcasecmp(path, "ALL"))) {

		if (! program_name || strchr(program_name, ' ')) {
			fprintf(stderr, "bad program name.\n");
			exit(1);
		}
		if (strchr(cdir, '\'')) {
			fprintf(stderr, "bad certdir char: %s\n", cdir);
			exit(1);
		}

		tca = (char *) malloc(2*strlen(cdir)+strlen(program_name)+1000);

		sprintf(tca, "find '%s' | egrep '/(CA|tmp|clients)$|"
		    "\\.(crt|pem|key|req)$' | grep -v CA/newcerts", cdir);

		if (!strcasecmp(path, "ALL")) {
			/* ugh.. */
			strcat(tca, " | egrep -v 'private/cakey.pem|"
			    "(CA|tmp|clients)$' | xargs -n1 ");
			strcat(tca, program_name);
			strcat(tca, " -ssldir '");
			strcat(tca, cdir);
			strcat(tca, "' -sslCertInfo 2>&1 ");
		} else if (listlong) {
			strcat(tca, " | xargs ls -ld ");
		}
		system(tca);
		free(tca);

		depth--;
		return;

	} else if (info_only && (!strcasecmp(path, "HASHON")
	    || !strcasecmp(path, "HASHOFF"))) {

		tmp_fd = mkstemp(tmp);
		if (tmp_fd < 0) {
			exit(1);
		}

		write(tmp_fd, genCert, strlen(genCert));
		close(tmp_fd);

		scr = (char *) malloc(strlen("/bin/sh ") + strlen(tmp) + 1);
		sprintf(scr, "/bin/sh %s", tmp);

		set_env("BASE_DIR", cdir);
		set_env("OPENSSL", openssl);
		set_env("TYPE", "server");
		if (!strcasecmp(path, "HASHON")) {
			set_env("HASHON", "1");
		} else {
			set_env("HASHOFF", "1");
		}
		system(scr);
		unlink(tmp);
		free(scr);

		depth--;
		return;
	}


	if (stat(path, &sbuf) != 0) {
	    if (strstr(path, "client") || strchr(path, '/') == NULL) {
		int i;
		tca = (char *) malloc(strlen(cdir) + strlen(path) + 100);
		for (i = 1; i <= 15; i++)  {
			tca[0] = '\0';
			if (       i == 1) {
			    sprintf(tca, "%s/%s", cdir, path); 
			} else if (i == 2 && mode > 0) {
			    sprintf(tca, "%s/%s.crt", cdir, path); 
			} else if (i == 3) {
			    sprintf(tca, "%s/%s.pem", cdir, path); 
			} else if (i == 4 && mode > 1) {
			    sprintf(tca, "%s/%s.req", cdir, path); 
			} else if (i == 5 && mode > 1) {
			    sprintf(tca, "%s/%s.key", cdir, path); 
			} else if (i == 6) {
			    sprintf(tca, "%s/clients/%s", cdir, path); 
			} else if (i == 7 && mode > 0) {
			    sprintf(tca, "%s/clients/%s.crt", cdir, path); 
			} else if (i == 8) {
			    sprintf(tca, "%s/clients/%s.pem", cdir, path); 
			} else if (i == 9 && mode > 1) {
			    sprintf(tca, "%s/clients/%s.req", cdir, path); 
			} else if (i == 10 && mode > 1) {
			    sprintf(tca, "%s/clients/%s.key", cdir, path); 
			} else if (i == 11) {
			    sprintf(tca, "%s/server-%s", cdir, path); 
			} else if (i == 12 && mode > 0) {
			    sprintf(tca, "%s/server-%s.crt", cdir, path); 
			} else if (i == 13) {
			    sprintf(tca, "%s/server-%s.pem", cdir, path); 
			} else if (i == 14 && mode > 1) {
			    sprintf(tca, "%s/server-%s.req", cdir, path); 
			} else if (i == 15 && mode > 1) {
			    sprintf(tca, "%s/server-%s.key", cdir, path); 
			}
			if (tca[0] == '\0') {
				continue;
			}
			if (stat(tca, &sbuf) == 0) {
				path = tca;
				break;
			}
		}
	    }
	}

	if (stat(path, &sbuf) != 0) {
		rfbLog("sslEncKey: %s\n", path);
		rfbLogPerror("stat");
		exit(1);
	}

	if (! info_only) {
		cert = (char *) malloc(2*(sbuf.st_size + 1024));
		file = fopen(path, "r");
		if (file == NULL) {
			rfbLog("sslEncKey: %s\n", path);
			rfbLogPerror("fopen");
			exit(1);
		}
		incert = 0;
		cert[0] = '\0';
		while (fgets(line, 1024, file) != NULL) {
			if (strstr(line, "-----BEGIN CERTIFICATE-----")
			    == line) {
				incert = 1;
			}
			if (incert) {
				if (strlen(cert)+strlen(line) <
				    2 * (size_t) sbuf.st_size) {
					strcat(cert, line);
				}
			}
			if (strstr(line, "-----END CERTIFICATE-----")
			    == line) {
				incert = 0;
			}
		}
		fclose(file);
	}

	tmp_fd = mkstemp(tmp);
	if (tmp_fd < 0) {
		exit(1);
	}

	write(tmp_fd, genCert, strlen(genCert));
	close(tmp_fd);

        scr = (char *) malloc(strlen("/bin/sh ") + strlen(tmp) + 1);
	sprintf(scr, "/bin/sh %s", tmp);

	set_env("BASE_DIR", "/no/such/dir");
	set_env("OPENSSL", openssl);
	set_env("TYPE", "server");
	if (info_only) {
		set_env("INFO_ONLY", path);
	} else if (delete_only) {
		set_env("DELETE_ONLY", path);
	} else {
		set_env("ENCRYPT_ONLY", path);
	}
	system(scr);
	unlink(tmp);

	if (! mode && cert && cert[0] != '\0') {
		int got_cert = 0;
		file = fopen(path, "r");
		if (file == NULL) {
			rfbLog("sslEncKey: %s\n", path);
			rfbLogPerror("fopen");
			exit(1);
		}
		while (fgets(line, 1024, file) != NULL) {
			if (strstr(line, "-----BEGIN CERTIFICATE-----")
			    == line) {
				got_cert++;
			}
			if (strstr(line, "-----END CERTIFICATE-----")
			    == line) {
				got_cert++;
			}
		}
		fclose(file);
		if (got_cert < 2) {
			file = fopen(path, "a");
			if (file == NULL) {
				rfbLog("sslEncKey: %s\n", path);
				rfbLogPerror("fopen");
				exit(1);
			}
			fprintf(file, "%s", cert);
			fclose(file);
		}
		free(cert);
	}

	depth--;
}
Beispiel #18
0
Config* Config::load(const char *filename){
	FILE *fp = NULL;
	int lineno = 0;

	if(strcmp(filename, "stdin") == 0){
		fp = stdin;
	}else{
		fp = fopen(filename, "r");
		if(!fp){
			log_error("error opening file '%s': %s", filename, strerror(errno));
			return NULL;
		}
	}

	Config *root = new Config("root", "");
	Config *cfg = root;
	int last_indent = 0;
	char buf[CONFIG_MAX_LINE];
	while(fgets(buf, sizeof(buf), fp)){
		lineno++;

		buf[strlen(buf) - 1] = '\0'; /* 去除 '\n' */
		if(is_empty_str(buf)){
			continue;
		}

		/* 有效行以 \t* 开头 */
		int indent = strspn(buf, "\t");
		char *key = buf + indent;

		if(*key == '#'){
			cfg->add_child("#", key + 1, lineno);
			continue;
		}
		if(indent <= last_indent){
			for(int i = indent; i <= last_indent; i++){
				/* 第一个配置时, 此条件为真 */
				if(cfg != root){
					cfg = cfg->parent;
				}
			}
		}else if(indent > last_indent + 1){
			log_error("invalid indent line(%d)", lineno);
			goto err;
		}
		
		if(isspace(*key)){
			log_error("invalid line(%d): unexpected whitespace char '%c'", lineno, *key);
			goto err;
		}

		char *val = key;
		/* 跳过键名 */
		while(*val && !is_kv_seperator(*val)){
			val++;
		}
		if(*val == '\0'){
			log_error("invalid line(%d): %s, expecting ':' or '='", lineno, *val);
			goto err;
		}else if(!is_kv_seperator(*val)){
			log_error("invalid line(%d): unexpected char '%c', expecting ':' or '='", lineno, *val);
			goto err;
		}
		*val++ = '\0';

		/* key 或者 value 的前后空白字符会被过滤 */
		key = trim(key);
		val = trim(val);

		cfg = cfg->add_child(key, val, lineno);
		if(cfg == NULL){
			goto err;
		}

		last_indent = indent;
	}
	if(ferror(fp)){
		log_error("error while reading file %s", filename);
		goto err;
	}
	fclose(fp);
	return root;
err:
	if(root){
		delete root;
	}
	if(fp && fp != stdin){
		fclose(fp);
	}
	return NULL;
}
Beispiel #19
0
static int sha1_check( char *filename )
{
    int i;
    size_t n;
    FILE *f;
    int nb_err1, nb_err2;
    int nb_tot1, nb_tot2;
    unsigned char sum[20];
    char buf[41], line[1024];

    if( ( f = fopen( filename, "rb" ) ) == NULL )
    {
        printf( "failed to open: %s\n", filename );
        return( 1 );
    }

    nb_err1 = nb_err2 = 0;
    nb_tot1 = nb_tot2 = 0;

    memset( line, 0, sizeof( line ) );

    n = sizeof( line );

    while( fgets( line, (int) n - 1, f ) != NULL )
    {
        n = strlen( line );

        if( n < 44 )
            continue;

        if( line[40] != ' ' || line[41] != ' ' )
            continue;

        if( line[n - 1] == '\n' ) { n--; line[n] = '\0'; }
        if( line[n - 1] == '\r' ) { n--; line[n] = '\0'; }

        nb_tot1++;

        if( sha1_wrapper( line + 42, sum ) != 0 )
        {
            nb_err1++;
            continue;
        }

        nb_tot2++;

        for( i = 0; i < 20; i++ )
            sprintf( buf + i * 2, "%02x", sum[i] );

        if( memcmp( line, buf, 40 ) != 0 )
        {
            nb_err2++;
            fprintf( stderr, "wrong checksum: %s\n", line + 42 );
        }

        n = sizeof( line );
    }

    if( nb_err1 != 0 )
    {
        printf( "WARNING: %d (out of %d) input files could "
                "not be read\n", nb_err1, nb_tot1 );
    }

    if( nb_err2 != 0 )
    {
        printf( "WARNING: %d (out of %d) computed checksums did "
                "not match\n", nb_err2, nb_tot2 );
    }

    return( nb_err1 != 0 || nb_err2 != 0 );
}
Beispiel #20
0
// Load a BMFont file (AngelCode font file)
static SpriteFont LoadBMFont(const char *fileName)
{
    #define MAX_BUFFER_SIZE     256

    SpriteFont font = { 0 };
    font.texture.id = 0;

    char buffer[MAX_BUFFER_SIZE];
    char *searchPoint = NULL;

    int fontSize = 0;
    int texWidth, texHeight;
    char texFileName[128];
    int numChars = 0;

    int base;   // Useless data

    FILE *fntFile;

    fntFile = fopen(fileName, "rt");

    if (fntFile == NULL)
    {
        TraceLog(WARNING, "[%s] FNT file could not be opened", fileName);
        return font;
    }

    // NOTE: We skip first line, it contains no useful information
    fgets(buffer, MAX_BUFFER_SIZE, fntFile);
    //searchPoint = strstr(buffer, "size");
    //sscanf(searchPoint, "size=%i", &fontSize);

    fgets(buffer, MAX_BUFFER_SIZE, fntFile);
    searchPoint = strstr(buffer, "lineHeight");
    sscanf(searchPoint, "lineHeight=%i base=%i scaleW=%i scaleH=%i", &fontSize, &base, &texWidth, &texHeight);

    TraceLog(DEBUG, "[%s] Font size: %i", fileName, fontSize);
    TraceLog(DEBUG, "[%s] Font texture scale: %ix%i", fileName, texWidth, texHeight);

    fgets(buffer, MAX_BUFFER_SIZE, fntFile);
    searchPoint = strstr(buffer, "file");
    sscanf(searchPoint, "file=\"%128[^\"]\"", texFileName);

    TraceLog(DEBUG, "[%s] Font texture filename: %s", fileName, texFileName);

    fgets(buffer, MAX_BUFFER_SIZE, fntFile);
    searchPoint = strstr(buffer, "count");
    sscanf(searchPoint, "count=%i", &numChars);

    TraceLog(DEBUG, "[%s] Font num chars: %i", fileName, numChars);

    // Compose correct path using route of .fnt file (fileName) and texFileName
    char *texPath = NULL;
    char *lastSlash = NULL;

    lastSlash = strrchr(fileName, '/');

    // NOTE: We need some extra space to avoid memory corruption on next allocations!
    texPath = malloc(strlen(fileName) - strlen(lastSlash) + strlen(texFileName) + 4);

    // NOTE: strcat() and strncat() required a '\0' terminated string to work!
    *texPath = '\0';
    strncat(texPath, fileName, strlen(fileName) - strlen(lastSlash) + 1);
    strncat(texPath, texFileName, strlen(texFileName));

    TraceLog(DEBUG, "[%s] Font texture loading path: %s", fileName, texPath);
    
    Image imFont = LoadImage(texPath);
    
    if (imFont.format == UNCOMPRESSED_GRAYSCALE) 
    {
        Image imCopy = ImageCopy(imFont);
        
        for (int i = 0; i < imCopy.width*imCopy.height; i++) ((unsigned char *)imCopy.data)[i] = 0xff;  // WHITE pixel

        ImageAlphaMask(&imCopy, imFont);
        font.texture = LoadTextureFromImage(imCopy);
        UnloadImage(imCopy);
    }
    else font.texture = LoadTextureFromImage(imFont);
    
    font.size = fontSize;
    font.numChars = numChars;
    font.charValues = (int *)malloc(numChars*sizeof(int));
    font.charRecs = (Rectangle *)malloc(numChars*sizeof(Rectangle));
    font.charOffsets = (Vector2 *)malloc(numChars*sizeof(Vector2));
    font.charAdvanceX = (int *)malloc(numChars*sizeof(int));

    UnloadImage(imFont);
    
    free(texPath);

    int charId, charX, charY, charWidth, charHeight, charOffsetX, charOffsetY, charAdvanceX;

    for (int i = 0; i < numChars; i++)
    {
        fgets(buffer, MAX_BUFFER_SIZE, fntFile);
        sscanf(buffer, "char id=%i x=%i y=%i width=%i height=%i xoffset=%i yoffset=%i xadvance=%i",
                       &charId, &charX, &charY, &charWidth, &charHeight, &charOffsetX, &charOffsetY, &charAdvanceX);

        // Save data properly in sprite font
        font.charValues[i] = charId;
        font.charRecs[i] = (Rectangle){ charX, charY, charWidth, charHeight };
        font.charOffsets[i] = (Vector2){ (float)charOffsetX, (float)charOffsetY };
        font.charAdvanceX[i] = charAdvanceX;
    }

    fclose(fntFile);

    if (font.texture.id == 0)
    {
        UnloadSpriteFont(font);
        font = GetDefaultFont();
    }
    else TraceLog(INFO, "[%s] SpriteFont loaded successfully", fileName);

    return font;
}
/*
 *	split_old_dump
 *
 *	This function splits pg_dumpall output into global values and
 *	database creation, and per-db schemas.	This allows us to create
 *	the support functions between restoring these two parts of the
 *	dump.  We split on the first "\connect " after a CREATE ROLE
 *	username match;  this is where the per-db restore starts.
 *
 *	We suppress recreation of our own username so we don't generate
 *	an error during restore
 */
void
split_old_dump(void)
{
	FILE	   *all_dump,
			   *globals_dump,
			   *db_dump;
	FILE	   *current_output;
	char		line[LINE_ALLOC];
	bool		start_of_line = true;
	char		create_role_str[MAX_STRING];
	char		create_role_str_quote[MAX_STRING];
	char		filename[MAXPGPATH];
	bool		suppressed_username = false;

	/* 
	 * Open all files in binary mode to avoid line end translation on Windows,
	 * both for input and output.
	 */

	snprintf(filename, sizeof(filename), "%s/%s", os_info.cwd, ALL_DUMP_FILE);
	if ((all_dump = fopen(filename, PG_BINARY_R)) == NULL)
		pg_log(PG_FATAL, "Cannot open dump file %s\n", filename);
	snprintf(filename, sizeof(filename), "%s/%s", os_info.cwd, GLOBALS_DUMP_FILE);
	if ((globals_dump = fopen(filename, PG_BINARY_W)) == NULL)
		pg_log(PG_FATAL, "Cannot write to dump file %s\n", filename);
	snprintf(filename, sizeof(filename), "%s/%s", os_info.cwd, DB_DUMP_FILE);
	if ((db_dump = fopen(filename, PG_BINARY_W)) == NULL)
		pg_log(PG_FATAL, "Cannot write to dump file %s\n", filename);
	current_output = globals_dump;

	/* patterns used to prevent our own username from being recreated */
	snprintf(create_role_str, sizeof(create_role_str),
			 "CREATE ROLE %s;", os_info.user);
	snprintf(create_role_str_quote, sizeof(create_role_str_quote),
			 "CREATE ROLE %s;", quote_identifier(os_info.user));

	while (fgets(line, sizeof(line), all_dump) != NULL)
	{
		/* switch to db_dump file output? */
		if (current_output == globals_dump && start_of_line &&
			suppressed_username &&
			strncmp(line, "\\connect ", strlen("\\connect ")) == 0)
			current_output = db_dump;

		/* output unless we are recreating our own username */
		if (current_output != globals_dump || !start_of_line ||
			(strncmp(line, create_role_str, strlen(create_role_str)) != 0 &&
			 strncmp(line, create_role_str_quote, strlen(create_role_str_quote)) != 0))
			fputs(line, current_output);
		else
			suppressed_username = true;

		if (strlen(line) > 0 && line[strlen(line) - 1] == '\n')
			start_of_line = true;
		else
			start_of_line = false;
	}

	fclose(all_dump);
	fclose(globals_dump);
	fclose(db_dump);
}
Beispiel #22
0
int main(int argc, char *argv[])
{
	char buffer[BUFSIZ];
	unsigned long startch;
	unsigned long ch;
	char *ptr;
	char *catName;
	unsigned long upperch;
	unsigned long lowerch;
	unsigned long titlech;

	/* Initialize the value tables to straight-through mappings */
	for(ch = 0; ch < 65536; ++ch)
	{
		lower[ch] = (unsigned short)ch;
		upper[ch] = (unsigned short)ch;
		title[ch] = (unsigned short)ch;
	}

	/* Process UnicodeData.txt to get the case conversion information */
	startch = 0;
	while(fgets(buffer, sizeof(buffer), stdin))
	{
		ptr = buffer;

		/* Parse the character value */
		ch = parseHex(&ptr, 0);
		if(*ptr != ';')
		{
			continue;
		}

		/* Skip the character if not within the 16-bit range */
		if(ch >= 0x10000)
		{
			startch = ch + 1;
			continue;
		}

		/* Find the category name */
		++ptr;
		while(*ptr != '\0' && *ptr != ';')
		{
			++ptr;
		}
		if(*ptr == ';')
		{
			++ptr;
		}
		catName = ptr;
		while(*ptr != '\0' && *ptr != ';')
		{
			++ptr;
		}
		if(*ptr == ';')
		{
			++ptr;
		}

		/* If the character name ended in ", Last>", then ignore
		   the character range */
		if((catName - buffer) > 8 && !strncmp(catName - 8, ", Last>", 7))
		{
			continue;
		}

		/* Find the case conversion fields */
		while(*ptr != '\0' && *ptr != ';')
		{
			++ptr;
		}
		if(*ptr == ';')
		{
			++ptr;
		}
		while(*ptr != '\0' && *ptr != ';')
		{
			++ptr;
		}
		if(*ptr == ';')
		{
			++ptr;
		}
		while(*ptr != '\0' && *ptr != ';')
		{
			++ptr;
		}
		if(*ptr == ';')
		{
			++ptr;
		}
		while(*ptr != '\0' && *ptr != ';')
		{
			++ptr;
		}
		if(*ptr == ';')
		{
			++ptr;
		}
		while(*ptr != '\0' && *ptr != ';')
		{
			++ptr;
		}
		if(*ptr == ';')
		{
			++ptr;
		}
		while(*ptr != '\0' && *ptr != ';')
		{
			++ptr;
		}
		if(*ptr == ';')
		{
			++ptr;
		}
		while(*ptr != '\0' && *ptr != ';')
		{
			++ptr;
		}
		if(*ptr == ';')
		{
			++ptr;
		}
		while(*ptr != '\0' && *ptr != ';')
		{
			++ptr;
		}
		if(*ptr == ';')
		{
			++ptr;
		}
		while(*ptr != '\0' && *ptr != ';')
		{
			++ptr;
		}
		if(*ptr == ';')
		{
			++ptr;
		}

		/* Extract the upper, lower, and title mappings */
		upperch = parseHex(&ptr, ch);
		if(*ptr != ';')
		{
			continue;
		}
		++ptr;
		lowerch = parseHex(&ptr, ch);
		if(*ptr != ';')
		{
			continue;
		}
		++ptr;
		titlech = parseHex(&ptr, ch);

		/* Update the case mapping tables */
		upper[ch] = (unsigned short)upperch;
		lower[ch] = (unsigned short)lowerch;
		title[ch] = (unsigned short)titlech;
	}

	/* Write out the mapping tables */
	printf("/* This file is automatically generated - do not edit */\n");
	printf("#define	UNICASE_RANGE1_LOWER  0x%04X\n", RANGE1_LOWER);
	printf("#define	UNICASE_RANGE1_UPPER  0x%04X\n", RANGE1_UPPER);
	printf("#define	UNICASE_RANGE1_OFFSET 0x%04X\n", 0);
	printf("#define	UNICASE_RANGE2_LOWER  0x%04X\n", RANGE2_LOWER);
	printf("#define	UNICASE_RANGE2_UPPER  0x%04X\n", RANGE2_UPPER);
	printf("#define	UNICASE_RANGE2_OFFSET 0x%04X\n", RANGE1_UPPER + 1);
	printf("#define	UNICASE_RANGE3_LOWER  0x%04X\n", RANGE3_LOWER);
	printf("#define	UNICASE_RANGE3_UPPER  0x%04X\n", RANGE3_UPPER);
	printf("#define	UNICASE_RANGE3_OFFSET 0x%04X\n",
		   (RANGE1_UPPER - RANGE1_LOWER + 1) +
		   (RANGE2_UPPER - RANGE2_LOWER + 1));
	writeTable("unicodeToUpper", upper);
	writeTable("unicodeToLower", lower);
#if 0
	writeTable("unicodeToTitle", title);
#endif

	/* Done */
	return 0;
}
Beispiel #23
0
int main(int argc, char **argv)
{
	FILE *cgf;
	bool found_zdtmtstroot = false, found_newroot = false;
	char paux[1024];
	int ret = -1;
	int fd;

	test_init(argc, argv);

	if (mount_and_add(cgname, "prefix", subname))
		goto out;
	if (mount_and_add(cgname2, "prefix", subname)) {
		sprintf(paux, "%s/%s", dirname, cgname);
		umount(paux);
		rmdir(paux);
		goto out;
	}

	sprintf(paux, "%s/%s/prefix", dirname, cgname);
	fd = open(paux, O_DIRECTORY);
	if (fd < 0)
		goto out_umount;

	if (fchmod(fd, 0777) < 0) {
		fail("fchmod");
		goto out_umount;
	}

	test_daemon();
	test_waitsig();

	if (close(fd) < 0) {
		fail("fd didn't survive");
		goto out_umount;
	}

	cgf = fopen("/proc/self/mountinfo", "r");
	if (cgf == NULL) {
		fail("No mountinfo file");
		goto out_umount;
	}

	while (fgets(paux, sizeof(paux), cgf)) {
		char *s;

		s = strstr(paux, cgname);
		if (s && test_exists(paux, "prefix")) {
			found_zdtmtstroot = true;
		}

		s = strstr(paux, cgname2);
		if (s && test_exists(paux, "newroot")) {
			found_newroot = true;
		}
	}

	if (!found_zdtmtstroot) {
		fail("oldroot not rewritten to zdtmtstroot!\n");
		goto out_close;
	}

	if (!found_newroot) {
		fail("oldroot not rewritten to newroot!\n");
		goto out_close;
	}

	pass();
	ret = 0;


out_close:
	fclose(cgf);
out_umount:
	sprintf(paux, "%s/%s", dirname, cgname);
	umount(paux);
	rmdir(paux);

	sprintf(paux, "%s/%s", dirname, cgname2);
	umount(paux);
	rmdir(paux);
out:
	return ret;
}
Beispiel #24
0
Datei: gnu.c Projekt: VanL/zrt
static void
__tar_read_dir_file (void)
{
  dev_t dev;
  ino_t ino;
  char *strp;
  FILE *fp;
  char buf[512];
  static char *path = 0;

  if (path == 0)
    path = tar_xmalloc (PATH_MAX);
  time (&this_time);
  if (gnu_dumpfile[0] != '/')
    {
#ifdef HAVE_GETCWD
      if (!getcwd (path, PATH_MAX))
	ERROR ((TAREXIT_FAILURE, 0, _("Could not get current directory")));
#else
      char *getwd ();

      if (!getwd (path))
	ERROR ((TAREXIT_FAILURE, 0, _("Could not get current directory: %s"),
		path));
#endif

      /* If this doesn't fit, we're in serious trouble.  */

      strcat (path, "/");
      strcat (path, gnu_dumpfile);
      gnu_dumpfile = path;
    }
  fp = fopen (gnu_dumpfile, "r");
  if (fp == 0 && errno != ENOENT)
    {
      ERROR ((0, errno, _("Cannot open %s"), gnu_dumpfile));
      return;
    }
  if (!fp)
    return;
  fgets (buf, sizeof (buf), fp);
  if (!flag_new_files)
    {
      flag_new_files++;
      new_time = atol (buf);
    }
  while (fgets (buf, sizeof (buf), fp))
    {
      strp = &buf[strlen (buf)];
      if (strp[-1] == '\n')
	strp[-1] = '\0';
      strp = buf;
      dev = atol (strp);
      while (ISDIGIT (*strp))
	strp++;
      ino = atol (strp);
      while (ISSPACE (*strp))
	strp++;
      while (ISDIGIT (*strp))
	strp++;
      strp++;
      __tar_add_dir (__tar_un_quote_string (strp), dev, ino, (char *) 0);
    }
  fclose (fp);
}
Beispiel #25
0
int hairtunes_init(char *pAeskey, char *pAesiv, char *fmtpstr, int pCtrlPort, int pTimingPort,
         int pDataPort, char *pRtpHost, char*pPipeName, char *pLibaoDriver, char *pLibaoDeviceName, char *pLibaoDeviceId,
         int bufStartFill)
{
    if(pAeskey != NULL)    
        memcpy(aeskey, pAeskey, sizeof(aeskey));
    if(pAesiv != NULL)
        memcpy(aesiv, pAesiv, sizeof(aesiv));
    if(pRtpHost != NULL)
        rtphost = pRtpHost;
    if(pPipeName != NULL)
        pipename = pPipeName;
    if(pLibaoDriver != NULL)
        audio_set_driver(pLibaoDriver);
    if(pLibaoDeviceName != NULL)
        audio_set_device_name(pLibaoDeviceName);
    if(pLibaoDeviceId != NULL)
        audio_set_device_id(pLibaoDeviceId);
    
    controlport = pCtrlPort;
    timingport = pTimingPort;
    dataport = pDataPort;
    if(bufStartFill < 0)
        bufStartFill = START_FILL;
    buffer_start_fill = bufStartFill;

    AES_set_decrypt_key(aeskey, 128, &aes);

    memset(fmtp, 0, sizeof(fmtp));
    int i = 0;
    char *arg;
    while ( (arg = strsep(&fmtpstr, " \t")) )
        fmtp[i++] = atoi(arg);

    init_decoder();
    init_buffer();
    init_rtp();      // open a UDP listen port and start a listener; decode into ring buffer
    fflush(stdout);
    init_output();              // resample and output from ring buffer

    char line[128];
    int in_line = 0;
    int n;
    double f;
    while (fgets(line + in_line, sizeof(line) - in_line, stdin)) {
        n = strlen(line);
        if (line[n-1] != '\n') {
            in_line = strlen(line) - 1;
            if (n == sizeof(line)-1)
                in_line = 0;
            continue;
        }
        if (sscanf(line, "vol: %lf\n", &f)) {
#ifdef DEBUG
            assert(f<=0);
            fprintf(stderr, "VOL: %lf\n", f);
#endif
            pthread_mutex_lock(&vol_mutex);
            volume = pow(10.0,0.05*f);
            fix_volume = 65536.0 * volume;
            pthread_mutex_unlock(&vol_mutex);
            continue;
        }
        if (!strcmp(line, "exit\n")) {
            exit(0);
        }
        if (!strcmp(line, "flush\n")) {
            pthread_mutex_lock(&ab_mutex);
            ab_resync();
            pthread_mutex_unlock(&ab_mutex);
#ifdef DEBUG
                fprintf(stderr, "FLUSH\n");
#endif
        }
    }
    deinit_output();
    fprintf(stderr, "bye!\n");
    fflush(stderr);

    return EXIT_SUCCESS;
}
Beispiel #26
0
static void update_urbnum(char *path, uint64_t count, char *shortname)
{
	struct device_data *ptr;
	FILE *file;
	char fullpath[4096];
	char name[4096], vendor[4096];
	ptr = devices;

	while (ptr) {
		if (strcmp(ptr->pathname, path)==0) {
			ptr->urbs = count;
			sprintf(fullpath, "%s/power/active_duration", path);
			file = fopen(fullpath, "r");
			if (!file)
				return;
			fgets(name, 4096, file);
			ptr->active = strtoull(name, NULL, 10);
			fclose(file);
			sprintf(fullpath, "%s/power/connected_duration", path);
			file = fopen(fullpath, "r");
			if (!file)
				return;
			fgets(name, 4096, file);
			ptr->connected = strtoull(name, NULL, 10);
			fclose(file);

			return;
		}
		ptr = ptr->next;
	}
	/* no luck, new one */
	ptr = malloc(sizeof(struct device_data));
	assert(ptr!=0);
	memset(ptr, 0, sizeof(struct device_data));
	ptr->next = devices;
	devices = ptr;
	strcpy(ptr->pathname, path);
	ptr->urbs = ptr->previous_urbs = count;
	sprintf(fullpath, "%s/product", path);
	file = fopen(fullpath, "r");
	memset(name, 0, 4096);
	if (file) { 
		fgets(name, 4096, file);
		fclose(file);
	}
	sprintf(fullpath, "%s/manufacturer", path);
	file = fopen(fullpath, "r");
	memset(vendor, 0, 4096);
	if (file) { 
		fgets(vendor, 4096, file);
		fclose(file);
	}
	
	if (strlen(name)>0 && name[strlen(name)-1]=='\n')
		name[strlen(name)-1]=0;
	if (strlen(vendor)>0 && vendor[strlen(vendor)-1]=='\n')
		vendor[strlen(vendor)-1]=0;
	/* some devices have bogus names */
	if (strlen(name)<4)
		strcpy(ptr->human_name, path);
	else
		sprintf(ptr->human_name, _("USB device %4s : %s (%s)"), shortname, name, vendor);

	if (strstr(ptr->human_name, "Host Controller"))
		ptr->controller = 1;
	
}
Beispiel #27
0
int main(int argc, char **argv)
{	
  char *cli_port;
  char *srv_addr;
  char *cli_addr;
  char *srv_port;
  char *input_file;
  //char *message = "This is the future!";	//test message
  char line[128];

  struct sockaddr_in server, client;
  struct addrinfo hints, *res;
  int sock_fd, length;
  int data_sent=0;
  //socklen_t addr_size;		   //no use
  //struct sockaddr_storage server_addr;   //no use


  
  if (argc >= 2) {
      srv_addr = argv[1];
  } else {
      srv_addr = "127.0.0.1";
  }
  
  if (argc >= 3) {
      srv_port = argv[2];
  }
  else {
      srv_port = "9999";
  }

  if(argc >= 4) {
      cli_port = argv[3];
  } else {
      cli_port = "10001";
  }

  if(argc >= 5) {
      input_file = argv[4];
  } else {
      input_file = "junk";
  }
  
  cli_addr = "127.0.0.1";

  memset(&hints, 0, sizeof hints);
  hints.ai_family = AF_UNSPEC;
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_flags = AI_PASSIVE;

  FILE *file_handler = fopen(input_file,"r");
  getaddrinfo(cli_addr, cli_port, &hints, &res);  
  sock_fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);

  memset(&client, 0, sizeof (struct sockaddr_in));
  client.sin_family = AF_INET;
  client.sin_port = atoi(argv[3]);
  //client.sin_addr.s_addr = inet_addr(LOCAL_IP_ADDRESS);

  bind(sock_fd, res->ai_addr, res->ai_addrlen); 
 
  getaddrinfo(srv_addr, srv_port, &hints, &res);  
  							//  getaddrinfo(srv_addr, srv_port, &hints, &res);  
  memset(&server, 0, sizeof (struct sockaddr_in));
  server.sin_family = AF_INET;
  server.sin_port = atoi(argv[2]);
  server.sin_addr.s_addr = inet_addr(srv_addr);

  connect(sock_fd, res->ai_addr, res->ai_addrlen);
  
  printf("starting client using port %s, connecting to server %s:%s, reading file %s\n",
		  cli_port, srv_addr, srv_port, input_file);

  while(fgets(line, 128, file_handler)!=NULL)			// and connection not r
   {
    //sscanf(line,"%s");
    length = strlen(line);  
    data_sent = write(sock_fd, line, length);
    //printf("Data sent: %d\nLength of line: %d\nLine Sent: %s\nClient Port: %s\n", data_sent, length, line, cli_port);
/*    if(data_sent == -1)
     {
      printf("%s\n",errbuf);
     }*/
    printf("%d\n", data_sent);
    sleep(1);
   }
  
  printf("test3: %d \n", sock_fd);
  fclose(file_handler);
  close(sock_fd);
  return 0;
}
Beispiel #28
0
int main(int argc,char *argv[]) {

	int c,rcode=0,colnum=0,srcfsize;
	long int numLines=10000, fsize=5, pref_indicator=0;
	char seperator=',';
	char *col_stmt=NULL;
	char *ifname=NULL,*ofname=NULL;
	FILE *ofile=NULL, *ifile=NULL;
	short int prefix_select=0;
	//char buff[MAX_LENGTH];
	char buff[2048];
	int quot_val = 0;

	arg_options argopts = { 0 , 0, 0, 0, 0, 0, 0, 0, 0 };

	while ((c = getopt(argc, argv, "vs:hnaf:o:il:z:c:")) != -1 ) 
		switch(c) {
			case 'v':
				argopts.ver_opt = 1;
			break;
			
			case 's':
				seperator = optarg[0];
			break;

			case 'h':
				Help(0);
			break;

			case 'n':
				argopts.num_opt = 1;
			break;

			case 'a':
				argopts.alph_opt = 1;
			break;

			case 'f':
				ifname = optarg;
				argopts.ifile_opt = 1;
			break;

			case 'o':
				argopts.ofile_opt = 1;
				ofname = optarg;

			break;
		
			case 'i':
				argopts.incl_opt = 1;
			break;

			case 'l':
				argopts.line_opt =1;
				numLines = atoi(optarg);
			break;

			case 'z':
				argopts.size_opt =1;
				fsize = atoi(optarg);
			break;
			
			case 'c':
				col_stmt = optarg;
			break;	

			default:
				Help(1);
			break;
		}

	if (argopts.ifile_opt == 0) {
		fprintf(stderr,"an input file must be specified\n");
		Help(1);
	}

	if ( (argopts.num_opt == 1) && (argopts.alph_opt == 1 ) ) {
		fprintf(stderr,"only one of the arguments should be specified ( -n  \\ -a) \n");
		Help(2);
	}
	else if ( argopts.alph_opt == 1 )
		fsize = fsize * 1024;

	if (argopts.alph_opt == 1 )
		prefix_select = 1;
	else
		prefix_select = 0;

	if (getenv("CSVS_SEPERATOR"))
		strncpy(&seperator,getenv("CSVS_SEPERATOR"),1);

	if (getenv("CSVS_OUTPUT"))
		ofname = getenv("CSVS_OUTPUT");

	if (getenv("CSVS_LINE_NUMBER"))
		numLines = atoi(getenv("CSVS_LINE_NUMBER"));

	if ( (getenv("CSVS_FILE_SIZE")) && (!getenv("CSVS_LINE_NUMBER")) ) 
		fsize = atoi(getenv("CSVS_FILE_SIZE")) * 1024;
	
	if ( getenv("CSVS_COLUMNS_NAME") )
		col_stmt = getenv("CSVS_COLUMNS_NAME");	
	
	//  openning the read file 
	
	if (ifile = fopen(ifname,"r")){
		if ( argopts.ver_opt == 1 )
			printf("the file %s is o.k.\n",ifname);

		argopts.ifile_opt = 1;
	}

	else {
		fprintf(stderr,"the file \"%s\" can not be opened\n",ifname);
		exit(1);
	}

	// 1) chicking if the read file is not empty 
	
	if (ifile) {

		fseek (ifile ,0, SEEK_END);
		srcfsize = ftell(ifile);

		if ( srcfsize == 0 ) {
			fclose(ifile);
			fprintf(stderr,"The Input file is empty !!!, exiting\n");
			exit(4);
		}
	}	
	
	// 2) setting the new file name according to user choice & \
	// creating the new file for writing (with a function)

	if ( argopts.ofile_opt == 0 ) {
	
		ofname = ifname;
		ofname =  basename(ofname);
	}


	if (argopts.alph_opt == 1 ) 
		strcat(ofname,".a");
	else
		strcat(ofname,".1");
	
 	if ( argopts.ver_opt == 1 )
		printf("the first output file name is : %s \n",ofname);

	// going over the read file and making sure each line is CSV competable
	

	fseek (ifile ,0, SEEK_SET);

	while( fgets(buff,2048,ifile) != NULL )  {


                if (strlen(buff) < (colnum+1))
                        break;
	
		if ( col_stmt == NULL ) {
		
			colnum = firstlinetst(buff,argopts.ver_opt,seperator,&quot_val);	
			col_stmt = (char *)calloc(strlen(buff),sizeof(char));
			strcpy(col_stmt,buff);
			continue;
		}

		

	}

	// 5) for each approved line inserting it to the new file while checking predefine limits
	// 6) if the write file as reached a limit start a new file
	// 7) if the read file is done , close all the files
	// 8) 
	


   return rcode;
}
int main(int argc, char *argv[])
{

    FILE *in=NULL, *wikiout=NULL,*htmlout=NULL;
    char * ptrch;
    char header[MAX_BUFFER][MAX_STRING];
    char col[MAX_BUFFER][MAX_STRING];
    char buffer[4096];
    int c,index, option_index = 0;
    char *param_wiki_output=NULL;
    char *param_html_output=NULL;
    char *param_file_input=NULL;
    int  linecounter=0;
    static struct option long_options[] = {
            {"wiki", 1, 0, 0},
            {"html", 1, 0, 0},
            {"i", 1, 0, 0}
     };

    int j=0,i=0;
    char separator[5];
    separator[0]=',';
    separator[1]='"';
    separator[2]='\0';


    prog_desc(argv);  //program descripton and title
    while(1) {
        c = getopt_long (argc, argv,"",long_options, &option_index);

        if (c == -1)
            break;

        switch (c) {
            case 0:
                index=option_index;
                switch (index) {
                   case 0:  //wiki
                        param_wiki_output = optarg;
                        break;
                   case 1:  // html
                        param_html_output = optarg;
                        break;
                    case 2:  // input
                        param_file_input = optarg;
                        break;
                    default:
                        printf("Unknown Parameter: %i\n",index);
                        helpme(argv);

                }
                break;
            default:
                        printf("Invalid Parameter: %i\n",c);
                        helpme(argv);

        }
    }

    if (optind < argc) {
        printf (" Ignored no option parameter(s): ");
        while (optind < argc)
            printf ("%s ", argv[optind++]);
        printf ("\n");
    }


    if ((param_wiki_output==NULL) &&( param_html_output==NULL)) {

         printf(" Error:  No output file specified:  use --wiki fname or --html fname\n\n");
         helpme(argv);

    }
    else {
		if (param_wiki_output !=NULL){
            wikiout=fopen(param_wiki_output,"w");
            if(wikiout==NULL ){
                printf("Can't create wiki output file %s\n",param_wiki_output);
                exit(1);
            }
		}
		if (param_html_output !=NULL) {
            htmlout=fopen(param_html_output,"w");
            if(htmlout==NULL ){
                printf("Can't create html output file %s\n",param_html_output);
                exit(1);
            }
        }
    }
    if (param_file_input ==NULL){
        printf("input text file required\n");
        helpme(argv);
    }
    else {
       in =fopen(param_file_input,"r");
       if(in==NULL ){
             printf("Can't open input file %s\n",param_file_input);
             exit(1);
       }
    }

	linecounter=0;
	while(!feof(in)) {
		if(fgets(buffer, MAX_STRING, in)) {
			//buflen=strlen(buffer);
			if (linecounter==0){
				// linecounter==0 means we are dealing with a header
				//remove double quotes("), replace comman (,) with !
				// do the column header first

				ptrch = strtok (buffer,",");  //tokens are delimited with pairs of quote comma
				i=0;
				while (ptrch != NULL) {
					   strcpy(header[i],ptrch);
					   removeQuotes(header[i]);
					   i++;
					   ptrch = strtok (NULL, ",");
				}

				if (htmlout!=NULL){
					 fprintf(htmlout,"<table class='wikitable' border='1'>\n");
					 fprintf(htmlout,"<tr>\n");
					 for (j=0; j < i;j++) {
						fprintf(htmlout,"<th scope='col'>%s</th>\n",header[j]);
					 }
					 fprintf(htmlout,"</tr>\n");
				}
				if (wikiout!=NULL){
					 fprintf(wikiout,"== Partlist ==\n\n");
					 fprintf(wikiout,"{| border='1' class='wikitable'\n");
					 fprintf(wikiout,"!%s",header[0]);
					 for(j=1;j < i;j++) {
						fprintf(wikiout,"!!%s",header[j]);
					 }
					// fprintf(wikiout,"\n");
				}



			}   // linecounter =0 only
            else {
                // tokens are separated by pair of quotes

				ptrch = strtok (buffer,"\"");  //tokens are delimited with quotes
				i=0;
				while (ptrch != NULL) {
				       if(*ptrch !=','){
                           strcpy(col[i],ptrch);
                           removeQuotes(col[i]);
                           i++;
                        }
					    ptrch = strtok (NULL, "\"");
				}


				 if (htmlout!=NULL){
					 fprintf(htmlout,"<tr>");
					 for (j=0;j < i-1;j++) {
						fprintf(htmlout,"<td>%s</td> ",col[j]);
					 }
					 fprintf(htmlout,"</tr>\n");

				 }
				  if (wikiout!=NULL){
					 fprintf(wikiout,"|-\n");
					 fprintf(wikiout,"|%s",col[0]);
					 for (j=1;j<i-1;j++) {
						fprintf(wikiout,"||%s",col[j]);
					 }
					  fprintf(wikiout,"\n");

				 }
            }

		}  //if (fgets(
         linecounter++;
	} //while !feof

	if (htmlout!=NULL){
	fprintf(htmlout,"</table>\n\n");
	printf("\n HTML FIle created: %s\n",param_html_output);
	}

   if (wikiout!=NULL){
        fprintf(wikiout,"|}\n\n");
        printf("\n Wiki FIle created: %s\n",param_wiki_output);
   }


   fclose(in);

   if(htmlout!=NULL ){
         fclose(htmlout);
   }
   if(wikiout!=NULL ) {
         fclose(wikiout);
   }
   return 0;
}
Beispiel #30
0
void load_contacts_with_hashtable(FILE *fsource, struct Region *aRegion, struct Hashtable *table, int mode, time_t *startAt, time_t *endAt)
{
	char buf[128], *vName1, *vName2, *tm1,*tm2, *strp, key[128];
	struct Contact *newContact;
	struct Item *aPairItem, *anEgoItem, *aLinkmanItem;
	struct Pair *aPair = NULL;
	struct Ego *anEgo = NULL;
	struct Linkman *aLinkman = NULL;

	time_t sAt, eAt;
	time_t tableStartAt, tableEndAt;
	struct Point aPoint;
	int xNumber, yNumber;
	int needed;
	int first;

	if(table == NULL)
		return;
	first = 1;
	while(fgets(buf, 128, fsource)) {

		vName1 = strtok(buf, ",");
		vName2 = strtok(NULL, ",");
		tm1 = strtok(NULL, ",");
		tm2 = strtok(NULL, ",");
		strp = strtok(NULL, ",");
		aPoint.x = atof(strp);
		strp = strtok(NULL, ",");
		aPoint.y = atof(strp);
		strp = strtok(NULL, ",");
		xNumber = atoi(strp);
		strp = strtok(NULL, ",");
		yNumber = atoi(strp);
		sAt = strtot(tm1);
		eAt = strtot(tm2);

		if(aRegion == NULL && *startAt == 0 && *endAt == 0) {
			needed = 1;
		} else if (aRegion == NULL && *startAt == 0 && *endAt) {
			if (eAt <= *endAt) needed = 1; else needed = 0;
		} else if (aRegion == NULL && *startAt && *endAt == 0) {
			if (sAt >= *startAt) needed = 1; else needed = 0;
		} else if (aRegion == NULL && *startAt && *endAt) {
			if (eAt <= *endAt && sAt >= *startAt) needed = 1; else needed = 0;
		} else if (aRegion && *startAt == 0 && *endAt == 0) {
			if (is_point_in_polygon(&aPoint, aRegion->chosen_polygon))
				needed = 1; else needed = 0;
		} else if (aRegion && *startAt == 0 && *endAt) {
			if (eAt <= *endAt && is_point_in_polygon(&aPoint, aRegion->chosen_polygon))
				needed = 1; else needed = 0;
		} else if (aRegion && *startAt && *endAt == 0) {
			if (is_point_in_polygon(&aPoint, aRegion->chosen_polygon) && sAt >= *startAt)
				needed = 1; else needed = 0;
		} else if (aRegion && *startAt && *endAt) {
			if (is_point_in_polygon(&aPoint, aRegion->chosen_polygon) && sAt >= *startAt && eAt <= *endAt)
				needed = 1; else needed = 0;
		} 
		if( needed ) {	
			newContact = (struct Contact*)malloc(sizeof(struct Contact));
			newContact->gPoint.x = aPoint.x;
			newContact->gPoint.y = aPoint.y;
			newContact->xNumber = xNumber;
			newContact->yNumber = yNumber;
			newContact->startAt = sAt;
			newContact->endAt = eAt;

			if(mode == PAIRWISE_TABLE) {
				sprintf(key, "%s,%s", vName1, vName2);
				aPairItem = hashtable_find(table, key);
				if(aPairItem == NULL) {
					aPair = (struct Pair*)malloc(sizeof(struct Pair));
					pair_init_func(aPair);
					strncpy(aPair->vName1, vName1, strlen(vName1)+1);
					strncpy(aPair->vName2, vName2, strlen(vName2)+1);
					hashtable_add(table, key, aPair);
					aPair->color.integer = rand();
					aPair->startAt = sAt;
					aPair->endAt = eAt;
					if(first) {
						tableStartAt = aPair->startAt;
						tableEndAt = aPair->endAt;
						first = 0;
					}	
				} else {
					aPair = (struct Pair*)aPairItem->datap;
					if(sAt < aPair->startAt) {
						aPair->startAt = sAt;
						if(aPair->startAt < tableStartAt)
							tableStartAt = aPair->startAt;
					}
					if(eAt > aPair->endAt) {
						aPair->endAt = eAt;
						if(aPair->endAt > tableEndAt)
							tableEndAt = aPair->endAt;
					}
				}

				newContact->fromPair = aPair;
				duallist_add_to_tail(&aPair->contents, newContact);
			} else {
				/* Ego vName1 */
				anEgoItem = hashtable_find(table, vName1);
				if(anEgoItem == NULL) {
					anEgo = (struct Ego*)malloc(sizeof(struct Ego));
					ego_init_func(anEgo);
					strncpy(anEgo->vName, vName1, strlen(vName1)+1);
					hashtable_add(table, vName1, anEgo);
					anEgo->startAt = sAt;
					anEgo->endAt = eAt;
					if(first) {
						tableStartAt = anEgo->startAt;
						tableEndAt = anEgo->endAt;
						first = 0;
					}	
				} else {
					anEgo = (struct Ego*)anEgoItem->datap;
					if(sAt < anEgo->startAt) {
						anEgo->startAt = sAt;
						if(anEgo->startAt < tableStartAt)
							tableStartAt = anEgo->startAt;
					}
					if(eAt > anEgo->endAt) {
						anEgo->endAt = eAt;
						if(anEgo->endAt > tableEndAt)
							tableEndAt = anEgo->endAt;
					}
				}

				aLinkmanItem = duallist_find(&anEgo->linkmen, vName2, (int(*)(void*,void*))linkman_has_name);
				if(aLinkmanItem == NULL) {
					aLinkman = (struct Linkman*)malloc(sizeof(struct Linkman));
					linkman_init_func(aLinkman);
					aLinkman->color.integer=rand();
					strncpy(aLinkman->vName, vName2, strlen(vName2)+1);
					duallist_add_to_tail(&anEgo->linkmen, aLinkman);
				} else 
					aLinkman = (struct Linkman*)aLinkmanItem->datap;
				newContact->fromPair = NULL;
				duallist_add_to_tail(&aLinkman->contacts, newContact);

				/* Ego vName2 */
				anEgoItem = hashtable_find(table, vName2);
				if(anEgoItem == NULL) {
					anEgo = (struct Ego*)malloc(sizeof(struct Ego));
					ego_init_func(anEgo);
					strncpy(anEgo->vName, vName2, strlen(vName2)+1);
					hashtable_add(table, vName2, anEgo);
					anEgo->startAt = sAt;
					anEgo->endAt = eAt;
				} else {
					anEgo = (struct Ego*)anEgoItem->datap;
					if(sAt < anEgo->startAt) {
						anEgo->startAt = sAt;
					}
					if(eAt > anEgo->endAt) {
						anEgo->endAt = eAt;
					}
				}

				aLinkmanItem = duallist_find(&anEgo->linkmen, vName1, (int(*)(void*,void*))linkman_has_name);
				if(aLinkmanItem == NULL) {
					aLinkman = (struct Linkman*)malloc(sizeof(struct Linkman));
					linkman_init_func(aLinkman);
					aLinkman->color.integer=rand();
					strncpy(aLinkman->vName, vName1, strlen(vName1)+1);
					duallist_add_to_tail(&anEgo->linkmen, aLinkman);
				} else 
					aLinkman = (struct Linkman*)aLinkmanItem->datap;
				duallist_add_to_tail(&aLinkman->contacts, contact_copy_func(newContact));
			}
		}

	}
	if(table->count) {
		*startAt = tableStartAt;
		*endAt = tableEndAt;
	}
}