static BUFFER_HANDLE sendDeviceRegistryInfo(IOTHUB_ACCOUNT_INFO* accountInfo, BUFFER_HANDLE deviceBuffer, HTTPAPI_REQUEST_TYPE requestType)
{
    BUFFER_HANDLE result;

    STRING_HANDLE accessKey = STRING_construct(accountInfo->sharedAccessKey);
    STRING_HANDLE uriResouce = STRING_construct(accountInfo->hostname);
    STRING_HANDLE keyName = STRING_construct(accountInfo->keyName);
    if (accessKey != NULL && uriResouce != NULL && keyName != NULL)
    {
        HTTPAPIEX_SAS_HANDLE httpHandle = HTTPAPIEX_SAS_Create(accessKey, uriResouce, keyName);
        if (httpHandle != NULL)
        {
            HTTPAPIEX_HANDLE httpExApi = HTTPAPIEX_Create(accountInfo->hostname);
            if (httpExApi == NULL)
            {
                LogError("Failure creating httpApiEx with hostname: %s.\r\n", accountInfo->hostname);
                result = NULL;
            }
            else
            {
                char relativePath[256];
                if (sprintf_s(relativePath, 256, RELATIVE_PATH_FMT, accountInfo->deviceId, URL_API_VERSION) <= 0)
                {
                    LogError("Failure creating relative path.\r\n");
                    result = NULL;
                }
                else
                {

                    unsigned int statusCode = 0;

                    // Send PUT method to url
                    HTTP_HEADERS_HANDLE httpHeader = getContentHeaders((deviceBuffer == NULL) ? true : false);
                    if (httpHeader == NULL)
                    {
                        result = NULL;
                    }
                    else
                    {
                        BUFFER_HANDLE responseContent = BUFFER_new();
                        if (HTTPAPIEX_SAS_ExecuteRequest(httpHandle, httpExApi, requestType, relativePath, httpHeader, deviceBuffer, &statusCode, NULL, responseContent) != HTTPAPIEX_OK)
                        {
                            LogError("Failure calling HTTPAPIEX_SAS_ExecuteRequest.\r\n");
                            result = NULL;
                        }
                        else
                        {
                            // 409 means the device is already created so we don't need
                            // to create another one.
                            if (statusCode != 409 && statusCode > 300)
                            {
                                LogError("Http Failure status code %d.\r\n", statusCode);
                                BUFFER_delete(responseContent);
                                result = NULL;
                            }
                            else
                            {
                                result = responseContent;
                            }
                        }
                    }
                    HTTPHeaders_Free(httpHeader);
                }
                HTTPAPIEX_Destroy(httpExApi);
            }
            HTTPAPIEX_SAS_Destroy(httpHandle);
        }
        else
        {
            LogError("Http Failure with HTTPAPIEX_SAS_Create.\r\n");
            result = NULL;
        }
    }
    STRING_delete(accessKey);
    STRING_delete(uriResouce);
    STRING_delete(keyName);
    return result;
}
Example #2
0
void *ReadStdinThread( void *param )
{
    (void)param;

    while ( 1 )
    {
        char    ch;

        if ( read( fileno( stdin ), &ch, 1 ) < 1 )
        {
            LogDebug( "read of stdin failed\n" );
            break;
        }

        gKeyboardInputReceived = true;

#if USE_I2C
        if ( gDongle )
        {
            if ( gSerialDongleAddr == 0 )
            {
                Log( "Retrieving i2c address of serial dongle ...\n" );
                if ( !gSerialDongle.GetI2CAddress( &gSerialDongleAddr ))
                {
                    LogError( "Unable to retrieve serial dongle i2c address\n" );
                    break;
                }
                Log( "    Serial Dongle i2c Address: 0x%02x\n", gSerialDongleAddr );
            }

            switch ( ch )
            {
                case 'c':
                {
                    LogDebug( "Call\n" );

                    I2C_Adapter::Buffer  writeBuf;
                    I2C_Adapter::Buffer  readBuf;

                    char    writeMem[ 40 ];
                    char    readMem[ 40 ];

                    writeMem[ 0 ] = gSerialDongleAddr;
                    sprintf( &writeMem[ 1 ], "-c-%d-c-", gCounter++ );

                    writeBuf.data = (unsigned char *)writeMem;
                    writeBuf.dataLen = strlen( writeMem ) + 2;  // +1 for i2c addr +1 for terminating null

                    readBuf.data = (unsigned char *)readMem;
                    readBuf.dataLen = sizeof( readMem );

                    if ( gSerialDongle.Call( gSlaveAddr, BL_CMD_TEST_CALL, &writeBuf, &readBuf ))
                    {
                        printf( "Call: Wrote: '%s' to 0x%02x, read '%s' from 0x%02x\n", &writeMem[ 1 ], writeMem[ 0 ], &readMem[ 1 ], readMem[ 0 ] );
                    }
                    else
                    {
                        printf( "Call: Wrote: '%s' to 0x%02x, read failed\n", &writeMem[ 1 ], writeMem[ 0 ] );
                    }
                    break;
                }

                case 'd':
                {
                    LogDebug( "Download\n" );

                    if ( gDownloadFileName == NULL )
                    {
                        LogError( "No filename specified to download\n" );
                        break;
                    }

                    I2C_BootLoader bootLoader( &gSerialDongle, gSlaveAddr );

                    if ( !bootLoader.DownloadFile( gDownloadInfo ))
                    {
                        LogError( "Unable to download file\n" );
                    }
                    break;
                }

                case 'i':
                {
                    LogDebug( "GetBootInfo\n" );

                    I2C_BootLoader bootLoader( &gSerialDongle, gSlaveAddr );

                    BootLoaderInfo_t    bootInfo;

                    if ( bootLoader.GetBootLoaderInfo( &bootInfo ))
                    {
                        bootLoader.PrintBootLoaderInfo( bootInfo );
                    }
                    else
                    {
                        LogError( "Unable to retrieve bootloader info\n" );
                    }
                    break;
                }

                case 'r':
                {
                    LogDebug( "Read\n" );

                    I2C_Adapter::Buffer readBuf;
                    char                readMem[ 40 ];

                    readBuf.data = (unsigned char *)readMem;
                    readBuf.dataLen = sizeof( readMem );

                    if ( gSerialDongle.Read( gSlaveAddr, BL_CMD_TEST_READ, &readBuf ))
                    {
                        printf( "Read: '%s' from 0x%02x\n", &readMem[ 1 ], readMem[ 0 ] );
                    }
                    else
                    {
                        printf( "Read: failed\n" );
                    }
                    break;
                }

                case 'w':
                {
                    LogDebug( "Write\n" );

                    I2C_Adapter::Buffer writeBuf;
                    char                writeMem[ 40 ];

                    writeMem[ 0 ] = gSerialDongleAddr;
                    sprintf( &writeMem[ 1 ], "-w-%d-w-", gCounter++ );

                    writeBuf.data = (unsigned char *)writeMem;
                    writeBuf.dataLen = strlen( writeMem ) + 2;  // +1 for i2c addr, +1 for temrinating null

                    printf( "Write: Wrote: '%s' to 0x%02x\n", &writeMem[ 1 ], writeMem[ 0 ] );

                    if ( !gSerialDongle.Write( gSlaveAddr, BL_CMD_TEST_WRITE, &writeBuf ))
                    {
                        printf( "Write: failed\n" );
                    }
                    break;
                }

                default:
                {
                    printf( "Rcvd: 0x%02x\n", ch );

                    //gSerialPort.Write( &ch, 1 );
                    break;
                }
            }
        }
        else
#endif
        {
            gSerialPort.Write( &ch, 1 );
        }
    }

} // ReadStdinThread
Example #3
0
File: vglogo.c Project: juddy/edcde
void 
MakeLogo( void )
{
    register int i;

    char	*logoFile;		/* name of logo bitmap file	   */
    
    Pixmap	logoPixmap;		/* logo pixmap			   */
    char	*logoName;		/* logo name			   */

    int		logoWidth, logoHeight;	/* width, height of logo	   */
    Pixel	fg, bg;			/* foreground, background colors   */

    Pixmap	dsPixmap;		/* drop shadow pixmap		   */
    int		dsWidth, dsHeight;	/* width, height of drop shadow    */

    Pixmap		pixmap;			/* scratch pixmap	   */
    GC		gc;			/* scratch GC		   */
    XGCValues	gcval;			/* GC values		   */
    unsigned int	width, height;		/* width, height of bitmap */
    int		x_hot, y_hot;		/* bitmap hot spot (if any)*/

    
    /*
     *  get the user's logo preferences...
     */
     
    XtGetSubresources(table, &logoInfo, "logo", "Logo",
	logoResources, XtNumber(logoResources), NULL, 0);

    /*
     *  create the logo frame...
     */

    i = InitArg(Frame);
	XtSetArg(argt[i], XmNshadowType, XmSHADOW_OUT); i++;
    XtSetArg(argt[i], XmNshadowThickness, 2); i++; 
    XtSetArg(argt[i], XmNtopAttachment, XmATTACH_FORM); i++;
    XtSetArg(argt[i], XmNtopOffset, 15); i++;
    XtSetArg(argt[i], XmNbottomAttachment, XmATTACH_FORM); i++;
    XtSetArg(argt[i], XmNbottomOffset, 15); i++;
	XtSetArg(argt[i], XmNrightAttachment, XmATTACH_FORM); i++;
	XtSetArg(argt[i], XmNrightOffset, 15); i++;
    XtSetArg(argt[i], XmNleftAttachment, XmATTACH_WIDGET); i++;
    XtSetArg(argt[i], XmNleftWidget, matteFrame); i++;
    logo1 = XmCreateFrame(matte, "logo", argt, i); 
    XtManageChild(logo1);


    /*
     *  get the colors of the frame...
     */

    XtSetArg(argt[0], XmNforeground, &fg);
    XtSetArg(argt[1], XmNbackground, &bg);
    XtGetValues(logo1, argt, 2);
    

    /*
     *  create the logo pixmap...
     */

    logoFile = logoInfo.bitmapFile;

#if defined (_AIX) && defined (_POWER)
/*
 * On AIX4 we have a Dtlogo.s.pm
 */
# define LOGO_TYPE (LOWRES ? DtSMALL : 0)
#else 
# define LOGO_TYPE 0
#endif
    
    logoName = _DtGetIconFileName(DefaultScreenOfDisplay(dpyinfo.dpy), 
        logoFile, NULL, NULL, LOGO_TYPE);

    if (logoName == NULL)
    {
	LogError(
		ReadCatalog(MC_LOG_SET,MC_LOG_NO_LOGOBIT,MC_DEF_LOG_NO_LOGOBIT),
		logoFile);
	logoFile = NULL;
    }


    /*
     *  create the logo control...
     */

    i = InitArg(LabelG);
    XtSetArg(argt[i], XmNmarginWidth, 0); i++;
    XtSetArg(argt[i], XmNmarginHeight, 0); i++;
    XtSetArg(argt[i], XmNhighlightThickness, 0); i++;
    XtSetArg(argt[i], XmNbehavior, XmICON_LABEL); i++;
    XtSetArg(argt[i], XmNfillMode, XmFILL_TRANSPARENT); i++;
    XtSetArg(argt[i], XmNstring, NULL); i++;
    if (logoName != NULL)
    {
        XtSetArg(argt[i], XmNpixmapForeground, fg); i++;
        XtSetArg(argt[i], XmNpixmapBackground, bg); i++;
        XtSetArg(argt[i], XmNimageName, logoName); i++;
    }
    else
    {
        /*
         *  use built-in logo if no logo was not found
         */
     
        logoPixmap = XCreatePixmapFromBitmapData(
                                dpyinfo.dpy,		/* display	   */
                                dpyinfo.root,		/* drawable	   */
                                (char *)dt_logo_bits,	/* data		   */
				dt_logo_width,          /* width	   */
                                dt_logo_height,	        /* height	   */
                                fg,			/* foreground	   */
                                bg,			/* background	   */
                                dpyinfo.depth);		/* depth	   */

        logoWidth  = dt_logo_width;
        logoHeight = dt_logo_height;

        XtSetArg(argt[i], XmNpixmap, logoPixmap); i++;
    }

    	logo_pixmap = _DtCreateIcon(logo1, "logo_pixmap", argt, i);
    	XtManageChild(logo_pixmap);

        XtSetArg(argt[0], XmNheight,  245); /* keeps dialog a consistent height and width */
        XtSetArg(argt[1], XmNwidth,   245);
        XtSetValues(logo1, argt, 2);
}
Example #4
0
bool Master::_CheckDBVersion()
{
    QueryResult* wqr = WorldDatabase.QueryNA("SELECT LastUpdate FROM world_db_version ORDER BY id DESC LIMIT 1;");
    if (wqr == NULL)
    {
        LogError("Database : World database is missing the table `world_db_version` OR the table doesn't contain any rows. Can't validate database version. Exiting.");
        LogError("Database : You may need to update your database");
        return false;
    }

    Field* f = wqr->Fetch();
    const char *WorldDBVersion = f->GetString();

    LogNotice("Database : Last world database update: %s", WorldDBVersion);
    int result = strcmp(WorldDBVersion, REQUIRED_WORLD_DB_VERSION);
    if (result != 0)
    {
        LogError("Database : Last world database update doesn't match the required one which is %s.", REQUIRED_WORLD_DB_VERSION);

        if (result < 0)
        {
            LogError("Database : You need to apply the world update queries that are newer than %s. Exiting.", WorldDBVersion);
            LogError("Database : You can find the world update queries in the sql/world_updates sub-directory of your AscEmu source directory.");
        }
        else
        {
            LogError("Database : Your world database is probably too new for this AscEmu version, you need to update your server. Exiting.");
        }

        delete wqr;
        return false;
    }

    delete wqr;

    QueryResult* cqr = CharacterDatabase.QueryNA("SELECT LastUpdate FROM character_db_version;");
    if (cqr == NULL)
    {
        LogError("Database : Character database is missing the table `character_db_version` OR the table doesn't contain any rows. Can't validate database version. Exiting.");
        LogError("Database : You may need to update your database");
        return false;
    }

    f = cqr->Fetch();
    const char *CharDBVersion = f->GetString();

    LogNotice("Database : Last character database update: %s", CharDBVersion);
    result = strcmp(CharDBVersion, REQUIRED_CHAR_DB_VERSION);
    if (result != 0)
    {
        LogError("Database : Last character database update doesn't match the required one which is %s.", REQUIRED_CHAR_DB_VERSION);
        if (result < 0)
        {
            LogError("Database : You need to apply the character update queries that are newer than %s. Exiting.", CharDBVersion);
            LogError("Database : You can find the character update queries in the sql/character_updates sub-directory of your AscEmu source directory.");
        }
        else
        LogError("Database : Your character database is too new for this AscEmu version, you need to update your server. Exiting.");

        delete cqr;
        return false;
    }

    delete cqr;

    LogDetail("Database : Database successfully validated.");

    return true;
}
Example #5
0
int main( int argc, char **argv )
{
    int         sig;
    sigset_t    termSig;
    pthread_t   readSerialThreadId;
    pthread_t   readStdinThreadId;
    int         rc;
    int         opt;
    const char *baudStr = NULL;
#if defined( linux )
    const char *portStr = "ttyS0";
#else
    const char *portStr = "com1";
#endif

#if USE_I2C
    PKT_TextChar        = PacketTextChar;
    PKT_SendChar        = PacketSendChar;
    PKT_PacketReceived  = PacketReceived;
#endif

//    signal( SIGINT, ControlC );
//    signal( SIGTERM, ControlC );

    LogInit( stdout );

    while (( opt = getopt_long( argc, argv, "b:dhmp:sv", gLongOption, NULL )) > 0 )
    {
        switch ( opt )
        {
            case 'b':
            {
                baudStr = optarg;
                break;
            }

            case 'd':
            {
                gDebug = true;
                break;
            }

            case 'g':
            {
                gDongle = true;
                break;
            }

            case 'm':
            {
                gMegaLoad = true;
                break;
            }

            case 'p':
            {
                portStr = optarg;
                break;
            }

            case 'r':
            {
                gUseRtsToReset = true;
                break;
            }

            case 's':
            {
                gStk500 = true;
                break;
            }

            case 'v':
            {
                gVerbose = true;
                break;
            }

#if USE_I2C
            case OPT_DEBUG_DONGLE:
            {
                gSerialDongle.m_debugDongle = true;
                break;
            }

            case OPT_DEBUG_DONGLE_DATA:
            {
                gSerialDongle.m_debugDongleData = true;
                break;
            }
#endif

            case '?':
            case 'h':
            {
                Usage();
                return 1;
            }
        }
    }

    if ( optind < argc )
    {
        if (( optind + 1 ) != argc )
        {
            fprintf( stderr, "Only one download file supported\n" );
            return 1;
        }

        gDownloadFileName = argv[ optind ];
    }

    // Open the file to download

    if ( gDownloadFileName != NULL )
    {
        // If we are asked to download a file, then read the entire file
        // into memory.

        if (( gDownloadInfo = ReadFile( gDownloadFileName )) == NULL )
        {
            return 1;
        }
    }

    if ( !gSerialPort.Open( portStr, baudStr ))
    {
        return 1;
    }
    gSerialPort.UseRTStoReset( gUseRtsToReset );
    gSerialPort.ResetTarget();

    // Put stdin in raw mode

    setbuf( stdin, NULL );
    setbuf( stdout, NULL );

#if defined( unix )
    sigemptyset( &termSig );
    sigaddset( &termSig, SIGINT );
    sigaddset( &termSig, SIGTERM );

    pthread_sigmask( SIG_BLOCK, &termSig, NULL );

    struct termios tio_new;

    if ( tcgetattr( fileno( stdin ), &gTio_org ) < 0 )
    {
        LogError( "Unable to retrieve terminal settings\n" );
        return 1;
    }
    
    tio_new = gTio_org;
    tio_new.c_lflag &= ~( ICANON | ECHO );
    tio_new.c_cc[VMIN] = 1;
    tio_new.c_cc[VTIME] = 0;

    if ( tcsetattr( fileno( stdin ), TCSANOW, &tio_new ) < 0 )
    {
        LogError( "Unable to update terminal settings\n" );
        return 1;
    }
#endif

    const char *bootLoaderType = "*** Unknown ***";

    if ( gDongle )
    {
        bootLoaderType = "Serial Dongle";
    }
    else
    if ( gMegaLoad )
    {
        bootLoaderType = "MegaLoad v2.3";
    }
    else
    if ( gStk500 )
    {
        bootLoaderType = "STK500";
    }

    gLogFs2 = fopen( "BootHost.log", "wb" );

    Log( "BootHost - BootLoader: %s\n", bootLoaderType );

    // Kick off the serial port reader thread.

    rc = pthread_create( &readSerialThreadId, NULL, ReadSerialThread, &gSerialPort );
    if ( rc != 0 )
    {
        fprintf( stderr, "Error creating ReadSerialThread: %d\n", rc );
        return 1;
    }

    // Kick off the stdin reader thread.

    rc = pthread_create( &readStdinThreadId, NULL, ReadStdinThread, NULL );
    if ( rc != 0 )
    {
        fprintf( stderr, "Error creating ReadSerialThread: %d\n", rc );
        return 1;
    }

#if defined( unix )

    // Wait for a termmination signal

    if (( rc = sigwait( &termSig, &sig )) != 0 )
    {
        fprintf( stderr, "sigwait failed\n" );
    }
    else
    {
        fprintf( stderr, "Exiting...\n" );
    }

    pthread_cancel( readSerialThreadId );
    pthread_cancel( readStdinThreadId );

    // Restore stdin back to the way it was when we started

    if ( tcsetattr( fileno( stdin ), TCSANOW, &gTio_org ) == -1 )
    {
        LogError( "Unable to restore terminal settings\n" );
    }
#endif

#if defined( __CYGWIN__ )

    // Under Windows closing the serial port and stdin will cause the reads
    // to unblock. Under linux, this isn't required, but it doesn't hurt 
    // either.

    gSerialPort.Close();
    fclose( stdin );
#endif

    // Unblock the termination signals so the user can kill us if we hang up
    // waiting for the reader threads to exit.

#if defined( unix )
    pthread_sigmask( SIG_UNBLOCK, &termSig, NULL );
#endif

    pthread_join( readSerialThreadId, NULL );
    pthread_join( readStdinThreadId, NULL );

#if !defined( __CYGWIN__ )
    gSerialPort.Close();
    fclose( stdin );
#endif

    if ( gVerbose )
    {
        printf( "Done\n" );
    }

    return 0;

} // main
Example #6
0
void BattleItem::update(GameState &state, unsigned int ticks)
{
	item->update(state, ticks);
	// May have exploded
	if (!tileObject)
	{
		return;
	}

	if (ticksUntilCollapse > 0)
	{
		if (ticksUntilCollapse > ticks)
		{
			ticksUntilCollapse -= ticks;
		}
		else
		{
			ticksUntilCollapse = 0;
			collapse();
		}
	}

	if (!falling)
	{
		return;
	}

	if (ownerInvulnerableTicks > 0)
	{
		if (ownerInvulnerableTicks > ticks)
		{
			ownerInvulnerableTicks -= ticks;
		}
		else
		{
			ownerInvulnerableTicks = 0;
		}
	}

	if (collisionIgnoredTicks > 0)
	{
		if (collisionIgnoredTicks > ticks)
		{
			collisionIgnoredTicks -= ticks;
		}
		else
		{
			collisionIgnoredTicks = 0;
		}
	}

	int remainingTicks = ticks;

	auto previousPosition = position;
	auto newPosition = position;

	while (remainingTicks-- > 0)
	{
		velocity.z -= FALLING_ACCELERATION_ITEM;
		newPosition += this->velocity / (float)TICK_SCALE / VELOCITY_SCALE_BATTLE;
	}

	// Check if new position is valid
	// FIXME: Collide with units but not with us
	bool collision = false;
	auto c = checkItemCollision(previousPosition, newPosition);
	if (c)
	{
		collision = true;
		// If colliding with anything but ground, bounce back once
		switch (c.obj->getType())
		{
			case TileObject::Type::Unit:
			case TileObject::Type::LeftWall:
			case TileObject::Type::RightWall:
			case TileObject::Type::Feature:
				if (!bounced)
				{
					// If bounced do not try to find support this time
					collision = false;
					bounced = true;
					newPosition = previousPosition;
					velocity.x = -velocity.x / 4;
					velocity.y = -velocity.y / 4;
					velocity.z = std::abs(velocity.z / 4);
					break;
				}
			// Intentional fall-through
			case TileObject::Type::Ground:
				// Let item fall so that it can collide with scenery or ground if falling on top of
				// it
				newPosition = {previousPosition.x, previousPosition.y,
				               std::min(newPosition.z, previousPosition.z)};
				break;
			default:
				LogError("What the hell is this item colliding with? Type is %d",
				         (int)c.obj->getType());
				break;
		}
	}

	// If moved but did not find support - check if within level bounds and set position
	if (newPosition != previousPosition)
	{
		auto mapSize = this->tileObject->map.size;

		// Collision with ceiling
		if (newPosition.z >= mapSize.z)
		{
			collision = true;
			newPosition.z = mapSize.z - 0.01f;
			velocity = {0.0f, 0.0f, 0.0f};
		}
		// Collision with map edge
		if (newPosition.x < 0 || newPosition.y < 0 || newPosition.y >= mapSize.y ||
		    newPosition.x >= mapSize.x || newPosition.y >= mapSize.y)
		{
			collision = true;
			velocity.x = -velocity.x / 4;
			velocity.y = -velocity.y / 4;
			velocity.z = 0;
			newPosition = previousPosition;
		}
		// Fell below 0???
		if (newPosition.z < 0)
		{
			LogError("Item at %f %f fell off the end of the world!?", newPosition.x, newPosition.y);
			die(state, false);
			return;
		}
		setPosition(newPosition);
	}

	if (collision)
	{
		if (findSupport())
		{
			getSupport();
			auto tile = tileObject->getOwningTile();
			if (tile->objectDropSfx)
			{
				fw().soundBackend->playSample(tile->objectDropSfx, getPosition(), 0.25f);
			}
		}
	}
}
Example #7
0
void
get_credential(UINT32 type, UINT32 *size, BYTE **cred)
{
	int rc, fd;
	char *path = NULL;
	void *file = NULL;
	struct stat stat_buf;
	size_t file_size;

	switch (type) {
		case TSS_TCS_CREDENTIAL_PLATFORMCERT:
			path = tcsd_options.platform_cred;
			break;
		case TSS_TCS_CREDENTIAL_TPM_CC:
			path = tcsd_options.conformance_cred;
			break;
		case TSS_TCS_CREDENTIAL_EKCERT:
			path = tcsd_options.endorsement_cred;
			break;
		default:
			LogDebugFn("Bad credential type");
			break;
	}

	if (path == NULL)
		goto done;

	if ((fd = open(path, O_RDONLY)) < 0) {
		LogError("open(%s): %s", path, strerror(errno));
		goto done;
	}

	if ((rc = fstat(fd, &stat_buf)) == -1) {
		LogError("Error stating credential: %s: %s", path, strerror(errno));
		close(fd);
		goto done;
	}

	file_size = (size_t)stat_buf.st_size;

	LogDebugFn("%s, (%zd bytes)", path, file_size);

	file = mmap(0, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
	if (file == MAP_FAILED) {
		LogError("Error reading credential: %s: %s", path, strerror(errno));
		close(fd);
		goto done;
	}
	close(fd);

	if ((*cred = malloc(file_size)) == NULL) {
		LogError("malloc of %zd bytes failed.", file_size);
		munmap(file, file_size);
		goto done;
	}

	memcpy(*cred, file, file_size);
	*size = file_size;
	munmap(file, file_size);

	return;
done:
	*cred = NULL;
	*size = 0;
}
/**
 * Read all processes to initialize the information tree.
 * @param reference reference of ProcessTree
 * @param pflags Process engine flags
 * @return treesize > 0 if succeeded otherwise 0
 */
int initprocesstree_sysdep(ProcessTree_T **reference, ProcessEngine_Flags pflags) {
        size_t size = sizeof(maxslp);
        static int mib_maxslp[] = {CTL_VM, VM_MAXSLP};
        if (sysctl(mib_maxslp, 2, &maxslp, &size, NULL, 0) < 0) {
                LogError("system statistic error -- vm.maxslp failed\n");
                return 0;
        }

        int mib_proc2[6] = {CTL_KERN, KERN_PROC2, KERN_PROC_ALL, 0, sizeof(struct kinfo_proc2), 0};
        if (sysctl(mib_proc2, 6, NULL, &size, NULL, 0) == -1) {
                LogError("system statistic error -- kern.proc2 #1 failed\n");
                return 0;
        }

        size *= 2; // Add reserve for new processes which were created between calls of sysctl
        struct kinfo_proc2 *pinfo = CALLOC(1, size);
        mib_proc2[5] = (int)(size / sizeof(struct kinfo_proc2));
        if (sysctl(mib_proc2, 6, pinfo, &size, NULL, 0) == -1) {
                FREE(pinfo);
                LogError("system statistic error -- kern.proc2 #2 failed\n");
                return 0;
        }

        int treesize = (int)(size / sizeof(struct kinfo_proc2));

        ProcessTree_T *pt = CALLOC(sizeof(ProcessTree_T), treesize);

        char buf[_POSIX2_LINE_MAX];
        kvm_t *kvm_handle = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, buf);
        if (! kvm_handle) {
                FREE(pinfo);
                FREE(pt);
                LogError("system statistic error -- kvm_openfiles failed: %s\n", buf);
                return 0;
        }

        StringBuffer_T cmdline = NULL;
        if (pflags & ProcessEngine_CollectCommandLine)
                cmdline = StringBuffer_create(64);
        for (int i = 0; i < treesize; i++) {
                pt[i].pid          = pinfo[i].p_pid;
                pt[i].ppid         = pinfo[i].p_ppid;
                pt[i].cred.uid     = pinfo[i].p_ruid;
                pt[i].cred.euid    = pinfo[i].p_uid;
                pt[i].cred.gid     = pinfo[i].p_rgid;
                pt[i].threads      = pinfo[i].p_nlwps;
                pt[i].uptime       = systeminfo.time / 10. - pinfo[i].p_ustart_sec;
                pt[i].cpu.time     = pinfo[i].p_rtime_sec * 10 + (double)pinfo[i].p_rtime_usec / 100000.;
                pt[i].memory.usage = (uint64_t)pinfo[i].p_vm_rssize * (uint64_t)pagesize;
                pt[i].zombie       = pinfo[i].p_stat == SZOMB ? true : false;
                if (pflags & ProcessEngine_CollectCommandLine) {
                        char **args = kvm_getargv2(kvm_handle, &pinfo[i], 0);
                        if (args) {
                                StringBuffer_clear(cmdline);
                                for (int j = 0; args[j]; j++)
                                        StringBuffer_append(cmdline, args[j + 1] ? "%s " : "%s", args[j]);
                                if (StringBuffer_length(cmdline))
                                        pt[i].cmdline = Str_dup(StringBuffer_toString(StringBuffer_trim(cmdline)));
                        }
                        if (! pt[i].cmdline || ! *pt[i].cmdline) {
                                FREE(pt[i].cmdline);
                                pt[i].cmdline = Str_dup(pinfo[i].p_comm);
                        }
                }
        }
        if (pflags & ProcessEngine_CollectCommandLine)
                StringBuffer_free(&cmdline);
        FREE(pinfo);
        kvm_close(kvm_handle);

        *reference = pt;

        return treesize;
}
/**
 *  Tests about Log streams and special printf functions.
 */
int Test1(char *str, char *file)
{
  char tempstr[2048];
  int  i;

  SetComponentLogFile(COMPONENT_INIT, "STDOUT");
  LogAlways(COMPONENT_INIT, "%s", "Starting Log Tests");
  LogTest("My PID = %d", getpid());

  LogTest("------------------------------------------------------");

  LogTest("Test ERR_DUMMY");
  LogTest("A numerical error : error %%d = %%J%%R, in ERR_DUMMY_2 %%J%%R");
  log_snprintf(tempstr, sizeof(tempstr), "A numerical error : error %d = %J%R, in ERR_DUMMY_2 %J%R",
               ERR_SIGACTION, ERR_SYS, ERR_SIGACTION, ERR_DUMMY, ERR_DUMMY_2);
  LogTest("%s", tempstr);
  LogTest("A numerical error : error %d = %J%R, in ERR_DUMMY_1 %J%R",
          ERR_OPEN, ERR_SYS, ERR_OPEN, ERR_DUMMY, ERR_DUMMY_1);

  LogTest("------------------------------------------------------");
  LogTest("Test conversion of log levels between string and integer");
  for (i = NIV_NULL; i < NB_LOG_LEVEL; i++)
    {
      int j;
      if (strcmp(tabLogLevel[i].str, ReturnLevelInt(i)) != 0)
        {
          LogTest("FAILURE: Log level %d did not convert to %s, it converted to %s", i, tabLogLevel[i].str, ReturnLevelInt(i));
          exit(1);
        }
      j = ReturnLevelAscii(tabLogLevel[i].str);
      if (j != i)
        {
          LogTest("FAILURE: Log level %s did not convert to %d, it converted to %d", tabLogLevel[i].str, i, j);
          exit(1);
        }
    }

  LogTest("------------------------------------------------------");

  log_snprintf(tempstr, sizeof(tempstr), "Test log_snprintf");
  LogTest("%s", tempstr);
  LogTest("\nTesting LogError function");
  LogError(COMPONENT_CONFIG, ERR_SYS, ERR_MALLOC, EINVAL);
  LogTest("\nTesting possible environment variable");
  LogTest("COMPONENT_MEMCORRUPT debug level is %s", ReturnLevelInt(LogComponents[COMPONENT_MEMCORRUPT].comp_log_level));
  LogFullDebug(COMPONENT_MEMCORRUPT, "This should appear if environment is set properly");

  LogTest("------------------------------------------------------");
  LogTest("Send some messages to various files");
  SetComponentLogFile(COMPONENT_DISPATCH, "STDERR");
  LogEvent(COMPONENT_DISPATCH, "This should go to stderr");
  SetComponentLogFile(COMPONENT_DISPATCH, "STDOUT");
  LogEvent(COMPONENT_DISPATCH, "This should go to stdout");
  SetComponentLogFile(COMPONENT_DISPATCH, "SYSLOG");
  LogEvent(COMPONENT_DISPATCH, "This should go to syslog (verf = %s)", str);
  LogTest("About to set %s", file);
  SetComponentLogFile(COMPONENT_DISPATCH, file);
  LogTest("Got it set");
  LogEvent(COMPONENT_DISPATCH, "This should go to %s", file);

  /*
   * Set up for tests that will verify what was actually produced by log messages.
   * This is used to test log levels and to test the log_vnsprintf function.
   */
  SetComponentLogBuffer(COMPONENT_MAIN, tempstr);
  SetComponentLogBuffer(COMPONENT_INIT, tempstr);

#ifdef _SNMP_ADM_ACTIVE
  {
    snmp_adm_type_union param;
    int rc;
    strcpy(param.string, "FAILED");

    LogTest("------------------------------------------------------");
    LogTest("Test SNMP functions");
    SetLevelDebug(NIV_DEBUG);

    rc = getComponentLogLevel(&param, (void *)COMPONENT_ALL);
    LogTest("getComponentLogLevel(&param, (void *)COMPONENT_ALL) rc=%d result=%s",
            rc, param.string);
    if (rc != 0)
    {
      LogTest("FAILURE");
      exit(1);
    }
    strcpy(param.string, "NIV_EVENT");
    rc = setComponentLogLevel(&param, (void *)COMPONENT_MAIN);
    LogTest("setComponentLogLevel(&param, (void *)COMPONENT_MAIN) rc=%d", rc);
    if (rc != 0)
    {
      LogTest("FAILURE");
      exit(1);
    }
    TestAlways    (TRUE,  tempstr, COMPONENT_MAIN, "LogAlways (should print)");
    TestMajor     (TRUE,  tempstr, COMPONENT_MAIN, "LogMajor (should print)");
    TestCrit      (TRUE,  tempstr, COMPONENT_MAIN, "LogCrit (should print)");
    TestEvent     (TRUE,  tempstr, COMPONENT_MAIN, "LogEvent (should print)");
    TestDebug     (FALSE, tempstr, COMPONENT_MAIN, "LogDebug (shouldn't print)");
    TestFullDebug (FALSE, tempstr, COMPONENT_MAIN, "LogFullDebug (shouldn't print)");
    TestAlways    (TRUE,  tempstr, COMPONENT_INIT, "LogAlways (should print)");
    TestMajor     (TRUE,  tempstr, COMPONENT_INIT, "LogMajor (should print)");
    TestCrit      (TRUE,  tempstr, COMPONENT_INIT, "LogCrit (should print)");
    TestEvent     (TRUE,  tempstr, COMPONENT_INIT, "LogEvent (should print)");
    TestDebug     (TRUE,  tempstr, COMPONENT_INIT, "LogDebug (should print)");
    TestFullDebug (FALSE, tempstr, COMPONENT_INIT, "LogFullDebug (shouldn't print)");
  }
#endif /* _SNMP_ADM_ACTIVE */

  LogTest("------------------------------------------------------");
  LogTest("Test all levels of log filtering");
  SetComponentLogLevel(COMPONENT_MAIN, NIV_NULL);
  TestAlways    (TRUE,  tempstr, COMPONENT_MAIN, "LogAlways (should print)");
  TestMajor     (FALSE, tempstr, COMPONENT_MAIN, "LogMajor (shouldn't print)");
  TestCrit      (FALSE, tempstr, COMPONENT_MAIN, "LogCrit (shouldn't print)");
  TestEvent     (FALSE, tempstr, COMPONENT_MAIN, "LogEvent (shouldn't print)");
  TestDebug     (FALSE, tempstr, COMPONENT_MAIN, "LogDebug (shouldn't print)");
  TestFullDebug (FALSE, tempstr, COMPONENT_MAIN, "LogFullDebug (shouldn't print)");
  SetComponentLogLevel(COMPONENT_MAIN, NIV_MAJOR);
  TestAlways    (TRUE,  tempstr, COMPONENT_MAIN, "LogAlways (should print)");
  TestMajor     (TRUE,  tempstr, COMPONENT_MAIN, "LogMajor (should print)");
  TestCrit      (FALSE, tempstr, COMPONENT_MAIN, "LogCrit (shouldn't print)");
  TestEvent     (FALSE, tempstr, COMPONENT_MAIN, "LogEvent (shouldn't print)");
  TestDebug     (FALSE, tempstr, COMPONENT_MAIN, "LogDebug (shouldn't print)");
  TestFullDebug (FALSE, tempstr, COMPONENT_MAIN, "LogFullDebug (shouldn't print)");
  SetComponentLogLevel(COMPONENT_MAIN, NIV_CRIT);
  TestAlways    (TRUE,  tempstr, COMPONENT_MAIN, "LogAlways (should print)");
  TestMajor     (TRUE,  tempstr, COMPONENT_MAIN, "LogMajor (should print)");
  TestCrit      (TRUE,  tempstr, COMPONENT_MAIN, "LogCrit (should print)");
  TestEvent     (FALSE, tempstr, COMPONENT_MAIN, "LogEvent (shouldn't print)");
  TestDebug     (FALSE, tempstr, COMPONENT_MAIN, "LogDebug (shouldn't print)");
  TestFullDebug (FALSE, tempstr, COMPONENT_MAIN, "LogFullDebug (shouldn't print)");
  SetComponentLogLevel(COMPONENT_MAIN, NIV_EVENT);
  TestAlways    (TRUE,  tempstr, COMPONENT_MAIN, "LogAlways (should print)");
  TestMajor     (TRUE,  tempstr, COMPONENT_MAIN, "LogMajor (should print)");
  TestCrit      (TRUE,  tempstr, COMPONENT_MAIN, "LogCrit (should print)");
  TestEvent     (TRUE,  tempstr, COMPONENT_MAIN, "LogEvent (should print)");
  TestDebug     (FALSE, tempstr, COMPONENT_MAIN, "LogDebug (shouldn't print)");
  TestFullDebug (FALSE, tempstr, COMPONENT_MAIN, "LogFullDebug (shouldn't print)");
  SetComponentLogLevel(COMPONENT_MAIN, NIV_DEBUG);
  TestAlways    (TRUE,  tempstr, COMPONENT_MAIN, "LogAlways (should print)");
  TestMajor     (TRUE,  tempstr, COMPONENT_MAIN, "LogMajor (should print)");
  TestCrit      (TRUE,  tempstr, COMPONENT_MAIN, "LogCrit (should print)");
  TestEvent     (TRUE,  tempstr, COMPONENT_MAIN, "LogEvent (should print)");
  TestDebug     (TRUE,  tempstr, COMPONENT_MAIN, "LogDebug (should print)");
  TestFullDebug (FALSE, tempstr, COMPONENT_MAIN, "LogFullDebug (shouldn't print)");
  SetComponentLogLevel(COMPONENT_MAIN, NIV_FULL_DEBUG);
  TestAlways    (TRUE,  tempstr, COMPONENT_MAIN, "LogAlways (should print)");
  TestMajor     (TRUE,  tempstr, COMPONENT_MAIN, "LogMajor (should print)");
  TestCrit      (TRUE,  tempstr, COMPONENT_MAIN, "LogCrit (should print)");
  TestEvent     (TRUE,  tempstr, COMPONENT_MAIN, "LogEvent (should print)");
  TestDebug     (TRUE,  tempstr, COMPONENT_MAIN, "LogDebug (should print)");
  TestFullDebug (TRUE,  tempstr, COMPONENT_MAIN, "LogFullDebug (should print)");
}
Example #10
0
// Process context menu items...
BOOL CStatisticsTree::OnCommand(WPARAM wParam, LPARAM /*lParam*/)
{
	switch (wParam) {
		case MP_STATTREE_RESET:
			{
				if(AfxMessageBox(GetResString(IDS_STATS_MBRESET_TXT), MB_YESNO | MB_ICONEXCLAMATION) == IDNO)
					break;

				thePrefs.ResetCumulativeStatistics();
				AddLogLine(false, GetResString(IDS_STATS_NFORESET));
				theApp.emuledlg->statisticswnd->ShowStatistics();

				CString myBuffer; 
				myBuffer.Format(GetResString(IDS_STATS_LASTRESETSTATIC), thePrefs.GetStatsLastResetStr(false));
				GetParent()->GetDlgItem(IDC_STATIC_LASTRESET)->SetWindowText(myBuffer);

				break;
			}
		case MP_STATTREE_RESTORE:
			{
				if (AfxMessageBox(GetResString(IDS_STATS_MBRESTORE_TXT), MB_YESNO | MB_ICONQUESTION) == IDNO)
					break;

				if(!thePrefs.LoadStats(1))
					LogError(LOG_STATUSBAR, GetResString(IDS_ERR_NOSTATBKUP));
				else {
					AddLogLine(false, GetResString(IDS_STATS_NFOLOADEDBKUP));
					CString myBuffer;
					myBuffer.Format(GetResString(IDS_STATS_LASTRESETSTATIC), thePrefs.GetStatsLastResetStr(false));
					GetParent()->GetDlgItem(IDC_STATIC_LASTRESET)->SetWindowText(myBuffer);
				}

				break;
			}
		case MP_STATTREE_EXPANDMAIN:
			{
				SetRedraw(false);
				ExpandAll(true);
				goto lblSaveExpanded;
			}
		case MP_STATTREE_EXPANDALL:
			{
				SetRedraw(false);
				ExpandAll();
				goto lblSaveExpanded;
			}
		case MP_STATTREE_COLLAPSEALL:
			{
				SetRedraw(false);
				CollapseAll();
lblSaveExpanded:
				thePrefs.SetExpandedTreeItems(GetExpandedMask());
				SetRedraw(true);
				break;
			}
		case MP_STATTREE_COPYSEL:
		case MP_STATTREE_COPYVIS:
		case MP_STATTREE_COPYALL:
			{
				CopyText(wParam);
				break;
			}
		case MP_STATTREE_HTMLCOPYSEL:
		case MP_STATTREE_HTMLCOPYVIS:
		case MP_STATTREE_HTMLCOPYALL:
			{
				CopyHTML(wParam);
				break;
			}
		case MP_STATTREE_HTMLEXPORT:
			{
				ExportHTML();
				break;
			}
	}

	return true;
}
Example #11
0
void TileObject::setPosition(Vec3<float> newPosition)
{
	auto thisPtr = shared_from_this();
	if (!thisPtr)
	{
		LogError("This == null");
	}
	if (newPosition.x < 0 || newPosition.y < 0 || newPosition.z < 0 ||
	    newPosition.x > map.size.x + 1 || newPosition.y > map.size.y + 1 ||
	    newPosition.z > map.size.z + 1)
	{
		LogWarning("Trying to place object at {%f,%f,%f} in map of size {%d,%d,%d}", newPosition.x,
		           newPosition.y, newPosition.z, map.size.x, map.size.y, map.size.z);
		newPosition.x = clamp(newPosition.x, 0.0f, (float)map.size.x + 1);
		newPosition.y = clamp(newPosition.y, 0.0f, (float)map.size.y + 1);
		newPosition.z = clamp(newPosition.z, 0.0f, (float)map.size.z + 1);
		LogWarning("Clamped object to {%f,%f,%f}", newPosition.x, newPosition.y, newPosition.z);
	}
	this->removeFromMap();

	this->owningTile = map.getTile(newPosition);
	if (!this->owningTile)
	{
		LogError("Failed to get tile for position {%f,%f,%f}", newPosition.x, newPosition.y,
		         newPosition.z);
	}

	auto inserted = this->owningTile->ownedObjects.insert(thisPtr);
	if (!inserted.second)
	{
		LogError("Object already in owned object list?");
	}

	int layer = map.getLayer(this->type);

	this->owningTile->drawnObjects[layer].push_back(thisPtr);
	std::sort(this->owningTile->drawnObjects[layer].begin(),
	          this->owningTile->drawnObjects[layer].end(), TileObjectZComparer{});

	Vec3<int> minBounds = {floorf(newPosition.x - this->bounds.x / 2.0f),
	                       floorf(newPosition.y - this->bounds.y / 2.0f),
	                       floorf(newPosition.z - this->bounds.z / 2.0f)};
	Vec3<int> maxBounds = {ceilf(newPosition.x + this->bounds.x / 2.0f),
	                       ceilf(newPosition.y + this->bounds.y / 2.0f),
	                       ceilf(newPosition.z + this->bounds.z / 2.0f)};

	for (int x = minBounds.x; x < maxBounds.x; x++)
	{
		for (int y = minBounds.y; y < maxBounds.y; y++)
		{
			for (int z = minBounds.z; z < maxBounds.z; z++)
			{
				if (x < 0 || y < 0 || z < 0 || x > map.size.x || y > map.size.y || z > map.size.z)
				{
					// TODO: Decide if having bounds outside the map are really valid?
					continue;
				}
				Tile *intersectingTile = map.getTile(x, y, z);
				if (!intersectingTile)
				{
					LogError("Failed to get intersecting tile at {%d,%d,%d}", x, y, z);
					continue;
				}
				this->intersectingTiles.push_back(intersectingTile);
				intersectingTile->intersectingObjects.insert(thisPtr);
			}
		}
	}
	// Quick sanity check
	for (auto *t : this->intersectingTiles)
	{
		if (t->intersectingObjects.find(shared_from_this()) == t->intersectingObjects.end())
		{
			LogError("Intersecting objects inconsistent");
		}
	}
}
Example #12
0
IOTHUB_MESSAGE_HANDLE IoTHubMessage_CreateFromByteArray(const unsigned char* byteArray, size_t size)
{
    IOTHUB_MESSAGE_HANDLE_DATA* result;
    result = malloc(sizeof(IOTHUB_MESSAGE_HANDLE_DATA));
    if (result == NULL)
    {
        LogError("unable to malloc\r\n");
        /*Codes_SRS_IOTHUBMESSAGE_02_024: [If there are any errors then IoTHubMessage_CreateFromByteArray shall return NULL.] */
        /*let it go through*/
    }
    else
    {
        const unsigned char* source;
        unsigned char temp = 0x00;
        if (size != 0)
        {
            /*Codes_SRS_IOTHUBMESSAGE_06_002: [If size is NOT zero then byteArray MUST NOT be NULL*/
            if (byteArray == NULL)
            {
                LogError("Attempted to create a Hub Message from a NULL pointer!\r\n");
                free(result);
                result = NULL;
                source = NULL;
            }
            else
            {
                source = byteArray;
            }
        }
        else
        {
            /*Codes_SRS_IOTHUBMESSAGE_06_001: [If size is zero then byteArray may be NULL.]*/
            source = &temp;
        }
        if (result != NULL)
        {
            /*Codes_SRS_IOTHUBMESSAGE_02_022: [IoTHubMessage_CreateFromByteArray shall call BUFFER_create passing byteArray and size as parameters.] */
            if ((result->value.byteArray = BUFFER_create(source, size)) == NULL)
            {
                LogError("BUFFER_create failed\r\n");
                /*Codes_SRS_IOTHUBMESSAGE_02_024: [If there are any errors then IoTHubMessage_CreateFromByteArray shall return NULL.] */
                free(result);
                result = NULL;
            }
            /*Codes_SRS_IOTHUBMESSAGE_02_023: [IoTHubMessage_CreateFromByteArray shall call Map_Create to create the message properties.] */
            else if ((result->properties = Map_Create(ValidateAsciiCharactersFilter)) == NULL)
            {
                LogError("Map_Create failed\r\n");
                /*Codes_SRS_IOTHUBMESSAGE_02_024: [If there are any errors then IoTHubMessage_CreateFromByteArray shall return NULL.] */
                BUFFER_delete(result->value.byteArray);
                free(result);
                result = NULL;
            }
            else
            {
                /*Codes_SRS_IOTHUBMESSAGE_02_025: [Otherwise, IoTHubMessage_CreateFromByteArray shall return a non-NULL handle.] */
                /*Codes_SRS_IOTHUBMESSAGE_02_026: [The type of the new message shall be IOTHUBMESSAGE_BYTEARRAY.] */
                result->contentType = IOTHUBMESSAGE_BYTEARRAY;
                /*all is fine, return result*/
            }
        }
    }
    return result;
}
Example #13
0
/*Codes_SRS_IOTHUBMESSAGE_03_001: [IoTHubMessage_Clone shall create a new IoT hub message with data content identical to that of the iotHubMessageHandle parameter.]*/
IOTHUB_MESSAGE_HANDLE IoTHubMessage_Clone(IOTHUB_MESSAGE_HANDLE iotHubMessageHandle)
{
    IOTHUB_MESSAGE_HANDLE_DATA* result;
    const IOTHUB_MESSAGE_HANDLE_DATA* source = (const IOTHUB_MESSAGE_HANDLE_DATA*)iotHubMessageHandle;
    /* Codes_SRS_IOTHUBMESSAGE_03_005: [IoTHubMessage_Clone shall return NULL if iotHubMessageHandle is NULL.] */
    if (source == NULL)
    {
        result = NULL;
        LogError("iotHubMessageHandle parameter cannot be NULL for IoTHubMessage_Clone\r\n");
    }
    else
    {
        result = (IOTHUB_MESSAGE_HANDLE_DATA*)malloc(sizeof(IOTHUB_MESSAGE_HANDLE_DATA));
        /*Codes_SRS_IOTHUBMESSAGE_03_004: [IoTHubMessage_Clone shall return NULL if it fails for any reason.]*/
        if (result == NULL)
        {
            /*Codes_SRS_IOTHUBMESSAGE_03_004: [IoTHubMessage_Clone shall return NULL if it fails for any reason.]*/
            /*do nothing and return as is*/
            LogError("unable to malloc\r\n");
        }
        else
        {
            if (source->contentType == IOTHUBMESSAGE_BYTEARRAY)
            {
                /*Codes_SRS_IOTHUBMESSAGE_02_006: [IoTHubMessage_Clone shall clone to content by a call to BUFFER_clone] */
                if ((result->value.byteArray = BUFFER_clone(source->value.byteArray)) == NULL)
                {
                    /*Codes_SRS_IOTHUBMESSAGE_03_004: [IoTHubMessage_Clone shall return NULL if it fails for any reason.]*/
                    LogError("unable to BUFFER_clone\r\n");
                    free(result);
                    result = NULL;
                }
                /*Codes_SRS_IOTHUBMESSAGE_02_005: [IoTHubMessage_Clone shall clone the properties map by using Map_Clone.] */
                else if ((result->properties = Map_Clone(source->properties)) == NULL)
                {
                    /*Codes_SRS_IOTHUBMESSAGE_03_004: [IoTHubMessage_Clone shall return NULL if it fails for any reason.]*/
                    LogError("unable to Map_Clone\r\n");
                    BUFFER_delete(result->value.byteArray);
                    free(result);
                    result = NULL;
                }
                else
                {
                    result->contentType = IOTHUBMESSAGE_BYTEARRAY;
                    /*Codes_SRS_IOTHUBMESSAGE_03_002: [IoTHubMessage_Clone shall return upon success a non-NULL handle to the newly created IoT hub message.]*/
                    /*return as is, this is a good result*/
                }
            }
            else /*can only be STRING*/
            {
                /*Codes_SRS_IOTHUBMESSAGE_02_006: [IoTHubMessage_Clone shall clone the content by a call to BUFFER_clone or STRING_clone] */
                if ((result->value.string = STRING_clone(source->value.string)) == NULL)
                {
                    /*Codes_SRS_IOTHUBMESSAGE_03_004: [IoTHubMessage_Clone shall return NULL if it fails for any reason.]*/
                    free(result);
                    result = NULL;
                    LogError("failed to STRING_clone\r\n");
                }
                /*Codes_SRS_IOTHUBMESSAGE_02_005: [IoTHubMessage_Clone shall clone the properties map by using Map_Clone.] */
                else if ((result->properties = Map_Clone(source->properties)) == NULL)
                {
                    /*Codes_SRS_IOTHUBMESSAGE_03_004: [IoTHubMessage_Clone shall return NULL if it fails for any reason.]*/
                    LogError("unable to Map_Clone\r\n");
                    STRING_delete(result->value.string);
                    free(result);
                    result = NULL;
                }
                else
                {
                    result->contentType = IOTHUBMESSAGE_STRING;
                    /*all is fine*/
                }
            }
        }
    }
    return result;
}
static int retrieveConnStringInfo(IOTHUB_ACCOUNT_INFO* accountInfo)
{
    int result;
    int beginName, endName, beginIothub, endIothub, beginHost, endHost, beginKey;
    int totalLen = strlen(accountInfo->connString);

    if (sscanf(accountInfo->connString, "HostName=%n%*[^.]%n.%n%*[^;];%nSharedAccessKeyName=%n%*[^;];%nSharedAccessKey=%n", &beginHost, &endHost, &beginIothub, &endIothub, &beginName, &endName, &beginKey) != 0)
    {
        LogError("Failure determining the string length parameters.\r\n");
        result = __LINE__;
    }
    else
    {
        if ((accountInfo->iothubName = (char*)malloc(endHost - beginHost + 1)) == NULL)
        {
            LogError("Failure allocating iothubName.\r\n");
            result = __LINE__;
        }
        else if ((accountInfo->hostname = (char*)malloc(endIothub - beginHost + 1)) == NULL)
        {
            LogError("Failure allocating hostname.\r\n");
            free(accountInfo->iothubName);
            result = __LINE__;
        }
        else if ((accountInfo->keyName = (char*)malloc(endName - beginName + 1)) == NULL)
        {
            LogError("Failure allocating hostName.\r\n");
            free(accountInfo->iothubName);
            free(accountInfo->hostname);
            result = __LINE__;
        }
        else if ((accountInfo->sharedAccessKey = (char*)malloc(totalLen + 1 - beginKey + 1)) == NULL)
        {
            LogError("Failure allocating hostName.\r\n");
            free(accountInfo->iothubName);
            free(accountInfo->keyName);
            free(accountInfo->hostname);
            result = __LINE__;
        }
        else if (sscanf(accountInfo->connString, "HostName=%[^.].%[^;];SharedAccessKeyName=%[^;];SharedAccessKey=%s", accountInfo->iothubName,
            accountInfo->hostname + endHost - beginHost + 1,
            accountInfo->keyName,
            accountInfo->sharedAccessKey) != 4)
        {
            LogError("Failure determining the string values.\r\n");
            free(accountInfo->iothubName);
            free(accountInfo->hostname);
            free(accountInfo->keyName);
            free(accountInfo->sharedAccessKey);
            result = __LINE__;
        }
        else
        {
            (void)strcpy(accountInfo->hostname, accountInfo->iothubName);
            accountInfo->hostname[endHost - beginHost] = '.';
            if (mallocAndStrcpy_s(&accountInfo->iothubSuffix, accountInfo->hostname + endHost - beginHost + 1) != 0)
            {
				LogError("[IoTHubAccount] Failure constructing the iothubSuffix.");
                free(accountInfo->iothubName);
                free(accountInfo->hostname);
                free(accountInfo->keyName);
                free(accountInfo->sharedAccessKey);
                result = __LINE__;
            }
            else
            {
                result = 0;
            }
        }
    }
    return result;
}
Example #15
0
    void
    CacheMonitorServer::ScanFolder(const fs::path & folder)
    {
        CacheManager * cache = Factory::GetCacheManager();
        fs::path folderMeta = Factory::GetMetaFolder() / Factory::GetService();

        try {
            fs::directory_iterator end;
            for ( fs::directory_iterator i(folder); i != end; ++ i ) {
                if ( fs::is_directory(i->status()) ) {
                    ScanFolder(i->path());
                } else {
                    struct stat stat;
                    if ( 0 != ::stat(i->path().string().c_str(),&stat) ) {
                        continue;
                    }

                    ExtendedAttribute ea(i->path());
                    unsigned long long number;
                    int valuesize;
                    if ( ! ea.GetValue(
                            Inode::ATTRIBUTE_NUMBER,
                            &number,
                            sizeof(number),
                            valuesize ) ) {
                        continue;
                    }
                    long state;
                    if ( ! ea.GetValue(
                            Inode::ATTRIBUTE_STATE,
                            &state,
                            sizeof(state),
                            valuesize) ) {
                        continue;
                    }
                    if ( state != Inode::StateBegin ) {
                        continue;
                    }
                    long long size = 0;
                    if ( ! ea.GetValue(
                            Inode::ATTRIBUTE_SIZE,
                            &size,
                            sizeof(size),
                            valuesize) ) {
                        continue;
                    }
                    if ( size <= 0 ) {
                        continue;
                    }

                    if ( ! cache->ExistFile(number) ) {
                        continue;
                    }

                    vector<FileInfo> files;
                    FileMap::iterator iter = files_.insert(
                            FileMap::value_type(stat.st_atime,files) ).first;
                    FileInfo file;
                    file.service = Factory::GetService();
                    file.path = i->path().string().substr(
                            folderMeta.string().size() );
                    iter->second.push_back(file);
                }
            }
        } catch ( const boost::filesystem::filesystem_error& e ) {
        	LogError(e.what());
        } catch ( const std::exception & e ) {
        	LogError(e.what());
        }
    }
int StorePcapFlow(FlowSource_t *fs, struct FlowNode *Node) {
common_record_t		*common_record;
uint32_t			packets, bytes, pcap_output_record_size;
uint64_t	start_time, end_time;
int			j, id;
char		*string;
void		*data_ptr;

#ifdef SAGAN
char            sagan_string[MAX_SAGAN_STRING];
#endif

	if ( !pcap_extension_map ) {
		pcap_extension_map	= (extension_map_t *)malloc(pcap_extension_info.map->size);
		if ( !pcap_extension_map ) {
			LogError("Process_pcap: malloc() error in %s line %d: %s\n", __FILE__, __LINE__, strerror (errno));
			return 0;
		}
		memcpy((void *)pcap_extension_map, (void *)pcap_extension_info.map, pcap_extension_info.map->size);
		if ( !AddExtensionMap(fs, pcap_extension_map) ) {
			LogError("Process_pcap: Fatal: AddExtensionMap() failed in %s line %d\n", __FILE__, __LINE__);
			return 0;
		}

	}

	if ( Node->version == AF_INET6 ) {
		pcap_output_record_size = pcap_output_record_size_v6;
		dbg_printf("Store Flow v6 node: size: %u\n", pcap_output_record_size);
	} else if ( Node->version == AF_INET ) {
		pcap_output_record_size = pcap_output_record_size_v4;
		dbg_printf("Store Flow v4 node: size: %u\n", pcap_output_record_size);
	} else {
		LogError("Process_pcap: Unexpected version in %s line %d: %u\n", __FILE__, __LINE__, Node->version);
		return 0;
	}

	// output buffer size check for all expected records
	if ( !CheckBufferSpace(fs->nffile, pcap_output_record_size) ) {
		// fishy! - should never happen. maybe disk full?
		LogError("Process_pcap: output buffer size error. Abort pcap record processing");
		return 0;
	}

	// map output record to memory buffer
	common_record	= (common_record_t *)fs->nffile->buff_ptr;

	// header data
	common_record->flags		= 0;
  	common_record->type			= CommonRecordType;
	common_record->exporter_sysid = 0;
	common_record->ext_map		= pcap_extension_map->map_id;
	common_record->size			= pcap_output_record_size;

	// pcap common fields
	common_record->srcport		= Node->src_port;
	common_record->dstport		= Node->dst_port;
	common_record->tcp_flags	= Node->flags;
	common_record->prot			= Node->proto;
	common_record->tos			= 0;
	common_record->fwd_status 	= 0;

	if ( Node->version == AF_INET6 ) {
		SetFlag(common_record->flags, FLAG_IPV6_ADDR);
		pcap_v6_block_t *pcap_v6_block = (pcap_v6_block_t *)common_record->data;
		pcap_v6_block->srcaddr[0] = Node->src_addr.v6[0];
		pcap_v6_block->srcaddr[1] = Node->src_addr.v6[1];
		pcap_v6_block->dstaddr[0] = Node->dst_addr.v6[0];
		pcap_v6_block->dstaddr[1] = Node->dst_addr.v6[1];
		pcap_v6_block->dPkts	  = packets = Node->packets;
		pcap_v6_block->dOctets	  = bytes   = Node->bytes;

		data_ptr = (void *)pcap_v6_block->data;
	} else {
		pcap_v4_block_t *pcap_v4_block = (pcap_v4_block_t *)common_record->data;
		pcap_v4_block->srcaddr = Node->src_addr.v4;
		pcap_v4_block->dstaddr = Node->dst_addr.v4;
		pcap_v4_block->dPkts   = packets = Node->packets;
		pcap_v4_block->dOctets = bytes   = Node->bytes;

		data_ptr = (void *)pcap_v4_block->data;
	}

	// process optional extensions
	j = 0;
	while ( (id = pcap_extension_map->ex_id[j]) != 0 ) {
		switch (id) {
			case EX_IO_SNMP_2:	{	// 2 byte input/output interface index
				tpl_ext_4_t *tpl = (tpl_ext_4_t *)data_ptr;
 					tpl->input  = 0;
 					tpl->output = 0;
				data_ptr = (void *)tpl->data;
				} break;
			default:
				// this should never happen, as pcap has no other extensions
				LogError("Process_pcap: Unexpected extension %i for pcap record. Skip extension", id);
		}
		j++;
	}

	common_record->first 		= Node->t_first.tv_sec;
	common_record->msec_first	= Node->t_first.tv_usec / 1000;

	common_record->last 		= Node->t_last.tv_sec;
	common_record->msec_last	= Node->t_last.tv_usec / 1000;

	start_time = (1000LL * (uint64_t)common_record->first) + (uint64_t)common_record->msec_first;
	end_time   = (1000LL * (uint64_t)common_record->last) + (uint64_t)common_record->msec_last;

	// update first_seen, last_seen
	if ( start_time < fs->first_seen )
		fs->first_seen = start_time;
	if ( end_time > fs->last_seen )
		fs->last_seen = end_time;


	// Update stats
	switch (common_record->prot) {
		case IPPROTO_ICMP:
		case IPPROTO_ICMPV6:
			fs->nffile->stat_record->numflows_icmp++;
			fs->nffile->stat_record->numpackets_icmp += packets;
			fs->nffile->stat_record->numbytes_icmp   += bytes;
			// fix odd CISCO behaviour for ICMP port/type in src port
			if ( common_record->srcport != 0 ) {
				uint8_t *s1, *s2;
				s1 = (uint8_t *)&(common_record->srcport);
				s2 = (uint8_t *)&(common_record->dstport);
				s2[0] = s1[1];
				s2[1] = s1[0];
				common_record->srcport = 0;
			}
			break;
		case IPPROTO_TCP:
			fs->nffile->stat_record->numflows_tcp++;
			fs->nffile->stat_record->numpackets_tcp += packets;
			fs->nffile->stat_record->numbytes_tcp   += bytes;
			break;
		case IPPROTO_UDP:
			fs->nffile->stat_record->numflows_udp++;
			fs->nffile->stat_record->numpackets_udp += packets;
			fs->nffile->stat_record->numbytes_udp   += bytes;
			break;
		default:
			fs->nffile->stat_record->numflows_other++;
			fs->nffile->stat_record->numpackets_other += packets;
			fs->nffile->stat_record->numbytes_other   += bytes;
	}

	fs->nffile->stat_record->numflows++;
	fs->nffile->stat_record->numpackets	+= packets;
	fs->nffile->stat_record->numbytes	+= bytes;

	if ( fs->xstat ) {
		uint32_t bpp = packets ? bytes/packets : 0;
		if ( bpp > MAX_BPP ) 
			bpp = MAX_BPP;
		if ( common_record->prot == IPPROTO_TCP ) {
			fs->xstat->bpp_histogram->tcp.bpp[bpp]++;
			fs->xstat->bpp_histogram->tcp.count++;

			fs->xstat->port_histogram->src_tcp.port[common_record->srcport]++;
			fs->xstat->port_histogram->dst_tcp.port[common_record->dstport]++;
			fs->xstat->port_histogram->src_tcp.count++;
			fs->xstat->port_histogram->dst_tcp.count++;
		} else if ( common_record->prot == IPPROTO_UDP ) {
			fs->xstat->bpp_histogram->udp.bpp[bpp]++;
			fs->xstat->bpp_histogram->udp.count++;

			fs->xstat->port_histogram->src_udp.port[common_record->srcport]++;
			fs->xstat->port_histogram->dst_udp.port[common_record->dstport]++;
			fs->xstat->port_histogram->src_udp.count++;
			fs->xstat->port_histogram->dst_udp.count++;
		}
	}

	if ( verbose ) {
		master_record_t master_record;
		ExpandRecord_v2((common_record_t *)common_record, &pcap_extension_info, NULL, &master_record);
	 	format_file_block_record(&master_record, &string, 0);
		printf("%s\n", string);
	}

#ifdef SAGAN
	if ( sagan ) {
		master_record_t master_record;
		ExpandRecord_v2((common_record_t *)common_record, &pcap_extension_info, NULL, &master_record);
		flow_record_to_sagan(&master_record, &string, 0);

		snprintf(sagan_string, sizeof(sagan_string), "%s\n", string);
		sagan_string[MAX_SAGAN_STRING-1] = '\0';

		Sagan_Send_FIFO(sagan_string);
	}
#endif


	// update file record size ( -> output buffer size )
	fs->nffile->block_header->NumRecords += 1;
	fs->nffile->block_header->size 		 += pcap_output_record_size;
	fs->nffile->buff_ptr 				 = data_ptr;

	return 1;

} /* End of StorePcapFlow */
Example #17
0
/**
 * Execute the given command. If the execution fails, the wait_start()
 * thread in control.c should notice this and send an alert message.
 * @param S A Service object
 * @param C A Command object
 * @param E An optional event object. May be NULL.
 */
void spawn(Service_T S, command_t C, Event_T E) {
        pid_t pid;
        sigset_t mask;
        sigset_t save;
        int stat_loc = 0;
        int exit_status;
        char date[42];

        ASSERT(S);
        ASSERT(C);

        if (access(C->arg[0], X_OK) != 0) {
                LogError("Error: Could not execute %s\n", C->arg[0]);
                return;
        }

        /*
         * Block SIGCHLD
         */
        sigemptyset(&mask);
        sigaddset(&mask, SIGCHLD);
        pthread_sigmask(SIG_BLOCK, &mask, &save);

        Time_string(Time_now(), date);
        pid = fork();
        if (pid < 0) {
                LogError("Cannot fork a new process -- %s\n", STRERROR);
                pthread_sigmask(SIG_SETMASK, &save, NULL);
                return;
        }

        if (pid == 0) {
                if (C->has_gid) {
                        if (setgid(C->gid) != 0) {
                                stat_loc |= setgid_ERROR;
                        }
                }
                if (C->has_uid) {
                        struct passwd *user = getpwuid(C->uid);
                        if (user) {
                                if (initgroups(user->pw_name, getgid()) == 0) {
                                        if (setuid(C->uid) != 0) {
                                                stat_loc |= setuid_ERROR;
                                        }
                                } else {
                                        stat_loc |= initgroups_ERROR;
                                }
                        } else {
                                stat_loc |= getpwuid_ERROR;
                        }
                }

                set_monit_environment(S, C, E, date);

                if (! (Run.flags & Run_Daemon)) {
                        for (int i = 0; i < 3; i++)
                                if (close(i) == -1 || open("/dev/null", O_RDWR) != i)
                                        stat_loc |= redirect_ERROR;
                }

                Util_closeFds();

                setsid();

                pid = fork();
                if (pid < 0) {
                        stat_loc |= fork_ERROR;
                        _exit(stat_loc);
                }

                if (pid == 0) {
                        /*
                         * Reset all signals, so the spawned process is *not* created
                         * with any inherited SIG_BLOCKs
                         */
                        sigemptyset(&mask);
                        pthread_sigmask(SIG_SETMASK, &mask, NULL);
                        signal(SIGINT, SIG_DFL);
                        signal(SIGHUP, SIG_DFL);
                        signal(SIGTERM, SIG_DFL);
                        signal(SIGUSR1, SIG_DFL);
                        signal(SIGPIPE, SIG_DFL);

                        (void) execv(C->arg[0], C->arg);
                        _exit(errno);
                }

                /* Exit first child and return errors to parent */
                _exit(stat_loc);
        }

        /* Wait for first child - aka second parent, to exit */
        if (waitpid(pid, &stat_loc, 0) != pid) {
                LogError("Waitpid error\n");
        }

        exit_status = WEXITSTATUS(stat_loc);
        if (exit_status & setgid_ERROR)
                LogError("Failed to change gid to '%d' for '%s'\n", C->gid, C->arg[0]);
        if (exit_status & setuid_ERROR)
                LogError("Failed to change uid to '%d' for '%s'\n", C->uid, C->arg[0]);
        if (exit_status & initgroups_ERROR)
                LogError("initgroups for UID %d failed when executing '%s'\n", C->uid, C->arg[0]);
        if (exit_status & fork_ERROR)
                LogError("Cannot fork a new process for '%s'\n", C->arg[0]);
        if (exit_status & redirect_ERROR)
                LogError("Cannot redirect IO to /dev/null for '%s'\n", C->arg[0]);
        if (exit_status & getpwuid_ERROR)
                LogError("UID %d not found on the system when executing '%s'\n", C->uid, C->arg[0]);

        /*
         * Restore the signal mask
         */
        pthread_sigmask(SIG_SETMASK, &save, NULL);

        /*
         * We do not need to wait for the second child since we forked twice,
         * the init system-process will wait for it. So we just return
         */

}
Example #18
0
NTSTATUS INTERNAL
GetString(
    _In_ PDEVICE_EXTENSION DevExt,
    _In_ PIRP              Irp
    )
{
    NTSTATUS            status = STATUS_SUCCESS;
    PIO_STACK_LOCATION  irpsp = NULL;
    PWSTR               pwstrID = NULL;
    ULONG_PTR           lenID = 0;
    ULONG_PTR           ulpStringID = 0;

    UNREFERENCED_PARAMETER(DevExt);

    PAGED_CODE();

    irpsp = IoGetCurrentIrpStackLocation(Irp);

    ulpStringID = (ULONG_PTR)(irpsp->Parameters.DeviceIoControl.Type3InputBuffer);
    TEnter(Func,("(DevExt=%p,Irp=%p,IrpSp=%p,StringID=%x)\n",
                DevExt, Irp, irpsp,
                (unsigned int)ulpStringID));

    switch (0xFFFF & ulpStringID)
    {
        case HID_STRING_ID_IMANUFACTURER:
            pwstrID = gpwstrManufacturerID;
            break;

        case HID_STRING_ID_IPRODUCT:
            pwstrID = gpwstrProductID;
            break;

        case HID_STRING_ID_ISERIALNUMBER:
            pwstrID = gpwstrSerialNumber;
            break;

        default:
            pwstrID = NULL;
            break;
    }

    lenID = pwstrID? wcslen(pwstrID)*sizeof(WCHAR) + sizeof(UNICODE_NULL): 0;
    if (pwstrID == NULL)
    {
        status = STATUS_INVALID_PARAMETER;
        LogError(ERRLOG_INVALID_PARAMETER,
                 status,
                 UNIQUE_ERRID(0x70),
                 NULL,
                 NULL);
        TWarn(("invalid string ID (ID=%x).\n",
                   (unsigned int)ulpStringID));
    }
    else if (irpsp->Parameters.DeviceIoControl.OutputBufferLength < lenID)
    {
        status = STATUS_BUFFER_TOO_SMALL;
        LogError(ERRLOG_BUFFER_TOO_SMALL,
                 status,
                 UNIQUE_ERRID(0x80),
                 NULL,
                 NULL);
        TWarn(("output buffer too small (len=%d,need=%d).\n",
                   irpsp->Parameters.DeviceIoControl.OutputBufferLength,
                   (LONG)lenID));
    }
    else
    {
        RtlCopyMemory(Irp->UserBuffer, pwstrID, lenID);

        Irp->IoStatus.Information = lenID;
        status = STATUS_SUCCESS;
    }

    TExit(Func,("=%x (string=%S)\n", status, pwstrID? pwstrID: L"Null"));
    return status;
}       //GetString
Example #19
0
    bool MixSegment::cut(Unicode::const_iterator begin, Unicode::const_iterator end, vector<string>& res)const
    {
        if(!_getInitFlag())
        {
            LogError("not inited.");
            return false;
        }
		if(begin == end)
		{
			return false;
		}
        vector<TrieNodeInfo> infos;
        if(!_mpSeg.cut(begin, end, infos))
        {
            LogError("mpSeg cutDAG failed.");
            return false;
        }
        Unicode unico;
        vector<Unicode> hmmRes;
        string tmp;
        for(uint i= 0; i < infos.size(); i++)
        {
            TransCode::encode(infos[i].word,tmp);
            if(1 == infos[i].word.size())
            {
                unico.push_back(infos[i].word[0]);
            }
            else
            {
                if(!unico.empty())
                {
                    hmmRes.clear();
                    if(!_hmmSeg.cut(unico.begin(), unico.end(), hmmRes))
                    {
                        LogError("_hmmSeg cut failed.");
                        return false;
                    }
                    for(uint j = 0; j < hmmRes.size(); j++)
                    {
                        TransCode::encode(hmmRes[j], tmp);
                        res.push_back(tmp);
                    }
                }
                unico.clear();
                TransCode::encode(infos[i].word, tmp);
                res.push_back(tmp);
            }
        }
        if(!unico.empty())
        {
            hmmRes.clear();
            if(!_hmmSeg.cut(unico.begin(), unico.end(), hmmRes))
            {
                LogError("_hmmSeg cut failed.");
                return false;
            }
            for(uint j = 0; j < hmmRes.size(); j++)
            {
                TransCode::encode(hmmRes[j], tmp);
                res.push_back(tmp);
            }
        }
        
        return true;
    }
Example #20
0
NTSTATUS EXTERNAL
HbtnInternalIoctl(
    IN PDEVICE_OBJECT DevObj,
    IN PIRP           Irp
    )
{
    NTSTATUS            status = STATUS_SUCCESS;
    PDEVICE_EXTENSION   devext = GET_MINIDRIVER_DEVICE_EXTENSION(DevObj);
    PIO_STACK_LOCATION  irpsp = IoGetCurrentIrpStackLocation(Irp);

    TEnter(Func,("(DevObj=%p,Irp=%p,IrpSp=%p,Ioctl=%s)\n",
                DevObj, Irp, irpsp,
                LookupName(irpsp->Parameters.DeviceIoControl.IoControlCode,
                           HidIoctlNames)));

    Irp->IoStatus.Information = 0;
    status = IoAcquireRemoveLock(&devext->RemoveLock, Irp);
    if (!NT_SUCCESS(status))
    {
        LogError(ERRLOG_DEVICE_REMOVED,
                 status,
                 UNIQUE_ERRID(0x10),
                 NULL,
                 NULL);
        TWarn(("received IRP after device was removed.\n"));
        Irp->IoStatus.Status = status;
        IoCompleteRequest(Irp, IO_NO_INCREMENT);
    }
    else if (!(devext->dwfHBtn & HBTNF_DEVICE_STARTED))
    {
        IoReleaseRemoveLock(&devext->RemoveLock, Irp);
        status = STATUS_DEVICE_NOT_READY;
        LogError(ERRLOG_DEVICE_NOT_STARTED,
                 status,
                 UNIQUE_ERRID(0x20),
                 NULL,
                 NULL);
        TWarn(("digitizer is not started.\n"));
        Irp->IoStatus.Status = status;
        IoCompleteRequest(Irp, IO_NO_INCREMENT);
    }
    else
    {
        switch(irpsp->Parameters.DeviceIoControl.IoControlCode)
        {
            case IOCTL_HID_GET_DEVICE_DESCRIPTOR:
                status = GetDeviceDescriptor(devext, Irp);
                break;

            case IOCTL_HID_GET_REPORT_DESCRIPTOR:
                status = GetReportDescriptor(devext, Irp);
                break;

            case IOCTL_HID_READ_REPORT:
                status = ReadReport(devext, Irp);
                break;

            case IOCTL_HID_WRITE_REPORT:
                status = OemWriteReport(devext, Irp);
                break;

            case IOCTL_HID_GET_STRING:
                status = GetString(devext, Irp);
                break;

            case IOCTL_HID_GET_DEVICE_ATTRIBUTES:
                status = GetAttributes(devext, Irp);
                break;

            case IOCTL_HID_ACTIVATE_DEVICE:
            case IOCTL_HID_DEACTIVATE_DEVICE:
                status = STATUS_SUCCESS;
                break;

            default:
                status = STATUS_NOT_SUPPORTED;
                LogError(ERRLOG_NOT_SUPPORTED,
                         status,
                         UNIQUE_ERRID(0x30),
                         NULL,
                         NULL);
                TWarn(("unsupported (IOCTL=%x).\n",
                           irpsp->Parameters.DeviceIoControl.IoControlCode));
                break;
        }

        if (status != STATUS_PENDING)
        {
            IoReleaseRemoveLock(&devext->RemoveLock, Irp);
            Irp->IoStatus.Status = status;
            IoCompleteRequest(Irp, IO_NO_INCREMENT);
        }
        else
        {
            IoMarkIrpPending(Irp);
        }
    }

    TExit(Func,("=%x\n", status));
    return status;
}       //HbtnInternalIoctl
Example #21
0
int check_ntp3(Socket_T s) 
{
  int  br;
  char ntpRequest[NTPLEN];
  char ntpResponse[NTPLEN];

  ASSERT(s);

  memset(ntpRequest, 0, NTPLEN);
  memset(ntpResponse, 0, NTPLEN);

  /*
    Prepare NTP request. The first octet consists of:
       bits 0-1 ... Leap Indicator
       bits 2-4 ... Version Number
       bits 5-7 ... Mode
   */
  ntpRequest[0]=
    (NTP_LEAP_NOTSYNC << 6)
    |
    (NTP_VERSION << 3)
    |
    (NTP_MODE_CLIENT);

  /* Send request to NTP server */
  if(socket_write(s, ntpRequest, NTPLEN) <= 0 ) {
    LogError("NTP: error sending NTP request -- %s\n", STRERROR);
    return FALSE;
  }

  /* Receive and validate response */
  if( (br= socket_read(s, ntpResponse, NTPLEN)) <= 0) {
    LogError("NTP: did not receive answer from server -- %s\n", STRERROR);
    return FALSE;
  }

  if( br != NTPLEN ) {
    LogError("NTP: Received %d bytes from server, expected %d bytes\n",
      br, NTPLEN);
    return FALSE;
  }

  /*
    Compare NTP response. The first octet consists of:
       bits 0-1 ... Leap Indicator
       bits 2-4 ... Version Number
       bits 5-7 ... Mode
   */
  if( (ntpResponse[0] & 0x07) != NTP_MODE_SERVER )
  {
    LogError("NTP: Server mode error\n");
    return FALSE;
  }
  if( (ntpResponse[0] & 0x38) != NTP_VERSION<<3 )
  {
    LogError("NTP: Server protocol version error\n");
    return FALSE;
  }
  if( (ntpResponse[0] & 0xc0) == NTP_LEAP_NOTSYNC<<6 )
  {
    LogError("NTP: Server not synchronized\n");
    return FALSE;
  }

  return TRUE;
}
Example #22
0
void CDMRSlot::setShortLC(unsigned int slotNo, unsigned int id, FLCO flco)
{
	assert(m_modem != NULL);

	switch (slotNo) {
		case 1U:
			m_id1   = 0U;
			m_flco1 = flco;
			if (id != 0U) {
				unsigned char buffer[3U];
				buffer[0U] = (id << 16) & 0xFFU;
				buffer[1U] = (id << 8)  & 0xFFU;
				buffer[2U] = (id << 0)  & 0xFFU;
				m_id1 = CCRC::crc8(buffer, 3U);
			}
			break;
		case 2U:
			m_id2   = 0U;
			m_flco2 = flco;
			if (id != 0U) {
				unsigned char buffer[3U];
				buffer[0U] = (id << 16) & 0xFFU;
				buffer[1U] = (id << 8)  & 0xFFU;
				buffer[2U] = (id << 0)  & 0xFFU;
				m_id2 = CCRC::crc8(buffer, 3U);
			}
			break;
		default:
			LogError("Invalid slot number passed to setShortLC - %u", slotNo);
			return;
	}

	unsigned char lc[5U];
	lc[0U] = 0x01U;
	lc[1U] = 0x00U;
	lc[2U] = 0x00U;
	lc[3U] = 0x00U;

	if (m_id1 != 0U) {
		lc[2U] = m_id1;
		if (m_flco1 == FLCO_GROUP)
			lc[1U] |= 0x80U;
		else
			lc[1U] |= 0x90U;
	}

	if (m_id2 != 0U) {
		lc[3U] = m_id2;
		if (m_flco2 == FLCO_GROUP)
			lc[1U] |= 0x08U;
		else
			lc[1U] |= 0x09U;
	}

	lc[4U] = CCRC::crc8(lc, 4U);

	unsigned char sLC[9U];

	CUtils::dump(1U, "Input Short LC", lc, 5U);

	CShortLC shortLC;
	shortLC.encode(lc, sLC);

	CUtils::dump(1U, "Output Short LC", sLC, 9U);

	m_modem->writeDMRShortLC(sLC);
}
Example #23
0
TSS_RESULT
RPC_TakeOwnership_TP(struct host_table_entry *hte,
		      UINT16 protocolID,	/* in */
		      UINT32 encOwnerAuthSize,	/* in */
		      BYTE * encOwnerAuth,	/* in */
		      UINT32 encSrkAuthSize,	/* in */
		      BYTE * encSrkAuth,	/* in */
		      UINT32 srkInfoSize,	/* in */
		      BYTE * srkInfo,	/* in */
		      TPM_AUTH * ownerAuth,	/* in, out */
		      UINT32 * srkKeySize,
		      BYTE ** srkKey)
{
	TSS_RESULT result;

	initData(&hte->comm, 9);
	hte->comm.hdr.u.ordinal = TCSD_ORD_TAKEOWNERSHIP;
	LogDebugFn("TCS Context: 0x%x", hte->tcsContext);

	if (setData(TCSD_PACKET_TYPE_UINT32, 0, &hte->tcsContext, 0, &hte->comm))
		return TSPERR(TSS_E_INTERNAL_ERROR);
	if (setData(TCSD_PACKET_TYPE_UINT16, 1, &protocolID, 0, &hte->comm))
		return TSPERR(TSS_E_INTERNAL_ERROR);
	if (setData(TCSD_PACKET_TYPE_UINT32, 2, &encOwnerAuthSize, 0, &hte->comm))
		return TSPERR(TSS_E_INTERNAL_ERROR);
	if (setData(TCSD_PACKET_TYPE_PBYTE, 3, encOwnerAuth, encOwnerAuthSize, &hte->comm))
		return TSPERR(TSS_E_INTERNAL_ERROR);
	if (setData(TCSD_PACKET_TYPE_UINT32, 4, &encSrkAuthSize, 0, &hte->comm))
		return TSPERR(TSS_E_INTERNAL_ERROR);
	if (setData(TCSD_PACKET_TYPE_PBYTE, 5, encSrkAuth, encSrkAuthSize, &hte->comm))
		return TSPERR(TSS_E_INTERNAL_ERROR);
	if (setData(TCSD_PACKET_TYPE_UINT32, 6, &srkInfoSize, 0, &hte->comm))
		return TSPERR(TSS_E_INTERNAL_ERROR);
	if (setData(TCSD_PACKET_TYPE_PBYTE, 7, srkInfo, srkInfoSize, &hte->comm))
		return TSPERR(TSS_E_INTERNAL_ERROR);
	if (setData(TCSD_PACKET_TYPE_AUTH, 8, ownerAuth, 0, &hte->comm))
		return TSPERR(TSS_E_INTERNAL_ERROR);

	result = sendTCSDPacket(hte);

	if (result == TSS_SUCCESS)
		result = hte->comm.hdr.u.result;

	if (result == TSS_SUCCESS) {
		if (getData(TCSD_PACKET_TYPE_AUTH, 0, ownerAuth, 0, &hte->comm)) {
			result = TSPERR(TSS_E_INTERNAL_ERROR);
			goto done;
		}
		if (getData(TCSD_PACKET_TYPE_UINT32, 1, srkKeySize, 0, &hte->comm)) {
			result = TSPERR(TSS_E_INTERNAL_ERROR);
			goto done;
		}

		*srkKey = (BYTE *) malloc(*srkKeySize);
		if (*srkKey == NULL) {
			LogError("malloc of %u bytes failed.", *srkKeySize);
			result = TSPERR(TSS_E_OUTOFMEMORY);
			goto done;
		}
		if (getData(TCSD_PACKET_TYPE_PBYTE, 2, *srkKey, *srkKeySize, &hte->comm)) {
			free(*srkKey);
			result = TSPERR(TSS_E_INTERNAL_ERROR);
		}
	}

done:
	return result;
}
Example #24
0
TSS_RESULT
RPC_CertifySelfTest_TP(struct host_table_entry *hte,
			TCS_KEY_HANDLE keyHandle,	/* in */
			TCPA_NONCE antiReplay,	/* in */
			TPM_AUTH * privAuth,	/* in, out */
			UINT32 * sigSize,	/* out */
			BYTE ** sig)	/* out */
{
	TSS_RESULT result;
	int i;

	initData(&hte->comm, 4);
	hte->comm.hdr.u.ordinal = TCSD_ORD_CERTIFYSELFTEST;
	LogDebugFn("TCS Context: 0x%x", hte->tcsContext);

	if (setData(TCSD_PACKET_TYPE_UINT32, 0, &hte->tcsContext, 0, &hte->comm))
		return TSPERR(TSS_E_INTERNAL_ERROR);
	if (setData(TCSD_PACKET_TYPE_UINT32, 1, &keyHandle, 0, &hte->comm))
		return TSPERR(TSS_E_INTERNAL_ERROR);
	if (setData(TCSD_PACKET_TYPE_NONCE, 2, &antiReplay, 0, &hte->comm))
		return TSPERR(TSS_E_INTERNAL_ERROR);

	if (privAuth) {
		if (setData(TCSD_PACKET_TYPE_AUTH, 3, privAuth, 0, &hte->comm))
			return TSPERR(TSS_E_INTERNAL_ERROR);
	}

	result = sendTCSDPacket(hte);

	if (result == TSS_SUCCESS)
		result = hte->comm.hdr.u.result;

	if (result == TSS_SUCCESS) {
		i = 0;
		if (privAuth) {
			if (getData(TCSD_PACKET_TYPE_AUTH, i++, privAuth, 0, &hte->comm)) {
				LogDebug("privAuth");
				result = TSPERR(TSS_E_INTERNAL_ERROR);
				goto done;
			}
		}
		if (getData(TCSD_PACKET_TYPE_UINT32, i++, sigSize, 0, &hte->comm)) {
			LogDebug("sigSize");
			result = TSPERR(TSS_E_INTERNAL_ERROR);
			goto done;
		}
		*sig = (BYTE *) malloc(*sigSize);
		if (*sig == NULL) {
			LogError("malloc of %u bytes failed.", *sigSize);
			result = TSPERR(TSS_E_OUTOFMEMORY);
			goto done;
		}
		if (getData(TCSD_PACKET_TYPE_PBYTE, i++, *sig, *sigSize, &hte->comm)) {
			LogDebug("sig");
			free(*sig);
			result = TSPERR(TSS_E_INTERNAL_ERROR);
		}
	}

done:
	return result;
}
Example #25
0
void LogUnrecognizedChar( char ch, const char *label )
{
    LogError( "Unrecognized character received: 0x%02x while waiting for %s\n", ch, label );

} // LogUnrecognizedChar
Example #26
0
/**
 * Read all processes to initialize the information tree.
 * @param reference  reference of ProcessTree
 * @return treesize>0 if succeeded otherwise =0.
 */
int initprocesstree_sysdep(ProcessTree_T ** reference) {
  int                        treesize;
  size_t                     size = sizeof(maxslp);
  char                       buf[_POSIX2_LINE_MAX];
  int                        mib_proc2[6] = {CTL_KERN, KERN_PROC2, KERN_PROC_ALL, 0, sizeof(struct kinfo_proc2), 0};
  static int                 mib_maxslp[] = {CTL_VM, VM_MAXSLP};
  ProcessTree_T             *pt;
  kvm_t                     *kvm_handle;
  static struct kinfo_proc2 *pinfo;

  if (sysctl(mib_maxslp, 2, &maxslp, &size, NULL, 0) < 0) {
    LogError("system statistic error -- vm.maxslp failed");
    return FALSE;
  }

  if (sysctl(mib_proc2, 6, NULL, &size, NULL, 0) == -1) {
    LogError("system statistic error -- kern.proc2 #1 failed");
    return FALSE;
  }

  size *= 2; // Add reserve for new processes which were created between calls of sysctl
  pinfo = CALLOC(1, size);
  mib_proc2[5] = (int)(size / sizeof(struct kinfo_proc2));
  if (sysctl(mib_proc2, 6, pinfo, &size, NULL, 0) == -1) {
    FREE(pinfo);
    LogError("system statistic error -- kern.proc2 #2 failed");
    return FALSE;
  }

  treesize = (int)(size / sizeof(struct kinfo_proc2));

  pt = CALLOC(sizeof(ProcessTree_T), treesize);

  if (! (kvm_handle = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, buf))) {
    LogError("system statistic error -- kvm_openfiles failed: %s", buf);
    return FALSE;
  }

  for (int i = 0; i < treesize; i++) {
    pt[i].pid         = pinfo[i].p_pid;
    pt[i].ppid        = pinfo[i].p_ppid;
    pt[i].starttime   = pinfo[i].p_ustart_sec;
    pt[i].cputime     = (long)((pinfo[i].p_rtime_sec * 10) + (pinfo[i].p_rtime_usec / 100000));
    pt[i].cpu_percent = 0;
    pt[i].mem_kbyte   = (unsigned long)(pinfo[i].p_vm_rssize * pagesize_kbyte);
    if (pinfo[i].p_stat == SZOMB)
      pt[i].status_flag |= PROCESS_ZOMBIE;
    pt[i].time = get_float_time();
    char **args;
    if ((args = kvm_getargv2(kvm_handle, &pinfo[i], 0))) {
      StringBuffer_T cmdline = StringBuffer_create(64);
      for (int j = 0; args[j]; j++)
        StringBuffer_append(cmdline, args[j + 1] ? "%s " : "%s", args[j]);
      pt[i].cmdline = Str_dup(StringBuffer_toString(StringBuffer_trim(cmdline)));
      StringBuffer_free(&cmdline);
    }
    if (! pt[i].cmdline || ! *pt[i].cmdline)
      pt[i].cmdline = Str_dup(pinfo[i].p_comm);
  }
  FREE(pinfo);
  kvm_close(kvm_handle);

  *reference = pt;

  return treesize;
}
void GetTrianglesFromMesh(Ogre::Mesh* mesh, std::vector<float3>& dest)
{
    dest.clear();
    
    try
    {

    for(uint i = 0; i < mesh->getNumSubMeshes(); ++i)
    {
        Ogre::SubMesh* submesh = mesh->getSubMesh(i);
        
        Ogre::VertexData* vertex_data = submesh->useSharedVertices ? mesh->sharedVertexData : submesh->vertexData;
        const Ogre::VertexElement* posElem = vertex_data->vertexDeclaration->findElementBySemantic(Ogre::VES_POSITION);
        Ogre::HardwareVertexBufferSharedPtr vbuf = vertex_data->vertexBufferBinding->getBuffer(posElem->getSource());
        unsigned char* vertices = static_cast<unsigned char*>(vbuf->lock(Ogre::HardwareBuffer::HBL_READ_ONLY));
        size_t vertexSize = vbuf->getVertexSize();
        float* pReal = 0;
        
        Ogre::IndexData* index_data = submesh->indexData;
        size_t numTris = index_data->indexCount / 3;
        Ogre::HardwareIndexBufferSharedPtr ibuf = index_data->indexBuffer;
        u32*  pLong = static_cast<u32*>(ibuf->lock(Ogre::HardwareBuffer::HBL_READ_ONLY));
        u16* pShort = reinterpret_cast<u16*>(pLong);
        bool use32bitindexes = (ibuf->getType() == Ogre::HardwareIndexBuffer::IT_32BIT);
        
        if (use32bitindexes)
        {
            for(size_t k = 0; k < numTris * 3; k += 3)
            {
                uint i1 = pLong[k];
                uint i2 = pLong[k+1];
                uint i3 = pLong[k+2];
                
                posElem->baseVertexPointerToElement(vertices + i1 * vertexSize, &pReal);
                dest.push_back(float3(pReal[0], pReal[1], pReal[2]));
                    
                posElem->baseVertexPointerToElement(vertices + i2 * vertexSize, &pReal);
                dest.push_back(float3(pReal[0], pReal[1], pReal[2]));
                    
                posElem->baseVertexPointerToElement(vertices + i3 * vertexSize, &pReal);
                dest.push_back(float3(pReal[0], pReal[1], pReal[2]));
                

            }
        }
        else
        {
            for(size_t k = 0; k < numTris * 3; k += 3)
            {
                uint i1 = pShort[k];
                uint i2 = pShort[k+1];
                uint i3 = pShort[k+2];
                
                posElem->baseVertexPointerToElement(vertices + i1 * vertexSize, &pReal);
                dest.push_back(float3(pReal[0], pReal[1], pReal[2]));
                    
                posElem->baseVertexPointerToElement(vertices + i2 * vertexSize, &pReal);
                dest.push_back(float3(pReal[0], pReal[1], pReal[2]));
                    
                posElem->baseVertexPointerToElement(vertices + i3 * vertexSize, &pReal);
                dest.push_back(float3(pReal[0], pReal[1], pReal[2]));
            }
        }
        
        vbuf->unlock();
        ibuf->unlock();
    }

    } catch(Ogre::Exception &e)
    {
        ///\todo Fix Ogre to not allow meshes like this to be successfully created.
        LogError("GetTrianglesFromMesh failed for mesh! Ogre threw an exception: " + QString(e.what()));
        dest.clear();
    }
}
Example #28
0
    void
    CacheMonitorServer::ServerThread()
    {
        static int waitTime = Factory::GetConfigure()->GetValueSize(
                Configure::CachePurgeWaitTime );

        while ( run_ ) {
            boost::this_thread::sleep(boost::posix_time::seconds(waitTime));

#ifdef MORE_TEST
#else
            TapeLibraryMgr * mgr = TapeLibraryMgr::Instance();
            SystemHwMode mode = mgr->GetSystemHwMode();
            if ( mode == SYSTEM_HW_NEED_DIAGNOSE ) {
                continue;
            }
            if ( mode == SYSTEM_HW_DIAGNOSING ) {
                continue;
            }

            int action;
            if ( mgr->GetWriteCacheAction(action) ) {
                if ( ! mgr->SetWriteCacheAction(action) ) {
                    LogError("Failure to set write cache action: " << action);
                }
            } else {
                LogError("Failure to get write cache action");
            }
#endif

            if ( ! fs::exists(folderMeta_) || ! fs::is_directory(folderMeta_) ) {
                LogWarn(folderMeta_);
                continue;
            }
            if ( CheckFreeSize(minFreeSize_) ) {
                continue;
            }
            LogInfo(folderMeta_);

            fs::directory_iterator end;
            for ( fs::directory_iterator i(folderMeta_); i != end; ++ i ) {
                if ( ! fs::is_directory(i->status()) ) {
                    continue;
                }
                string service = i->path().filename().string();
                Factory::SetService(service);
                Factory::CreateCacheManager();
                ScanFolder(i->path());
                Factory::ReleaseCacheManager();
                Factory::SetService("");
            }

            for ( FileMap::iterator i = files_.begin();
                    i != files_.end();
                    ++ i ) {
                if ( CheckFreeSize(maxFreeSize_) ) {
                    break;
                }

                for ( vector<FileInfo>::iterator iter = i->second.begin();
                        iter != i->second.end();
                        ++ iter ) {
                    if ( CheckFreeSize(maxFreeSize_) ) {
                        break;
                    }

                    ReleaseFile(*iter);
                }
            }

            files_.clear();
        }
    }
Example #29
0
int verbTOC::DoWork(const char *nameOfInput)
{
    LogVerbose("Indexing from '%s' into '%s.mct'", nameOfInput, nameOfInput);

    MethodContextIterator mci;
    if (!mci.Initialize(nameOfInput))
        return -1;

    int savedCount = 0;

    TOCElementNode *head = nullptr;
    TOCElementNode *curElem = nullptr;

    while (mci.MoveNext())
    {
        MethodContext* mc = mci.Current();

        TOCElementNode *nxt = new TOCElementNode(mci.MethodContextNumber(), mci.CurrentPos());
        mc->dumpMethodMD5HashToBuffer(nxt->tocElement.Hash, MD5_HASH_BUFFER_SIZE);

        if (curElem != nullptr)
        {
            curElem->Next = nxt;
        }
        else
        {
            head = nxt;
        }
        curElem = nxt;
        savedCount++;
    }

    size_t maxLen = strlen(nameOfInput) + 5;
    char *nameOfOutput = (char*)_alloca(maxLen);
    strcpy_s(nameOfOutput, maxLen, nameOfInput);
    strcat_s(nameOfOutput, maxLen, ".mct");
    HANDLE hFileOut = CreateFileA(nameOfOutput, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hFileOut == INVALID_HANDLE_VALUE)
    {
        LogError("Failed to open input 1 '%s'. GetLastError()=%u", nameOfOutput, GetLastError());
        return -1;
    }

    DWORD written;
    // Write out the signature "INDX" and then the element count
    LARGE_INTEGER token;
    token.u.LowPart = *(const int*)"INDX"; // cuz Type Safety is for languages that have good IO facilities
    token.u.HighPart = savedCount;
    if (!WriteFile(hFileOut, &token, sizeof(token), &written, nullptr) || written != sizeof(token))
    {
        LogError("Failed to write index header. GetLastError()=%u", GetLastError());
    }

    // Now just dump sizeof(TOCElement) byte chunks into the file.
    // I could probably do this more efficiently, but I don't think it matters
    DWORD chunkSize = sizeof(TOCElement);
    for (curElem = head; curElem != nullptr; curElem = curElem->Next)
    {
        if (!WriteFile(hFileOut, &curElem->tocElement, chunkSize, &written, nullptr) || written != chunkSize)
        {
            LogError("Failed to write index element '%d'. GetLastError()=%u", curElem->tocElement.Number, GetLastError());
            return -1;
        }
    }
    // Now write out a final "INDX" to flag the end of the file...
    if (!WriteFile(hFileOut, &token.u.LowPart, sizeof(token.u.LowPart), &written, nullptr) || (written != sizeof(token.u.LowPart)))
    {
        LogError("Failed to write index terminal. GetLastError()=%u", GetLastError());
    }

    LogInfo("Loaded %d, added %d to Table of Contents", mci.MethodContextNumber(), savedCount);

    if (CloseHandle(hFileOut) == 0)
    {
        LogError("CloseHandle failed. GetLastError()=%u", GetLastError());
        return -1;
    }

    if (!mci.Destroy())
        return -1;

    return 0;
}
Example #30
0
/*
 * BSPSplitPoly:  Split given polygon with given wall.  Fill in pos_poly and
 *   neg_poly with polygons on + and - side.
 *   Modifies poly (essentially destroys it)
 *   Returns True iff split goes OK.
 */
Bool BSPSplitPoly(Poly *poly, WallData *wall, Poly *pos_poly, Poly *neg_poly)
{
  int a,b,c;
  int i,j;
  Poly tmp;
  WallData temp_wall;
  int x,y, side;
  
  int intr[2];
  int intrcount;
  
  intrcount = 0;
  
  BSPGetLineEquationFromWall(wall, &a, &b, &c);
  
  /* copy first point */
  j = 0;
  tmp.p[j] = poly->p[0];
  j++;
  
  for(i=0; i<poly->npts; i++)
    {
      temp_wall.x0 = poly->p[i].x;
      temp_wall.y0 = poly->p[i].y;
      temp_wall.x1 = poly->p[i+1].x;
      temp_wall.y1 = poly->p[i+1].y;
      
      switch(BSPWallIntersection(wall, &temp_wall, &x, &y))
	{
	case NoIntersection:
	  tmp.p[j] = poly->p[i+1];
	  j++;
	  break;
	case Coincide:
	  goto oneside;
	case FirstEndpoint:
	  if (intrcount < 2)
	    {
	      intr[intrcount] = j-1;
	      intrcount++;
	    }
	  else
	    {
	      LogError("more than 2 intersections! (1)\n");
	      pos_poly->npts = neg_poly->npts = 0;
	      return False;
	    }
	  tmp.p[j] = poly->p[i+1];
	  j++;
	  break;
	case SecondEndpoint:
	  tmp.p[j] = poly->p[i+1];
	  j++;
	  break;
	case Inexpressible:
//	  dprintf("inexpressible intersection in BSPSplitWalls, using approximate intersection...\n");
	case Middle:
	  tmp.p[j].x = x;
	  tmp.p[j].y = y;
	  
	  if (intrcount < 2)
	    {
	      intr[intrcount] = j;
	      intrcount++;
	    }
	  else
	    {
	      LogError("more than 2 intersections! (2)\n");
	      pos_poly->npts = neg_poly->npts = 0;
	      return False;
	    }
	  j++;
	  
	  tmp.p[j] = poly->p[i+1];
	  j++;
	  break;
	}
    }
  tmp.npts = j-1;  /* j points added, but last is == to first */
  
#if 0
  dprintf("expanded: %d ", tmp.npts);
  for (i=0; i<=tmp.npts; i++)
    dprintf("(%d %d) ", tmp.p[i].x, tmp.p[i].y);
  dprintf("\n");
#endif
  
  if (intrcount < 2)
    {
      LogError("less than 2 intersections!\n");
      pos_poly->npts = neg_poly->npts = 0;
      return False;
    }
  
  i = 0;
  while(1)
    {
      int k = (i + intr[0]) % tmp.npts;
      pos_poly->p[i] = tmp.p[k];
      i++;
      if (k == intr[1]) break;
    }
  pos_poly->p[i] = pos_poly->p[0];
  pos_poly->npts = i;
  
  i = 0;
  while(1)
    {
      int k = (i + intr[1]) % tmp.npts;
      neg_poly->p[i] = tmp.p[k];
      i++;
      if (k == intr[0]) break;
    }
  neg_poly->p[i] = neg_poly->p[0];
  neg_poly->npts = i;
  
  /* check to see if we need to switch polys */
  side = 0;
  for(i=0; i<pos_poly->npts; i++)
    {
      side += a * pos_poly->p[i].x + b * pos_poly->p[i].y + c;
    }
  if (side < 0)
    {
      memcpy(&tmp, pos_poly, sizeof(Poly));
      memcpy(pos_poly, neg_poly, sizeof(Poly));
      memcpy(neg_poly, &tmp, sizeof(Poly));
    }
  
  return True;
  
  
  
 oneside:        /* polygon all on one side of wall */
  for(i=0; i<poly->npts; i++)
    {
      side = a * poly->p[i].x + b * poly->p[i].y + c;
      if (side > 0)
	{
	  memcpy(pos_poly, poly, sizeof(Poly));
	  neg_poly->npts = 0;
	  return True;
	}
      else if (side < 0)
	{
	  memcpy(neg_poly, poly, sizeof(Poly));
	  pos_poly->npts = 0;
	  return True;
	}
    }
  LogError("all polygon points in plane!\n");
  pos_poly->npts = neg_poly->npts = 0;
  return False;
}