Exemplo n.º 1
0
static void read_data (FILE *fp)
/* ------------------------------------------------------------------------- *
 * Read in data files.  If NZ > 1, it is assumed that data are in the file
 * in plane-by-plane order.  For each plane, the ordering of data varies
 * depending on whether the file is in ASCII or binary format: for ASCII, the
 * fields are in column order, element-by-element (row-major), whereas for
 * binary formats the fields are written in the file sequentially.
 *
 * Automatic conversion between little- and big-endian binary formats.
 * ------------------------------------------------------------------------- */
{
  int  i, m, n, nplane;
  int  nr_chk, ns_chk, nz_chk, nel_chk;
  char buf[STR_MAX], *c;
  
  /* -- Read the header down to the field list, check size of input. */

  for (n = 0; n < 3; n++) fgets(buf, STR_MAX, fp);

  if (sscanf (buf, "%d%d%d%d", &nr_chk, &ns_chk, &nz_chk, &nel_chk) != 4) {
    fputs ("error while reading mesh\n", stderr);
    exit  (EXIT_FAILURE);
  }

  if (nr != nr_chk || ns != ns_chk || nel != nel_chk) {
    fputs ("2D structure of mesh and field file do not agree\n", stderr);
    exit (EXIT_FAILURE);
  }

  for (n = 3; n < 9; n++) fgets(buf, STR_MAX, fp);

  /* -- Read the list of fields. */

  n       = 0;
  c       = buf;
  nfields = 0;
  while (n++ < 25 && nfields < MAXFIELDS) 
    if (isalnum(*c++)) type[nfields++] = *(c-1);

  if (nfields > MAXFIELDS) {
    fprintf(stderr, "sem2tec: a maximum of %d fields may be converted.\n", 
	    MAXFIELDS);
    exit(EXIT_FAILURE);
  }

  /* -- Allocate memory. */

  nplane = nr * ns * nel;
  for (n = 0; n < nfields; n++)
    data[n] = (double*) malloc (nzp * nplane * sizeof (double));

  /* -- Check the format. */

  c = fgets(buf, STR_MAX, fp); 
  while (isspace(*c)) c++;

  switch (tolower(*c)) {                     /* ASCII or binary read? */

  case 'a':
    for (m = 0; m < nz; m++)
      for (i = 0; i < nplane; i++)
	for (n = 0; n < nfields; n++)
	  if (fscanf(fp, "%lf", data[n] + m * nplane + i) < 0) {
	    fputs("sem2tec: field file (ASCII) read error\n", stderr);
	    exit (EXIT_FAILURE);
	  }
    break;

  case 'b': {
    int swab, machine  = iformat();

    swab = (strstr (buf, "little") && machine == 0 ||
	    strstr (buf, "big"   ) && machine == 1  ) ? 1 : 0;

    for (n = 0; n < nfields; n++) {
      if (fread (data[n], sizeof(double), nz * nplane, fp) != nz * nplane) {
 fputs("sem2tec: field file (binary) read error\n", stderr);
	  exit (EXIT_FAILURE);
      }
      if (swab) dbrev (nz * nplane, data[n], 1, data[n], 1);
    }
    break;
  }

  default:
    fprintf (stderr, "sem2tec: unknown format flag: '%c'\n", *c);
    exit    (EXIT_FAILURE);
    break;
  }
}
Exemplo n.º 2
0
void ObjectMgr::LoadExtraCreatureProtoStuff()
{
	{
		StorageContainerIterator<CreatureProto> * itr = CreatureProtoStorage.MakeIterator();
		CreatureProto* cn;
		while(!itr->AtEnd())
		{
			cn = itr->Get();

			// Process spell fields
			for( uint32 i = 0; i < MAX_CREATURE_PROTO_SPELLS; i++ ){
				if( cn->AISpells[ i ] == 0 )
					continue;

				SpellEntry *sp = dbcSpell.LookupEntryForced( cn->AISpells[ i ] );
				if( sp == NULL )
					continue;

				if( ( sp->Attributes & ATTRIBUTES_PASSIVE ) == 0 )
					cn->castable_spells.push_back( sp->Id );
				else
					cn->start_auras.insert( sp->Id );

			}

			// process creature spells from creaturespelldata.dbc
			if( cn->spelldataid != 0 ){
				CreatureSpellDataEntry* spe = dbcCreatureSpellData.LookupEntry( cn->spelldataid );
				for( uint32 i = 0; i < 3; i++ ){
					if( spe->Spells[ i ] == 0 )
						continue;

					SpellEntry *sp = dbcSpell.LookupEntryForced( spe->Spells[ i ] );
					if( sp == NULL )
						continue;

					if( ( sp->Attributes & ATTRIBUTES_PASSIVE ) == 0 )
						cn->castable_spells.push_back( sp->Id );
					else
						cn->start_auras.insert( sp->Id );
				}
			}

			if(cn->aura_string)
			{
				string auras = string(cn->aura_string);
				vector<string> aurs = StrSplit(auras, " ");
				for(vector<string>::iterator it = aurs.begin(); it != aurs.end(); ++it)
				{
					uint32 id = atol((*it).c_str());
					if(id)
						cn->start_auras.insert(id);
				}
			}

			if(!cn->MinHealth)
				cn->MinHealth = 1;
			if(!cn->MaxHealth)
				cn->MaxHealth = 1;
			if(cn->AttackType > SCHOOL_ARCANE)
				cn->AttackType = SCHOOL_NORMAL;

			cn->m_canFlee = cn->m_canRangedAttack = cn->m_canCallForHelp = false;
			cn->m_fleeHealth = 0.0f;
			// please.... m_fleeDuration is a uint32...
			//cn->m_fleeDuration = 0.0f;
			cn->m_fleeDuration = 0;

			if(!itr->Inc())
				break;
		}

		itr->Destruct();
	}

	{
		StorageContainerIterator<CreatureInfo> * itr = CreatureNameStorage.MakeIterator();
		CreatureInfo* ci;
		while(!itr->AtEnd())
		{
			ci = itr->Get();

			ci->lowercase_name = string(ci->Name);
			for(uint32 j = 0; j < ci->lowercase_name.length(); ++j)
				ci->lowercase_name[j] = static_cast<char>(tolower(ci->lowercase_name[j]));   // Darvaleo 2008/08/15 - Copied lowercase conversion logic from ItemPrototype task

			for(int i = 0; i < NUM_MONSTER_SAY_EVENTS; i++)
				ci->MonsterSay[i] = objmgr.HasMonsterSay(ci->Id, MONSTER_SAY_EVENTS(i));

			if(!itr->Inc())
				break;
		}
		itr->Destruct();
	}

	// Load AI Agents
	if(Config.MainConfig.GetBoolDefault("Server", "LoadAIAgents", true))
	{
		QueryResult* result = WorldDatabase.Query("SELECT * FROM ai_agents");
		CreatureProto* cn;

		if(result != NULL)
		{
			AI_Spell* sp;
			SpellEntry* spe;
			uint32 entry;

			do
			{
				Field* fields = result->Fetch();
				entry = fields[0].GetUInt32();
				cn = CreatureProtoStorage.LookupEntry(entry);
				spe = dbcSpell.LookupEntryForced(fields[6].GetUInt32());
				if(spe == NULL)
				{
					Log.Error("AIAgent", "For %u has nonexistent spell %u.", fields[0].GetUInt32(), fields[6].GetUInt32());
					continue;
				}
				if(!cn)
					continue;

				sp = new AI_Spell;
				sp->entryId = fields[0].GetUInt32();
				sp->instance_mode = fields[1].GetUInt32();
				sp->agent = fields[2].GetUInt16();
				sp->procChance = fields[4].GetUInt32();
				sp->procCount = fields[5].GetUInt32();
				sp->spell = spe;
				sp->spellType = static_cast<uint8>(fields[7].GetUInt32());

				int32  targettype = fields[8].GetInt32();
				if(targettype == -1)
					sp->spelltargetType = static_cast<uint8>(GetAiTargetType(spe));
				else sp->spelltargetType = static_cast<uint8>(targettype);

				sp->cooldown = fields[9].GetInt32();
				sp->floatMisc1 = fields[10].GetFloat();
				sp->autocast_type = (uint32) - 1;
				sp->cooldowntime = getMSTime();
				sp->procCounter = 0;
				sp->Misc2 = fields[11].GetUInt32();
				if(sp->agent == AGENT_SPELL)
				{
					if(!sp->spell)
					{
						LOG_DEBUG("SpellId %u in ai_agent for %u is invalid.", (unsigned int)fields[6].GetUInt32(), (unsigned int)sp->entryId);
						delete sp;
						sp = NULL;
						continue;
					}

					if(sp->spell->Effect[0] == SPELL_EFFECT_LEARN_SPELL || sp->spell->Effect[1] == SPELL_EFFECT_LEARN_SPELL ||
					        sp->spell->Effect[2] == SPELL_EFFECT_LEARN_SPELL)
					{
						LOG_DEBUG("Teaching spell %u in ai_agent for %u", (unsigned int)fields[6].GetUInt32(), (unsigned int)sp->entryId);
						delete sp;
						sp = NULL;
						continue;
					}

					sp->minrange = GetMinRange(dbcSpellRange.LookupEntry(sp->spell->rangeIndex));
					sp->maxrange = GetMaxRange(dbcSpellRange.LookupEntry(sp->spell->rangeIndex));

					//omg the poor darling has no clue about making ai_agents
					if(sp->cooldown == (uint32) - 1)
					{
						//now this will not be exact cooldown but maybe a bigger one to not make him spam spells to often
						int cooldown;
						SpellDuration* sd = dbcSpellDuration.LookupEntry(sp->spell->DurationIndex);
						int Dur = 0;
						int Casttime = 0; //most of the time 0
						int RecoveryTime = sp->spell->RecoveryTime;
						if(sp->spell->DurationIndex)
							Dur =::GetDuration(sd);
						Casttime = GetCastTime(dbcSpellCastTime.LookupEntry(sp->spell->CastingTimeIndex));
						cooldown = Dur + Casttime + RecoveryTime;
						if(cooldown < 0)
							sp->cooldown = 2000; //huge value that should not loop while adding some timestamp to it
						else sp->cooldown = cooldown;
					}

					/*
					//now apply the moron filter
					if(sp->procChance== 0)
					{
						//printf("SpellId %u in ai_agent for %u is invalid.\n", (unsigned int)fields[5].GetUInt32(), (unsigned int)sp->entryId);
						delete sp;
						sp = NULL;
						continue;
					}
					if(sp->spellType== 0)
					{
						//right now only these 2 are used
						if(IsBeneficSpell(sp->spell))
							sp->spellType==STYPE_HEAL;
						else sp->spellType==STYPE_BUFF;
					}
					if(sp->spelltargetType== 0)
						sp->spelltargetType = RecommandAISpellTargetType(sp->spell);
						*/
				}

				if(sp->agent == AGENT_RANGED)
				{
					cn->m_canRangedAttack = true;
					delete sp;
					sp = NULL;
				}
				else if(sp->agent == AGENT_FLEE)
				{
					cn->m_canFlee = true;
					if(sp->floatMisc1)
						cn->m_canFlee = (sp->floatMisc1 > 0.0f ? true : false);
					else
						cn->m_fleeHealth = 0.2f;

					if(sp->Misc2)
						cn->m_fleeDuration = sp->Misc2;
					else
						cn->m_fleeDuration = 10000;

					delete sp;
					sp = NULL;
				}
				else if(sp->agent == AGENT_CALLFORHELP)
				{
					cn->m_canCallForHelp = true;
					if(sp->floatMisc1)
						cn->m_callForHelpHealth = 0.2f;
					delete sp;
					sp = NULL;
				}
				else
				{
					cn->spells.push_back(sp);
				}
			}
			while(result->NextRow());

			delete result;
		}
	}
}
static int conntrack_parse(int c, char **argv, int invert, unsigned int *flags,
                           const void *entry, struct xt_entry_match **match)
{
	struct xt_conntrack_info *sinfo = (void *)(*match)->data;
	char *protocol = NULL;
	unsigned int naddrs = 0;
	struct in_addr *addrs = NULL;


	switch (c) {
	case '1':
		xtables_check_inverse(optarg, &invert, &optind, 0);

		parse_states(argv[optind-1], sinfo);
		if (invert) {
			sinfo->invflags |= XT_CONNTRACK_STATE;
		}
		sinfo->flags |= XT_CONNTRACK_STATE;
		break;

	case '2':
		xtables_check_inverse(optarg, &invert, &optind, 0);

		if(invert)
			sinfo->invflags |= XT_CONNTRACK_PROTO;

		/* Canonicalize into lower case */
		for (protocol = argv[optind-1]; *protocol; protocol++)
			*protocol = tolower(*protocol);

		protocol = argv[optind-1];
		sinfo->tuple[IP_CT_DIR_ORIGINAL].dst.protonum =
			xtables_parse_protocol(protocol);

		if (sinfo->tuple[IP_CT_DIR_ORIGINAL].dst.protonum == 0
		    && (sinfo->invflags & XT_INV_PROTO))
			xtables_error(PARAMETER_PROBLEM,
				   "rule would never match protocol");

		sinfo->flags |= XT_CONNTRACK_PROTO;
		break;

	case '3':
		xtables_check_inverse(optarg, &invert, &optind, 0);

		if (invert)
			sinfo->invflags |= XT_CONNTRACK_ORIGSRC;

		xtables_ipparse_any(argv[optind-1], &addrs,
					&sinfo->sipmsk[IP_CT_DIR_ORIGINAL],
					&naddrs);
		if(naddrs > 1)
			xtables_error(PARAMETER_PROBLEM,
				"multiple IP addresses not allowed");

		if(naddrs == 1) {
			sinfo->tuple[IP_CT_DIR_ORIGINAL].src.ip = addrs[0].s_addr;
		}

		sinfo->flags |= XT_CONNTRACK_ORIGSRC;
		break;

	case '4':
		xtables_check_inverse(optarg, &invert, &optind, 0);

		if (invert)
			sinfo->invflags |= XT_CONNTRACK_ORIGDST;

		xtables_ipparse_any(argv[optind-1], &addrs,
					&sinfo->dipmsk[IP_CT_DIR_ORIGINAL],
					&naddrs);
		if(naddrs > 1)
			xtables_error(PARAMETER_PROBLEM,
				"multiple IP addresses not allowed");

		if(naddrs == 1) {
			sinfo->tuple[IP_CT_DIR_ORIGINAL].dst.ip = addrs[0].s_addr;
		}

		sinfo->flags |= XT_CONNTRACK_ORIGDST;
		break;

	case '5':
		xtables_check_inverse(optarg, &invert, &optind, 0);

		if (invert)
			sinfo->invflags |= XT_CONNTRACK_REPLSRC;

		xtables_ipparse_any(argv[optind-1], &addrs,
					&sinfo->sipmsk[IP_CT_DIR_REPLY],
					&naddrs);
		if(naddrs > 1)
			xtables_error(PARAMETER_PROBLEM,
				"multiple IP addresses not allowed");

		if(naddrs == 1) {
			sinfo->tuple[IP_CT_DIR_REPLY].src.ip = addrs[0].s_addr;
		}

		sinfo->flags |= XT_CONNTRACK_REPLSRC;
		break;

	case '6':
		xtables_check_inverse(optarg, &invert, &optind, 0);

		if (invert)
			sinfo->invflags |= XT_CONNTRACK_REPLDST;

		xtables_ipparse_any(argv[optind-1], &addrs,
					&sinfo->dipmsk[IP_CT_DIR_REPLY],
					&naddrs);
		if(naddrs > 1)
			xtables_error(PARAMETER_PROBLEM,
				"multiple IP addresses not allowed");

		if(naddrs == 1) {
			sinfo->tuple[IP_CT_DIR_REPLY].dst.ip = addrs[0].s_addr;
		}

		sinfo->flags |= XT_CONNTRACK_REPLDST;
		break;

	case '7':
		xtables_check_inverse(optarg, &invert, &optind, 0);

		parse_statuses(argv[optind-1], sinfo);
		if (invert) {
			sinfo->invflags |= XT_CONNTRACK_STATUS;
		}
		sinfo->flags |= XT_CONNTRACK_STATUS;
		break;

	case '8':
		xtables_check_inverse(optarg, &invert, &optind, 0);

		parse_expires(argv[optind-1], sinfo);
		if (invert) {
			sinfo->invflags |= XT_CONNTRACK_EXPIRES;
		}
		sinfo->flags |= XT_CONNTRACK_EXPIRES;
		break;

	default:
		return 0;
	}

	*flags = sinfo->flags;
	return 1;
}
Exemplo n.º 4
0
std::string get_codec_name(AVCodecContext *pCodecCtx)
{
  AVCodecID id = pCodecCtx->codec_id;

  // Grab the codec
  const AVCodec *p = avcodec_find_decoder(id);
  const AVCodecDescriptor *desc = avcodec_descriptor_get(id);
  const char *profile = avcodec_profile_name(id, pCodecCtx->profile);

  std::ostringstream codec_name;

  const char *nice_name = nullptr;
  for (int i = 0; i < countof(nice_codec_names); ++i)
  {
    if (nice_codec_names[i].id == id) {
      nice_name = nice_codec_names[i].name;
      break;
    }
  }

  if (id == AV_CODEC_ID_DTS && pCodecCtx->codec_tag == 0xA2) {
    profile = "DTS Express";
  }

  if (id == AV_CODEC_ID_H264 && profile) {
    codec_name << nice_name << " " << tolower(profile);
    if (pCodecCtx->level && pCodecCtx->level != FF_LEVEL_UNKNOWN && pCodecCtx->level < 1000) {
      char l_buf[5];
      sprintf_s(l_buf, "%.1f", pCodecCtx->level / 10.0);
      codec_name << " L" << l_buf;
    }
  } else if (id == AV_CODEC_ID_VC1 && profile) {
    codec_name << nice_name << " " << tolower(profile);
    if (pCodecCtx->level != FF_LEVEL_UNKNOWN) {
      codec_name << " L" << pCodecCtx->level;
    }
  } else if (id == AV_CODEC_ID_DTS && profile) {
    codec_name << tolower(profile);
  } else if (id == AV_CODEC_ID_JPEG2000 && profile) {
    codec_name << tolower(profile);
  } else if (nice_name) {
    codec_name << nice_name;
    if (profile)
      codec_name << " " << tolower(profile);
  } else if (desc && desc->name) {
    codec_name << desc->name;
    if (profile)
      codec_name << " " << tolower(profile);
  } else if (p && p->name) {
    codec_name << p->name;
    if (profile)
      codec_name << " " << tolower(profile);
  } else {
    /* output avi tags */
    char buf[32];
    av_get_codec_tag_string(buf, sizeof(buf), pCodecCtx->codec_tag);
    codec_name << buf;
    sprintf_s(buf, "0x%04X", pCodecCtx->codec_tag);
    codec_name  << " / " << buf;
  }
  return codec_name.str();
}
Exemplo n.º 5
0
VOID
__cdecl
main(
    _In_ int argc,
    _In_z_ char *argv[]
    )

{
    BOOL status = 0;
    DWORD accessMode = 0, shareMode = 0;
    HANDLE fileHandle = NULL;
    ULONG alignmentMask = 0; // default == no alignment requirement
    UCHAR srbType = 0; // default == SRB_TYPE_SCSI_REQUEST_BLOCK
    PUCHAR dataBuffer = NULL;
    PUCHAR pUnAlignedBuffer = NULL;
    SCSI_PASS_THROUGH_WITH_BUFFERS sptwb;
    SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER sptdwb;
    SCSI_PASS_THROUGH_WITH_BUFFERS_EX sptwb_ex;
    SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER_EX sptdwb_ex;
    CHAR string[NAME_COUNT];

    ULONG length = 0,
          errorCode = 0,
          returned = 0,
          sectorSize = 512;

    if ((argc < 2) || (argc > 3)) {
       printf("Usage:  %s <port-name> [-mode]\n", argv[0] );
       printf("Examples:\n");
       printf("    spti g:       (open the disk class driver in SHARED READ/WRITE mode)\n");
       printf("    spti Scsi2:   (open the miniport driver for the 3rd host adapter)\n");
       printf("    spti Tape0 w  (open the tape class driver in SHARED WRITE mode)\n");
       printf("    spti i: c     (open the CD-ROM class driver in SHARED READ mode)\n");
       return;
    }

    StringCbPrintf(string, sizeof(string), "\\\\.\\%s", argv[1]);

    shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;  // default
    accessMode = GENERIC_WRITE | GENERIC_READ;       // default

    if (argc == 3) {

        switch(tolower(argv[2][0])) {
            case 'r':
                shareMode = FILE_SHARE_READ;
                break;

            case 'w':
                shareMode = FILE_SHARE_WRITE;
                break;

            case 'c':
                shareMode = FILE_SHARE_READ;
                sectorSize = 2048;
                break;

            default:
                printf("%s is an invalid mode.\n", argv[2]);
                puts("\tr = read");
                puts("\tw = write");
                puts("\tc = read CD (2048 byte sector mode)");
                return;
        }
    }

    fileHandle = CreateFile(string,
       accessMode,
       shareMode,
       NULL,
       OPEN_EXISTING,
       0,
       NULL);

    if (fileHandle == INVALID_HANDLE_VALUE) {
        errorCode = GetLastError();
        printf("Error opening %s. Error: %d\n",
               string, errorCode);
        PrintError(errorCode);
        return;
    }

    //
    // Get the alignment requirements
    //

    status = QueryPropertyForDevice(fileHandle, &alignmentMask, &srbType);
    if (!status ) {
        errorCode = GetLastError();
        printf("Error getting device and/or adapter properties; "
               "error was %d\n", errorCode);
        PrintError(errorCode);
        CloseHandle(fileHandle);
        return;
    }

    printf("\n"
           "            *****     Detected Alignment Mask    *****\n"
           "            *****             was %08x       *****\n\n\n",
           alignmentMask);

    //
    // Send SCSI Pass Through
    //

    puts("            ***** MODE SENSE -- return all pages *****");
    puts("            *****      with SenseInfo buffer     *****\n");

    if(srbType == 1)
    {
        ZeroMemory(&sptwb_ex,sizeof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX));
        sptwb_ex.spt.Version = 0;
        sptwb_ex.spt.Length = sizeof(SCSI_PASS_THROUGH_EX);
        sptwb_ex.spt.ScsiStatus = 0;
        sptwb_ex.spt.CdbLength = CDB6GENERIC_LENGTH;
        sptwb_ex.spt.StorAddressLength = sizeof(STOR_ADDR_BTL8);
        sptwb_ex.spt.SenseInfoLength = SPT_SENSE_LENGTH;
        sptwb_ex.spt.DataOutTransferLength = 0;
        sptwb_ex.spt.DataInTransferLength = 192;
        sptwb_ex.spt.DataDirection = SCSI_IOCTL_DATA_IN;
        sptwb_ex.spt.TimeOutValue = 2;
        sptwb_ex.spt.StorAddressOffset =
            offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,StorAddress);
        sptwb_ex.StorAddress.Type = STOR_ADDRESS_TYPE_BTL8;
        sptwb_ex.StorAddress.Port = 0;
        sptwb_ex.StorAddress.AddressLength = STOR_ADDR_BTL8_ADDRESS_LENGTH;
        sptwb_ex.StorAddress.Path = 0;
        sptwb_ex.StorAddress.Target = 1;
        sptwb_ex.StorAddress.Lun = 0;
        sptwb_ex.spt.SenseInfoOffset =
           offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,ucSenseBuf);
        sptwb_ex.spt.DataOutBufferOffset = 0;
        sptwb_ex.spt.DataInBufferOffset =
           offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,ucDataBuf);
        sptwb_ex.spt.Cdb[0] = SCSIOP_MODE_SENSE;
        sptwb_ex.spt.Cdb[2] = MODE_SENSE_RETURN_ALL;
        sptwb_ex.spt.Cdb[4] = 192;
        length = offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,ucDataBuf) +
           sptwb_ex.spt.DataInTransferLength;

        status = DeviceIoControl(fileHandle,
                                 IOCTL_SCSI_PASS_THROUGH_EX,
                                 &sptwb_ex,
                                 sizeof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX),
                                 &sptwb_ex,
                                 length,
                                 &returned,
                                 FALSE);

        PrintStatusResultsEx(status,returned,&sptwb_ex,length);
    }
    else
    {
        ZeroMemory(&sptwb,sizeof(SCSI_PASS_THROUGH_WITH_BUFFERS));
        sptwb.spt.Length = sizeof(SCSI_PASS_THROUGH);
        sptwb.spt.PathId = 0;
        sptwb.spt.TargetId = 1;
        sptwb.spt.Lun = 0;
        sptwb.spt.CdbLength = CDB6GENERIC_LENGTH;
        sptwb.spt.SenseInfoLength = SPT_SENSE_LENGTH;
        sptwb.spt.DataIn = SCSI_IOCTL_DATA_IN;
        sptwb.spt.DataTransferLength = 192;
        sptwb.spt.TimeOutValue = 2;
        sptwb.spt.DataBufferOffset =
           offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS,ucDataBuf);
        sptwb.spt.SenseInfoOffset =
           offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS,ucSenseBuf);
        sptwb.spt.Cdb[0] = SCSIOP_MODE_SENSE;
        sptwb.spt.Cdb[2] = MODE_SENSE_RETURN_ALL;
        sptwb.spt.Cdb[4] = 192;
        length = offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS,ucDataBuf) +
           sptwb.spt.DataTransferLength;

        status = DeviceIoControl(fileHandle,
                                 IOCTL_SCSI_PASS_THROUGH,
                                 &sptwb,
                                 sizeof(SCSI_PASS_THROUGH),
                                 &sptwb,
                                 length,
                                 &returned,
                                 FALSE);

        PrintStatusResults(status,returned,&sptwb,length);
    }


    printf("            ***** MODE SENSE -- return all pages *****\n");
    printf("            *****    without SenseInfo buffer    *****\n\n");

    if(srbType == 1)
    {
        ZeroMemory(&sptwb_ex,sizeof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX));
        sptwb_ex.spt.Version = 0;
        sptwb_ex.spt.Length = sizeof(SCSI_PASS_THROUGH_EX);
        sptwb_ex.spt.ScsiStatus = 0;
        sptwb_ex.spt.CdbLength = CDB6GENERIC_LENGTH;
        sptwb_ex.spt.StorAddressLength = sizeof(STOR_ADDR_BTL8);
        sptwb_ex.spt.SenseInfoLength = 0;
        sptwb_ex.spt.DataOutTransferLength = 0;
        sptwb_ex.spt.DataInTransferLength = 192;
        sptwb_ex.spt.DataDirection = SCSI_IOCTL_DATA_IN;
        sptwb_ex.spt.TimeOutValue = 2;
        sptwb_ex.spt.StorAddressOffset =
            offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,StorAddress);
        sptwb_ex.StorAddress.Type = STOR_ADDRESS_TYPE_BTL8;
        sptwb_ex.StorAddress.Port = 0;
        sptwb_ex.StorAddress.AddressLength = STOR_ADDR_BTL8_ADDRESS_LENGTH;
        sptwb_ex.StorAddress.Path = 0;
        sptwb_ex.StorAddress.Target = 1;
        sptwb_ex.StorAddress.Lun = 0;
        sptwb_ex.spt.SenseInfoOffset = 0;
        sptwb_ex.spt.DataOutBufferOffset = 0;
        sptwb_ex.spt.DataInBufferOffset =
           offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,ucDataBuf);
        sptwb_ex.spt.Cdb[0] = SCSIOP_MODE_SENSE;
        sptwb_ex.spt.Cdb[2] = MODE_SENSE_RETURN_ALL;
        sptwb_ex.spt.Cdb[4] = 192;
        length = offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,ucDataBuf) +
           sptwb_ex.spt.DataInTransferLength;

        status = DeviceIoControl(fileHandle,
                                 IOCTL_SCSI_PASS_THROUGH_EX,
                                 &sptwb_ex,
                                 sizeof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX),
                                 &sptwb_ex,
                                 length,
                                 &returned,
                                 FALSE);

        PrintStatusResultsEx(status,returned,&sptwb_ex,length);
    }
    else
    {
        ZeroMemory(&sptwb,sizeof(SCSI_PASS_THROUGH_WITH_BUFFERS));
        sptwb.spt.Length = sizeof(SCSI_PASS_THROUGH);
        sptwb.spt.PathId = 0;
        sptwb.spt.TargetId = 1;
        sptwb.spt.Lun = 0;
        sptwb.spt.CdbLength = CDB6GENERIC_LENGTH;
        sptwb.spt.SenseInfoLength = 0;
        sptwb.spt.DataIn = SCSI_IOCTL_DATA_IN;
        sptwb.spt.DataTransferLength = 192;
        sptwb.spt.TimeOutValue = 2;
        sptwb.spt.DataBufferOffset =
           offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS,ucDataBuf);
        sptwb.spt.Cdb[0] = SCSIOP_MODE_SENSE;
        sptwb.spt.Cdb[2] = MODE_SENSE_RETURN_ALL;
        sptwb.spt.Cdb[4] = 192;
        length = offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS,ucDataBuf) +
           sptwb.spt.DataTransferLength;

        status = DeviceIoControl(fileHandle,
                                 IOCTL_SCSI_PASS_THROUGH,
                                 &sptwb,
                                 sizeof(SCSI_PASS_THROUGH),
                                 &sptwb,
                                 length,
                                 &returned,
                                 FALSE);

        PrintStatusResults(status,returned,&sptwb,length);
    }


    printf("            *****      TEST UNIT READY      *****\n");
    printf("            *****   DataInBufferLength = 0  *****\n\n");

    if(srbType == 1)
    {
        ZeroMemory(&sptwb_ex,sizeof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX));
        sptwb_ex.spt.Version = 0;
        sptwb_ex.spt.Length = sizeof(SCSI_PASS_THROUGH_EX);
        sptwb_ex.spt.ScsiStatus = 0;
        sptwb_ex.spt.CdbLength = CDB6GENERIC_LENGTH;
        sptwb_ex.spt.StorAddressLength = sizeof(STOR_ADDR_BTL8);
        sptwb_ex.spt.SenseInfoLength = SPT_SENSE_LENGTH;
        sptwb_ex.spt.DataOutTransferLength = 0;
        sptwb_ex.spt.DataInTransferLength = 0;
        sptwb_ex.spt.DataDirection = SCSI_IOCTL_DATA_IN;
        sptwb_ex.spt.TimeOutValue = 2;
        sptwb_ex.spt.StorAddressOffset =
            offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,StorAddress);
        sptwb_ex.StorAddress.Type = STOR_ADDRESS_TYPE_BTL8;
        sptwb_ex.StorAddress.Port = 0;
        sptwb_ex.StorAddress.AddressLength = STOR_ADDR_BTL8_ADDRESS_LENGTH;
        sptwb_ex.StorAddress.Path = 0;
        sptwb_ex.StorAddress.Target = 1;
        sptwb_ex.StorAddress.Lun = 0;
        sptwb_ex.spt.SenseInfoOffset =
           offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,ucSenseBuf);
        sptwb_ex.spt.DataOutBufferOffset = 0;
        sptwb_ex.spt.DataInBufferOffset = 0;
        sptwb_ex.spt.Cdb[0] = SCSIOP_TEST_UNIT_READY;
        length = offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,ucDataBuf);

        status = DeviceIoControl(fileHandle,
                                 IOCTL_SCSI_PASS_THROUGH_EX,
                                 &sptwb_ex,
                                 sizeof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX),
                                 &sptwb_ex,
                                 length,
                                 &returned,
                                 FALSE);

        PrintStatusResultsEx(status,returned,&sptwb_ex,length);
    }
    else
    {
        ZeroMemory(&sptwb,sizeof(SCSI_PASS_THROUGH_WITH_BUFFERS));
        sptwb.spt.Length = sizeof(SCSI_PASS_THROUGH);
        sptwb.spt.PathId = 0;
        sptwb.spt.TargetId = 1;
        sptwb.spt.Lun = 0;
        sptwb.spt.CdbLength = CDB6GENERIC_LENGTH;
        sptwb.spt.SenseInfoLength = SPT_SENSE_LENGTH;
        sptwb.spt.DataIn = SCSI_IOCTL_DATA_IN;
        sptwb.spt.DataTransferLength = 0;
        sptwb.spt.TimeOutValue = 2;
        sptwb.spt.DataBufferOffset = 0;
        sptwb.spt.SenseInfoOffset =
           offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS,ucSenseBuf);
        sptwb.spt.Cdb[0] = SCSIOP_TEST_UNIT_READY;
        length = offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS,ucDataBuf);

        status = DeviceIoControl(fileHandle,
                                 IOCTL_SCSI_PASS_THROUGH,
                                 &sptwb,
                                 sizeof(SCSI_PASS_THROUGH),
                                 &sptwb,
                                 length,
                                 &returned,
                                 FALSE);

        PrintStatusResults(status,returned,&sptwb,length);
    }


    //
    //  Do a mode sense with a bad data buffer offset.  This will fail.
    //
    printf("            *****      MODE SENSE -- return all pages      *****\n");
    printf("            *****   bad DataBufferOffset -- should fail    *****\n\n");

    if(srbType == 1)
    {
        ZeroMemory(&sptwb_ex,sizeof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX));
        sptwb_ex.spt.Version = 0;
        sptwb_ex.spt.Length = sizeof(SCSI_PASS_THROUGH_EX);
        sptwb_ex.spt.ScsiStatus = 0;
        sptwb_ex.spt.CdbLength = CDB6GENERIC_LENGTH;
        sptwb_ex.spt.StorAddressLength = sizeof(STOR_ADDR_BTL8);
        sptwb_ex.spt.SenseInfoLength = SPT_SENSE_LENGTH;
        sptwb_ex.spt.DataOutTransferLength = 0;
        sptwb_ex.spt.DataInTransferLength = 192;
        sptwb_ex.spt.DataDirection = SCSI_IOCTL_DATA_IN;
        sptwb_ex.spt.TimeOutValue = 2;
        sptwb_ex.spt.StorAddressOffset =
            offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,StorAddress);
        sptwb_ex.StorAddress.Type = STOR_ADDRESS_TYPE_BTL8;
        sptwb_ex.StorAddress.Port = 0;
        sptwb_ex.StorAddress.AddressLength = STOR_ADDR_BTL8_ADDRESS_LENGTH;
        sptwb_ex.StorAddress.Path = 0;
        sptwb_ex.StorAddress.Target = 1;
        sptwb_ex.StorAddress.Lun = 0;
        sptwb_ex.spt.SenseInfoOffset =
           offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,ucSenseBuf);
        sptwb_ex.spt.DataOutBufferOffset = 0;
        sptwb_ex.spt.DataInBufferOffset = 0;
        sptwb_ex.spt.Cdb[0] = SCSIOP_MODE_SENSE;
        sptwb_ex.spt.Cdb[2] = MODE_SENSE_RETURN_ALL;
        sptwb_ex.spt.Cdb[4] = 192;
        length = offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,ucDataBuf) +
           sptwb_ex.spt.DataInTransferLength;

        status = DeviceIoControl(fileHandle,
                                 IOCTL_SCSI_PASS_THROUGH_EX,
                                 &sptwb_ex,
                                 sizeof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX),
                                 &sptwb_ex,
                                 length,
                                 &returned,
                                 FALSE);

        PrintStatusResultsEx(status,returned,&sptwb_ex,length);
    }
    else
    {
        ZeroMemory(&sptwb,sizeof(SCSI_PASS_THROUGH_WITH_BUFFERS));
        sptwb.spt.Length = sizeof(SCSI_PASS_THROUGH);
        sptwb.spt.PathId = 0;
        sptwb.spt.TargetId = 1;
        sptwb.spt.Lun = 0;
        sptwb.spt.CdbLength = CDB6GENERIC_LENGTH;
        sptwb.spt.SenseInfoLength = 0;
        sptwb.spt.DataIn = SCSI_IOCTL_DATA_IN;
        sptwb.spt.DataTransferLength = 192;
        sptwb.spt.TimeOutValue = 2;
        sptwb.spt.DataBufferOffset = 0;
        sptwb.spt.SenseInfoOffset =
           offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS,ucSenseBuf);
        sptwb.spt.Cdb[0] = SCSIOP_MODE_SENSE;
        sptwb.spt.Cdb[2] = MODE_SENSE_RETURN_ALL;
        sptwb.spt.Cdb[4] = 192;
        length = offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS,ucDataBuf) +
           sptwb.spt.DataTransferLength;

        status = DeviceIoControl(fileHandle,
                                 IOCTL_SCSI_PASS_THROUGH,
                                 &sptwb,
                                 sizeof(SCSI_PASS_THROUGH),
                                 &sptwb,
                                 length,
                                 &returned,
                                 FALSE);

        PrintStatusResults(status,returned,&sptwb,length);
    }


    //
    // Get caching mode sense page.
    //
    printf("            *****               MODE SENSE                  *****\n");
    printf("            *****     return caching mode sense page        *****\n\n");

    if(srbType == 1)
    {
        ZeroMemory(&sptwb_ex,sizeof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX));
        sptwb_ex.spt.Version = 0;
        sptwb_ex.spt.Length = sizeof(SCSI_PASS_THROUGH_EX);
        sptwb_ex.spt.ScsiStatus = 0;
        sptwb_ex.spt.CdbLength = CDB6GENERIC_LENGTH;
        sptwb_ex.spt.StorAddressLength = sizeof(STOR_ADDR_BTL8);
        sptwb_ex.spt.SenseInfoLength = SPT_SENSE_LENGTH;
        sptwb_ex.spt.DataOutTransferLength = 0;
        sptwb_ex.spt.DataInTransferLength = 192;
        sptwb_ex.spt.DataDirection = SCSI_IOCTL_DATA_IN;
        sptwb_ex.spt.TimeOutValue = 2;
        sptwb_ex.spt.StorAddressOffset =
            offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,StorAddress);
        sptwb_ex.StorAddress.Type = STOR_ADDRESS_TYPE_BTL8;
        sptwb_ex.StorAddress.Port = 0;
        sptwb_ex.StorAddress.AddressLength = STOR_ADDR_BTL8_ADDRESS_LENGTH;
        sptwb_ex.StorAddress.Path = 0;
        sptwb_ex.StorAddress.Target = 1;
        sptwb_ex.StorAddress.Lun = 0;
        sptwb_ex.spt.SenseInfoOffset =
           offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,ucSenseBuf);
        sptwb_ex.spt.DataOutBufferOffset = 0;
        sptwb_ex.spt.DataInBufferOffset =
           offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,ucDataBuf);
        sptwb_ex.spt.Cdb[0] = SCSIOP_MODE_SENSE;
        sptwb_ex.spt.Cdb[1] = 0x08; // target shall not return any block descriptors
        sptwb_ex.spt.Cdb[2] = MODE_PAGE_CACHING;
        sptwb_ex.spt.Cdb[4] = 192;
        length = offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX,ucDataBuf) +
           sptwb_ex.spt.DataInTransferLength;

        status = DeviceIoControl(fileHandle,
                                 IOCTL_SCSI_PASS_THROUGH_EX,
                                 &sptwb_ex,
                                 sizeof(SCSI_PASS_THROUGH_WITH_BUFFERS_EX),
                                 &sptwb_ex,
                                 length,
                                 &returned,
                                 FALSE);

        PrintStatusResultsEx(status,returned,&sptwb_ex,length);
    }
    else
    {
        ZeroMemory(&sptwb,sizeof(SCSI_PASS_THROUGH_WITH_BUFFERS));
        sptwb.spt.Length = sizeof(SCSI_PASS_THROUGH);
        sptwb.spt.PathId = 0;
        sptwb.spt.TargetId = 1;
        sptwb.spt.Lun = 0;
        sptwb.spt.CdbLength = CDB6GENERIC_LENGTH;
        sptwb.spt.SenseInfoLength = SPT_SENSE_LENGTH;
        sptwb.spt.DataIn = SCSI_IOCTL_DATA_IN;
        sptwb.spt.DataTransferLength = 192;
        sptwb.spt.TimeOutValue = 2;
        sptwb.spt.DataBufferOffset =
           offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS,ucDataBuf);
        sptwb.spt.SenseInfoOffset =
           offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS,ucSenseBuf);
        sptwb.spt.Cdb[0] = SCSIOP_MODE_SENSE;
        sptwb.spt.Cdb[1] = 0x08; // target shall not return any block descriptors
        sptwb.spt.Cdb[2] = MODE_PAGE_CACHING;
        sptwb.spt.Cdb[4] = 192;
        length = offsetof(SCSI_PASS_THROUGH_WITH_BUFFERS,ucDataBuf) +
           sptwb.spt.DataTransferLength;

        status = DeviceIoControl(fileHandle,
                                 IOCTL_SCSI_PASS_THROUGH,
                                 &sptwb,
                                 sizeof(SCSI_PASS_THROUGH),
                                 &sptwb,
                                 length,
                                 &returned,
                                 FALSE);

        PrintStatusResults(status,returned,&sptwb,length);
    }


    printf("            *****       WRITE DATA BUFFER operation         *****\n");
    
    dataBuffer = AllocateAlignedBuffer(sectorSize,alignmentMask, &pUnAlignedBuffer);
    FillMemory(dataBuffer,sectorSize/2,'N');
    FillMemory(dataBuffer + sectorSize/2,sectorSize/2,'T');

    if(srbType == 1)
    {
        ZeroMemory(&sptdwb_ex,sizeof(SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER_EX));
        sptdwb_ex.sptd.Version = 0;
        sptdwb_ex.sptd.Length = sizeof(SCSI_PASS_THROUGH_DIRECT_EX);
        sptdwb_ex.sptd.ScsiStatus = 0;
        sptdwb_ex.sptd.CdbLength = CDB10GENERIC_LENGTH;
        sptdwb_ex.sptd.StorAddressLength = sizeof(STOR_ADDR_BTL8);
        sptdwb_ex.sptd.SenseInfoLength = SPT_SENSE_LENGTH;
        sptdwb_ex.sptd.DataOutTransferLength = sectorSize;
        sptdwb_ex.sptd.DataInTransferLength = 0;
        sptdwb_ex.sptd.DataDirection = SCSI_IOCTL_DATA_OUT;
        sptdwb_ex.sptd.TimeOutValue = 2;
        sptdwb_ex.sptd.StorAddressOffset =
            offsetof(SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER_EX,StorAddress);
        sptdwb_ex.StorAddress.Type = STOR_ADDRESS_TYPE_BTL8;
        sptdwb_ex.StorAddress.Port = 0;
        sptdwb_ex.StorAddress.AddressLength = STOR_ADDR_BTL8_ADDRESS_LENGTH;
        sptdwb_ex.StorAddress.Path = 0;
        sptdwb_ex.StorAddress.Target = 1;
        sptdwb_ex.StorAddress.Lun = 0;
        sptdwb_ex.sptd.SenseInfoOffset = 
           offsetof(SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER_EX,ucSenseBuf);
        sptdwb_ex.sptd.DataOutBuffer = dataBuffer;
        sptdwb_ex.sptd.DataInBuffer = NULL;
        sptdwb_ex.sptd.Cdb[0] = SCSIOP_WRITE_DATA_BUFF;
        sptdwb_ex.sptd.Cdb[1] = 2;                         // Data mode
        sptdwb_ex.sptd.Cdb[7] = (UCHAR)(sectorSize >> 8);  // Parameter List length
        sptdwb_ex.sptd.Cdb[8] = 0;
        length = sizeof(SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER_EX);

        status = DeviceIoControl(fileHandle,
                                 IOCTL_SCSI_PASS_THROUGH_DIRECT_EX,
                                 &sptdwb_ex,
                                 length,
                                 &sptdwb_ex,
                                 length,
                                 &returned,
                                 FALSE);

        PrintStatusResultsEx(status,returned,
           (PSCSI_PASS_THROUGH_WITH_BUFFERS_EX)&sptdwb_ex,length);

        if ((sptdwb_ex.sptd.ScsiStatus == 0) && (status != 0)) {
           PrintDataBuffer(dataBuffer,sptdwb_ex.sptd.DataOutTransferLength);
        }
    }
Exemplo n.º 6
0
int main(int argc, char* argv[]) {
	int opt = 0;
	int optindex = 0;
	char* ipsw = NULL;
	char* uuid = NULL;
	int tss_enabled = 0;
	int shsh_only = 0;
	char* shsh_dir = NULL;
	use_apple_server=1;

	// create an instance of our context
	struct idevicerestore_client_t* client = (struct idevicerestore_client_t*) malloc(sizeof(struct idevicerestore_client_t));
	if (client == NULL) {
		error("ERROR: Out of memory\n");
		return -1;
	}
	memset(client, '\0', sizeof(struct idevicerestore_client_t));

	while ((opt = getopt_long(argc, argv, "dhcesxtpi:u:", longopts, &optindex)) > 0) {
		switch (opt) {
		case 'h':
			usage(argc, argv);
			return 0;

		case 'd':
			client->flags |= FLAG_DEBUG;
			idevicerestore_debug = 1;
			break;

		case 'e':
			client->flags |= FLAG_ERASE;
			break;

		case 'c':
			client->flags |= FLAG_CUSTOM;
			break;

		case 's':
			use_apple_server=0;
			break;

		case 'x':
			client->flags |= FLAG_EXCLUDE;
			break;

		case 'i':
			if (optarg) {
				char* tail = NULL;
				client->ecid = strtoull(optarg, &tail, 16);
				if (tail && (tail[0] != '\0')) {
					client->ecid = 0;
				}
				if (client->ecid == 0) {
					error("ERROR: Could not parse ECID from '%s'\n", optarg);
					return -1;
				}
			}
			break;

		case 'u':
			uuid = optarg;
			break;

		case 't':
			shsh_only = 1;
			break;

		case 'p':
			client->flags |= FLAG_PWN;
			break;

		default:
			usage(argc, argv);
			return -1;
		}
	}

	if (((argc-optind) == 1) || (client->flags & FLAG_PWN)) {
		argc -= optind;
		argv += optind;

		ipsw = argv[0];
	} else {
		usage(argc, argv);
		return -1;
	}

	if (client->flags & FLAG_DEBUG) {
		idevice_set_debug_level(1);
		irecv_set_debug_level(1);
	}

	client->uuid = uuid;
	client->ipsw = ipsw;

	// update version data (from cache, or apple if too old)
	load_version_data(client);

	// check which mode the device is currently in so we know where to start
	if (check_mode(client) < 0 || client->mode->index == MODE_UNKNOWN) {
		error("ERROR: Unable to discover device mode. Please make sure a device is attached.\n");
		return -1;
	}
	info("Found device in %s mode\n", client->mode->string);

	if (client->mode->index == MODE_WTF) {
		int cpid = 0;

		if (dfu_client_new(client) != 0) {
			error("ERROR: Could not open device in WTF mode\n");
			return -1;
		}
		if ((dfu_get_cpid(client, &cpid) < 0) || (cpid == 0)) { 
			error("ERROR: Could not get CPID for WTF mode device\n");
			dfu_client_free(client);
			return -1;
		}

		char* s_wtfurl = NULL;
		plist_t wtfurl = plist_access_path(client->version_data, 7, "MobileDeviceSoftwareVersionsByVersion", "5", "RecoverySoftwareVersions", "WTF", "304218112", "5", "FirmwareURL");
		if (wtfurl && (plist_get_node_type(wtfurl) == PLIST_STRING)) {
			plist_get_string_val(wtfurl, &s_wtfurl);
		}
		if (!s_wtfurl) {
			info("Using hardcoded x12220000_5_Recovery.ipsw URL\n");
			s_wtfurl = strdup("http://appldnld.apple.com.edgesuite.net/content.info.apple.com/iPhone/061-6618.20090617.Xse7Y/x12220000_5_Recovery.ipsw");
		}

		// make a local file name
		char* fnpart = strrchr(s_wtfurl, '/');
		if (!fnpart) {
			fnpart = "x12220000_5_Recovery.ipsw";
		} else {
			fnpart++;
		}
		struct stat fst;
		char wtfipsw[256];
		sprintf(wtfipsw, "cache/%s", fnpart);
		if (stat(wtfipsw, &fst) != 0) {
			__mkdir("cache", 0755);
			download_to_file(s_wtfurl, wtfipsw);
		}

		char wtfname[256];
		sprintf(wtfname, "Firmware/dfu/WTF.s5l%04xxall.RELEASE.dfu", cpid);
		char* wtftmp = NULL;
		uint32_t wtfsize = 0;
		ipsw_extract_to_memory(wtfipsw, wtfname, &wtftmp, &wtfsize);
		if (!wtftmp) {
			error("ERROR: Could not extract WTF\n");
		} else {
			if (dfu_send_buffer(client, wtftmp, wtfsize) != 0) {
				error("ERROR: Could not send WTF...\n");
			}
		}
		dfu_client_free(client);

		sleep(1);

		free(wtftmp);
		client->mode = &idevicerestore_modes[MODE_DFU];
	}

	// discover the device type
	if (check_device(client) < 0 || client->device->index == DEVICE_UNKNOWN) {
		error("ERROR: Unable to discover device type\n");
		return -1;
	}
	info("Identified device as %s\n", client->device->product);

	if ((client->flags & FLAG_PWN) && (client->mode->index != MODE_DFU)) {
		error("ERROR: you need to put your device into DFU mode to pwn it.\n");
		return -1;
	}

	if (client->flags & FLAG_PWN) {
		recovery_client_free(client);

		info("connecting to DFU\n");
		if (dfu_client_new(client) < 0) {
			return -1;
		}
		info("exploiting with limera1n...\n");
		// TODO: check for non-limera1n device and fail
		if (limera1n_exploit(client->device, client->dfu->client) != 0) {
			error("ERROR: limera1n exploit failed\n");
			dfu_client_free(client);
			return -1;
		}
		dfu_client_free(client);
		info("Device should be in pwned DFU state now.\n");

		return 0;
	}

	if (client->mode->index == MODE_RESTORE) {
		if (restore_reboot(client) < 0) {
			error("ERROR: Unable to exit restore mode\n");
			return -1;
		}
	}

	// extract buildmanifest
	plist_t buildmanifest = NULL;
	if (client->flags & FLAG_CUSTOM) {
		info("Extracting Restore.plist from IPSW\n");
		if (ipsw_extract_restore_plist(ipsw, &buildmanifest) < 0) {
			error("ERROR: Unable to extract Restore.plist from %s\n", ipsw);
			return -1;
		}
	} else {
		info("Extracting BuildManifest from IPSW\n");
		if (ipsw_extract_build_manifest(ipsw, &buildmanifest, &tss_enabled) < 0) {
			error("ERROR: Unable to extract BuildManifest from %s\n", ipsw);
			return -1;
		}
	}

	/* check if device type is supported by the given build manifest */
	if (build_manifest_check_compatibility(buildmanifest, client->device->product) < 0) {
		error("ERROR: could not make sure this firmware is suitable for the current device. refusing to continue.\n");
		return -1;
	}

	/* print iOS information from the manifest */
	build_manifest_get_version_information(buildmanifest, &client->version, &client->build);

	info("Product Version: %s\n", client->version);
	info("Product Build: %s\n", client->build);

	if (client->flags & FLAG_CUSTOM) {
		/* prevent signing custom firmware */
		tss_enabled = 0;
		info("Custom firmware requested. Disabled TSS request.\n");
	}

	// choose whether this is an upgrade or a restore (default to upgrade)
	client->tss = NULL;
	plist_t build_identity = NULL;
	if (client->flags & FLAG_CUSTOM) {
		build_identity = plist_new_dict();
		{
			plist_t node;
			plist_t comp;
			plist_t info;
			plist_t manifest;

			info = plist_new_dict();
			plist_dict_insert_item(info, "RestoreBehavior", plist_new_string((client->flags & FLAG_ERASE) ? "Erase" : "Update"));
			plist_dict_insert_item(info, "Variant", plist_new_string((client->flags & FLAG_ERASE) ? "Customer Erase Install (IPSW)" : "Customer Upgrade Install (IPSW)"));
			plist_dict_insert_item(build_identity, "Info", info);

			manifest = plist_new_dict();

			char tmpstr[256];
			char p_all_flash[128];
			char lcmodel[8];
			strcpy(lcmodel, client->device->model);
			int x = 0;
			while (lcmodel[x]) {
				lcmodel[x] = tolower(lcmodel[x]);
				x++;
			}

			sprintf(p_all_flash, "Firmware/all_flash/all_flash.%s.%s", lcmodel, "production");
			strcpy(tmpstr, p_all_flash);
			strcat(tmpstr, "/manifest");

			// get all_flash file manifest
			char *files[16];
			char *fmanifest = NULL;
			uint32_t msize = 0;
			if (ipsw_extract_to_memory(ipsw, tmpstr, &fmanifest, &msize) < 0) {
				error("ERROR: could not extract %s from IPSW\n", tmpstr);
				return -1;
			}

			char *tok = strtok(fmanifest, "\r\n");
			int fc = 0;
			while (tok) {
				files[fc++] = strdup(tok);
				if (fc >= 16) {
					break;
				}
				tok = strtok(NULL, "\r\n");
			}
			free(fmanifest);

			for (x = 0; x < fc; x++) {
				info = plist_new_dict();
				strcpy(tmpstr, p_all_flash);
				strcat(tmpstr, "/");
				strcat(tmpstr, files[x]);
				plist_dict_insert_item(info, "Path", plist_new_string(tmpstr));
				comp = plist_new_dict();
				plist_dict_insert_item(comp, "Info", info);
				const char* compname = get_component_name(files[x]);
				if (compname) {
					plist_dict_insert_item(manifest, compname, comp);
					if (!strncmp(files[x], "DeviceTree", 10)) {
						plist_dict_insert_item(manifest, "RestoreDeviceTree", plist_copy(comp));
					}
				} else {
					error("WARNING: unhandled component %s\n", files[x]);
					plist_free(comp);
				}
				free(files[x]);
				files[x] = NULL;
			}

			// add iBSS
			sprintf(tmpstr, "Firmware/dfu/iBSS.%s.%s.dfu", lcmodel, "RELEASE");
			info = plist_new_dict();
			plist_dict_insert_item(info, "Path", plist_new_string(tmpstr));
			comp = plist_new_dict();
			plist_dict_insert_item(comp, "Info", info);
			plist_dict_insert_item(manifest, "iBSS", comp);

			// add iBEC
			sprintf(tmpstr, "Firmware/dfu/iBEC.%s.%s.dfu", lcmodel, "RELEASE");
			info = plist_new_dict();
			plist_dict_insert_item(info, "Path", plist_new_string(tmpstr));
			comp = plist_new_dict();
			plist_dict_insert_item(comp, "Info", info);
			plist_dict_insert_item(manifest, "iBEC", comp);

			// add kernel cache
			node = plist_dict_get_item(buildmanifest, "KernelCachesByTarget");
			if (node && (plist_get_node_type(node) == PLIST_DICT)) {
				char tt[4];
				strncpy(tt, lcmodel, 3);
				tt[3] = 0;
				plist_t kdict = plist_dict_get_item(node, tt);
				if (kdict && (plist_get_node_type(kdict) == PLIST_DICT)) {
					plist_t kc = plist_dict_get_item(kdict, "Release");
					if (kc && (plist_get_node_type(kc) == PLIST_STRING)) {
						info = plist_new_dict();
						plist_dict_insert_item(info, "Path", plist_copy(kc));
						comp = plist_new_dict();
						plist_dict_insert_item(comp, "Info", info);
						plist_dict_insert_item(manifest, "KernelCache", comp);
						plist_dict_insert_item(manifest, "RestoreKernelCache", plist_copy(comp));

					}
				}
			}

			// add ramdisk
			node = plist_dict_get_item(buildmanifest, "RestoreRamDisks");
			if (node && (plist_get_node_type(node) == PLIST_DICT)) {
				plist_t rd = plist_dict_get_item(node, (client->flags & FLAG_ERASE) ? "User" : "Update");
				if (rd && (plist_get_node_type(rd) == PLIST_STRING)) {
					info = plist_new_dict();
					plist_dict_insert_item(info, "Path", plist_copy(rd));
					comp = plist_new_dict();
					plist_dict_insert_item(comp, "Info", info);
					plist_dict_insert_item(manifest, "RestoreRamDisk", comp);
				}
			}

			// add OS filesystem
			node = plist_dict_get_item(buildmanifest, "SystemRestoreImages");
			if (!node) {
				error("ERROR: missing SystemRestoreImages in Restore.plist\n");
			}
			plist_t os = plist_dict_get_item(node, "User");
			if (!os) {
				error("ERROR: missing filesystem in Restore.plist\n");
			} else {
				info = plist_new_dict();
				plist_dict_insert_item(info, "Path", plist_copy(os));
				comp = plist_new_dict();
				plist_dict_insert_item(comp, "Info", info);
				plist_dict_insert_item(manifest, "OS", comp);
			}

			// finally add manifest
			plist_dict_insert_item(build_identity, "Manifest", manifest);
		}
	} else if (client->flags & FLAG_ERASE) {
		build_identity = build_manifest_get_build_identity(buildmanifest, 0);
		if (build_identity == NULL) {
			error("ERROR: Unable to find any build identities\n");
			plist_free(buildmanifest);
			return -1;
		}
	} else {
		// loop through all build identities in the build manifest
		// and list the valid ones
		int i = 0;
		int valid_builds = 0;
		int build_count = build_manifest_get_identity_count(buildmanifest);
		for (i = 0; i < build_count; i++) {
			build_identity = build_manifest_get_build_identity(buildmanifest, i);
			valid_builds++;
		}
	}

	/* print information about current build identity */
	build_identity_print_information(build_identity);

	/* retrieve shsh blobs if required */
	if (tss_enabled) {
		debug("Getting device's ECID for TSS request\n");
		/* fetch the device's ECID for the TSS request */
		if (get_ecid(client, &client->ecid) < 0) {
			error("ERROR: Unable to find device ECID\n");
			return -1;
		}
		info("Found ECID " FMT_qu "\n", (long long unsigned int)client->ecid);

		if (get_shsh_blobs(client, client->ecid, NULL, 0, build_identity, &client->tss) < 0) {
			error("ERROR: Unable to get SHSH blobs for this device\n");
			return -1;
		}
	}

	if (shsh_only) {
		if (!tss_enabled) {
			info("This device does not require a TSS record");
			return 0;
		}
		if (!client->tss) {
			error("ERROR: could not fetch TSS record");
			plist_free(buildmanifest);
			return -1;
		} else {
			char *bin = NULL;
			uint32_t blen = 0;
			plist_to_bin(client->tss, &bin, &blen);
			if (bin) {
				char zfn[512];
				sprintf(zfn, "shsh/" FMT_qu "-%s-%s.shsh", (long long int)client->ecid, client->device->product, client->version);
				__mkdir("shsh", 0755);
				struct stat fst;
				if (stat(zfn, &fst) != 0) {
					gzFile zf = gzopen(zfn, "wb");
					gzwrite(zf, bin, blen);
					gzclose(zf);
					info("SHSH saved to '%s'\n", zfn);
				} else {
					info("SHSH '%s' already present.\n", zfn);
				}
				free(bin);
			} else {
				error("ERROR: could not get TSS record data\n");
			}
			plist_free(client->tss);
			plist_free(buildmanifest);
			return 0;
		}
	}

	/* verify if we have tss records if required */
	if ((tss_enabled) && (client->tss == NULL)) {
		error("ERROR: Unable to proceed without a TSS record.\n");
		plist_free(buildmanifest);
		return -1;
	}

	if ((tss_enabled) && client->tss) {
		/* fix empty dicts */
		fixup_tss(client->tss);
	}

	// Extract filesystem from IPSW and return its name
	char* filesystem = NULL;
	if (ipsw_extract_filesystem(client->ipsw, build_identity, &filesystem) < 0) {
		error("ERROR: Unable to extract filesystem from IPSW\n");
		if (client->tss)
			plist_free(client->tss);
		plist_free(buildmanifest);
		return -1;
	}

	// if the device is in normal mode, place device into recovery mode
	if (client->mode->index == MODE_NORMAL) {
		info("Entering recovery mode...\n");
		if (normal_enter_recovery(client) < 0) {
			error("ERROR: Unable to place device into recovery mode\n");
			if (client->tss)
				plist_free(client->tss);
			plist_free(buildmanifest);
			return -1;
		}
	}

	// if the device is in DFU mode, place device into recovery mode
	if (client->mode->index == MODE_DFU) {
		recovery_client_free(client);
		if (client->flags & FLAG_CUSTOM) {
			info("connecting to DFU\n");
			if (dfu_client_new(client) < 0) {
				return -1;
			}
			info("exploiting with limera1n\n");
			// TODO: check for non-limera1n device and fail
			if (limera1n_exploit(client->device, client->dfu->client) != 0) {
				error("ERROR: limera1n exploit failed\n");
				dfu_client_free(client);
				return -1;
			}
			dfu_client_free(client);
			info("exploited\n");
		}
		if (dfu_enter_recovery(client, build_identity) < 0) {
			error("ERROR: Unable to place device into recovery mode\n");
			plist_free(buildmanifest);
			if (client->tss)
				plist_free(client->tss);
			return -1;
		}
	}

	if (client->mode->index == MODE_DFU) {
		client->mode = &idevicerestore_modes[MODE_RECOVERY];
	} else {
		/* now we load the iBEC */
		if (recovery_send_ibec(client, build_identity) < 0) {
			error("ERROR: Unable to send iBEC\n");
			return -1;
		}
		recovery_client_free(client);
	
		/* this must be long enough to allow the device to run the iBEC */
		/* FIXME: Probably better to detect if the device is back then */
		sleep(7);
	}

	if (client->build[0] > '8') {
		// we need another tss request with nonce.
		unsigned char* nonce = NULL;
		int nonce_size = 0;
		int nonce_changed = 0;
		if (get_nonce(client, &nonce, &nonce_size) < 0) {
			error("ERROR: Unable to get nonce from device!\n");
			recovery_send_reset(client);
			return -1;
		}

		if (!client->nonce || (nonce_size != client->nonce_size) || (memcmp(nonce, client->nonce, nonce_size) != 0)) {
			nonce_changed = 1;
			if (client->nonce) {
				free(client->nonce);
			}
			client->nonce = nonce;
			client->nonce_size = nonce_size;
		} else {
			free(nonce);
		}

		info("Nonce: ");
		int i;
		for (i = 0; i < client->nonce_size; i++) {
			info("%02x ", client->nonce[i]);
		}
		info("\n");

		if (nonce_changed && !(client->flags & FLAG_CUSTOM)) {
			// Welcome iOS5. We have to re-request the TSS with our nonce.
			plist_free(client->tss);
			if (get_shsh_blobs(client, client->ecid, client->nonce, client->nonce_size, build_identity, &client->tss) < 0) {
				error("ERROR: Unable to get SHSH blobs for this device\n");
				return -1;
			}
			if (!client->tss) {
				error("ERROR: can't continue without TSS\n");
				return -1;
			}
			fixup_tss(client->tss);
		}
	}

	// now finally do the magic to put the device into restore mode
	if (client->mode->index == MODE_RECOVERY) {
		if (client->srnm == NULL) {
			error("ERROR: could not retrieve device serial number. Can't continue.\n");
			return -1;
		}
		if (recovery_enter_restore(client, build_identity) < 0) {
			error("ERROR: Unable to place device into restore mode\n");
			plist_free(buildmanifest);
			if (client->tss)
				plist_free(client->tss);
			return -1;
		}
	}

	// device is finally in restore mode, let's do this
	if (client->mode->index == MODE_RESTORE) {
		info("About to restore device... \n");
		if (restore_device(client, build_identity, filesystem) < 0) {
			error("ERROR: Unable to restore device\n");
			return -1;
		}
	}

	info("Cleaning up...\n");
	if (filesystem)
		unlink(filesystem);

	info("DONE\n");
	return 0;
}
/*start function*/
int gravacao ()
{
    system("title grava e le arquivo");
    FILE *p;
    char nome[20],tele[10], opcao;
    
    
    p = fopen("dados.001","rt");
    
    if (p==NULL){
                 
                 printf("\n ....:Programa Dados Alunos:.....\n\n");
                 printf("\n arquivo nao existe...novo criado\n");
                 p= fopen("dados.001","wt");
                 if (p == NULL) return (-1);
                 }else{
                       printf("\t ....:Programa Dados Alunos:.....\n\n");
                       printf("\nlogado\n");
                       fclose(p);
                       p = fopen("dados.001", "at");
                       }
                while (1){
                      printf("\n<C A D A S T R O>\n\n\n\n");                      
                      printf("\nNome :");
                      scanf("%s", nome);
                      printf("\nTelefone :");
                      scanf("%s", tele); 
                
                 printf("\nconfirma gravar este registro? [s/n]:");
                 do{
                      opcao = getchar();
                      }while (tolower(opcao) != 's' && tolower(opcao) != 'n');
                      
                      if (tolower(opcao) == ' '){
                           fprintf(p, "%s %s\n", nome, tele);
                           printf("\n registro gravado");
                         }
                         
                         else{printf("\n registro nao gravado");
                              }
                              
                 printf("\ndeseja continuar gravando este registro? [s/n]:");
                   do{
                      opcao = getchar();
                      }while (tolower(opcao) != 's' && tolower(opcao) != 'n');
                      if (tolower(opcao) == 'n'){
                           printf("fim da gravacao");
                           break;}
                            
                            }                                                             
                                                                                                
                 fprintf(p,"%s %s \n",nome, tele);
                 
                                
                                                  
                 fclose(p);
                                    
                 main();
        
    

}
Exemplo n.º 8
0
char* strlower(char * str) {//changes string in place
  if (str==NULL) return NULL;
  int i=0;
  while (str[i]!=0) { str[i]=tolower(str[i]); i++; }
  return str;
}
Exemplo n.º 9
0
bool startsiWith(const char* s, const char* prefix) {
 if (prefix==NULL || s==NULL) return false;
 int i=0;
 while (prefix[i]!='\0' && tolower(prefix[i])==tolower(s[i])) i++;
 return (prefix[i]=='\0');
 }
Exemplo n.º 10
0
/* take the current date and see if the range "date" passes it */
static boolean check_time(const void *AT, const char *times, int len, int rule)
{
     boolean not,pass;
     int marked_day, time_start, time_end;
     const TIME *at;
     int i,j=0;

     at = AT;
     D(("chcking: 0%o/%.4d vs. %s", at->day, at->minute, times));

     if (times == NULL) {
	  /* this should not happen */
	  _log_err("internal error: " __FILE__ " line %d", __LINE__);
	  return FALSE;
     }

     if (times[j] == '!') {
	  ++j;
	  not = TRUE;
     } else {
	  not = FALSE;
     }

     for (marked_day = 0; len > 0 && isalpha(times[j]); --len) {
	  int this_day=-1;

	  D(("%c%c ?", times[j], times[j+1]));
	  for (i=0; days[i].d != NULL; ++i) {
	       if (tolower(times[j]) == days[i].d[0]
		   && tolower(times[j+1]) == days[i].d[1] ) {
		    this_day = days[i].bit;
		    break;
	       }
	  }
	  j += 2;
	  if (this_day == -1) {
	       _log_err("bad day specified (rule #%d)", rule);
	       return FALSE;
	  }
	  marked_day ^= this_day;
     }
     if (marked_day == 0) {
	  _log_err("no day specified");
	  return FALSE;
     }
     D(("day range = 0%o", marked_day));

     time_start = 0;
     for (i=0; len > 0 && i < 4 && isdigit(times[i+j]); ++i, --len) {
	  time_start *= 10;
	  time_start += times[i+j]-'0';        /* is this portable? */
     }
     j += i;

     if (times[j] == '-') {
	  time_end = 0;
	  for (i=1; len > 0 && i < 5 && isdigit(times[i+j]); ++i, --len) {
	       time_end *= 10;
	       time_end += times[i+j]-'0';    /* is this portable */
	  }
	  j += i;
     } else
	  time_end = -1;

     D(("i=%d, time_end=%d, times[j]='%c'", i, time_end, times[j]));
     if (i != 5 || time_end == -1) {
	  _log_err("no/bad times specified (rule #%d)", rule);
	  return TRUE;
     }
     D(("times(%d to %d)", time_start,time_end));
     D(("marked_day = 0%o", marked_day));

     /* compare with the actual time now */

     pass = FALSE;
     if (time_start < time_end) {    /* start < end ? --> same day */
	  if ((at->day & marked_day) && (at->minute >= time_start)
	      && (at->minute < time_end)) {
	       D(("time is listed"));
	       pass = TRUE;
	  }
     } else {                                    /* spans two days */
	  if ((at->day & marked_day) && (at->minute >= time_start)) {
	       D(("caught on first day"));
	       pass = TRUE;
	  } else {
	       marked_day <<= 1;
	       marked_day |= (marked_day & 0200) ? 1:0;
	       D(("next day = 0%o", marked_day));
	       if ((at->day & marked_day) && (at->minute <= time_end)) {
		    D(("caught on second day"));
		    pass = TRUE;
	       }
	  }
     }

     return (not ^ pass);
}
Exemplo n.º 11
0
OSCL_EXPORT_REF char oscl_tolower(const char car)
{
    return tolower(car);
}
Exemplo n.º 12
0
void *processline(char *s) {
	char name[80],value[80];
	int nvstate = 0;


	memset (name,0,sizeof name);
	memset (value,0,sizeof value);

	do {
		*s = tolower(*s);

		if ( *s == ' ' || *s == '\t')
			continue;
		if ( *s == ';' || *s == '#' || *s == '\r' || *s == '\n' )
			break;
		if ( *s == '=' ) {
			nvstate = 1;
			continue;
		}
		if (!nvstate)
			strncat(name, s, 1);
		else
			strncat(value, s, 1);
	} while (*(s++));

	if (debug)
		debugmsg("config: %s, %s", name, value);

	if ( !strcmp(name,"host") )
		add_server(value);
	else if (!strcmp(name,"retryinterval") )
		pc.retryinterval = atoi(value);
	else if (!strcmp(name,"maxretries") )
		pc.maxretries = atoi(value);
	else if (!strcmp(name,"listenaddress") )
		strcpy(pc.listen_addr, value);
	else if (!strcmp(name,"listenport") )
		pc.listen_port = atoi(value);
	else if (!strcmp(name,"asteriskwritetimeout") )
		pc.asteriskwritetimeout = atoi(value);
	else if (!strcmp(name,"clientwritetimeout") )
		pc.clientwritetimeout = atoi(value);
	else if (!strcmp(name,"sslclienthellotimeout") )
		pc.sslclhellotimeout = atoi(value);
	else if (!strcmp(name,"authrequired") )
		pc.authrequired = strcmp(value,"yes") ? 0 : 1;
	else if (!strcmp(name,"acceptencryptedconnection") )
		pc.acceptencryptedconnection = strcmp(value,"yes") ? 0 : 1;
	else if (!strcmp(name,"acceptunencryptedconnection") )
		pc.acceptunencryptedconnection = strcmp(value,"yes") ? 0 : 1;
	else if (!strcmp(name,"certfile") )
		strcpy(pc.certfile, value);
	else if (!strcmp(name,"proxykey") )
		strcpy(pc.key, value);
	else if (!strcmp(name,"proc_user") )
		strcpy(pc.proc_user, value);
	else if (!strcmp(name,"proc_group") )
		strcpy(pc.proc_group, value);
	else if (!strcmp(name,"logfile") )
		strcpy(pc.logfile, value);
	else if (!strcmp(name,"autofilter") )
		pc.autofilter = strcmp(value,"on") ? 0 : 1;
	else if (!strcmp(name,"outputformat") )
		strcpy(pc.outputformat, value);
	else if (!strcmp(name,"inputformat") )
		strcpy(pc.inputformat, value);

	return 0;
}
Exemplo n.º 13
0
//Format:
//caid:prov:srvid:pid:chid:ecmlen=caid:prov:srvid:pid:chid:ecmlen[,validfrom,validto]
//validfrom: default=-2000
//validto: default=4000
//valid time if found in cache
static struct s_cacheex_matcher *cacheex_matcher_read_int(void)
{
	FILE *fp = open_config_file(cs_cacheex_matcher);
	if(!fp)
		{ return NULL; }

	char token[1024];
	uint8_t type;
	int32_t i, ret, count = 0;
	struct s_cacheex_matcher *new_cacheex_matcher = NULL, *entry, *last = NULL;
	uint32_t line = 0;

	while(fgets(token, sizeof(token), fp))
	{
		line++;
		if(strlen(token) <= 1) { continue; }
		if(token[0] == '#' || token[0] == '/') { continue; }
		if(strlen(token) > 100) { continue; }

		for(i = 0; i < (int)strlen(token); i++)
		{
			if((token[i] == ':' || token[i] == ' ') && token[i + 1] == ':')
			{
				memmove(token + i + 2, token + i + 1, strlen(token) - i + 1);
				token[i + 1] = '0';
			}
			if(token[i] == '#' || token[i] == '/')
			{
				token[i] = '\0';
				break;
			}
		}

		type = 'm';
		uint32_t caid = 0, provid = 0, srvid = 0, pid = 0, chid = 0, ecmlen = 0;
		uint32_t to_caid = 0, to_provid = 0, to_srvid = 0, to_pid = 0, to_chid = 0, to_ecmlen = 0;
		int32_t valid_from = -2000, valid_to = 4000;

		ret = sscanf(token, "%c:%4x:%6x:%4x:%4x:%4x:%4X=%4x:%6x:%4x:%4x:%4x:%4X,%4d,%4d",
					 &type,
					 &caid, &provid, &srvid, &pid, &chid, &ecmlen,
					 &to_caid, &to_provid, &to_srvid, &to_pid, &to_chid, &to_ecmlen,
					 &valid_from, &valid_to);

		type = tolower(type);

		if(ret < 7 || type != 'm')
			{ continue; }

		if(!cs_malloc(&entry, sizeof(struct s_cacheex_matcher)))
		{
			fclose(fp);
			return new_cacheex_matcher;
		}
		count++;
		entry->line = line;
		entry->type = type;
		entry->caid = caid;
		entry->provid = provid;
		entry->srvid = srvid;
		entry->pid = pid;
		entry->chid = chid;
		entry->ecmlen = ecmlen;
		entry->to_caid = to_caid;
		entry->to_provid = to_provid;
		entry->to_srvid = to_srvid;
		entry->to_pid = to_pid;
		entry->to_chid = to_chid;
		entry->to_ecmlen = to_ecmlen;
		entry->valid_from = valid_from;
		entry->valid_to = valid_to;

		cs_log_dbg(D_TRACE, "cacheex-matcher: %c: %04X@%06X:%04X:%04X:%04X:%02X = %04X@%06X:%04X:%04X:%04X:%02X valid %d/%d",
					entry->type, entry->caid, entry->provid, entry->srvid, entry->pid, entry->chid, entry->ecmlen,
					entry->to_caid, entry->to_provid, entry->to_srvid, entry->to_pid, entry->to_chid, entry->to_ecmlen,
					entry->valid_from, entry->valid_to);

		if(!new_cacheex_matcher)
		{
			new_cacheex_matcher = entry;
			last = new_cacheex_matcher;
		}
		else
		{
			last->next = entry;
			last = entry;
		}
	}

	if(count)
		{ cs_log("%d entries read from %s", count, cs_cacheex_matcher); }

	fclose(fp);

	return new_cacheex_matcher;
}
Exemplo n.º 14
0
TA_RetCode TA_GetFuncHandle( const char *name, const TA_FuncHandle **handle )
{
   TA_PROLOG
   char firstChar, tmp;
   const TA_FuncDef **funcDefTable;
   const TA_FuncDef *funcDef;
   const TA_FuncInfo *funcInfo;
   unsigned int i, funcDefTableSize;

   TA_TRACE_BEGIN( TA_GetFuncHandle );

   /* A TA_FuncHandle is internally a TA_FuncDef. Let's find it
    * by using the alphabetical tables.
    */
   if( (name == NULL) || (handle == NULL) )
   {
      TA_TRACE_RETURN( TA_BAD_PARAM );
   }

   *handle = NULL;

   firstChar = name[0];

   if( firstChar == '\0' )
   {
      TA_TRACE_RETURN( TA_BAD_PARAM );
   }

   tmp = (char)tolower( firstChar );

   if( (tmp < 'a') || (tmp > 'z') )
   {
      TA_TRACE_RETURN( TA_FUNC_NOT_FOUND );
   }

   /* Identify the table. */
   tmp -= (char)'a';
   funcDefTable = TA_DEF_Tables[(int)tmp];

   /* Identify the table size. */
   funcDefTableSize = *TA_DEF_TablesSize[(int)tmp];
   if( funcDefTableSize < 1 )
   {
      TA_TRACE_RETURN( TA_FUNC_NOT_FOUND );
   }

   /* Iterate all entries of the table and return as soon as found. */
   for( i=0; i < funcDefTableSize; i++ )
   {
      funcDef = funcDefTable[i];
      TA_DEBUG_ASSERT( funcDef != NULL );
      TA_DEBUG_ASSERT( funcDef->funcInfo != NULL );

      funcInfo = funcDef->funcInfo;      
      TA_DEBUG_ASSERT( funcInfo != NULL );
      
      if( strcmp( funcInfo->name, name ) == 0 )
      {
         *handle = (TA_FuncHandle *)funcDef;
         TA_TRACE_RETURN( TA_SUCCESS );
      }
   }

   TA_TRACE_RETURN( TA_FUNC_NOT_FOUND );
}
Exemplo n.º 15
0
int builtin_which(Environment &env, const std::vector<std::string> &tokens, const fdmask &fds) {

	// which [-a] [-p] [command]
	bool _a = false;
	bool _p = false;
	bool error = false;

	std::vector<std::string> argv = getopt(tokens, [&](char c){
		switch(tolower(c))
		{
			case 'a': _a = true; break;
			case 'p': _p = true; break;

			default:
				fdprintf(stderr, "### Which - \"-%c\" is not an option.\n", c);
				error = true;
				break;
		}
	});

	if (argv.size() > 1) {
		fdprintf(stderr, "### Which - Too many parameters were specified.\n");
		error = true;
	}

	if (error) {
		fdprintf(stderr, "# Usage - Which [-a] [-p] [name]\n");
		return 1;
	}

	std::string s = env.get("commands");
	string_splitter ss(s, ',');

	if (argv.empty()) {
		// just print the paths.
		for (; ss; ++ss) {
			fdprintf(stdout, "%s\n", ss->c_str());
		}
		return 0;
	}
	std::string target = argv[0];
	

	bool found = false;

	// if absolute or relative path, check that.
	if (target.find_first_of("/:") != target.npos) {

		std::error_code ec;
		fs::path p(ToolBox::MacToUnix(target));

		if (fs::exists(p, ec)) {
			fdprintf(stdout, "%s\n", quote(p).c_str());
			return 0;
		}
		else {
			fdprintf(stderr, "### Which - File \"%s\" not found.\n", target.c_str());
			return 2;
		}
	}

	for(; ss; ++ss) {
		if (_p) fdprintf(stderr, "checking %s\n", ss->c_str());

		std::error_code ec;
		fs::path p(ToolBox::MacToUnix(ss->c_str()));

		p /= target;
		if (fs::exists(p, ec)) {
			found = true;
			fdprintf(stdout, "%s\n", quote(p).c_str());
			if (!_a) break;
		}

	}

	// check builtins...
	if (!found || _a) {

		static const char *builtins[] = {
			"aboutbox",
			"alias",
			"catenate",
			"directory",
			"echo",
			"execute",
			"exists",
			"export",
			"help",
			"false", // not in MPW
			"parameters",
			"quote",
			"set",
			"shift",
			"true", // not in MPW
			"unalias",
			"unexport",
			"unset",
			"version",
			"which",
		};

		lowercase(target);

		auto iter = std::find(std::begin(builtins), std::end(builtins), target);
		if (iter != std::end(builtins)) {
			fdprintf(stdout, "%s\n", *iter);
			found = true;
		}

	}

	if (found) return 0;

	// also check built-ins?

	fdprintf(stderr, "### Which - Command \"%s\" was not found.\n", target.c_str());
	return 2; // not found.
}
Exemplo n.º 16
0
/*
 * Identify a character, allow recall of monsters
 *
 * Several "special" responses recall "multiple" monsters:
 *   ^A (all monsters)
 *   ^U (all unique monsters)
 *   ^N (all non-unique monsters)
 *
 * The responses may be sorted in several ways, see below.
 *
 * Note that the player ghosts are ignored. XXX XXX XXX
 */
void do_cmd_query_symbol(void)
{
	int		i, n, r_idx;
	char	sym, query;
	char	buf[128];

	bool	all = FALSE;
	bool	uniq = FALSE;
	bool	norm = FALSE;
	char temp[80] = "";

	bool	recall = FALSE;

	u16b	why = 0;
	u16b	*who;


	/* Get a character, or abort */
#ifdef JP
	if (!get_com("知りたい文字を入力して下さい(記号 or ^A全,^Uユ,^N非ユ,^M名前): ", &sym)) return;
#else
	if (!get_com("Enter character to be identified(^A:All,^U:Uniqs,^N:Non uniqs,^M:Name): ", &sym)) return;
#endif


	/* Find that character info, and describe it */
	for (i = 0; ident_info[i]; ++i)
	{
		if (sym == ident_info[i][0]) break;
	}

	/* Describe */
	if (sym == KTRL('A'))
	{
		all = TRUE;
#ifdef JP
		strcpy(buf, "全モンスターのリスト");
#else
		strcpy(buf, "Full monster list.");
#endif

	}
	else if (sym == KTRL('U'))
	{
		all = uniq = TRUE;
#ifdef JP
		strcpy(buf, "ユニーク・モンスターのリスト");
#else
		strcpy(buf, "Unique monster list.");
#endif

	}
	else if (sym == KTRL('N'))
	{
		all = norm = TRUE;
#ifdef JP
		strcpy(buf, "ユニーク外モンスターのリスト");
#else
		strcpy(buf, "Non-unique monster list.");
#endif

	}
	/* XTRA HACK WHATSEARCH */
	else if (sym == KTRL('M'))
	{
		all = TRUE;
#ifdef JP
		if (!get_string("名前(英語の場合小文字で可)",temp, 70))
#else
		if (!get_string("Enter name:",temp, 70))
#endif
		{
		     temp[0] = 0;
		     all = FALSE;
		}
#ifdef JP
		sprintf(buf, "名前:%sにマッチ",temp);
#else
		sprintf(buf, "Monsters with a name \"%s\"",temp);
#endif
	}
	else if (ident_info[i])
	{
#ifdef JP
		sprintf(buf, "%c - %s", sym, ident_info[i] + 2);
#else
		sprintf(buf, "%c - %s.", sym, ident_info[i] + 2);
#endif
	}
	else
	{
#ifdef JP
		sprintf(buf, "%c - %s", sym, "無効な文字");
#else
		sprintf(buf, "%c - %s.", sym, "Unknown Symbol");
#endif
	}

	/* Display the result */
	prt(buf, 0, 0);

	/* Allocate the "who" array */
	C_MAKE(who, max_r_idx, u16b);

	/* Collect matching monsters */
	for (n = 0, i = 1; i < max_r_idx; i++)
	{
		monster_race *r_ptr = &r_info[i];

		/* Nothing to recall */
		if (!cheat_know && !r_ptr->r_sights) continue;

		/* Require non-unique monsters if needed */
		if (norm && (r_ptr->flags1 & (RF1_UNIQUE))) continue;

		/* Require unique monsters if needed */
		if (uniq && !(r_ptr->flags1 & (RF1_UNIQUE))) continue;

		/* XTRA HACK WHATSEARCH */
		if (temp[0])
		{
			int xx;
			char temp2[80];
			
			for (xx=0; temp[xx] && xx<80; xx++)
			{
#ifdef JP
				if (iskanji(temp[xx])) { xx++; continue; }
#endif
				if (isupper(temp[xx])) temp[xx]=tolower(temp[xx]);
			}

#ifdef JP
			strcpy(temp2, r_name+r_ptr->E_name);
#else
			strcpy(temp2, r_name+r_ptr->name);
#endif

			for (xx=0; temp2[xx] && xx<80; xx++)
			{
				if (isupper(temp2[xx])) temp2[xx] = tolower(temp2[xx]);
			}

#ifdef JP
			if (my_strstr(temp2, temp) || my_strstr(r_name + r_ptr->name, temp))
#else
			if (my_strstr(temp2, temp))
#endif
				who[n++]=i;
		}
		else
		/* Collect "appropriate" monsters */
		if (all || (r_ptr->d_char == sym)) who[n++] = i;
	}

	if (!n)
	{
		/* XXX XXX Free the "who" array */
		C_KILL(who, max_r_idx, u16b);

		return;
	}

	/* Prompt XXX XXX XXX */
#ifdef JP
	put_str("思い出を見ますか? (k:殺害順/y/n): ", 0, 36);
#else
	put_str("Recall details? (k/y/n): ", 0, 40);
#endif


	/* Query */
	query = inkey();

	/* Restore */
	prt(buf, 0, 0);

	why = 2;

	/* Select the sort method */
	ang_sort_comp = ang_sort_comp_hook;
	ang_sort_swap = ang_sort_swap_hook;

	/* Sort the array */
	ang_sort(who, &why, n);

	/* Sort by kills (and level) */
	if (query == 'k')
	{
		why = 4;
		query = 'y';
	}

	/* Catch "escape" */
	if (query != 'y')
	{
		/* XXX XXX Free the "who" array */
		C_KILL(who, max_r_idx, u16b);

		return;
	}

	/* Sort if needed */
	if (why == 4)
	{
		/* Select the sort method */
		ang_sort_comp = ang_sort_comp_hook;
		ang_sort_swap = ang_sort_swap_hook;

		/* Sort the array */
		ang_sort(who, &why, n);
	}


	/* Start at the end */
	i = n - 1;

	/* Scan the monster memory */
	while (1)
	{
		/* Extract a race */
		r_idx = who[i];

		/* Hack -- Auto-recall */
		monster_race_track(r_idx);

		/* Hack -- Handle stuff */
		handle_stuff();

		/* Hack -- Begin the prompt */
		roff_top(r_idx);

		/* Hack -- Complete the prompt */
#ifdef JP
		Term_addstr(-1, TERM_WHITE, " ['r'思い出, ESC]");
#else
		Term_addstr(-1, TERM_WHITE, " [(r)ecall, ESC]");
#endif


		/* Interact */
		while (1)
		{
			/* Recall */
			if (recall)
			{
				/* Save the screen */
				screen_save();

				/* Recall on screen */
				screen_roff(who[i], 0);

				/* Hack -- Complete the prompt (again) */
#ifdef JP
				Term_addstr(-1, TERM_WHITE, " ['r'思い出, ESC]");
#else
				Term_addstr(-1, TERM_WHITE, " [(r)ecall, ESC]");
#endif

			}

			/* Command */
			query = inkey();

			/* Unrecall */
			if (recall)
			{
				/* Restore */
				screen_load();
			}

			/* Normal commands */
			if (query != 'r') break;

			/* Toggle recall */
			recall = !recall;
		}

		/* Stop scanning */
		if (query == ESCAPE) break;

		/* Move to "prev" monster */
		if (query == '-')
		{
			if (++i == n)
			{
				i = 0;
				if (!expand_list) break;
			}
		}

		/* Move to "next" monster */
		else
		{
			if (i-- == 0)
			{
				i = n - 1;
				if (!expand_list) break;
			}
		}
	}

	/* Free the "who" array */
	C_KILL(who, max_r_idx, u16b);

	/* Re-display the identity */
	prt(buf, 0, 0);
}
Exemplo n.º 17
0
Arquivo: tftpd.c Projeto: 274914765/C
/*
 * Handle initial connection protocol.
 */
void tftp (struct tftphdr *tp, int size)
{
    register char *cp;

    int first = 1, ecode;

    register struct formats *pf;

    char *filename, *mode;

    filename = cp = tp->th_stuff;
  again:
    while (cp < buf + size)
    {
        if (*cp == '\0')
            break;
        cp++;
    }
    if (*cp != '\0')
    {
        nak (EBADOP);
        exit (1);
    }
    if (first)
    {
        mode = ++cp;
        first = 0;
        goto again;
    }
    for (cp = mode; *cp; cp++)
        if (isupper (*cp))
            *cp = tolower (*cp);
    for (pf = formats; pf->f_mode; pf++)
        if (strcmp (pf->f_mode, mode) == 0)
            break;
    if (pf->f_mode == 0)
    {
        nak (EBADOP);
        exit (1);
    }
    ecode = (*pf->f_validate) (&filename, tp->th_opcode);
    if (logging)
    {
        syslog (LOG_INFO, "%s: %s request for %s: %s",
                verifyhost (&from), tp->th_opcode == WRQ ? "write" : "read", filename, errtomsg (ecode));
    }
    if (ecode)
    {
        /*
         * Avoid storms of naks to a RRQ broadcast for a relative
         * bootfile pathname from a diskless Sun.
         */
        if (suppress_naks && *filename != '/' && ecode == ENOTFOUND)
            exit (0);
        nak (ecode);
        exit (1);
    }
    if (tp->th_opcode == WRQ)
        (*pf->f_recv) (pf);
    else
        (*pf->f_send) (pf);
    exit (0);
}
Exemplo n.º 18
0
/*
 *  research_mon
 *  -KMW-
 */
bool research_mon(void)
{
	int i, n, r_idx;
	char sym, query;
	char buf[128];

	s16b oldkills;
	byte oldwake;
	bool oldcheat;

	bool notpicked;

	bool recall = FALSE;

	u16b why = 0;

	monster_race *r2_ptr;

	u16b	*who;

#ifdef JP
	/* XTRA HACK WHATSEARCH */
	bool    all = FALSE;
	bool    uniq = FALSE;
	bool    norm = FALSE;
	char temp[80] = "";

	/* XTRA HACK REMEMBER_IDX */
	static int old_sym = '\0';
	static int old_i = 0;
#endif
	oldcheat = cheat_know;


	/* Save the screen */
	screen_save();

	/* Get a character, or abort */
#ifdef JP
if (!get_com("モンスターの文字を入力して下さい(記号 or ^A全,^Uユ,^N非ユ,^M名前):", &sym)) 
#else
	if (!get_com("Enter character of monster: ", &sym))
#endif

	{
		/* Restore */
		screen_load();

		return (FALSE);
	}

	/* Allocate the "who" array */
	C_MAKE(who, max_r_idx, u16b);

	/* Find that character info, and describe it */
	for (i = 0; ident_info[i]; ++i)
	{
		if (sym == ident_info[i][0]) break;
	}

#ifdef JP
		/* XTRA HACK WHATSEARCH */
	if (sym == KTRL('A'))
	{
		all = TRUE;
		strcpy(buf, "全モンスターのリスト");
	}
	else if (sym == KTRL('U'))
	{
		all = uniq = TRUE;
		strcpy(buf, "ユニーク・モンスターのリスト");
	}
	else if (sym == KTRL('N'))
	{
		all = norm = TRUE;
		strcpy(buf, "ユニーク外モンスターのリスト");
	}
	else if (sym == KTRL('M'))
	{
		all = TRUE;
		if (!get_string("名前(英語の場合小文字で可)", temp, 70))
		{
		     all = FALSE;
		     temp[0] = 0;
		}
		sprintf(buf, "名前:%sにマッチ",temp);
	}

	else if (ident_info[i])
	{
		sprintf(buf, "%c - %s.", sym, ident_info[i] + 2);
	}
#else
	if (ident_info[i])
	{
		sprintf(buf, "%c - %s.", sym, ident_info[i] + 2);
	}
#endif
	else
	{
#ifdef JP
	  sprintf(buf, "%c - %s", sym, "無効な文字");
#else
		sprintf(buf, "%c - %s.", sym, "Unknown Symbol");
#endif

	}

	/* Display the result */
	prt(buf, 16, 10);


	/* Collect matching monsters */
	for (n = 0, i = 1; i < max_r_idx; i++)
	{
		monster_race *r_ptr = &r_info[i];

		cheat_know = TRUE;

#ifdef JP
		/* XTRA HACK WHATSEARCH */
		/* Require non-unique monsters if needed */
		if (norm && (r_ptr->flags1 & (RF1_UNIQUE))) continue;

		/* Require unique monsters if needed */
		if (uniq && !(r_ptr->flags1 & (RF1_UNIQUE))) continue;

		/* 名前検索 */
		if (temp[0]){
		    char temp2[80];
		    int xx;

		    for (xx=0; temp[xx] && xx<80; xx++){
		      if (iskanji(temp[xx])) { xx++; continue; }
		      if (isupper(temp[xx])) temp[xx]=tolower(temp[xx]);
		    }

		    strcpy(temp2, r_name+r_ptr->E_name);

		    for (xx=0; temp2[xx] && xx<80; xx++)
		      if (isupper(temp2[xx])) temp2[xx]=tolower(temp2[xx]);

		    if (my_strstr(temp2, temp) || my_strstr(r_name + r_ptr->name, temp) ) who[n++]=i;
		}

		else if (all || (r_ptr->d_char == sym)) who[n++] = i;
#else
		/* Collect "appropriate" monsters */
		if (r_ptr->d_char == sym) who[n++] = i;
#endif
	}

	/* Nothing to recall */
	if (!n)
	{
		cheat_know = oldcheat;

		/* Free the "who" array */
		C_KILL(who, max_r_idx, u16b);

		/* Restore */
		screen_load();

		return (FALSE);
	}

	/* Sort by level */
	why = 2;
	query = 'y';

	/* Sort if needed */
	if (why)
	{
		/* Select the sort method */
		ang_sort_comp = ang_sort_comp_hook;
		ang_sort_swap = ang_sort_swap_hook;

		/* Sort the array */
		ang_sort(who, &why, n);
	}


	/* Start at the end */
#ifdef JP
	/* XTRA HACK REMEMBER_IDX */
	if (old_sym == sym && old_i < n) i = old_i;
	else i = n - 1;
#else
	i = n - 1;
#endif

	notpicked = TRUE;

	/* Scan the monster memory */
	while (notpicked)
	{
		/* Extract a race */
		r_idx = who[i];

		/* Save this monster ID */
		p_ptr->monster_race_idx = r_idx;

		/* Hack -- Handle stuff */
		handle_stuff();

		/* Hack -- Begin the prompt */
		roff_top(r_idx);

		/* Hack -- Complete the prompt */
#ifdef JP
Term_addstr(-1, TERM_WHITE, " ['r'思い出, ' 'で続行, ESC]");
#else
		Term_addstr(-1, TERM_WHITE, " [(r)ecall, ESC, space to continue]");
#endif


		/* Interact */
		while (1)
		{
			/* Recall */
			if (recall)
			{
				/* Recall on screen */
				r2_ptr = &r_info[r_idx];

				oldkills = r2_ptr->r_tkills;
				oldwake = r2_ptr->r_wake;
				screen_roff(who[i], 1);
				r2_ptr->r_tkills = oldkills;
				r2_ptr->r_wake = oldwake;
				cheat_know = oldcheat;
				notpicked = FALSE;
#ifdef JP
				/* XTRA HACK REMEMBER_IDX */
				old_sym = sym;
				old_i = i;
#endif
			}

			/* Command */
			query = inkey();

			/* Normal commands */
			if (query != 'r') break;

			/* Toggle recall */
			recall = !recall;
		}

		/* Stop scanning */
		if (query == ESCAPE) break;

		/* Move to "prev" monster */
		if (query == '-')
		{
			if (++i == n)
			{
				i = 0;
				if (!expand_list) break;
			}
		}

		/* Move to "next" monster */
		else
		{
			if (i-- == 0)
			{
				i = n - 1;
				if (!expand_list) break;
			}
		}
	}


	/* Re-display the identity */
	/* prt(buf, 5, 5);*/

	cheat_know = oldcheat;

	/* Free the "who" array */
	C_KILL(who, max_r_idx, u16b);

	/* Restore */
	screen_load();

	return (!notpicked);
}
Exemplo n.º 19
0
static struct stash *stash_lookup_next(pr_stash_type_t sym_type,
    const char *name, size_t namelen, int idx, unsigned int hash, void *prev) {
  struct stash *sym = NULL;
  int last_hit = 0;
  xaset_t **symbol_table = NULL;

  switch (sym_type) {
    case PR_SYM_CONF:
      symbol_table = conf_symbol_table;
      break;

    case PR_SYM_CMD:
      symbol_table = cmd_symbol_table;
      break;

    case PR_SYM_AUTH:
      symbol_table = auth_symbol_table;
      break;

    case PR_SYM_HOOK:
      symbol_table = hook_symbol_table;
      break;

    default:
      errno = EINVAL;
      return NULL;
  }

  if (symbol_table[idx]) {
    for (sym = (struct stash *) symbol_table[idx]->xas_list; sym;
        sym = sym->next) {
      if (last_hit) {
        int res;

        if (name == NULL) {
          break;
        }

        if (sym->sym_hash != hash) {
          continue;
        }

        if (sym->sym_namelen != namelen) {
          continue;
        }

        /* Try to avoid strncmp(3) if we can. */
        if (namelen >= 1) {
          char c1, c2;

          c1 = tolower((int) sym->sym_name[0]);
          c2 = tolower((int) name[0]);

          if (c1 != c2) {
            continue;
          }

          /* Special case (unlikely, but possible) */
          if (namelen == 1 &&
              c1 == '\0') {
            break;
          }
        }

        if (namelen >= 2) {
          char c1, c2;

          c1 = tolower((int) sym->sym_name[1]);
          c2 = tolower((int) name[1]);

          if (c1 != c2) {
            continue;
          }

          /* Special case */
          if (namelen == 2 &&
              c1 == '\0') {
            break;
          }
        }

        res = strncasecmp(sym->sym_name + 2, name + 2, namelen - 2);
        if (res == 0) {
          break;
        }
      }

      if (sym->ptr.sym_generic == prev) {
        last_hit++;
      }
    }
  }

  return sym;
}
Exemplo n.º 20
0
 static string lowercase(string s) {
     size_t i, n = s.size();
     string lc(s);
     for (i = 0; i < n; i++) lc[i] = tolower(s[i]);
     return lc;
 }
Exemplo n.º 21
0
int string_to_key(const char *keystring)
{
   int ct, keywstate = 0;
   const char *kptr = keystring;

   while(1) {
      if (*kptr == '\0') return -1;
      if (!strncmp(kptr, "XK_", 3))
	 kptr += 3;
      else if (!strncmp(kptr, "Shift_", 6)) {
	 keywstate |= SHIFT;
	 kptr += 6;
      }
      else if (!strncmp(kptr, "Capslock_", 9)) {
	 keywstate |= CAPSLOCK;
	 kptr += 9;
      }
      else if (!strncmp(kptr, "Control_", 8)) {
	 keywstate |= CTRL;
	 kptr += 8;
      }
      else if (!strncmp(kptr, "Alt_", 4)) {
	 keywstate |= ALT;
	 kptr += 4;
      }
      else if (!strncmp(kptr, "Meta_", 5)) {
	 keywstate |= ALT;
	 kptr += 5;
      }
      else if (!strncmp(kptr, "Hold_", 5)) {
	 keywstate |= HOLD;
	 kptr += 5;
      }
      else if (*kptr == '^') {
	 kptr++;
	 ct = (int)tolower(*kptr);
	 keywstate |= CTRL | ct;
	 break;
      }
      else if (*(kptr + 1) == '\0') {
	 if ((*kptr) < 32)
	    keywstate |= CTRL | (int)('A' + (*kptr) - 1);
	 else
	    keywstate |= (int)(*kptr);
	 break;
      }
      else {
         if (!strncmp(kptr, "Button", 6)) {
	    switch (*(kptr + 6)) {
	       case '1': keywstate = (Button1Mask << 16); break;
	       case '2': keywstate = (Button2Mask << 16); break;
	       case '3': keywstate = (Button3Mask << 16); break;
	       case '4': keywstate = (Button4Mask << 16); break;
	       case '5': keywstate = (Button5Mask << 16); break;
	    }
         }
	 else {
	    /* When any modifier keys are used, presence of SHIFT */
	    /* requires that the corresponding key be uppercase,  */
	    /* and lack of SHIFT requires lowercase.  Enforce it  */
	    /* here so that it is not necessary for the user to	  */
	    /* do so.						  */
	    if (*(kptr + 1) == '\0') {
	       if (keywstate & SHIFT)
	          ct = (int)toupper(*kptr);
	       else
	          ct = (int)tolower(*kptr);
	       keywstate |= ct;
	    }
	    else
	       keywstate |= XStringToKeysym(kptr);
	 }
	 break;
      }
   }
   return keywstate;
}
Exemplo n.º 22
0
int builtin_help(Environment &env, const std::vector<std::string> &tokens, const fdmask &fds) {

	bool error = false;
	filesystem::path _f;

	// todo -- -f to specify help file.
	auto argv = getopt(tokens, [&](char c){
		switch(tolower(c))
		{

			default:
				fdprintf(stderr, "### Help - \"-%c\" is not an option.\n", c);
				error = true;
				break;
		}
	});

	if (error) {
		fdputs("# Usage - Help [-f helpfile] command...\n", stderr);
		return 1;
	}


	const filesystem::path sd(ToolBox::MacToUnix(env.get("shelldirectory")));
	const filesystem::path hd = sd / "Help";

	filesystem::path mono;
	mapped_file mono_file;
	std::error_code ec;

	if (_f.empty()) {
		mono = sd / "MPW.Help";
		mono_file = mapped_file(mono, mapped_file::priv, ec);
	} else {

		mono = _f;
		mono_file = mapped_file(mono, mapped_file::priv, ec);
		if (!mono_file && !_f.is_absolute()) {
			mono = sd / _f;
			mono_file = mapped_file(mono, mapped_file::priv, ec);
		}

		if (!mono_file) {
			fdprintf(stderr, "### Help: Unable to open %s\n", _f.c_str());
			fdprintf(stderr, "# %s\n", ec.message().c_str());
			return 3;
		}

	}

	if (mono_file) {
		std::replace(mono_file.begin(), mono_file.end(), '\r', '\n');
	}

	if (argv.empty()) {
		help_helper(mono_file, fds, "");
		return 0;
	}

	int rv = 0;
	for (const auto &cmd : argv) {


		// 1. check for $MPW:Help:command
		filesystem::path p(hd);
		p /= cmd;

		mapped_file f(p, mapped_file::priv, ec);
		if (!ec) {
			std::replace(f.begin(), f.end(), '\r', '\n');
			write(stdout, f.data(), f.size());
			fdputs("\n", stdout);
			continue;
		}


		if (mono_file) {
			bool ok = help_helper(mono_file, fds, cmd);
			if (ok) break;
		}

		fdprintf(stderr, "### Help - \"%s\" was not found.\n", cmd.c_str());
		rv = 2;
	}

	return rv;
}
Exemplo n.º 23
0
int
main(int argc, char **argv)
{
        register int ch;
        char **dbv = NULL;
#ifdef MMAP
        f_mmap = 1;		/* mmap is default */
#endif
	(void) setlocale(LC_ALL, "");

        while ((ch = getopt(argc, argv, "Scd:il:ms")) != -1)
                switch(ch) {
                case 'S':	/* statistic lines */   
                        f_statistic = 1;
                        break;
                case 'l': /* limit number of output lines, 0 == infinite */
                        f_limit = atoi(optarg);
                        break;
                case 'd':	/* database */
                        dbv = colon(dbv, optarg, _PATH_FCODES);
                        break;
                case 'i':	/* ignore case */
                        f_icase = 1;
                        break;
                case 'm':	/* mmap */
#ifdef MMAP
                        f_mmap = 1;
#else
						warnx("mmap(2) not implemented");
#endif
                        break;
                case 's':	/* stdio lib */
                        f_mmap = 0;
                        break;
                case 'c': /* suppress output, show only count of matches */
                        f_silent = 1;
                        break;
                default:
                        usage();
                }
        argv += optind;
        argc -= optind;

        /* to few arguments */
        if (argc < 1 && !(f_statistic))
                usage();

        /* no (valid) database as argument */
        if (dbv == NULL || *dbv == NULL) {
                /* try to read database from environment */
                if ((path_fcodes = getenv("LOCATE_PATH")) == NULL ||
		     *path_fcodes == '\0')
                        /* use default database */
                        dbv = colon(dbv, _PATH_FCODES, _PATH_FCODES);
                else		/* $LOCATE_PATH */
                        dbv = colon(dbv, path_fcodes, _PATH_FCODES);
        }

        if (f_icase && UCHAR_MAX < 4096) /* init tolower lookup table */
                for (ch = 0; ch < UCHAR_MAX + 1; ch++)
                        myctype[ch] = tolower(ch);

        /* foreach database ... */
        while((path_fcodes = *dbv) != NULL) {
                dbv++;

                if (!strcmp(path_fcodes, "-"))
                        f_stdin = 1;
		else
			f_stdin = 0;

#ifndef MMAP
		f_mmap = 0;	/* be paranoid */
#endif
                if (!f_mmap || f_stdin || f_statistic) 
			search_fopen(path_fcodes, argv);
                else 
			search_mmap(path_fcodes, argv);
        }

        if (f_silent)
                print_matches(counter);
        exit(0);
}
Exemplo n.º 24
0
int builtin_directory(Environment &env, const std::vector<std::string> &tokens, const fdmask &fds) {
	// directory [-q]
	// directory path

	// for relative names, uses {DirectoryPath} (if set) rather than .
	// set DirectoryPath ":,{MPW},{MPW}Projects:"

	/*
	 * Parameters:
	 * ----------
	 * directory
	 * Sets the default directory to directory. If you specify directory
	 * as a leafname (that is, the final portion of a full pathname), the
	 * MPW Shell searches for the directory in the current directory path
	 * (for example, searching "{MPW}Examples:" for CExamples). However, if
	 * the MPW Shell fails to find the directory in the current directory
	 * path, it searches the directories listed in the {DirectoryPath} MPW
	 * Shell variable, which contains a list of directories to be searched
	 * in order of precedence. The last example illustrates how to do this.
	 *
	 * Options:
	 * -------
	 * -q
	 * Inhibits quoting the directory pathname written to standard
	 * output. This option applies only if you omit the directory
	 * parameter Normally the MPW Shell quotes the current default
	 * directory name if it contains spaces or other special characters
	 *
	 * Status:
	 * ------
	 * Directory can return the following status codes:
	 *
	 * 0 no errors
	 * 1 directory not found; command aborted; or parameter error
	 *
	 */



	//io_helper io(fds);

	bool q = false;
	bool error = false;

	std::vector<std::string> argv = getopt(tokens, [&](char c){
		switch(tolower(c))
		{
			case 'q': q = true; break;
			default:
				fdprintf(stderr, "### Directory - \"-%c\" is not an option.\n", c);
				error = true;
				break;
		}
	});

	if (error) {
		fdputs("# Usage - Directory [-q | directory]\n", stderr);
		return 1;
	}

	if (argv.size() > 1) {
		fdputs("### Directory - Too many parameters were specified.\n", stderr);
		fdputs("# Usage - Directory [-q | directory]\n", stderr);
		return 1;	
	}


	if (argv.size() == 1) {
		//cd
		if (q) {
			fdputs("### Directory - Conflicting options or parameters were specified.\n", stderr);
			return 1;
		}

		// todo -- if relative path does not exist, check {DirectoryPath}
		fs::path path = ToolBox::MacToUnix(argv.front());
		std::error_code ec;
		current_path(path, ec);
		if (ec) {
			fdputs("### Directory - Unable to set current directory.\n", stderr);
			fdprintf(stderr, "# %s\n", ec.message().c_str());
			return 1;
		}
	}
	else {
		// pwd
		std::error_code ec;
		fs::path path = fs::current_path(ec);
		if (ec) {

			fdputs("### Directory - Unable to get current directory.\n", stderr);
			fdprintf(stderr, "# %s\n", ec.message().c_str());
			return 1;

		}
		// todo -- pathname translation?

		std::string s = path;
		if (!q) s = quote(std::move(s));
		fdprintf(stdout, "%s\n", s.c_str());
	}
	return 0;
}
Exemplo n.º 25
0
void ObjectMgr::LoadExtraItemStuff()
{
	map<uint32, uint32> foodItems;
	QueryResult* result = WorldDatabase.Query("SELECT * FROM itempetfood ORDER BY entry");
	if(result)
	{
		Field* f = result->Fetch();
		do
		{
			foodItems.insert(make_pair(f[0].GetUInt32(), f[1].GetUInt32()));
		}
		while(result->NextRow());
		delete result;
	}

	StorageContainerIterator<ItemPrototype> * itr = ItemPrototypeStorage.MakeIterator();
	ItemPrototype* pItemPrototype;
	while(!itr->AtEnd())
	{
		pItemPrototype = itr->Get();
		if(pItemPrototype->ItemSet > 0)
		{
			ItemSetContentMap::iterator itr2 = mItemSets.find(pItemPrototype->ItemSet);
			std::list<ItemPrototype*>* l;
			if(itr2 == mItemSets.end())
			{
				l = new std::list<ItemPrototype*>;
				mItemSets.insert(ItemSetContentMap::value_type(pItemPrototype->ItemSet, l));
			}
			else
			{
				l = itr2->second;
			}
			l->push_back(pItemPrototype);
		}


		// lowercase name, used for searches
		pItemPrototype->lowercase_name = pItemPrototype->Name1;
		for(uint32 j = 0; j < pItemPrototype->lowercase_name.length(); ++j)
			pItemPrototype->lowercase_name[j] = static_cast<char>(tolower(pItemPrototype->lowercase_name[j]));

		//load item_pet_food_type from extra table
		uint32 ft = 0;
		map<uint32, uint32>::iterator iter = foodItems.find(pItemPrototype->ItemId);
		if(iter != foodItems.end())
			ft = iter->second;
		pItemPrototype->FoodType = ft ;

		// forced pet entries
		switch(pItemPrototype->ItemId)
		{
			case 28071: //Grimoire of Anguish (Rank 1)
			case 28072: //Grimoire of Anguish (Rank 2)
			case 28073: //Grimoire of Anguish (Rank 3)
			case 25469: //Grimoire of Avoidance
			case 23734: //Grimoire of Cleave (Rank 1)
			case 23745: //Grimoire of Cleave (Rank 2)
			case 23755: //Grimoire of Cleave (Rank 3)
			case 25900: //Grimoire of Demonic Frenzy
			case 23711: //Grimoire of Intercept (Rank 1)
			case 23730: //Grimoire of Intercept (Rank 2)
			case 23731: //Grimoire of Intercept (Rank 3)
				// Felguard
				pItemPrototype->ForcedPetId = 17252;
				break;

			case 16321: //Grimoire of Blood Pact (Rank 1)
			case 16322: //Grimoire of Blood Pact (Rank 2)
			case 16323: //Grimoire of Blood Pact (Rank 3)
			case 16324: //Grimoire of Blood Pact (Rank 4)
			case 16325: //Grimoire of Blood Pact (Rank 5)
			case 22180: //Grimoire of Blood Pact (Rank 6)
			case 16326: //Grimoire of Fire Shield (Rank 1)
			case 16327: //Grimoire of Fire Shield (Rank 2)
			case 16328: //Grimoire of Fire Shield (Rank 3)
			case 16329: //Grimoire of Fire Shield (Rank 4)
			case 16330: //Grimoire of Fire Shield (Rank 5)
			case 22181: //Grimoire of Fire Shield (Rank 6)
			case 16302: //Grimoire of Firebolt (Rank 2)
			case 16316: //Grimoire of Firebolt (Rank 3)
			case 16317: //Grimoire of Firebolt (Rank 4)
			case 16318: //Grimoire of Firebolt (Rank 5)
			case 16319: //Grimoire of Firebolt (Rank 6)
			case 16320: //Grimoire of Firebolt (Rank 7)
			case 22179: //Grimoire of Firebolt (Rank 8)
			case 16331: //Grimoire of Phase Shift
				// Imp
				pItemPrototype->ForcedPetId = 416;
				break;

			case 16357: //Grimoire of Consume Shadows (Rank 1)
			case 16358: //Grimoire of Consume Shadows (Rank 2)
			case 16359: //Grimoire of Consume Shadows (Rank 3)
			case 16360: //Grimoire of Consume Shadows (Rank 4)
			case 16361: //Grimoire of Consume Shadows (Rank 5)
			case 16362: //Grimoire of Consume Shadows (Rank 6)
			case 22184: //Grimoire of Consume Shadows (Rank 7)
			case 16351: //Grimoire of Sacrifice (Rank 1)
			case 16352: //Grimoire of Sacrifice (Rank 2)
			case 16353: //Grimoire of Sacrifice (Rank 3)
			case 16354: //Grimoire of Sacrifice (Rank 4)
			case 16355: //Grimoire of Sacrifice (Rank 5)
			case 16356: //Grimoire of Sacrifice (Rank 6)
			case 22185: //Grimoire of Sacrifice (Rank 7)
			case 16363: //Grimoire of Suffering (Rank 1)
			case 16364: //Grimoire of Suffering (Rank 2)
			case 16365: //Grimoire of Suffering (Rank 3)
			case 16366: //Grimoire of Suffering (Rank 4)
			case 22183: //Grimoire of Suffering (Rank 5)
			case 28068: //Grimoire of Suffering (Rank 6)
			case 16346: //Grimoire of Torment (Rank 2)
			case 16347: //Grimoire of Torment (Rank 3)
			case 16348: //Grimoire of Torment (Rank 4)
			case 16349: //Grimoire of Torment (Rank 5)
			case 16350: //Grimoire of Torment (Rank 6)
			case 22182: //Grimoire of Torment (Rank 7)
				// Voidwalker
				pItemPrototype->ForcedPetId = 1860;
				break;

			case 16368: //Grimoire of Lash of Pain (Rank 2)
			case 16371: //Grimoire of Lash of Pain (Rank 3)
			case 16372: //Grimoire of Lash of Pain (Rank 4)
			case 16373: //Grimoire of Lash of Pain (Rank 5)
			case 16374: //Grimoire of Lash of Pain (Rank 6)
			case 22186: //Grimoire of Lash of Pain (Rank 7)
			case 16380: //Grimoire of Lesser Invisibility
			case 16379: //Grimoire of Seduction
			case 16375: //Grimoire of Soothing Kiss (Rank 1)
			case 16376: //Grimoire of Soothing Kiss (Rank 2)
			case 16377: //Grimoire of Soothing Kiss (Rank 3)
			case 16378: //Grimoire of Soothing Kiss (Rank 4)
			case 22187: //Grimoire of Soothing Kiss (Rank 5)
				// Succubus
				pItemPrototype->ForcedPetId = 1863;
				break;

			case 16381: //Grimoire of Devour Magic (Rank 2)
			case 16382: //Grimoire of Devour Magic (Rank 3)
			case 16383: //Grimoire of Devour Magic (Rank 4)
			case 22188: //Grimoire of Devour Magic (Rank 5)
			case 22189: //Grimoire of Devour Magic (Rank 6)
			case 16390: //Grimoire of Paranoia
			case 16388: //Grimoire of Spell Lock (Rank 1)
			case 16389: //Grimoire of Spell Lock (Rank 2)
			case 16384: //Grimoire of Tainted Blood (Rank 1)
			case 16385: //Grimoire of Tainted Blood (Rank 2)
			case 16386: //Grimoire of Tainted Blood (Rank 3)
			case 16387: //Grimoire of Tainted Blood (Rank 4)
			case 22190: //Grimoire of Tainted Blood (Rank 5)
				//Felhunter
				pItemPrototype->ForcedPetId = 417;
				break;

			case 21283:
			case 3144:
			case 21282:
			case 9214:
			case 21281:
			case 22891:
				// Player
				pItemPrototype->ForcedPetId = 0;
				break;

			default:
				pItemPrototype->ForcedPetId = -1;
				break;
		}

		if(!itr->Inc())
			break;
	}

	itr->Destruct();
	foodItems.clear();
}
Exemplo n.º 26
0
int builtin_exists(Environment &env, const std::vector<std::string> &tokens, const fdmask &fds) {

	bool _a = false; // print if alias/symlink
	bool _d = false; // print if directory
	bool _f = false; // print if normal file
	bool _n = false; // don't follow alias
	bool _w = false; // print if normal file + writable
	bool _q = false; // don't quote names
	bool error = false;

	std::vector<std::string> argv = getopt(tokens, [&](char c){
		switch(tolower(c))
		{
			case 'a': _a = true; break;
			case 'd': _d = true; break;
			case 'f': _f = true; break;
			case 'n': _n = true; break;
			case 'q': _q = true; break;
			case 'w': _w = true; break;
			default:
				fdprintf(stderr, "### Exists - \"-%c\" is not an option.\n", c);
				error = true;
				break;
		}
	});	

	if (_w) _f = false;

	if (_a + _d + _f + _w > 1) {
		fdputs("### Exists - Conflicting options were specified.\n", stderr);
		error = true;
	}

	if (argv.size() < 1) {
		fdputs("### Exists - Not enough parameters were specified.\n", stderr);
		error = true;
	}



	if (error) {
		fdputs("# Usage - Exists [-a | -d | -f | -w] [-n] [-q] name...\n", stderr);
		return 1;
	}

	for (auto &s : argv) {
		std::string path = ToolBox::MacToUnix(s);
		std::error_code ec;
		fs::file_status st = _n ? fs::symlink_status(path, ec) : fs::status(path, ec);
		if (ec) continue;

		if (_d && !fs::is_directory(st)) continue;
		if (_a && !fs::is_symlink(st)) continue;
		if (_f && !fs::is_regular_file(st)) continue;
		if (_w && !fs::is_regular_file(st)) continue;
		if (_w && (access(path.c_str(), W_OK | F_OK) < 0)) continue; 

		if (!_q) s = quote(std::move(s));
		fdprintf(stdout, "%s\n", s.c_str());

	}


	return 0;
}
Exemplo n.º 27
0
int
main(int argc, char *argv[])
{
	struct passwd *pwd;
	int ch, newline;
	char *file, *sender, *p;
#if MAXPATHLEN > BUFSIZ
	char buf[MAXPATHLEN];
#else
	char buf[BUFSIZ];
#endif

	file = sender = NULL;
	while ((ch = getopt(argc, argv, "f:s:")) != -1)
		switch((char)ch) {
		case 'f':
			file = optarg;
			break;
		case 's':
			sender = optarg;
			for (p = sender; *p; ++p)
				if (isupper(*p))
					*p = tolower(*p);
			break;
		case '?':
		default:
			fprintf(stderr,
			    "usage: from [-f file] [-s sender] [user]\n");
			exit(1);
		}
	argv += optind;

	/*
	 * We find the mailbox by:
	 *	1 -f flag
	 *	2 user
	 *	2 MAIL environment variable
	 *	3 _PATH_MAILDIR/file
	 */
	if (!file) {
		if (!(file = *argv)) {
			if (!(file = getenv("MAIL"))) {
				if (!(pwd = getpwuid(getuid())))
					errx(1, "no password file entry for you");
				if ((file = getenv("USER"))) {
					(void)snprintf(buf, sizeof(buf),
					    "%s/%s", _PATH_MAILDIR, file);
					file = buf;
				} else
					(void)snprintf(file = buf, sizeof(buf),
					    "%s/%s", _PATH_MAILDIR,
					    pwd->pw_name);
			}
		} else {
			(void)snprintf(buf, sizeof(buf), "%s/%s",
			    _PATH_MAILDIR, file);
			file = buf;
		}
	}
	if (!freopen(file, "r", stdin))
		err(1, "%s", file);
	for (newline = 1; fgets(buf, sizeof(buf), stdin);) {
		if (*buf == '\n') {
			newline = 1;
			continue;
		}
		if (newline && !strncmp(buf, "From ", 5) &&
		    (!sender || match(buf + 5, sender)))
			printf("%s", buf);
		newline = 0;
	}
	exit(0);
}
Exemplo n.º 28
0
int builtin_evaluate(Environment &env, std::vector<token> &&tokens, const fdmask &fds) {
	// evaluate expression
	// evaluate variable = expression
	// evaluate variable += expression
	// evaluate variable -= expression

	// flags -- -h -o -b -- print in hex, octal, or binary

	// convert the arguments to a stack.


	int output = 'd';

	//io_helper io(fds);

	std::reverse(tokens.begin(), tokens.end());

	// remove 'Evaluate'
	tokens.pop_back();

	// check for -h -x -o
	if (tokens.size() >= 2 && tokens.back().type == '-') {

		const token &t = tokens[tokens.size() - 2];
		if (t.type == token::text && t.string.length() == 1) {
			int flag = tolower(t.string[0]);
			switch(flag) {
				case 'o':
				case 'h':
				case 'b':
					output = flag;
					tokens.pop_back();
					tokens.pop_back();
			}
		}

	}

	if (tokens.size() >= 2 && tokens.back().type == token::text)
	{
		int type = tokens[tokens.size() -2].type;

		if (is_assignment(type)) {

			std::string name = tokens.back().string;

			tokens.pop_back();
			tokens.pop_back();

			int32_t i = evaluate_expression("Evaluate", std::move(tokens));

			switch(type) {
				case '=':
					env.set(name, i);
					break;
				case '+=':
				case '-=':
					{
						value old;
						auto iter = env.find(name);
						if (iter != env.end()) old = (const std::string &)iter->second;

						switch(type) {
							case '+=':
								i = old.to_number() + i;
								break;
							case '-=':
								i = old.to_number() - i;
								break;
						}

						env.set(name, i);
					}
					break;
			}
			return 0;
		}
	}

	int32_t i = evaluate_expression("Evaluate", std::move(tokens));

	if (output == 'h') {
		fdprintf(stdout, "0x%08x\n", i);
		return 0;
	}

	if (output == 'b') {
		std::string tmp("0b");

		for (int j = 0; j < 32; ++j) {
			tmp.push_back(i & 0x80000000 ? '1' : '0');
			i <<= 1;
		}
		tmp.push_back('\n');
		fdputs(tmp.c_str(), stdout);
		return 0;
	}

	if (output == 'o') {
		// octal.
		fdprintf(stdout, "0%o\n", i);
		return 0;
	}

	fdprintf(stdout, "%d\n", i);
	return 0;
}
static int
conntrack_mt_parse(int c, char **argv, int invert, unsigned int *flags,
                   struct xt_entry_match **match)
{
	struct xt_conntrack_mtinfo1 *info = (void *)(*match)->data;
	unsigned int port;
	char *p;

	switch (c) {
	case '1': /* --ctstate */
		conntrack_ps_states(info, optarg);
		info->match_flags |= XT_CONNTRACK_STATE;
		if (invert)
			info->invert_flags |= XT_CONNTRACK_STATE;
		break;

	case '2': /* --ctproto */
		/* Canonicalize into lower case */
		for (p = optarg; *p != '\0'; ++p)
			*p = tolower(*p);
		info->l4proto = xtables_parse_protocol(optarg);

		if (info->l4proto == 0 && (info->invert_flags & XT_INV_PROTO))
			xtables_error(PARAMETER_PROBLEM, "conntrack: rule would "
			           "never match protocol");

		info->match_flags |= XT_CONNTRACK_PROTO;
		if (invert)
			info->invert_flags |= XT_CONNTRACK_PROTO;
		break;

	case '7': /* --ctstatus */
		conntrack_ps_statuses(info, optarg);
		info->match_flags |= XT_CONNTRACK_STATUS;
		if (invert)
			info->invert_flags |= XT_CONNTRACK_STATUS;
		break;

	case '8': /* --ctexpire */
		conntrack_ps_expires(info, optarg);
		info->match_flags |= XT_CONNTRACK_EXPIRES;
		if (invert)
			info->invert_flags |= XT_CONNTRACK_EXPIRES;
		break;

	case 'a': /* --ctorigsrcport */
		if (!xtables_strtoui(optarg, NULL, &port, 0, UINT16_MAX))
			xtables_param_act(XTF_BAD_VALUE, "conntrack",
			          "--ctorigsrcport", optarg);
		info->match_flags |= XT_CONNTRACK_ORIGSRC_PORT;
		info->origsrc_port = htons(port);
		if (invert)
			info->invert_flags |= XT_CONNTRACK_ORIGSRC_PORT;
		break;

	case 'b': /* --ctorigdstport */
		if (!xtables_strtoui(optarg, NULL, &port, 0, UINT16_MAX))
			xtables_param_act(XTF_BAD_VALUE, "conntrack",
			          "--ctorigdstport", optarg);
		info->match_flags |= XT_CONNTRACK_ORIGDST_PORT;
		info->origdst_port = htons(port);
		if (invert)
			info->invert_flags |= XT_CONNTRACK_ORIGDST_PORT;
		break;

	case 'c': /* --ctreplsrcport */
		if (!xtables_strtoui(optarg, NULL, &port, 0, UINT16_MAX))
			xtables_param_act(XTF_BAD_VALUE, "conntrack",
			          "--ctreplsrcport", optarg);
		info->match_flags |= XT_CONNTRACK_REPLSRC_PORT;
		info->replsrc_port = htons(port);
		if (invert)
			info->invert_flags |= XT_CONNTRACK_REPLSRC_PORT;
		break;

	case 'd': /* --ctrepldstport */
		if (!xtables_strtoui(optarg, NULL, &port, 0, UINT16_MAX))
			xtables_param_act(XTF_BAD_VALUE, "conntrack",
			          "--ctrepldstport", optarg);
		info->match_flags |= XT_CONNTRACK_REPLDST_PORT;
		info->repldst_port = htons(port);
		if (invert)
			info->invert_flags |= XT_CONNTRACK_REPLDST_PORT;
		break;

	case 'e': /* --ctdir */
		xtables_param_act(XTF_NO_INVERT, "conntrack", "--ctdir", invert);
		if (strcasecmp(optarg, "ORIGINAL") == 0) {
			info->match_flags  |= XT_CONNTRACK_DIRECTION;
			info->invert_flags &= ~XT_CONNTRACK_DIRECTION;
		} else if (strcasecmp(optarg, "REPLY") == 0) {
			info->match_flags  |= XT_CONNTRACK_DIRECTION;
			info->invert_flags |= XT_CONNTRACK_DIRECTION;
		} else {
			xtables_param_act(XTF_BAD_VALUE, "conntrack", "--ctdir", optarg);
		}
		break;

	default:
		return false;
	}

	*flags = info->match_flags;
	return true;
}
Exemplo n.º 30
0
static void
find_and_hash_each_line (struct file_data *current)
{
  char const *p = current->prefix_end;
  lin i, *bucket;
  size_t length;

  /* Cache often-used quantities in local variables to help the compiler.  */
  char const **linbuf = current->linbuf;
  lin alloc_lines = current->alloc_lines;
  lin line = 0;
  lin linbuf_base = current->linbuf_base;
  lin *cureqs = xmalloc (alloc_lines * sizeof *cureqs);
  struct equivclass *eqs = equivs;
  lin eqs_index = equivs_index;
  lin eqs_alloc = equivs_alloc;
  char const *suffix_begin = current->suffix_begin;
  char const *bufend = FILE_BUFFER (current) + current->buffered;
  bool ig_case = ignore_case;
  enum DIFF_white_space ig_white_space = ignore_white_space;
  bool diff_length_compare_anyway =
    ig_white_space != IGNORE_NO_WHITE_SPACE;
  bool same_length_diff_contents_compare_anyway =
    diff_length_compare_anyway | ig_case;

  while (p < suffix_begin)
    {
      char const *ip = p;
      hash_value h = 0;
      unsigned char c;

      /* Hash this line until we find a newline.  */
      switch (ig_white_space)
	{
	case IGNORE_ALL_SPACE:
	  while ((c = *p++) != '\n')
	    if (! isspace (c))
	      h = HASH (h, ig_case ? tolower (c) : c);
	  break;

	case IGNORE_SPACE_CHANGE:
	  while ((c = *p++) != '\n')
	    {
	      if (isspace (c))
		{
		  do
		    if ((c = *p++) == '\n')
		      goto hashing_done;
		  while (isspace (c));

		  h = HASH (h, ' ');
		}

	      /* C is now the first non-space.  */
	      h = HASH (h, ig_case ? tolower (c) : c);
	    }
	  break;

	case IGNORE_TAB_EXPANSION:
	case IGNORE_TAB_EXPANSION_AND_TRAILING_SPACE:
	case IGNORE_TRAILING_SPACE:
	  {
	    size_t column = 0;
	    while ((c = *p++) != '\n')
	      {
		if (ig_white_space & IGNORE_TRAILING_SPACE
		    && isspace (c))
		  {
		    char const *p1 = p;
		    unsigned char c1;
		    do
		      if ((c1 = *p1++) == '\n')
			{
			  p = p1;
			  goto hashing_done;
			}
		    while (isspace (c1));
		  }

		size_t repetitions = 1;

		if (ig_white_space & IGNORE_TAB_EXPANSION)
		  switch (c)
		    {
		    case '\b':
		      column -= 0 < column;
		      break;

		    case '\t':
		      c = ' ';
		      repetitions = tabsize - column % tabsize;
		      column = (column + repetitions < column
				? 0
				: column + repetitions);
		      break;

		    case '\r':
		      column = 0;
		      break;

		    default:
		      column++;
		      break;
		    }

		if (ig_case)
		  c = tolower (c);

		do
		  h = HASH (h, c);
		while (--repetitions != 0);
	      }
	  }
	  break;

	default:
	  if (ig_case)
	    while ((c = *p++) != '\n')
	      h = HASH (h, tolower (c));
	  else
	    while ((c = *p++) != '\n')
	      h = HASH (h, c);
	  break;
	}

   hashing_done:;

      bucket = &buckets[h % nbuckets];
      length = p - ip - 1;

      if (p == bufend
	  && current->missing_newline
	  && ROBUST_OUTPUT_STYLE (output_style))
	{
	  /* The last line is incomplete and we do not silently
	     complete lines.  If the line cannot compare equal to any
	     complete line, put it into buckets[-1] so that it can
	     compare equal only to the other file's incomplete line
	     (if one exists).  */
	  if (ig_white_space < IGNORE_TRAILING_SPACE)
	    bucket = &buckets[-1];
	}

      for (i = *bucket;  ;  i = eqs[i].next)
	if (!i)
	  {
	    /* Create a new equivalence class in this bucket.  */
	    i = eqs_index++;
	    if (i == eqs_alloc)
	      {
		if (PTRDIFF_MAX / (2 * sizeof *eqs) <= eqs_alloc)
		  xalloc_die ();
		eqs_alloc *= 2;
		eqs = xrealloc (eqs, eqs_alloc * sizeof *eqs);
	      }
	    eqs[i].next = *bucket;
	    eqs[i].hash = h;
	    eqs[i].line = ip;
	    eqs[i].length = length;
	    *bucket = i;
	    break;
	  }
	else if (eqs[i].hash == h)
	  {
	    char const *eqline = eqs[i].line;

	    /* Reuse existing class if lines_differ reports the lines
               equal.  */
	    if (eqs[i].length == length)
	      {
		/* Reuse existing equivalence class if the lines are identical.
		   This detects the common case of exact identity
		   faster than lines_differ would.  */
		if (memcmp (eqline, ip, length) == 0)
		  break;
		if (!same_length_diff_contents_compare_anyway)
		  continue;
	      }
	    else if (!diff_length_compare_anyway)
	      continue;

	    if (! lines_differ (eqline, ip))
	      break;
	  }

      /* Maybe increase the size of the line table.  */
      if (line == alloc_lines)
	{
	  /* Double (alloc_lines - linbuf_base) by adding to alloc_lines.  */
	  if (PTRDIFF_MAX / 3 <= alloc_lines
	      || PTRDIFF_MAX / sizeof *cureqs <= 2 * alloc_lines - linbuf_base
	      || PTRDIFF_MAX / sizeof *linbuf <= alloc_lines - linbuf_base)
	    xalloc_die ();
	  alloc_lines = 2 * alloc_lines - linbuf_base;
	  cureqs = xrealloc (cureqs, alloc_lines * sizeof *cureqs);
	  linbuf += linbuf_base;
	  linbuf = xrealloc (linbuf,
			     (alloc_lines - linbuf_base) * sizeof *linbuf);
	  linbuf -= linbuf_base;
	}
      linbuf[line] = ip;
      cureqs[line] = i;
      ++line;
    }

  current->buffered_lines = line;

  for (i = 0;  ;  i++)
    {
      /* Record the line start for lines in the suffix that we care about.
	 Record one more line start than lines,
	 so that we can compute the length of any buffered line.  */
      if (line == alloc_lines)
	{
	  /* Double (alloc_lines - linbuf_base) by adding to alloc_lines.  */
	  if (PTRDIFF_MAX / 3 <= alloc_lines
	      || PTRDIFF_MAX / sizeof *cureqs <= 2 * alloc_lines - linbuf_base
	      || PTRDIFF_MAX / sizeof *linbuf <= alloc_lines - linbuf_base)
	    xalloc_die ();
	  alloc_lines = 2 * alloc_lines - linbuf_base;
	  linbuf += linbuf_base;
	  linbuf = xrealloc (linbuf,
			     (alloc_lines - linbuf_base) * sizeof *linbuf);
	  linbuf -= linbuf_base;
	}
      linbuf[line] = p;

      if (p == bufend)
	{
	  /* If the last line is incomplete and we do not silently
	     complete lines, don't count its appended newline.  */
	  if (current->missing_newline && ROBUST_OUTPUT_STYLE (output_style))
	    linbuf[line]--;
	  break;
	}

      if (context <= i && no_diff_means_no_output)
	break;

      line++;

      while (*p++ != '\n')
	continue;
    }

  /* Done with cache in local variables.  */
  current->linbuf = linbuf;
  current->valid_lines = line;
  current->alloc_lines = alloc_lines;
  current->equivs = cureqs;
  equivs = eqs;
  equivs_alloc = eqs_alloc;
  equivs_index = eqs_index;
}