static int GetTypeOf(ea_t ea)
{
	flags_t flags = getFlags(ea);

	if (isTail(flags)) {
		// check if it's a struct ptr
		ea_t head = get_item_head(ea);
		if (head == ea) return T_UNK;
		flags = getFlags(head);
		if (!isData(flags) || !isStruct(flags)) return T_UNK;
		return GetTypeOfStructInstance(ea, head, flags);
	}

	if (!isData(flags)) return T_UNK;
	
	if (isStruct(flags)) return GetTypeOfStructInstance(ea, ea, flags);

	if (isByte(flags)) {
		char s;
		if (has_cmt(flags) && (get_cmt(ea, false, &s, 1) != -1) && s == 'S') return T_I8;
		return T_U8;
	}
	if (isWord(flags)) {
		char s;
		if (has_cmt(flags) && (get_cmt(ea, false, &s, 1) != -1) && s == 'S') return T_I16;
		return T_U16;
	}
	if (isDwrd(flags))  return T_I32;

	return T_UNK;
}
Exemple #2
0
bool HumdrumLine::isKernBoundaryEnd(void) const {
	if (!isData()) {
		return false;
	}
	HumdrumToken* ntok;
	for (int i=0; i<getFieldCount(); i++) {
		if (!token(i)->isDataType("**kern")) {
			continue;
		}
		ntok = token(i)->getNextToken();
		if (ntok == NULL) {
			continue;
		}
		while ((ntok != NULL) && !ntok->isData()) {
			ntok = ntok->getNextToken();
		}
		if (ntok == NULL) {
			continue;
		}
		if (ntok->isNull()) {
			return false;
		}
	}
	return true;
}
Exemple #3
0
void IdaFrontend::createSections(core::image::Image *image) {
    for (int i = 0; i < get_segm_qty(); i++) {
        segment_t *idaSegment = getnseg(i);

        assert(idaSegment != NULL);

        char segName[MAXSTR];
        ssize_t segNameSize = get_segm_name(idaSegment, segName, sizeof(segName) - 1);
        if(segNameSize < 0) {
            segName[0] = '\0';
        } else if(segNameSize > 0 && segName[0] == '_') {
            segName[0] = '.';
        }

        auto section = std::make_unique<core::image::Section>(
            segName,
            checked_cast<ByteAddr>(idaSegment->startEA),
            checked_cast<ByteSize>(idaSegment->size())
        );

        section->setReadable(idaSegment->perm & SEGPERM_READ);
        section->setWritable(idaSegment->perm & SEGPERM_WRITE);
        section->setExecutable(idaSegment->perm & SEGPERM_EXEC);
        section->setCode(idaSegment->type == SEG_CODE);
        section->setData(idaSegment->type == SEG_DATA);
        section->setBss(idaSegment->type == SEG_BSS);
        section->setAllocated(section->isCode() || section->isData() || section->isBss());
        section->setExternalByteSource(std::make_unique<IdaByteSource>());

        image->addSection(std::move(section));
    }
}
Exemple #4
0
int
getObjType( rsComm_t *rsComm, char *objName, char * objType ) {
    if ( isData( rsComm, objName, NULL ) >= 0 ) {
        strcpy( objType, "-d" );
    }
    else if ( isColl( rsComm, objName, NULL ) >= 0 ) {
        strcpy( objType, "-c" );
    }
    else if ( isResc( rsComm, objName ) == 0 ) {
        strcpy( objType, "-r" );
    }
    else if ( isUser( rsComm, objName ) == 0 ) {
        strcpy( objType, "-u" );
    }
    else if ( isMeta( rsComm, objName ) == 0 ) {
        strcpy( objType, "-m" );
    }
    else if ( isToken( rsComm, objName ) == 0 ) {
        strcpy( objType, "-t" );
    }
    else {
        return INVALID_OBJECT_TYPE;
    }
    return 0;
}
static int GetTypeOf(ea_t ea)
{
	flags_t flags = getFlags(ea);

	if (!isData(flags)) return T_UNK;
	if (isByte(flags))  return T_8BIT;
	if (isWord(flags))  return T_16BIT;
	if (isDwrd(flags))  return T_I32;

	return T_UNK;
}
Exemple #6
0
// check and create a flat 32 bit jump table -- the most common case
static void check_and_create_flat32(
        jump_table_type_t /*jtt*/,
        switch_info_ex_t &si)
{
  // check the table contents
  ea_t table = si.jumps;
  segment_t *s = getseg(table);
  if ( s == NULL )
    return;
  size_t maxsize = size_t(s->endEA - table);
  int size = si.ncases;
  if ( size > maxsize )
    size = (int)maxsize;

  int i;
  insn_t saved = cmd;
  for ( i=0; i < size; i++ )
  {
    ea_t ea = table + 4*i;
    flags_t F = getFlags(ea);
    if ( !hasValue(F) )
      break;
    if ( i && (has_any_name(F) || hasRef(F)) )
      break;
    ea_t target = segm_adjust_ea(getseg(table), si.elbase + get_long(ea));
    if ( !isLoaded(target) )
      break;
    flags_t F2 = get_flags_novalue(target);
    if ( isTail(F2) || isData(F2) )
      break;
    if ( !isCode(F2) && !decode_insn(target) )
      break;
  }
  cmd = saved;
  size = i;
  // create the table
  for ( i=0; i < size; i++ )
  {
    ea_t ea = table + 4*i;
    doDwrd(ea, 4);
    op_offset(ea, 0, REF_OFF32, BADADDR, si.elbase);
    ea_t target = si.elbase + segm_adjust_diff(getseg(table), get_long(ea));
    ua_add_cref(0, target, fl_JN);
  }
  si.flags  |= SWI_J32;
  if ( si.defjump != BADADDR )
    si.flags |= SWI_DEFAULT;
  si.ncases  = (uint16)size;
  si.startea = cmd.ea;
  set_switch_info_ex(cmd.ea, &si);
}
Exemple #7
0
bool HumdrumLine::isKernBoundaryStart(void) const {
	if (!isData()) {
		return false;
	}
	for (int i=0; i<getFieldCount(); i++) {
		if (!token(i)->isDataType("**kern")) {
			continue;
		}
		if (token(i)->isNull()) {
			return false;
		}
	}
	return true;
}
Exemple #8
0
size_t 
VtableScanner::getVtableMethodsCount (
    ea_t curAddress
) {
    ea_t startTable = BADADDR;
    ea_t curEntry = 0;

    // Iterate until we find a result
    for (; ; curAddress += 4) 
    {
        flags_t flags = IDAUtils::GetFlags (curAddress);

        // First iteration
        if (startTable == BADADDR) {
            startTable = curAddress;
            if (!(hasRef (flags) && (has_name (flags) || (flags & FF_LABL)))) {
                // Start of vtable should have a xref and a name (auto or manual)
                return 0;
            }
        }
        else if (hasRef (flags)) {
            // Might mean start of next vtable
            break;
        }
        
        if (!hasValue (flags) || !isData (flags)) {
            break;
        }
        
        if ((curEntry = get_long (curAddress))) {
            flags = IDAUtils::GetFlags (curEntry);
            
            if (!hasValue (flags) || !isCode (flags) || get_long (curEntry) == 0) {
                break;
            }
        }
    }

    
    if (startTable != BADADDR) {
        return (curAddress - startTable) / 4;
    }
    
    else {
        // No vtable at this EA
        return 0;
    }
}
Exemple #9
0
int
getObjType(rsComm_t *rsComm, char *objName, char * objType)
{
    if (isData(rsComm, objName, NULL) >= 0)
      strcpy(objType,"-d");
    else if (isColl(rsComm, objName, NULL) >= 0)
      strcpy(objType,"-c");
    else if (isResc(rsComm, objName) == 0)
      strcpy(objType,"-r");
    else if (isRescGroup(rsComm, objName) == 0)
      strcpy(objType,"-g");
    else if (isUser(rsComm, objName) == 0)
      strcpy(objType,"-u");
    else if (isMeta(rsComm, objName) == 0)
      strcpy(objType,"-m");
    else if (isToken(rsComm, objName) == 0)
      strcpy(objType,"-t");
    else
      return(INVALID_OBJECT_TYPE);
    return (0);
}
Exemple #10
0
void
one_switch_entry(ea_t ea, ea_t ptr)
{
  if ( !isData(ea) )
   do_unknown_range(ea, 4, true);
  add_cref(ea, ptr, 
#if (IDP_INTERFACE_VERSION > 65)
  fl_USobsolete
#else
  fl_US
#endif
  );
  char abuf[0x10];
  btoa(abuf, 0x10, ptr, 0x10);
  rp_set_comment(ea, abuf, false );
  ua_code(ptr);
  doDwrd(ea, 4);
#ifdef PIC_DEBUG
 RP_TRACE2("add_cref %X to %X\n", ea, ptr );
#endif
}
Exemple #11
0
Fichier : loader.c Projet : 8l/YESS
/* Function Name: checkLine
 * Purpose:       Determines validity of a line of YAS
 *
 * Parameters:    char * to a line of YAS
 * Returns:       -1 : all spaces in line or instruction.
 *                0 : invalid line
 *                1 : valid line
 * Modifies:      -
 */
int checkLine(char * line)
{   
    if(isSpaces(line, 0, 21) && line[22] == '|') 
            return -1;            //The case of an empty line
    else{
        if(!isSpaces(line, 0, 1)) //Check initial spaces
            return 0;
        if(!isAddress(line))      //Check for address
            return 0;
        if(!(line[7] == ':' && line[8] == ' ' && line[21] == ' ' && line[22] == '|')) //Check particular spots
            return 0;
        if(!(isData(line)))       //Check for data
        {                         //If no data...
            if(!isSpaces(line, 9, 20))//Check if only spaces
                return 0;         //If not spaces OR valid data
            else
                return -1;        //If just spaces
        }
        return 1;
    }
}
Exemple #12
0
IArray* TypeManager::getArrayOf( IType* elementType )
{
	if( !elementType )
		CORAL_THROW( IllegalArgumentException, "null element type" );

	const std::string& elementTypeName = elementType->getName();

	std::string arrayName;
	arrayName.reserve( elementTypeName.length() + 2 );
	arrayName.append( elementTypeName );
	arrayName.append( "[]" );

	Namespace* ns = static_cast<Namespace*>( elementType->getNamespace() );

	// try to locate an existing array of this type
	IType* existingArrayType = ns->getType( arrayName );
	if( existingArrayType )
	{
		assert( existingArrayType->getKind() == TK_ARRAY );
		return static_cast<IArray*>( existingArrayType );
	}

	// otherwise, try to create it
	TypeKind kind = elementType->getKind();
	if( kind == TK_ARRAY )
		CORAL_THROW( IllegalArgumentException, "arrays of arrays are illegal" );

	if( !isData( kind ) )
		CORAL_THROW( IllegalArgumentException, "arrays of " << kind << "s are illegal" );

	RefPtr<ArrayType> arrayType = new ArrayType;
	arrayType->setType( TK_ARRAY, elementType->getName() + "[]", ns );
	arrayType->setElementType( elementType );

	ns->addType( arrayType.get() );

	return arrayType.get();
}
CFDataRef SOSItemCopy(CFStringRef service, CFErrorRef* error)
{
    CFDictionaryRef query = SOSItemCopyQueryForSyncItems(service, true);

    CFDataRef result = NULL;

    OSStatus copyResult = SecItemCopyMatching(query, (CFTypeRef*) &result);

    CFReleaseNull(query);

    if (copyResult != noErr) {
        SecError(copyResult, error, CFSTR("Error %@ reading for service '%@'"), result, service);
        CFReleaseNull(result);
        return NULL;
    }

    if (!isData(result)) {
        SOSCreateErrorWithFormat(kSOSErrorProcessingFailure, NULL, error, NULL, CFSTR("SecItemCopyMatching returned non-data in '%@'"), service);
        CFReleaseNull(result);
        return NULL;
    }

    return result;
}
Exemple #14
0
bool checkLine(char * record) {
    bool validLine = FALSE;
    if(isAddress(record)) {
        //If there is an address and there is data
        if(isData(record)){
           if(isSpaces(record,0,1) && isSpaces(record,8,8) && isSpaces(record,21,21)){
              if(record[22] == '|'){
                validLine =TRUE;
              }
           }
        }
        //If there is an address and no data
        else{
            if(isSpaces(record,0,1) && isSpaces(record,8,21) && record[22] == '|')
                validLine = TRUE;
        }
    }
    //If there is no address
    else{
        if(isSpaces(record,0,21) && record[22]== '|')
          validLine = TRUE;
    }
    return validLine;
}
Exemple #15
0
int
createPhyBundleDataObj( rsComm_t *rsComm, char *collection,
                        const std::string& _resc_name, const char* rescHier, dataObjInp_t *dataObjInp, // should be able to only use rescHier
                        char* dataType ) { // JMC - backport 4658
    int l1descInx;
    int status;

    /* XXXXXX We do bundle only with UNIX_FILE_TYPE for now */
    if ( _resc_name.empty() ) {
        return SYS_INTERNAL_NULL_INPUT_ERR;
    }

    std::string type;
    irods::error err = irods::get_resource_property< std::string >(
                           _resc_name,
                           irods::RESOURCE_TYPE,
                           type );
    if ( !err.ok() ) {
        irods::log( PASS( err ) );
    }

    do {
        int loopCnt = 0;
        bzero( dataObjInp, sizeof( dataObjInp_t ) );
        while ( 1 ) {
            status = rsMkBundlePath( rsComm, collection, dataObjInp->objPath,
                                     getRandomInt() );
            if ( status < 0 ) {
                rodsLog( LOG_ERROR,
                         "createPhyBundleFile: getPhyBundlePath err for %s.stat = %d",
                         collection, status );
                return status;
            }
            /* check if BundlePath already existed */
            if ( isData( rsComm, dataObjInp->objPath, NULL ) >= 0 ) {
                if ( loopCnt >= 100 ) {
                    break;
                }
                else {
                    loopCnt++;
                    continue;
                }
            }
            else {
                break;
            }
        }

        if ( dataType != NULL && strstr( dataType, BUNDLE_STR ) != NULL ) { // JMC - backport 4658
            addKeyVal( &dataObjInp->condInput, DATA_TYPE_KW, dataType );
        }
        else {
            /* assume it is TAR_BUNDLE_DT_STR */
            addKeyVal( &dataObjInp->condInput, DATA_TYPE_KW, TAR_BUNDLE_DT_STR );
        }

        if ( rescHier != NULL ) {
            addKeyVal( &dataObjInp->condInput, RESC_HIER_STR_KW, rescHier );
        }

        if ( dataType != NULL && strstr( dataType, ZIP_DT_STR ) != NULL ) { // JMC - backport 4664
            /* zipFile type. must end with .zip */
            int len = strlen( dataObjInp->objPath );
            if ( strcmp( &dataObjInp->objPath[len - 4], ".zip" ) != 0 ) {
                strcat( dataObjInp->objPath, ".zip" );
            }
        }

        l1descInx = _rsDataObjCreateWithResc( rsComm, dataObjInp, _resc_name );

        clearKeyVal( &dataObjInp->condInput );
    }
    while ( l1descInx == OVERWRITE_WITHOUT_FORCE_FLAG );

    if ( l1descInx >= 0 ) {
        l3Close( rsComm, l1descInx );
        L1desc[l1descInx].l3descInx = 0;
        if ( dataType != NULL && strstr( dataType, ZIP_DT_STR ) != NULL ) { // JMC - backport 4664
            l3Unlink( rsComm, L1desc[l1descInx].dataObjInfo );
        }
    }

    return l1descInx;
}
Exemple #16
0
XMLByte* Base64::decode (   const XMLByte*        const   inputData
                          ,       XMLSize_t*              decodedLength
                          ,       XMLByte*&               canRepData
                          ,       MemoryManager*  const   memMgr
                          ,       Conformance             conform
                        )
{
    if ((!inputData) || (!*inputData))
        return 0;
    
    //
    // remove all XML whitespaces from the base64Data
    //
    XMLSize_t inputLength = XMLString::stringLen( (const char*)inputData );
    XMLByte* rawInputData = (XMLByte*) getExternalMemory(memMgr, (inputLength+1) * sizeof(XMLByte));
    ArrayJanitor<XMLByte> jan(rawInputData, memMgr ? memMgr : XMLPlatformUtils::fgMemoryManager);

    XMLSize_t inputIndex = 0;
    XMLSize_t rawInputLength = 0;
    bool inWhiteSpace = false;

    switch (conform)
    {
    case Conf_RFC2045:
        while ( inputIndex < inputLength )
        {
            if (!XMLChar1_0::isWhitespace(inputData[inputIndex]))
            {
                rawInputData[ rawInputLength++ ] = inputData[ inputIndex ];
            }
            // RFC2045 does not explicitly forbid more than ONE whitespace 
            // before, in between, or after base64 octects.
            // Besides, S? allows more than ONE whitespace as specified in the production 
            // [3]   S   ::=   (#x20 | #x9 | #xD | #xA)+
            // therefore we do not detect multiple ws

            inputIndex++;
        }

        break;
    case Conf_Schema:
        // no leading #x20
        if (chSpace == inputData[inputIndex])
            return 0;

        while ( inputIndex < inputLength )
        {
            if (chSpace != inputData[inputIndex])
            {
                rawInputData[ rawInputLength++ ] = inputData[ inputIndex ];
                inWhiteSpace = false;
            }
            else
            {
                if (inWhiteSpace)
                    return 0; // more than 1 #x20 encountered
                else
                    inWhiteSpace = true;
            }

            inputIndex++;
        }

        // no trailing #x20
        if (inWhiteSpace)
            return 0;

        break;

    default:
        break;
    }

    //now rawInputData contains canonical representation 
    //if the data is valid Base64
    rawInputData[ rawInputLength ] = 0;

    // the length of raw data should be divisible by four
    if (( rawInputLength % FOURBYTE ) != 0 )
        return 0;

    int quadrupletCount = (int)rawInputLength / FOURBYTE;
    if ( quadrupletCount == 0 )
        return 0;

    //
    // convert the quadruplet(s) to triplet(s)
    //
    XMLByte  d1, d2, d3, d4;  // base64 characters
    XMLByte  b1, b2, b3, b4;  // base64 binary codes ( 0..64 )

    XMLSize_t rawInputIndex  = 0;
    XMLSize_t outputIndex    = 0;
    XMLByte *decodedData = (XMLByte*) getExternalMemory(memMgr, (quadrupletCount*3+1) * sizeof(XMLByte));

    //
    // Process all quadruplet(s) except the last
    //
    int quad = 1;
    for (; quad <= quadrupletCount-1; quad++ )
    {
        // read quadruplet from the input stream
        if (!isData( (d1 = rawInputData[ rawInputIndex++ ]) ) ||
            !isData( (d2 = rawInputData[ rawInputIndex++ ]) ) ||
            !isData( (d3 = rawInputData[ rawInputIndex++ ]) ) ||
            !isData( (d4 = rawInputData[ rawInputIndex++ ]) ))
        {
            // if found "no data" just return NULL
            returnExternalMemory(memMgr, decodedData);
            return 0;
        }

        b1 = base64Inverse[ d1 ];
        b2 = base64Inverse[ d2 ];
        b3 = base64Inverse[ d3 ];
        b4 = base64Inverse[ d4 ];

        // write triplet to the output stream
        decodedData[ outputIndex++ ] = set1stOctet(b1, b2);
        decodedData[ outputIndex++ ] = set2ndOctet(b2, b3);
        decodedData[ outputIndex++ ] = set3rdOctet(b3, b4);
    }

    //
    // process the last Quadruplet
    //
    // first two octets are present always, process them
    if (!isData( (d1 = rawInputData[ rawInputIndex++ ]) ) ||
        !isData( (d2 = rawInputData[ rawInputIndex++ ]) ))
    {
        // if found "no data" just return NULL
        returnExternalMemory(memMgr, decodedData);
        return 0;
    }

    b1 = base64Inverse[ d1 ];
    b2 = base64Inverse[ d2 ];

    // try to process last two octets
    d3 = rawInputData[ rawInputIndex++ ];
    d4 = rawInputData[ rawInputIndex++ ];

    if (!isData( d3 ) || !isData( d4 ))
    {
        // check if last two are PAD characters
        if (isPad( d3 ) && isPad( d4 ))
        {
            // two PAD e.g. 3c==
            if ((b2 & 0xf) != 0) // last 4 bits should be zero
            {
                returnExternalMemory(memMgr, decodedData);
                return 0;
            }

            decodedData[ outputIndex++ ] = set1stOctet(b1, b2);
        }
        else if (!isPad( d3 ) && isPad( d4 ))
        {
            // one PAD e.g. 3cQ=
            b3 = base64Inverse[ d3 ];
            if (( b3 & 0x3 ) != 0 ) // last 2 bits should be zero
            {
                returnExternalMemory(memMgr, decodedData);
                return 0;
            }

            decodedData[ outputIndex++ ] = set1stOctet( b1, b2 );
            decodedData[ outputIndex++ ] = set2ndOctet( b2, b3 );
        }
        else
        {
            // an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data
            returnExternalMemory(memMgr, decodedData);
            return 0;
        }
    }
    else
    {
        // no PAD e.g 3cQl
        b3 = base64Inverse[ d3 ];
        b4 = base64Inverse[ d4 ];
        decodedData[ outputIndex++ ] = set1stOctet( b1, b2 );
        decodedData[ outputIndex++ ] = set2ndOctet( b2, b3 );
        decodedData[ outputIndex++ ] = set3rdOctet( b3, b4 );
    }

    // write out the end of string
    decodedData[ outputIndex ] = 0;
    *decodedLength = outputIndex;

    //allow the caller to have access to the canonical representation
    jan.release(); 
    canRepData = rawInputData;

    return decodedData;
}
Exemple #17
0
void testFunctions(){
printf("inside main\n \n ");
printf("\n validFileName tests: \n");
printf("bumba.y should return 0: ");
printf("%d\n", validFileName("bumba.y"));
printf("noDot should return 0: ");
printf("%d\n", validFileName("noDot"));
printf("victory.yo should return 1: ");
printf("%d\n", validFileName("victory.yo"));

printf("\n isAddress tests: \n");
printf("  0x01H: should return 0:");
printf("%d\n",isAddress("  0x01H:"));
printf("  1x014: should return 0:");
printf("%d\n",isAddress("  1x014:"));
printf("  0x014: should return 1:");
printf("%d\n",isAddress("  0x014:"));
printf("  0x6A4: should return 1:");
printf("%d\n",isAddress("  0x064:"));

//need to add testing for 0x014:00 ... spaces ... |
printf("\n isData tests: \n");
printf("  0x014: 0z  should return 0:");
printf("%d\n",isData("  0x014: 0z"));
printf("  0x014: 00ddxx01daq should return 0:");
printf("%d\n",isData("  0x014: 00ddxx01da0q"));
printf("  0x014: 00345dzqa000 should return 0:");
printf("%d\n",isData("  0x014: 000345dzqa000"));
printf("  0x014: 00ddd0000000 should return 1:");
printf("%d\n",isData("  0x014: 00ddd0000000 "));
printf("  0x014: 00000000001 should return 1: ");
printf("%d\n",isData("  0x014: 000000000001"));
printf("  0x014: 01 should return 1: ");
printf("%d\n",isData("  0x014: 01"));

printf("\n isSpaces tests: \n");
printf("should return 0: wxrHtl-jhplzsk");
printf("%d\n",isSpaces("wxrHtl-jhplzsk",0,14));
printf("%d\n",isSpaces("wxrHtl-jhplzsk",0,14));
printf("isSpaces should return 1: ");
printf("%d\n",isSpaces("               ",0,14));
printf("isSpaces should return 1: ");
printf("%d\n",isSpaces("   ",0,2));
printf("isSpaces should return 0: ");
printf("%d\n",isSpaces("d  ",0,2));

printf("checkHex tests: \n");
printf("abcdzf0123456789 should return 0: ");
printf("%d\n",checkHex("abcdzf0123456789",0,15));
printf("abcdef0123456789 should return 1: ");
printf("%d\n",checkHex("abcdef0123456789",0,15));

printf("grabAddress tests: \n");
printf("  0x01a should return 0x01a: ");
printf("%x\n",grabAddress("  0x01a"));
printf("  0x014 should return 0x014: ");
printf("%x\n",grabAddress("  0x014"));

printf("grabDataByte tests: \n");
printf("  01a402, 4 should return 02: ");
printf("%x\n", grabDataByte("01a402",4));
printf("  01a402, 2 should return a4: ");
printf("%x\n", grabDataByte("01a402",2));
printf("  01, 0 should return 01: ");
printf("%x\n", grabDataByte("01",0));


printf("countBytes tests: \n");
printf("  0x014: 00000000001 should return 5: ");
printf("%x\n", countBytes("  0x014: 0000000001 "));
printf("  0x014: 0201 should return 2: ");
printf("%x\n", countBytes("  0x014: 0201"));
printf("  0x014: 020100 should return 3: ");
printf("%x\n", countBytes("  0x014: 020100"));
printf("  0x014:  should return 0: ");
printf("%x\n", countBytes("  0x014: "));

printf("checkLine tests: \n");
printf("  0x014 000000000001 |comments should return 0: ");
printf("%d\n", checkLine("  0x014 000000000001 |comments\n"));
printf("0x014: 000000000001 |comments should return 0: ");
printf("%d\n", checkLine("0x014: 000000000001 |comments\n"));
printf("  0x014: 000000000001 |comments should return 1: ");
printf("%d\n", checkLine("  0x014: 000000000001 |comments\n"));
//printf("  01a402, 2 should return a4: ");
//printf("%x\n", grabDataByte("01a402",2));

//printf("  01, 0 should return 01: ");
/*
printf("discardRest should return 0: \n");
printf("%d\n",discardRest("",0,15));
printf("discardRest should return 1: \n");
printf("%d\n",discardRest("",0,15));
*/
}
Exemple #18
0
SOSAccountRef SOSAccountCreateFromDER_V1(CFAllocatorRef allocator,
                                         SOSDataSourceFactoryRef factory,
                                         CFErrorRef* error,
                                         const uint8_t** der_p, const uint8_t *der_end)
{
    SOSAccountRef account = NULL;
    
    const uint8_t *sequence_end;
    *der_p = ccder_decode_constructed_tl(CCDER_CONSTRUCTED_SEQUENCE, &sequence_end, *der_p, der_end);
    
    {
        CFDictionaryRef decoded_gestalt = NULL;
        *der_p = der_decode_dictionary(kCFAllocatorDefault, kCFPropertyListImmutable, &decoded_gestalt, error,
                                       *der_p, der_end);
        
        if (*der_p == 0)
            return NULL;
        
        account = SOSAccountCreateBasic(allocator, decoded_gestalt, factory);
        CFReleaseNull(decoded_gestalt);
    }
    
    CFArrayRef array = NULL;
    *der_p = der_decode_array(kCFAllocatorDefault, 0, &array, error, *der_p, sequence_end);
    
    *der_p = ccder_decode_bool(&account->user_public_trusted, *der_p, sequence_end);
    *der_p = der_decode_public_bytes(kCFAllocatorDefault, kSecECDSAAlgorithmID, &account->user_public, error, *der_p, sequence_end);
    *der_p = der_decode_data_or_null(kCFAllocatorDefault, &account->user_key_parameters, error, *der_p, sequence_end);
    *der_p = der_decode_dictionary(kCFAllocatorDefault, kCFPropertyListMutableContainers, (CFDictionaryRef *) &account->retired_peers, error, *der_p, sequence_end);
    if (*der_p != sequence_end)
        *der_p = NULL;
    
    __block bool success = true;
    
    require_quiet(array && *der_p, fail);
    
    CFArrayForEach(array, ^(const void *value) {
        if (success) {
            if (isString(value)) {
                CFDictionaryAddValue(account->circles, value, kCFNull);
            } else {
                CFDataRef circleData = NULL;
                CFDataRef fullPeerInfoData = NULL;
                
                if (isData(value)) {
                    circleData = (CFDataRef) value;
                } else if (isArray(value)) {
                    CFArrayRef pair = (CFArrayRef) value;
                    
                    CFTypeRef circleObject = CFArrayGetValueAtIndex(pair, 0);
                    CFTypeRef fullPeerInfoObject = CFArrayGetValueAtIndex(pair, 1);
                    
                    if (CFArrayGetCount(pair) == 2 && isData(circleObject) && isData(fullPeerInfoObject)) {
                        circleData = (CFDataRef) circleObject;
                        fullPeerInfoData = (CFDataRef) fullPeerInfoObject;
                    }
                }
                
                if (circleData) {
                    SOSCircleRef circle = SOSCircleCreateFromData(kCFAllocatorDefault, circleData, error);
                    require_action_quiet(circle, fail, success = false);
                    
                    CFStringRef circleName = SOSCircleGetName(circle);
                    CFDictionaryAddValue(account->circles, circleName, circle);
                    
                    if (fullPeerInfoData) {
                        SOSFullPeerInfoRef full_peer = SOSFullPeerInfoCreateFromData(kCFAllocatorDefault, fullPeerInfoData, error);
                        require_action_quiet(full_peer, fail, success = false);
                        
                        CFDictionaryAddValue(account->circle_identities, circleName, full_peer);
                        CFReleaseNull(full_peer);
                    }
                fail:
                    CFReleaseNull(circle);
                }
            }
        }
    });
Exemple #19
0
static bool check_for_table_jump(void)
{
  ea_t base = BADADDR, table = BADADDR, defea = BADADDR;
  int size = 0, elsize = 0;

  int i;
  bool ok = false;
  insn_t saved = cmd;
  for ( i=0; !ok && i < qnumber(patterns); i++ )
  {
    ok = patterns[i](&base, &table, &defea, &size, &elsize);
    cmd = saved;
  }
  if ( !ok ) return false;

  if ( table != BADADDR ) table = toEA(cmd.cs, table);
  if ( base  != BADADDR ) base  = toEA(cmd.cs, base);
  if ( defea != BADADDR ) defea = toEA(cmd.cs, defea);

  // check the table contents
  int oldsize = size;
  segment_t *s = getseg(table);
  if ( s == NULL ) return false;
  int maxsize = int(s->endEA - table);
  if ( size > maxsize ) size = maxsize;

  for ( i=0; i < size; i++ )
  {
    ea_t ea = table+i*elsize;
    flags_t F = getFlags(ea);
    if ( !hasValue(F)
      || (i && (has_any_name(F) || hasRef(F))) ) break;
    int el = elsize == 1 ? get_byte(ea) : get_word(ea);
    flags_t F2 = get_flags_novalue(base+el);
    if ( isTail(F2)
      || isData(F2)
      || (!isCode(F2) && !decode_insn(base+el)) ) break;
  }
  cmd = saved;
  size = i;
  if ( size != oldsize )
    msg("Warning: jpt_%04a calculated size of %d forced to %d!\n",
                                      cmd.ip, oldsize, size);

  // create the table
  if ( size == 0 ) return false;
  for ( i=0; i < size; i++ )
  {
    ea_t ea = table + i*elsize;
    (elsize == 1 ? doByte : doWord)(ea, elsize);
    op_offset(ea, 0, elsize == 1 ? REF_OFF8 : REF_OFF16, BADADDR, base);
    ua_add_cref(0, base + (elsize==1?get_byte(ea):get_word(ea)), fl_JN);
  }
  char buf[MAXSTR];
  qsnprintf(buf, sizeof(buf), "def_%a", cmd.ip);
//  set_name(defea, buf, SN_NOWARN|SN_LOCAL);         // temporary kernel bug workaround
  set_name(defea, buf, SN_NOWARN);
  qsnprintf(buf, sizeof(buf), "jpt_%a", cmd.ip);
  set_name(table, buf, SN_NOWARN);
  return true;
}
Exemple #20
0
/**
 * load
 * This function takes a command line argument containing
 * the name of a file and loads the contents of the file
 * into memory byte by byte until there is an error
 * @param: argc: the number of args
 *         args: the name of the file
 * @return: goodLine: returns false if an error was found
 */
bool load(int argc, char *args) {
    bool goodLine = TRUE; 
    int lineNumber = 1;
    if(validFileName(args)){
        FILE * fi;
        fi = fopen(args,"r");
        char record[80];      
        int prevAdr = -1,startAdr,lineSize;
        int firstLine = 0;
        int loop;
        int dataLoc,byteLoc;
        int dataLength;
        bool lastLineData;
        bool memError;
        while(fgets(record,80,fi)!=NULL && goodLine){
            dataLoc = 9;  //Where data starts
            byteLoc = 0;  //Which byte of data to get
            if (isAddress(record)){ 
                startAdr=setLastAddress(record); //Address in a record
            }
            int lineSize = lineLength(record); //Length of record
                
            if(record[lineSize]!='\n') {
                discardRest(record,fi);
            }
            
            //Calls the checkLine
            if(checkLine(record)) {
                dataLength = lengthOfData(record); //Length of data in a record
                
                //If the record isn't the first line of the file
                if(firstLine==1) {
                   if(!(lastLineData&&startAdr>prevAdr)) { //If there was data on the last line make sure the address is bigger
                      goodLine = FALSE;
                      //printf("Error on line %d\n",lineNumber);
                   }
                }
                //If the record is the first line
                else{
                    if(isAddress(record)) {
                        firstLine = 1;
                    }
                }
            }
            
            //checkLine returns false
            else{ 
                //printf("Error on line %d\n",lineNumber);
                goodLine = FALSE;
            }
            
            //If all checks have passed
            if(goodLine){
                //Goes through the data
                for(loop = 0; loop < dataLength;loop+=2){
                    //Adds the byte to memory
                    putByte(startAdr,grabDataByte(record,byteLoc),&memError);
                    //printf("%x\n",grabDataByte(record,byteLoc));
                    startAdr++;
                    byteLoc+=2;
                }
                //puts(record); //Output record
                prevAdr = startAdr - 1;
                lineNumber++;
                lastLineData = isData(record);
           } 
           else if(goodLine == FALSE){
               printf("Error on line %d\n", lineNumber);
               puts(record);
           }
      }   
        fclose(fi);
     }
     
     
     //If the file didn't open   
     else{
         goodLine = FALSE;
         printf("Error opening file");
     }
     
     
     return goodLine;

     
}
Exemple #21
0
ostream& HumdrumLine::printXml(ostream& out, int level, const string& indent) {

	if (hasSpines()) {
		out << Convert::repeatString(indent, level) << "<frame";
		out << " n=\"" << getLineIndex() << "\"";
		out << " xml:id=\"" << getXmlId() << "\"";
		out << ">\n";
		level++;

		out << Convert::repeatString(indent, level) << "<frameInfo>\n";
		level++;

		out << Convert::repeatString(indent, level) << "<fieldCount>";
		out << getTokenCount() << "</fieldCount>\n";

		out << Convert::repeatString(indent, level);
		out << "<frameStart";
		out << Convert::getHumNumAttributes(getDurationFromStart());
		out << "/>\n";

		out << Convert::repeatString(indent, level);
		out << "<frameDuration";
		out << Convert::getHumNumAttributes(getDuration());
		out << "/>\n";

		out << Convert::repeatString(indent, level) << "<frameType>";
		if (isData()) {
			out << "data";
		} else if (isBarline()) {
			out << "barline";
		} else if (isInterpretation()) {
			out << "interpretation";
		} else if (isLocalComment()) {
			out << "local-comment";
		}
		out << "</frameType>\n";

		if (isBarline()) {
			// print the duration to the next barline or to the end of the score
			// if there is no barline at the end of the score.
			out << Convert::repeatString(indent, level);
			out << "<barlineDuration";
			out << Convert::getHumNumAttributes(getBarlineDuration());
			out << "/>\n";
		}

		bool bstart = isKernBoundaryStart();
		bool bend   = isKernBoundaryEnd();
		if (bstart || bend) {
			out << Convert::repeatString(indent, level);
			cout << "<kernBoundary";
			cout << " start=\"";
			if (bstart) {
				cout << "true";
			} else {
				cout << "false";
			}
			cout << "\"";
			cout << " end=\"";
			if (bend) {
				cout << "true";
			} else {
				cout << "false";
			}
			cout << "\"";
			cout << "/>\n";
		}

		level--;
		out << Convert::repeatString(indent, level) << "</frameInfo>\n";

		out << Convert::repeatString(indent, level) << "<fields>\n";
		level++;
		for (int i=0; i<getFieldCount(); i++) {
			token(i)->printXml(out, level, indent);
		}
		level--;
		out << Convert::repeatString(indent, level) << "</fields>\n";
		
		level--;
		out << Convert::repeatString(indent, level) << "</frame>\n";

	} else {
		// global comments, reference records, or blank lines print here.
		out << Convert::repeatString(indent, level) << "<metaFrame";
		out << " n=\"" << getLineIndex() << "\"";
		out << " token=\"" << Convert::encodeXml(((string)(*this))) << "\"";
		out << " xml:id=\"" << getXmlId() << "\"";
		out << "/>\n";
		level++;

		out << Convert::repeatString(indent, level) << "<frameInfo>\n";
		level++;

		out << Convert::repeatString(indent, level);
		out << "<startTime";
		out << Convert::getHumNumAttributes(getDurationFromStart());
		out << "/>\n";

		out << Convert::repeatString(indent, level) << "<frameType>";
		if (isReference()) {
			out << "reference";
		} else if (isBlank()) {
			out << "empty";
		} else {
			out << "global-comment";
		}
		out << "</frameType>\n";

		if (isReference()) {
			out << Convert::repeatString(indent, level);
			out << "<referenceKey>" << Convert::encodeXml(getReferenceKey());
			out << "</referenceKey>\n";

			out << Convert::repeatString(indent, level);
			out << "<referenceValue>" << Convert::encodeXml(getReferenceValue());
			out << "</referenceValue>\n";
		}

		level--;
		out << Convert::repeatString(indent, level) << "<frameInfo>\n";


		level--;
		out << Convert::repeatString(indent, level) << "</metaFrame>\n";
	}

	return out;
}
Exemple #22
0
int
dirPathReg (rsComm_t *rsComm, dataObjInp_t *phyPathRegInp, char *filePath,
rescInfo_t *rescInfo)
{
    collInp_t collCreateInp;
    fileOpendirInp_t fileOpendirInp;
    fileClosedirInp_t fileClosedirInp;
    int rescTypeInx;
    int status;
    int dirFd;
    dataObjInp_t subPhyPathRegInp;
    fileReaddirInp_t fileReaddirInp;
    rodsDirent_t *rodsDirent = NULL;
    rodsObjStat_t *rodsObjStatOut = NULL;
    int forceFlag;
    fileStatInp_t fileStatInp;
    rodsStat_t *myStat = NULL;

    rescTypeInx = rescInfo->rescTypeInx;

    status = collStat (rsComm, phyPathRegInp, &rodsObjStatOut);
    if (status < 0) {
        memset (&collCreateInp, 0, sizeof (collCreateInp));
        rstrcpy (collCreateInp.collName, phyPathRegInp->objPath, 
	  MAX_NAME_LEN);
	/* no need to resolve sym link */
	addKeyVal (&collCreateInp.condInput, TRANSLATED_PATH_KW, "");
#ifdef FILESYSTEM_META
        /* stat the source directory to track the         */
        /* original directory meta-data                   */
        memset (&fileStatInp, 0, sizeof (fileStatInp));
        rstrcpy (fileStatInp.fileName, filePath, MAX_NAME_LEN);
        fileStatInp.fileType = (fileDriverType_t)RescTypeDef[rescTypeInx].driverType;
        rstrcpy (fileStatInp.addr.hostAddr, rescInfo->rescLoc, NAME_LEN);

        status = rsFileStat (rsComm, &fileStatInp, &myStat);
        if (status != 0) {
            rodsLog (LOG_ERROR,
	      "dirPathReg: rsFileStat failed for %s, status = %d",
	      filePath, status);
	    return (status);
        }
        getFileMetaFromStat (myStat, &collCreateInp.condInput);
        addKeyVal(&collCreateInp.condInput, FILE_SOURCE_PATH_KW, filePath);
        free (myStat);
#endif /* FILESYSTEM_META */
        /* create the coll just in case it does not exist */
        status = rsCollCreate (rsComm, &collCreateInp);
	clearKeyVal (&collCreateInp.condInput);
	if (status < 0) return status;
    } else if (rodsObjStatOut->specColl != NULL) {
        freeRodsObjStat (rodsObjStatOut);
        rodsLog (LOG_ERROR,
          "mountFileDir: %s already mounted", phyPathRegInp->objPath);
        return (SYS_MOUNT_MOUNTED_COLL_ERR);
    }
    freeRodsObjStat (rodsObjStatOut);

    memset (&fileOpendirInp, 0, sizeof (fileOpendirInp));

    rstrcpy (fileOpendirInp.dirName, filePath, MAX_NAME_LEN);
    fileOpendirInp.fileType = (fileDriverType_t)RescTypeDef[rescTypeInx].driverType;
    rstrcpy (fileOpendirInp.addr.hostAddr,  rescInfo->rescLoc, NAME_LEN);

    dirFd = rsFileOpendir (rsComm, &fileOpendirInp);
    if (dirFd < 0) {
       rodsLog (LOG_ERROR,
          "dirPathReg: rsFileOpendir for %s error, status = %d",
          filePath, dirFd);
        return (dirFd);
    }

    fileReaddirInp.fileInx = dirFd;

    if (getValByKey (&phyPathRegInp->condInput, FORCE_FLAG_KW) != NULL) {
	forceFlag = 1;
    } else {
	forceFlag = 0;
    }

    while ((status = rsFileReaddir (rsComm, &fileReaddirInp, &rodsDirent))
      >= 0) {

        if (strcmp (rodsDirent->d_name, ".") == 0 ||
          strcmp (rodsDirent->d_name, "..") == 0) {
	    free (rodsDirent);
            continue;
        }

	memset (&fileStatInp, 0, sizeof (fileStatInp));

        snprintf (fileStatInp.fileName, MAX_NAME_LEN, "%s/%s",
          filePath, rodsDirent->d_name);

        fileStatInp.fileType = fileOpendirInp.fileType; 
	fileStatInp.addr = fileOpendirInp.addr;
        myStat = NULL;
        status = rsFileStat (rsComm, &fileStatInp, &myStat);

	if (status != 0) {
            rodsLog (LOG_ERROR,
	      "dirPathReg: rsFileStat failed for %s, status = %d",
	      fileStatInp.fileName, status);
	    free (rodsDirent);
	    return (status);
	}

	subPhyPathRegInp = *phyPathRegInp;
	snprintf (subPhyPathRegInp.objPath, MAX_NAME_LEN, "%s/%s",
	  phyPathRegInp->objPath, rodsDirent->d_name);

	if ((myStat->st_mode & S_IFREG) != 0) {     /* a file */
	    if (forceFlag > 0) {
		/* check if it already exists */
	        if (isData (rsComm, subPhyPathRegInp.objPath, NULL) >= 0) {
		    free (myStat);
	            free (rodsDirent);
		    continue;
		}
	    }
	    subPhyPathRegInp.dataSize = myStat->st_size;
	    if (getValByKey (&phyPathRegInp->condInput, REG_REPL_KW) != NULL) {
                status = filePathRegRepl (rsComm, &subPhyPathRegInp,
                  fileStatInp.fileName, rescInfo);
	    } else {
                addKeyVal (&subPhyPathRegInp.condInput, FILE_PATH_KW, 
	          fileStatInp.fileName);
	        status = filePathReg (rsComm, &subPhyPathRegInp, 
	          fileStatInp.fileName, rescInfo);
	    }
        } else if ((myStat->st_mode & S_IFDIR) != 0) {      /* a directory */
            status = dirPathReg (rsComm, &subPhyPathRegInp,
              fileStatInp.fileName, rescInfo);
	}
	free (myStat);
	free (rodsDirent);
    }
    if (status == -1) {         /* just EOF */
        status = 0;
    }

    fileClosedirInp.fileInx = dirFd;
    rsFileClosedir (rsComm, &fileClosedirInp);

    return (status);
}
Exemple #23
0
/**
 * Record a trace, this is a blocking function.
 * Use the ext interupt 0 and 1.
 * Use the timer 1.
 */
uchar* recordTrace(int *size) {
    uchar charIndex = 0;
    uchar charBuffer;

    uint state = STATE_BEGINING;

    uchar i = 0;
    uchar t0 = (uchar) 0x00;
    uint tmpEtu = NO_ETU_CHANGE;
    uchar protocol;
    uchar convention;

    convention = CONVENTION_DIRECTE;
    protocol = PROTOCOL_T0;

    initialiseInterupt();

    if(!waitForIO())
    {
        reInit();
        return NULL;
    }

    /* Configure the interupt on IO to answer on each falling edge*/
    ConfigINT2(EXT_INT_ENABLE | FALLING_EDGE_INT | EXT_INT_PRI_1);

    /* Configure the warm reset to trigger on falling edge*/
    ConfigINT1(EXT_INT_ENABLE | FALLING_EDGE_INT | EXT_INT_PRI_1);

    while( (STATE_TERMINATED != state))
    {
        state = getState();
        if( (isData() > 0) && dataIndex < DATA_SIZE)
        {
            charBuffer = 0x00;
            for(charIndex = 0 ; charIndex < 8 ; charIndex++ )
            {
                if(CONVENTION_INVERSE == convention)
                {
                    charBuffer ^= (getAcq() << (7-charIndex));
                }
                else if(CONVENTION_DIRECTE == convention)
                {
                    charBuffer ^= (getAcq() << charIndex);
                }
            }
            if(CONVENTION_INVERSE == convention)
            {
                charBuffer = 0xff ^ charBuffer;
            }
            dataArray[dataIndex] = charBuffer;

            dataIndex++;
            clearFlag();

            if(STATE_TS == state)
            {
                if((uchar) 0x3b == charBuffer)
                {
                    convention = CONVENTION_DIRECTE;
                }

                /* 0x03 is the way the byte 3f will be read with the tool
                 * For information, by default the Direct convention is used
                 * so we don't see directly the byte 3F but the byte 3f coded
                 * in direct convention = 0x03 */
                if((uchar) 0x03 == charBuffer)
                {
                    convention = CONVENTION_INVERSE;
                    dataArray[dataIndex-1] = 0x3f;
                }

                setState(STATE_T0);
            }
            else if(STATE_T0 == state)
            {
                t0 = charBuffer;
                setState(STATE_ATR);
            } /*Then we treats TAx, TBx, TCx, TDx,... and finaly hist bytes */
            else if(0 < (t0 & 0x10) )
            {
                t0 = t0 ^ 0x10;
                /* It's a TAx */
                if(0 == i) /* It's Ta1*/
                {
                    /*Configuring the new ATR value*/
                    tmpEtu = computeEtu(charBuffer);
                }
            }
            else if(0 < (t0 & 0x20) )
            {
                /*It's a TBx*/
                t0 = t0 ^ 0x20;
            }
            else if(0 < (t0 & 0x40) )
            {
                /*It's a TCx*/
                t0 = t0 ^ 0x40;
            }
            else if(0 < (t0 & 0x80) )
            {
                /*It's a TDx*/
                t0 = t0 ^ 0x80;
                /* t0 is only compose of the historical bytes We verify if
                 the TD bytes implies other bytes*/
                t0 ^= (charBuffer & 0xf0);
                i++;

                /* We also verify if it's a T=1 protocol */
                if( ((uchar) 0x01) == ((uchar) charBuffer ^ 0x01) )
                {
                    /*It's a t=1 card set the value to T=1*/
                    protocol = PROTOCOL_T1;
                }

            }
            else if(0 < (t0 & 0x0F))
            {
                /* This is historical bytes */
                t0--;
                if(t0 == 0)
                {
                    if(PROTOCOL_T1 == protocol)
                    {
                        setState(STATE_ATR_CRC);
                    }
                    else
                    {
                        setState(STATE_PROCESSING);
                        fixEtu(tmpEtu);
                    }
                }
            }
            else if(STATE_ATR_CRC == state) {
                setState(STATE_PROCESSING);
                fixEtu(tmpEtu);
            }
        }/*end of if(isData() > 0 )*/
        else if(STATE_RESET == getState()) {
            charIndex = 0;
            convention = CONVENTION_DIRECTE;
            warmAtrOffset = dataIndex;
            t0 = 0x00;
            setState(STATE_BEGINING);
        }
        if( !isData() && !PIN_VCC )
        {
            setState(STATE_TERMINATED);
        }
        if(dataIndex >= DATA_SIZE )
        {
#ifdef DEBUG
            sendDataBuffer("Array overflow\n");
#endif
            setState(STATE_TERMINATED);
        }
    }//End of while

    /* Stop the interupt on IO */
    ConfigINT0(EXT_INT_DISABLE);

    /* Stop the warm reset */
    ConfigINT1(EXT_INT_DISABLE);

#ifdef DEBUG
    sendDataBuffer("Trace recorded : \n");
#endif

    /* End of debug information */
    *size = dataIndex;
    reInit();
    return dataArray;
}
Exemple #24
0
/* AUDIT[securityd](done):
   receiver (unused) is a mach_port owned by this process.
   reply (checked by mig) is a caller provided mach_port.
   auditToken (ok) is a kernel provided audit token.
   request_id (checked by mig) is caller provided value, that matches the
       mig entry for this function.
   msg_id (ok) is caller provided value.
   msg_data (ok) is a caller provided data of length:
   msg_length (ok).
 */
kern_return_t securityd_server_request(mach_port_t receiver, mach_port_t reply,
        audit_token_t auditToken,
        uint32_t request_id, uint32_t msg_id, uint8_t *msg_data,
        mach_msg_type_number_t msg_length)
{
    CFTypeRef args_in = NULL;
    CFTypeRef args_out = NULL;
    bool sendResponse = true;
    const char *op_name;

    request_begin();

    if (msg_length) {
        CFDataRef data_in = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault,
            msg_data, msg_length, kCFAllocatorNull);
        if (data_in) {
            args_in = CFPropertyListCreateFromXMLData(kCFAllocatorDefault,
                data_in, kCFPropertyListImmutable, NULL);
            CFRelease(data_in);
        }
    }

#if 0
    static int crash_counter = 0;
    if (crash_counter++) {
        secdebug("server", "crash test");
        exit(1);
    }
#endif

    SecTaskRef clientTask = 
#if CHECK_ENTITLEMENTS
    SecTaskCreateWithAuditToken(kCFAllocatorDefault, auditToken);
#else 
    NULL;
#endif
    CFArrayRef groups = SecTaskCopyAccessGroups(clientTask);
    SecAccessGroupsSetCurrent(groups);
    OSStatus status = errSecParam;
    switch(msg_id) {
        case sec_item_add_id:
            op_name = "SecItemAdd";
            if (isDictionary(args_in))
                status = _SecItemAdd(args_in, &args_out, groups);
            break;
        case sec_item_copy_matching_id:
            op_name = "SecItemCopyMatching";
            if (isDictionary(args_in))
                status = _SecItemCopyMatching(args_in, &args_out, groups);
            break;
        case sec_item_delete_id:
            op_name = "SecItemDelete";
            if (isDictionary(args_in))
                status = _SecItemDelete(args_in, groups);
            break;
        case sec_item_update_id:
            op_name = "SecItemUpdate";
            if (isArrayOfLength(args_in, 2)) {
                CFDictionaryRef
                    in0 = (CFDictionaryRef)CFArrayGetValueAtIndex(args_in, 0),
                    in1 = (CFDictionaryRef)CFArrayGetValueAtIndex(args_in, 1);
                if (isDictionary(in0) && isDictionary(in1))
                    status = _SecItemUpdate(in0, in1, groups);
            }
            break;
        case sec_trust_store_contains_id:
        {
            op_name = "SecTrustStoreContains";
            if (!isArray(args_in))
                break;
            CFIndex argc_in = CFArrayGetCount(args_in);
            if (argc_in != 2)
                break;
            CFStringRef domainName = CFArrayGetValueAtIndex(args_in, 0);
            CFDataRef digest = CFArrayGetValueAtIndex(args_in, 1);
            if (!isString(domainName) || !isData(digest))
                break;

            SecTrustStoreRef ts = SecTrustStoreForDomainName(domainName);
            status = !SecTrustStoreContainsCertificateWithDigest(ts, digest);
            break;
        }
        case sec_trust_store_set_trust_settings_id:
        {
            op_name = "SecTrustStoreSetTrustSettings";
            /* Open the trust store unconditially so we can abuse this method
               even in clients that just want to read from the truststore,
               and this call will force it to be created. */
            SecTrustStoreRef ts = SecTrustStoreForDomain(kSecTrustStoreDomainUser);
            if (!isArray(args_in))
                break;
            CFIndex argc_in = CFArrayGetCount(args_in);
            if (argc_in != 1 && argc_in != 2)
                break;
            if (!SecTaskGetBooleanValueForEntitlement(clientTask,
                kSecEntitlementModifyAnchorCertificates)) {
                status = errSecMissingEntitlement;
                break;
            }
            CFDataRef certificateData = (CFDataRef)CFArrayGetValueAtIndex(args_in, 0);
            if (!isData(certificateData))
                break;
            SecCertificateRef certificate = SecCertificateCreateWithData(NULL, certificateData);
            if (certificate) {
                CFTypeRef trustSettingsDictOrArray;
                if (argc_in < 2) {
                    trustSettingsDictOrArray = NULL;
                } else {
                    trustSettingsDictOrArray = CFArrayGetValueAtIndex(args_in, 1);
                    if (trustSettingsDictOrArray) {
                        CFTypeID tst = CFGetTypeID(trustSettingsDictOrArray);
                        if (tst != CFArrayGetTypeID() && tst != CFDictionaryGetTypeID()) {
                            CFRelease(certificate);
                            break;
                        }
                    }
                }
                status = _SecTrustStoreSetTrustSettings(ts, certificate, trustSettingsDictOrArray);
                CFRelease(certificate);
            }
            break;
        }
        case sec_trust_store_remove_certificate_id:
            op_name = "SecTrustStoreRemoveCertificate";
            if (SecTaskGetBooleanValueForEntitlement(clientTask,
                    kSecEntitlementModifyAnchorCertificates)) {
                SecTrustStoreRef ts = SecTrustStoreForDomain(kSecTrustStoreDomainUser);
                if (isData(args_in)) {
                    status = SecTrustStoreRemoveCertificateWithDigest(ts, args_in);
                }
            } else {
                status = errSecMissingEntitlement;
            }
            break;
        case sec_delete_all_id:
            op_name = "SecDeleteAll";
            if (SecTaskGetBooleanValueForEntitlement(clientTask,
                kSecEntitlementWipeDevice)) {
                status = SecItemDeleteAll();
            } else {
                status = errSecMissingEntitlement;
            }
            break;
        case sec_trust_evaluate_id:
            op_name = "SecTrustEvaluate";
            if (isDictionary(args_in)) {
                struct securityd_server_trust_evaluation_context *tec = malloc(sizeof(*tec));
                tec->reply = reply;
                tec->request_id = request_id;
                status = SecTrustServerEvaluateAsync(args_in,
                    securityd_server_trust_evaluate_done, tec);
                if (status == noErr || status == errSecWaitForCallback) {
                    sendResponse = false;
                } else {
                    free(tec);
                }
            }
            break;
        case sec_restore_keychain_id:
            op_name = "SecRestoreKeychain";
            if (SecTaskGetBooleanValueForEntitlement(clientTask,
                kSecEntitlementRestoreKeychain)) {
                status = _SecServerRestoreKeychain();
            } else {
                status = errSecMissingEntitlement;
            }
            break;
        case sec_migrate_keychain_id:
            op_name = "SecMigrateKeychain";
            if (isArray(args_in)) {
                if (SecTaskGetBooleanValueForEntitlement(clientTask,
                    kSecEntitlementMigrateKeychain)) {
                    status = _SecServerMigrateKeychain(args_in, &args_out);
                } else {
                    status = errSecMissingEntitlement;
                }
            }
            break;
        case sec_keychain_backup_id:
            op_name = "SecKeychainBackup";
            if (!args_in || isArray(args_in)) {
                if (SecTaskGetBooleanValueForEntitlement(clientTask,
                    kSecEntitlementRestoreKeychain)) {
                    status = _SecServerKeychainBackup(args_in, &args_out);
                } else {
                    status = errSecMissingEntitlement;
                }
            }
            break;
        case sec_keychain_restore_id:
            op_name = "SecKeychainRestore";
            if (isArray(args_in)) {
                if (SecTaskGetBooleanValueForEntitlement(clientTask,
                    kSecEntitlementRestoreKeychain)) {
                    status = _SecServerKeychainRestore(args_in, &args_out);
                } else {
                    status = errSecMissingEntitlement;
                }
            }
            break;
        default:
            op_name = "invalid_operation";
            status = errSecParam;
            break;
    }

    const char *proc_name;
#ifdef NDEBUG
    if (status == errSecMissingEntitlement) {
#endif
        pid_t pid;
        audit_token_to_au32(auditToken, NULL, NULL, NULL, NULL, NULL, &pid, NULL, NULL);
        int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid};
        struct kinfo_proc kp;
        size_t len = sizeof(kp);
        if (sysctl(mib, 4, &kp, &len, NULL, 0) == -1 || len == 0)
            proc_name = strerror(errno);
        else
            proc_name = kp.kp_proc.p_comm;

#ifndef NDEBUG
    if (status == errSecMissingEntitlement) {
#endif
        asl_log(NULL, NULL, ASL_LEVEL_ERR,
            "%s[%u] %s: missing entitlement", proc_name, pid, op_name);
        /* Remap errSecMissingEntitlement -> errSecInteractionNotAllowed. */
        status = errSecInteractionNotAllowed;
    }

    secdebug("ipc", "%s[%u] %s: returning: %d", proc_name, pid, op_name,
        status);

    CFReleaseSafe(groups);
    CFReleaseSafe(clientTask);
    SecAccessGroupsSetCurrent(NULL);

    kern_return_t err = 0;
    if (sendResponse)
        err = securityd_server_send_reply(reply, request_id, status, args_out);

    CFReleaseSafe(args_in);

    return err;
}

extern boolean_t securityd_request_server(mach_msg_header_t *InHeadP, mach_msg_header_t *OutHeadP);

union max_msg_size_union {
    union __RequestUnion__securityd_client_securityd_reply_subsystem reply;
};

static uint8_t reply_buffer[sizeof(union max_msg_size_union) + MAX_TRAILER_SIZE];

static void *handle_message(void *msg, CFIndex size,
        CFAllocatorRef allocator, void *info)
{
    mach_msg_header_t *message = (mach_msg_header_t *)msg;
    mach_msg_header_t *reply = (mach_msg_header_t *)reply_buffer;

    securityd_request_server(message, reply);

    return NULL;
}
Exemple #25
0
/* -----------------------------------------------------------------------------
    l2tpvpn_listen - called by vpnd to setup listening socket
----------------------------------------------------------------------------- */
int l2tpvpn_listen(void)
{
	char *errstr;
        
    if (listen_sockfd <= 0)
        return -1;
    
    //set_flag(listen_sockfd, kerneldebug & 1, L2TP_FLAG_DEBUG);
    set_flag(listen_sockfd, 1, L2TP_FLAG_CONTROL);
    set_flag(listen_sockfd, !opt_noipsec, L2TP_FLAG_IPSEC);

    /* unknown src and dst addresses */
    any_address.sin_len = sizeof(any_address);
    any_address.sin_family = AF_INET;
    any_address.sin_port = 0;
    any_address.sin_addr.s_addr = INADDR_ANY;
    
    /* bind the socket in the kernel with L2TP port */
    listen_address.sin_len = sizeof(listen_address);
    listen_address.sin_family = AF_INET;
    listen_address.sin_port = htons(L2TP_UDP_PORT);
    listen_address.sin_addr.s_addr = INADDR_ANY;
    l2tp_set_ouraddress(listen_sockfd, (struct sockaddr *)&listen_address);
    our_address = listen_address;

    /* add security policies */
    if (!opt_noipsec) { 

		CFStringRef				auth_method;
		CFStringRef				string;
		CFDataRef				data;
		uint32_t						natt_multiple_users;

		/* get authentication method from the IPSec dict */
		auth_method = CFDictionaryGetValue(ipsec_settings, kRASPropIPSecAuthenticationMethod);
		if (!isString(auth_method))
			auth_method = kRASValIPSecAuthenticationMethodSharedSecret;

		/* get setting for nat traversal multiple user support - default is enabled for server */
		GetIntFromDict(ipsec_settings, kRASPropIPSecNattMultipleUsersEnabled, &natt_multiple_users, 1);
			
		ipsec_dict = IPSecCreateL2TPDefaultConfiguration(
			(struct sockaddr *)&our_address, (struct sockaddr *)&any_address, NULL, 
			auth_method, 0, natt_multiple_users, 0); 

		/* set the authentication information */
		if (CFEqual(auth_method, kRASValIPSecAuthenticationMethodSharedSecret)) {
			string = CFDictionaryGetValue(ipsec_settings, kRASPropIPSecSharedSecret);
			if (isString(string)) 
				CFDictionarySetValue(ipsec_dict, kRASPropIPSecSharedSecret, string);
			else if (isData(string) && ((CFDataGetLength((CFDataRef)string) % sizeof(UniChar)) == 0)) {
				CFStringEncoding    encoding;

				data = (CFDataRef)string;
#if     __BIG_ENDIAN__
				encoding = (*(CFDataGetBytePtr(data) + 1) == 0x00) ? kCFStringEncodingUTF16LE : kCFStringEncodingUTF16BE;
#else   // __LITTLE_ENDIAN__
				encoding = (*(CFDataGetBytePtr(data)    ) == 0x00) ? kCFStringEncodingUTF16BE : kCFStringEncodingUTF16LE;
#endif
				string = CFStringCreateWithBytes(NULL, (const UInt8 *)CFDataGetBytePtr(data), CFDataGetLength(data), encoding, FALSE);
				CFDictionarySetValue(ipsec_dict, kRASPropIPSecSharedSecret, string);
				CFRelease(string);
			}
			string = CFDictionaryGetValue(ipsec_settings, kRASPropIPSecSharedSecretEncryption);
			if (isString(string)) 
				CFDictionarySetValue(ipsec_dict, kRASPropIPSecSharedSecretEncryption, string);
		}
		else if (CFEqual(auth_method, kRASValIPSecAuthenticationMethodCertificate)) {
			data = CFDictionaryGetValue(ipsec_settings, kRASPropIPSecLocalCertificate);
			if (isData(data)) 
				CFDictionarySetValue(ipsec_dict, kRASPropIPSecLocalCertificate, data);
		}

		if (IPSecApplyConfiguration(ipsec_dict, &errstr)
			|| IPSecInstallPolicies(ipsec_dict, -1, &errstr)) {
			vpnlog(LOG_ERR, "L2TP plugin: cannot configure secure transport (%s).\n", errstr);
			IPSecRemoveConfiguration(ipsec_dict, &errstr);
			CFRelease(ipsec_dict);
			ipsec_dict = 0;
			return -1;
		}

        /* set IPSec Key management to prefer most recent key */
        if (IPSecSetSecurityAssociationsPreference(&key_preference, 0))
            vpnlog(LOG_ERR, "L2TP plugin: cannot set IPSec Key management preference (error %d)\n", errno);
		
		sick_timeleft = IPSEC_SICK_TIME;
		ping_timeleft = 0;

    }

    return listen_sockfd;
}
Exemple #26
0
int
dirPathReg (rsComm_t *rsComm, dataObjInp_t *phyPathRegInp, char *filePath,
rescInfo_t *rescInfo)
{
    collInp_t collCreateInp;
    fileOpendirInp_t fileOpendirInp;
    fileClosedirInp_t fileClosedirInp;
    int rescTypeInx;
    int status;
    int dirFd;
    dataObjInp_t subPhyPathRegInp;
    fileReaddirInp_t fileReaddirInp;
    rodsDirent_t *rodsDirent = NULL;
    rodsObjStat_t *rodsObjStatOut = NULL;
    int forceFlag;
    fileStatInp_t fileStatInp;
    rodsStat_t *myStat = NULL;
    char curcoll[MAX_NAME_LEN];

    *curcoll = '\0';
    rescTypeInx = rescInfo->rescTypeInx;

    status = collStat (rsComm, phyPathRegInp, &rodsObjStatOut);
    if (status < 0) {
        memset (&collCreateInp, 0, sizeof (collCreateInp));
        rstrcpy (collCreateInp.collName, phyPathRegInp->objPath, 
	  MAX_NAME_LEN);
	/* no need to resolve sym link */
	addKeyVal (&collCreateInp.condInput, TRANSLATED_PATH_KW, "");
#ifdef FILESYSTEM_META
        /* stat the source directory to track the         */
        /* original directory meta-data                   */
        memset (&fileStatInp, 0, sizeof (fileStatInp));
        rstrcpy (fileStatInp.fileName, filePath, MAX_NAME_LEN);
        fileStatInp.fileType = (fileDriverType_t)RescTypeDef[rescTypeInx].driverType;
        rstrcpy (fileStatInp.addr.hostAddr, rescInfo->rescLoc, NAME_LEN);

        status = rsFileStat (rsComm, &fileStatInp, &myStat);
        if (status != 0) {
            rodsLog (LOG_ERROR,
	      "dirPathReg: rsFileStat failed for %s, status = %d",
	      filePath, status);
	    return (status);
        }
        getFileMetaFromStat (myStat, &collCreateInp.condInput);
        addKeyVal(&collCreateInp.condInput, FILE_SOURCE_PATH_KW, filePath);
        free (myStat);
#endif /* FILESYSTEM_META */
        /* create the coll just in case it does not exist */
        status = rsCollCreate (rsComm, &collCreateInp);
	clearKeyVal (&collCreateInp.condInput);
	if (status < 0) {
            rodsLog (LOG_ERROR,
              "dirPathReg: rsCollCreate %s error. status = %d", 
              phyPathRegInp->objPath, status);
            return status;
        }
    } else if (rodsObjStatOut->specColl != NULL) {
        freeRodsObjStat (rodsObjStatOut);
        rodsLog (LOG_ERROR,
          "dirPathReg: %s already mounted", phyPathRegInp->objPath);
        return (SYS_MOUNT_MOUNTED_COLL_ERR);
    }
    freeRodsObjStat (rodsObjStatOut);

    memset (&fileOpendirInp, 0, sizeof (fileOpendirInp));

    rstrcpy (fileOpendirInp.dirName, filePath, MAX_NAME_LEN);
    fileOpendirInp.fileType = (fileDriverType_t)RescTypeDef[rescTypeInx].driverType;
    rstrcpy (fileOpendirInp.addr.hostAddr,  rescInfo->rescLoc, NAME_LEN);

    dirFd = rsFileOpendir (rsComm, &fileOpendirInp);
    if (dirFd < 0) {
       rodsLog (LOG_ERROR,
          "dirPathReg: rsFileOpendir for %s error, status = %d",
          filePath, dirFd);
        return (dirFd);
    }

    fileReaddirInp.fileInx = dirFd;

    if (getValByKey (&phyPathRegInp->condInput, FORCE_FLAG_KW) != NULL) {
	forceFlag = 1;
    } else {
	forceFlag = 0;
    }

    while ((status = rsFileReaddir (rsComm, &fileReaddirInp, &rodsDirent))
      >= 0) {
	int len;

        if (strlen (rodsDirent->d_name) == 0) break;

        if (strcmp (rodsDirent->d_name, ".") == 0 ||
          strcmp (rodsDirent->d_name, "..") == 0) {
	    free (rodsDirent);
            continue;
        }

        if (matchPathname(ExcludePatterns, rodsDirent->d_name, filePath)) {
            continue;
        }

	memset (&fileStatInp, 0, sizeof (fileStatInp));

        if (RescTypeDef[rescTypeInx].incParentDir == NO_INC_PARENT_DIR) {
	    /* don't include parent path */
            snprintf (fileStatInp.fileName, MAX_NAME_LEN, "%s",
             rodsDirent->d_name);
        } else if (RescTypeDef[rescTypeInx].incParentDir == 
          PHYPATH_IN_DIR_PTR) {
            /* we can do this locally because this API is executed at the
             * resource server */
            getPhyPathInOpenedDir (dirFd, rodsDirent->d_ino, 
              fileStatInp.fileName);
        } else {
	    len = strlen (filePath);
	    if (filePath[len - 1] == '/') {
                /* already has a '/' */
                snprintf (fileStatInp.fileName, MAX_NAME_LEN, "%s%s",
                 filePath, rodsDirent->d_name);
            } else {
                snprintf (fileStatInp.fileName, MAX_NAME_LEN, "%s/%s",
                  filePath, rodsDirent->d_name);
            }
        }
        fileStatInp.fileType = fileOpendirInp.fileType; 
	fileStatInp.addr = fileOpendirInp.addr;
        myStat = NULL;
        status = rsFileStat (rsComm, &fileStatInp, &myStat);

	if (status != 0) {
            rodsLog (LOG_ERROR,
	      "dirPathReg: rsFileStat failed for %s, status = %d",
	      fileStatInp.fileName, status);
	    free (rodsDirent);
	    return (status);
	}

        if (RescTypeDef[rescTypeInx].driverType == TDS_FILE_TYPE &&
          strchr (rodsDirent->d_name, '/') != NULL) {
            /* TDS may contain '/' in the file path */
            char *tmpPtr = rodsDirent->d_name;
            /* replace '/' with '.' */
            while (*tmpPtr != '\0') {
               if (*tmpPtr == '/') *tmpPtr = '.';
               tmpPtr ++;
            }
        }
        if (RescTypeDef[rescTypeInx].incParentDir == PHYPATH_IN_DIR_PTR) {
            /* the st_mode is stored in the opened dir */
            myStat->st_mode = getStModeInOpenedDir (dirFd, rodsDirent->d_ino);
            freePhyPathInOpenedDir (dirFd, rodsDirent->d_ino);
        }
	subPhyPathRegInp = *phyPathRegInp;
        if (RescTypeDef[rescTypeInx].incParentDir == NO_INC_PARENT_DIR) {
	    char myDir[MAX_NAME_LEN], myFile[MAX_NAME_LEN];
	    /* d_name is a full path, need to split it */
            if ((status = splitPathByKey (rodsDirent->d_name, myDir, myFile, 
              '/')) < 0) {
                rodsLog (LOG_ERROR,
                  "dirPathReg: splitPathByKey error for %s ", 
                  rodsDirent->d_name);
                continue;
            }
	    snprintf (subPhyPathRegInp.objPath, MAX_NAME_LEN, "%s/%s",
	      phyPathRegInp->objPath, myFile);
        } else if (RescTypeDef[rescTypeInx].incParentDir == 
            PHYPATH_IN_DIR_PTR) {
            char curdir[MAX_NAME_LEN];
            *curdir = '\0';
            getCurDirInOpenedDir (dirFd, curdir);
            if (strlen (curdir) > 0) {
                /* see if we have done it already */
                int len = strlen (subPhyPathRegInp.objPath);
                if (*curcoll == '\0'  || 
                  strcmp (&curcoll[len + 1], curdir) != 0) {
                    snprintf (curcoll, MAX_NAME_LEN, "%s/%s",
                      phyPathRegInp->objPath, curdir);
                    rsMkCollR (rsComm, phyPathRegInp->objPath, curcoll);
                }
	        snprintf (subPhyPathRegInp.objPath, MAX_NAME_LEN, "%s/%s",
	          curcoll, rodsDirent->d_name);
            } else {
                snprintf (subPhyPathRegInp.objPath, MAX_NAME_LEN, "%s/%s",
                  phyPathRegInp->objPath, rodsDirent->d_name);
            }
        } else {
	    snprintf (subPhyPathRegInp.objPath, MAX_NAME_LEN, "%s/%s",
	      phyPathRegInp->objPath, rodsDirent->d_name);
        }
	if ((myStat->st_mode & S_IFREG) != 0) {     /* a file */
	    if (forceFlag > 0) {
		/* check if it already exists */
	        if (isData (rsComm, subPhyPathRegInp.objPath, NULL) >= 0) {
		    free (myStat);
	            free (rodsDirent);
		    continue;
		}
	    }
	    subPhyPathRegInp.dataSize = myStat->st_size;
	    if (getValByKey (&phyPathRegInp->condInput, REG_REPL_KW) != NULL) {
                status = filePathRegRepl (rsComm, &subPhyPathRegInp,
                  fileStatInp.fileName, rescInfo);
	    } else {
                addKeyVal (&subPhyPathRegInp.condInput, FILE_PATH_KW, 
	          fileStatInp.fileName);
	        status = filePathReg (rsComm, &subPhyPathRegInp, 
	          fileStatInp.fileName, rescInfo);
	    }
        } else if ((myStat->st_mode & S_IFDIR) != 0) {      /* a directory */
            len = strlen (subPhyPathRegInp.objPath);
            if (subPhyPathRegInp.objPath[len - 1] == '/') {
                /* take out the end '/' for objPath */
                subPhyPathRegInp.objPath[len - 1] = '\0';
            }
            status = dirPathReg (rsComm, &subPhyPathRegInp,
              fileStatInp.fileName, rescInfo);
	}
        if (status < 0) return status;
	free (myStat);
	free (rodsDirent);
    }
    if (status == -1) {         /* just EOF */
        status = 0;
    }

    fileClosedirInp.fileInx = dirFd;
    rsFileClosedir (rsComm, &fileClosedirInp);

    return (status);
}