Exemple #1
0
static int
parse_subtree(//subtree, input, output, out_len)
    struct snmp_mib_tree *subtree,
    char *input,
    oid	*output,
    int	*out_len)   /* number of subid's */
{
    char buf[128], *to = buf;
    u_int subid = 0;
    struct snmp_mib_tree *tp;

    /*
     * No empty strings.  Can happen if there is a trailing '.' or two '.'s
     * in a row, i.e. "..".
     */
    if ((*input == '\0') ||
	(*input == '.'))
	return (0);

    if (isdigit(*input)) {
	/*
	 * Read the number, then try to find it in the subtree.
	 */
	while (isdigit(*input)) {
	    subid *= 10;
	    subid += *input++ - '0';
	}
	for (tp = subtree; tp; tp = tp->next_peer) {
	    if (tp->subid == subid)
		goto found;
	}
	tp = NULL;
    }
    else {
	/*
	 * Read the name into a buffer.
	 */
	while ((*input != '\0') &&
	       (*input != '.')) {
	    *to++ = *input++;
	}
	*to = '\0';

	/*
	 * Find the name in the subtree;
	 */
	for (tp = subtree; tp; tp = tp->next_peer) {
	    if (lc_cmp(tp->label, buf) == 0) {
		subid = tp->subid;
		goto found;
	    }
	}

	/*
	 * If we didn't find the entry, punt...
	 */
	if (tp == NULL) {
#ifdef STDERR_OUTPUT
	    fprintf(stderr, WIDE("sub-identifier not found: %s\n"), buf);
#endif
	    return (0);
	}
    }

 found:
    //cpg26dec2006 src\snmplib\mib.c(808): Warning! W124: Comparison result always 0
	 if(subid > (u_int)MAX_SUBID){
		 {
#ifdef STDERR_OUTPUT
			 fprintf(stderr, WIDE("sub-identifier too large: %s\n"), buf);
#endif
			 return (0);
		 }
	 }

    if ((*out_len)-- <= 0){
#ifdef STDERR_OUTPUT
	fprintf(stderr, WIDE("object identifier too long\n"));
#endif
	return (0);
    }
    *output++ = subid;

    if (*input != '.')
	return (1);
    if ((*out_len =
	 parse_subtree(tp ? tp->child_list : NULL, ++input, output, out_len)) == 0)
	return (0);
    return (++*out_len);
}
Exemple #2
0
/* This is the slowpoll function which gathers up network/hard drive
   performance data for the random pool */
BOOL SlowPoll (void)
{
	static int isWorkstation = -1;
	static int cbPerfData = 0x10000;
	HANDLE hDevice;
	LPBYTE lpBuffer;
	DWORD dwSize, status;
	LPWSTR lpszLanW, lpszLanS;
	int nDrive;

	/* Find out whether this is an NT server or workstation if necessary */
	if (isWorkstation == -1)
	{
		HKEY hKey;

		if (RegOpenKeyEx (HKEY_LOCAL_MACHINE,
		       "SYSTEM\\CurrentControlSet\\Control\\ProductOptions",
				  0, KEY_READ, &hKey) == ERROR_SUCCESS)
		{
			unsigned char szValue[32];
			dwSize = sizeof (szValue);

			isWorkstation = TRUE;
			status = RegQueryValueEx (hKey, "ProductType", 0, NULL,
						  szValue, &dwSize);

			if (status == ERROR_SUCCESS && _stricmp ((char *) szValue, "WinNT"))
				/* Note: There are (at least) three cases for
				   ProductType: WinNT = NT Workstation,
				   ServerNT = NT Server, LanmanNT = NT Server
				   acting as a Domain Controller */
				isWorkstation = FALSE;

			RegCloseKey (hKey);
		}
	}
	/* Initialize the NetAPI32 function pointers if necessary */
	if (hNetAPI32 == NULL)
	{
		/* Obtain a handle to the module containing the Lan Manager
		   functions */
		hNetAPI32 = LoadLibrary ("NETAPI32.DLL");
		if (hNetAPI32 != NULL)
		{
			/* Now get pointers to the functions */
			pNetStatisticsGet = (NETSTATISTICSGET) GetProcAddress (hNetAPI32,
							"NetStatisticsGet");
			pNetApiBufferSize = (NETAPIBUFFERSIZE) GetProcAddress (hNetAPI32,
							"NetApiBufferSize");
			pNetApiBufferFree = (NETAPIBUFFERFREE) GetProcAddress (hNetAPI32,
							"NetApiBufferFree");

			/* Make sure we got valid pointers for every NetAPI32
			   function */
			if (pNetStatisticsGet == NULL ||
			    pNetApiBufferSize == NULL ||
			    pNetApiBufferFree == NULL)
			{
				/* Free the library reference and reset the
				   static handle */
				FreeLibrary (hNetAPI32);
				hNetAPI32 = NULL;
			}
		}
	}

	/* Get network statistics.  Note: Both NT Workstation and NT Server
	   by default will be running both the workstation and server
	   services.  The heuristic below is probably useful though on the
	   assumption that the majority of the network traffic will be via
	   the appropriate service */
	lpszLanW = (LPWSTR) WIDE ("LanmanWorkstation");
	lpszLanS = (LPWSTR) WIDE ("LanmanServer");
	if (hNetAPI32 &&
	    pNetStatisticsGet (NULL,
			       isWorkstation ? lpszLanW : lpszLanS,
			       0, 0, &lpBuffer) == 0)
	{
		pNetApiBufferSize (lpBuffer, &dwSize);
		RandaddBuf ((unsigned char *) lpBuffer, dwSize);
		pNetApiBufferFree (lpBuffer);
	}

	/* Get disk I/O statistics for all the hard drives */
	for (nDrive = 0;; nDrive++)
	{
		DISK_PERFORMANCE diskPerformance;
		char szDevice[24];

		/* Check whether we can access this device */
		sprintf (szDevice, "\\\\.\\PhysicalDrive%d", nDrive);
		hDevice = CreateFile (szDevice, 0, FILE_SHARE_READ | FILE_SHARE_WRITE,
				      NULL, OPEN_EXISTING, 0, NULL);
		if (hDevice == INVALID_HANDLE_VALUE)
			break;


		/* Note: This only works if you have turned on the disk
		   performance counters with 'diskperf -y'.  These counters
		   are off by default */
		if (DeviceIoControl (hDevice, IOCTL_DISK_PERFORMANCE, NULL, 0,
				&diskPerformance, sizeof (DISK_PERFORMANCE),
				     &dwSize, NULL))
		{
			RandaddBuf ((unsigned char *) &diskPerformance, dwSize);
		}
		CloseHandle (hDevice);
	}

	// CryptoAPI
	if (CryptoAPIAvailable && CryptGenRandom (hCryptProv, sizeof (buffer), buffer)) 
		RandaddBuf (buffer, sizeof (buffer));

	burn(buffer, sizeof (buffer));
	Randmix();
	return TRUE;
}
Exemple #3
0
void CPROC ShowSQLStates( CTEXTSTR message )
{
	fprintf( stderr, WIDE("%s\n"), message );
}
Exemple #4
0
static genxStatus WriteBufferBounded( void *UserData, constUtf8 s, constUtf8 end )
{
	vtprintf( (PVARTEXT)UserData, WIDE("%*.*s"), end-s, end-s, s );
	return GENX_SUCCESS;
}
Exemple #5
0
int SystemCheck( void )
{
	WSADATA wd;
	int i;
	int protoIndex = -1;
	int size;
	//lprintf( "Global is %d %p", sizeof( globalNetworkData ), &globalNetworkData.uNetworkPauseTimer, &globalNetworkData.nProtos );

	if (WSAStartup(MAKEWORD(2, 0), &wd) != 0)
	{
		lprintf(WIDE( "WSAStartup 2.0 failed: %d" ), h_errno);
		return 0;
	}
	if( globalNetworkData.flags.bLogProtocols )
		lprintf(WIDE( "Winsock Version: %d.%d" ), LOBYTE(wd.wVersion), HIBYTE(wd.wVersion));

	size = 0;
	if ((globalNetworkData.nProtos = WSAEnumProtocolsW(NULL, NULL, (DWORD *) &size)) == -1)
	{
		if( WSAGetLastError() != WSAENOBUFS )
		{
			lprintf(WIDE( "WSAEnumProtocols: %d" ), h_errno);
			return 0;
		}
	}

	globalNetworkData.pProtos = (WSAPROTOCOL_INFOW*)Allocate( size );
	if ((globalNetworkData.nProtos = WSAEnumProtocolsW(NULL, globalNetworkData.pProtos, (DWORD *) &size)) == -1)
	{
		lprintf(WIDE( "WSAEnumProtocols: %d" ), h_errno);
		return 0;
	}
	for (i = 0; i < globalNetworkData.nProtos; i++)
	{
		// IPv6
		if (wcscmp(globalNetworkData.pProtos[i].szProtocol, L"MSAFD Tcpip [TCP/IP]" ) == 0)
		{
			globalNetworkData.tcp_protocol = i;
			protoIndex = i;
		}
		if (wcscmp(globalNetworkData.pProtos[i].szProtocol, L"MSAFD Tcpip [UDP/IP]" ) == 0)
		{
			globalNetworkData.udp_protocol = i;
		}
		if (wcscmp(globalNetworkData.pProtos[i].szProtocol, L"MSAFD Tcpip [TCP/IPv6]" ) == 0)
		{
			globalNetworkData.tcp_protocolv6 = i;
		}
		if (wcscmp(globalNetworkData.pProtos[i].szProtocol, L"MSAFD Tcpip [UDP/IPv6]" ) == 0)
		{
			globalNetworkData.udp_protocolv6 = i;
		}
		if( globalNetworkData.flags.bLogProtocols )
			lprintf(WIDE( "Index #%d - name: '%S', type: %d, proto: %d" ), i, globalNetworkData.pProtos[i].szProtocol,
					  globalNetworkData.pProtos[i].iSocketType, globalNetworkData.pProtos[i].iProtocol);
	}
	if (protoIndex == -1)
	{
		lprintf(WIDE( "no valid TCP/IP protocol available" ));
		return 0;
	}
	return 0;
}
Exemple #6
0
 void  BlotScaledImageSizedEx ( ImageFile *pifDest, ImageFile *pifSrc
                                    , int32_t xd, int32_t yd
                                    , uint32_t wd, uint32_t hd
                                    , int32_t xs, int32_t ys
                                    , uint32_t ws, uint32_t hs
                                    , uint32_t nTransparent
                                    , uint32_t method, ... )
     // integer scalar... 0x10000 = 1
{
	CDATA *po, *pi;
	static uint32_t lock;
	uint32_t  oo;
	uint32_t srcwidth;
	int errx, erry;
	uint32_t dhd, dwd, dhs, dws;
	va_list colors;
	va_start( colors, method );
	//lprintf( WIDE("Blot enter (%d,%d)"), _wd, _hd );
	if( nTransparent > ALPHA_TRANSPARENT_MAX )
	{
		return;
	}
	if( !pifSrc ||  !pifDest
	   || !pifSrc->image //|| !pifDest->image
	   || !wd || !hd || !ws || !hs )
	{
		return;
	}

	if( ( xd > ( pifDest->x + pifDest->width ) )
	  || ( yd > ( pifDest->y + pifDest->height ) )
	  || ( ( xd + (signed)wd ) < pifDest->x )
		|| ( ( yd + (signed)hd ) < pifDest->y ) )
	{
		return;
	}
	dhd = hd;
	dhs = hs;
	dwd = wd;
	dws = ws;

	// ok - how to figure out how to do this
	// need to update the position and width to be within the 
	// the bounds of pifDest....
	//lprintf(" begin scaled output..." );
	errx = -(signed)dwd;
	erry = -(signed)dhd;

	if( xd < pifDest->x )
	{
		while( xd < pifDest->x )
		{
			errx += (signed)dws;
			while( errx >= 0 )
			{
	            errx -= (signed)dwd;
				ws--;
				xs++;
			}
			wd--;
			xd++;
		}
	}
	//Log8( WIDE("Blot scaled params: %d %d %d %d / %d %d %d %d "), 
	//       xs, ys, ws, hs, xd, yd, wd, hd );
	if( yd < pifDest->y )
	{
		while( yd < pifDest->y )
		{
			erry += (signed)dhs;
			while( erry >= 0 )
			{
				erry -= (signed)dhd;
				hs--;
				ys++;
			}
			hd--;
			yd++;
		}
	}
	//Log8( WIDE("Blot scaled params: %d %d %d %d / %d %d %d %d "), 
	//       xs, ys, ws, hs, xd, yd, wd, hd );
	if( ( xd + (signed)wd ) > ( pifDest->x + pifDest->width) )
	{
		//int newwd = TOFIXED(pifDest->width);
		//ws -= ((int64_t)( (int)wd - newwd)* (int64_t)ws )/(int)wd;
		wd = ( pifDest->x + pifDest->width ) - xd;
	}
	//Log8( WIDE("Blot scaled params: %d %d %d %d / %d %d %d %d "), 
	//       xs, ys, ws, hs, xd, yd, wd, hd );
	if( ( yd + (signed)hd ) > (pifDest->y + pifDest->height) )
	{
		//int newhd = TOFIXED(pifDest->height);
		//hs -= ((int64_t)( hd - newhd)* hs )/hd;
		hd = (pifDest->y + pifDest->height) - yd;
	}
	if( (int32_t)wd <= 0 ||
       (int32_t)hd <= 0 ||
       (int32_t)ws <= 0 ||
		 (int32_t)hs <= 0 )
	{
		return;
	}
   
	//Log9( WIDE("Image locations: %d(%d %d) %d(%d) %d(%d) %d(%d)")
	//          , xs, FROMFIXED(xs), FIXEDPART(xs)
	//          , ys, FROMFIXED(ys)
	//          , xd, FROMFIXED(xd)
	//          , yd, FROMFIXED(yd) );
#ifdef _INVERT_IMAGE
	// set pointer in to the starting x pixel
	// on the last line of the image to be copied 
	pi = IMG_ADDRESS( pifSrc, (xs), (ys) );
	po = IMG_ADDRESS( pifDest, (xd), (yd) );
	oo = 4*(-((signed)wd) - (pifDest->pwidth) ); // w is how much we can copy...
	// adding in multiple of 4 because it's C...
	srcwidth = -(4* pifSrc->pwidth);
#else
	// set pointer in to the starting x pixel
	// on the first line of the image to be copied...
	pi = IMG_ADDRESS( pifSrc, (xs), (ys) );
	po = IMG_ADDRESS( pifDest, (xd), (yd) );
	oo = 4*(pifDest->pwidth - (wd)); // w is how much we can copy...
	// adding in multiple of 4 because it's C...
	srcwidth = 4* pifSrc->pwidth;
#endif
	while( LockedExchange( &lock, 1 ) )
		Relinquish();
   //Log8( WIDE("Do blot work...%d(%d),%d(%d) %d(%d) %d(%d)")
   //    , ws, FROMFIXED(ws), hs, FROMFIXED(hs) 
	//    , wd, FROMFIXED(wd), hd, FROMFIXED(hd) );

	if( ( pifDest->flags & IF_FLAG_FINAL_RENDER )
		&& !( pifDest->flags & IF_FLAG_IN_MEMORY ) )
	{
		int updated = 0;
		Image topmost_parent;

		// closed loop to get the top imgae size.
		for( topmost_parent = pifSrc; topmost_parent->pParent; topmost_parent = topmost_parent->pParent );

		ReloadOpenGlTexture( pifSrc, 0 );
		if( !pifSrc->glActiveSurface )
		{
			lprintf( WIDE( "gl texture hasn't downloaded or went away?" ) );
			lock = 0;
			return;
		}
		//lprintf( WIDE( "use regular texture %p (%d,%d)" ), pifSrc, pifSrc->width, pifSrc->height );

		{
			int glDepth = 1;
			VECTOR v1[2], v3[2], v4[2], v2[2];
			int v = 0;
			double x_size, x_size2, y_size, y_size2;
			/*
			 * only a portion of the image is actually used, the rest is filled with blank space
			 *
			 */
			TranslateCoord( pifDest, &xd, &yd );
			TranslateCoord( pifSrc, &xs, &ys );

			v1[v][0] = xd;
			v1[v][1] = yd;
			v1[v][2] = 0.0;

			v2[v][0] = xd;
			v2[v][1] = yd+hd;
			v2[v][2] = 0.0;

			v3[v][0] = xd+wd;
			v3[v][1] = yd+hd;
			v3[v][2] = 0.0;

			v4[v][0] = xd+wd;
			v4[v][1] = yd;
			v4[v][2] = 0.0;

			x_size = (double) xs/ (double)topmost_parent->width;
			x_size2 = (double) (xs+ws)/ (double)topmost_parent->width;
			y_size = (double) ys/ (double)topmost_parent->height;
			y_size2 = (double) (ys+hs)/ (double)topmost_parent->height;

			while( pifDest && pifDest->pParent )
			{
				glDepth = 0;
				if( pifDest->transform )
				{
					Apply( pifDest->transform, v1[1-v], v1[v] );
					Apply( pifDest->transform, v2[1-v], v2[v] );
					Apply( pifDest->transform, v3[1-v], v3[v] );
					Apply( pifDest->transform, v4[1-v], v4[v] );
					v = 1-v;
				}
				pifDest = pifDest->pParent;
			}
			if( pifDest->transform )
			{
				Apply( pifDest->transform, v1[1-v], v1[v] );
				Apply( pifDest->transform, v2[1-v], v2[v] );
				Apply( pifDest->transform, v3[1-v], v3[v] );
				Apply( pifDest->transform, v4[1-v], v4[v] );
				v = 1-v;
			}
#if 0
			if( glDepth )
			{
				//lprintf( WIDE( "enqable depth..." ) );
				glEnable( GL_DEPTH_TEST );
			}
			else
			{
				//lprintf( WIDE( "disable depth..." ) );
				glDisable( GL_DEPTH_TEST );
			}
#endif
			glBindTexture(GL_TEXTURE_2D, pifSrc->glActiveSurface);				// Select Our Texture
			if( method == BLOT_COPY )
				glColor4ub( 255,255,255,255 );
			else if( method == BLOT_SHADED )
			{
				CDATA tmp = va_arg( colors, CDATA );
				glColor4ubv( (GLubyte*)&tmp );
			}
			else if( method == BLOT_MULTISHADE )
			{
#if !defined( __ANDROID__ )
				InitShader();
				if( glUseProgram && l.glActiveSurface->shader.multi_shader )
				{
					int err;
					CDATA r = va_arg( colors, CDATA );
					CDATA g = va_arg( colors, CDATA );
					CDATA b = va_arg( colors, CDATA );
		 			glEnable(GL_FRAGMENT_PROGRAM_ARB);
					glUseProgram( l.glActiveSurface->shader.multi_shader );
					err = glGetError();
					glProgramLocalParameter4fARB( GL_FRAGMENT_PROGRAM_ARB, 0, (float)GetRedValue( r )/255.0f, (float)GetGreenValue( r )/255.0f, (float)GetBlueValue( r )/255.0f, (float)GetAlphaValue( r )/255.0f );
					err = glGetError();
					glProgramLocalParameter4fARB( GL_FRAGMENT_PROGRAM_ARB, 1, (float)GetRedValue( g )/255.0f, (float)GetGreenValue( g )/255.0f, (float)GetBlueValue( g )/255.0f, (float)GetAlphaValue( g )/255.0f );
					err = glGetError();
					glProgramLocalParameter4fARB( GL_FRAGMENT_PROGRAM_ARB, 2, (float)GetRedValue( b )/255.0f, (float)GetGreenValue( b )/255.0f, (float)GetBlueValue( b )/255.0f, (float)GetAlphaValue( b )/255.0f );					
					err = glGetError();
				}
				else
#endif
				{
					Image output_image;
					CDATA r = va_arg( colors, CDATA );
					CDATA g = va_arg( colors, CDATA );
					CDATA b = va_arg( colors, CDATA );
					output_image = GetShadedImage( pifSrc, r, g, b );
					glBindTexture( GL_TEXTURE_2D, output_image->glActiveSurface );
					glColor4ub( 255,255,255,255 );
				}
			}
			else if( method == BLOT_INVERTED )
			{
#if !defined( __ANDROID__ )
				InitShader();
				if( l.glActiveSurface->shader.inverse_shader )
				{
					int err;
					//lprintf( WIDE( "HAVE SHADER %d" ), l.glActiveSurface->shader.inverse_shader );
					glEnable(GL_FRAGMENT_PROGRAM_ARB);
					glUseProgram( l.glActiveSurface->shader.inverse_shader );
					err = glGetError();
				}
				else
#endif
				{
					Image output_image;
					//lprintf( WIDE( "DID NOT HAVE SHADER" ) );
					output_image = GetInvertedImage( pifSrc );
					glBindTexture( GL_TEXTURE_2D, output_image->glActiveSurface );
					glColor4ub( 255,255,255,255 );
				}
			}

			glBegin(GL_TRIANGLE_STRIP);
			//glBegin(GL_QUADS);
			// Front Face
			//glColor4ub( 255,120,32,192 );
			scale( v1[v], v1[v], l.scale );
			scale( v2[v], v2[v], l.scale );
			scale( v3[v], v3[v], l.scale );
			scale( v4[v], v4[v], l.scale );
			glTexCoord2f(x_size, y_size); glVertex3fv(v1[v]);	// Bottom Left Of The Texture and Quad
			glTexCoord2f(x_size, y_size2); glVertex3fv(v2[v]);	// Bottom Right Of The Texture and Quad
			glTexCoord2f(x_size2, y_size); glVertex3fv(v4[v]);	// Top Left Of The Texture and Quad
			glTexCoord2f(x_size2, y_size2); glVertex3fv(v3[v]);	// Top Right Of The Texture and Quad
			// Back Face
			glEnd();
#if !defined( __ANDROID__ )
			if( method == BLOT_MULTISHADE )
			{
				if( l.glActiveSurface->shader.multi_shader )
				{
 					glDisable(GL_FRAGMENT_PROGRAM_ARB);
				}
			}
			else if( method == BLOT_INVERTED )
			{
				if( l.glActiveSurface->shader.inverse_shader )
				{
 					glDisable(GL_FRAGMENT_PROGRAM_ARB);
				}
			}
#endif
			glBindTexture(GL_TEXTURE_2D, 0);				// Select Our Texture
		}
	}

	else switch( method )
	{
	case BLOT_COPY:
		if( !nTransparent )
			cBlotScaledT0( po, pi, errx, erry, wd, hd, dwd, dhd, dws, dhs, oo, srcwidth );       
		else if( nTransparent == 1 )
			cBlotScaledT1( po, pi, errx, erry, wd, hd, dwd, dhd, dws, dhs, oo, srcwidth );       
		else if( nTransparent & ALPHA_TRANSPARENT )
			cBlotScaledTImgA( po, pi, errx, erry, wd, hd, dwd, dhd, dws, dhs, oo, srcwidth, nTransparent&0xFF );
		else if( nTransparent & ALPHA_TRANSPARENT_INVERT )
			cBlotScaledTImgAI( po, pi, errx, erry, wd, hd, dwd, dhd, dws, dhs, oo, srcwidth, nTransparent&0xFF );        
		else
			cBlotScaledTA( po, pi, errx, erry, wd, hd, dwd, dhd, dws, dhs, oo, srcwidth, nTransparent );        
		break;
	case BLOT_SHADED:
		if( !nTransparent )
			cBlotScaledShadedT0( po, pi, errx, erry, wd, hd, dwd, dhd, dws, dhs, oo, srcwidth, va_arg( colors, CDATA ) );
		else if( nTransparent == 1 )
			cBlotScaledShadedT1( po, pi, errx, erry, wd, hd, dwd, dhd, dws, dhs, oo, srcwidth, va_arg( colors, CDATA ) );
		else if( nTransparent & ALPHA_TRANSPARENT )
			cBlotScaledShadedTImgA( po, pi, errx, erry, wd, hd, dwd, dhd, dws, dhs, oo, srcwidth, nTransparent&0xFF, va_arg( colors, CDATA ) );
		else if( nTransparent & ALPHA_TRANSPARENT_INVERT )
			cBlotScaledShadedTImgAI( po, pi, errx, erry, wd, hd, dwd, dhd, dws, dhs, oo, srcwidth, nTransparent&0xFF, va_arg( colors, CDATA ) );
		else
			cBlotScaledShadedTA( po, pi, errx, erry, wd, hd, dwd, dhd, dws, dhs, oo, srcwidth, nTransparent, va_arg( colors, CDATA ) );
		break;
	case BLOT_MULTISHADE:
		{
			CDATA r,g,b;
			r = va_arg( colors, CDATA );
			g = va_arg( colors, CDATA );
			b = va_arg( colors, CDATA );
			if( !nTransparent )
				cBlotScaledMultiT0( po, pi, errx, erry, wd, hd, dwd, dhd, dws, dhs, oo, srcwidth
									  , r, g, b );
			else if( nTransparent == 1 )
				cBlotScaledMultiT1( po, pi, errx, erry, wd, hd, dwd, dhd, dws, dhs, oo, srcwidth
									  , r, g, b );
			else if( nTransparent & ALPHA_TRANSPARENT )
				cBlotScaledMultiTImgA( po, pi, errx, erry, wd, hd, dwd, dhd, dws, dhs, oo, srcwidth
										  , nTransparent & 0xFF
										  , r, g, b );
			else if( nTransparent & ALPHA_TRANSPARENT_INVERT )
				cBlotScaledMultiTImgAI( po, pi, errx, erry, wd, hd, dwd, dhd, dws, dhs, oo, srcwidth
											, nTransparent & 0xFF
											, r, g, b );
			else
				cBlotScaledMultiTA( po, pi, errx, erry, wd, hd, dwd, dhd, dws, dhs, oo, srcwidth
									  , nTransparent
									  , r, g, b );
		}
		break;
	}
	lock = 0;
//   Log( WIDE("Blot done") );
}
Exemple #7
0
//----------------------------------------------------------------------------------------
// Output handler for system call
void CPROC LogOutput( uintptr_t psv, PTASK_INFO task, CTEXTSTR buffer, size_t size )
{
	lprintf( WIDE("%s"), buffer );
}
Exemple #8
0
PUBLIC( TEXTCHAR *, RegisterRoutines )( void )
{                           
   myTypeID = RegisterDevice( WIDE("command"), WIDE("Performs command processing burst, history..."), Open );
   return DekVersion;
}
Exemple #9
0
PUBLIC( void, UnloadPlugin )( void ) // this routine is called when /unload is invoked
{
	UnregisterDevice( WIDE("command") );
}
Exemple #10
0
void CPROC NotSoFatalError2( png_structp png_ptr, png_const_charp c )
{
	lprintf( WIDE("Error in PNG stuff: %s"), c );
}
Exemple #11
0
void CPROC ReadComplete( PCLIENT pc, POINTER buffer, size_t size )
{
    static uint64_t LastMessage; // this is safe - only ONE connection EVER
    uint64_t test;
    int ToRead = 8;
    if( !buffer )
    {
        Log( WIDE("Initial Read issued allocated  buffer...read events a go.") );
        buffer = Allocate( 1024 );
    }
    else
    {
        ((TEXTCHAR*)buffer)[size] = 0;
        if( !LastMessage )
        {
            Log1( WIDE("Message is: %8.8s"), buffer );
            if( *(uint64_t*)buffer == *(uint64_t*)"USERLIST" )
            {
                Log1( WIDE("Message is: USERLIST!!"), buffer );
                ToRead = 2;
                LastMessage = *(uint64_t*)buffer;
                Log1( WIDE("Last Message is: %8.8s"), &LastMessage );
            }
            else if( *(uint64_t*)buffer == *(uint64_t*)"USERDEAD" )
            {
                BasicMessageBox( WIDE("Relay Responce"), WIDE("User has been terminated!") );
                RemoveClient( pc );
            }
            else if( *(uint64_t*)buffer == *(uint64_t*)"ALL DONE" )
            {
                RemoveClient( pc );
            }
            else if( *(uint64_t*)buffer == *(uint64_t*)"MESSAGE!" ||
                     *(uint64_t*)buffer == *(uint64_t*)"WINNERS:" )
            {
                ToRead = 1;
                LastMessage = *(uint64_t*)buffer;
            }
            else if( *(uint64_t*)buffer == *(uint64_t*)"MASTERIS" )
            {
                LastMessage = *(uint64_t*)buffer;
            }
            else
            {
                printf( WIDE("Unknown responce from relay: %8.8s"), buffer );
            }
        }
        else
        {
            Log1( WIDE("Continuing message: %8.8s"), &LastMessage );
            if( LastMessage == *(uint64_t*)"MESSAGE!" ||
                    LastMessage == *(uint64_t*)"WINNERS:" )
            {
                Log( WIDE("(1)") );
                ToRead = *(uint8_t*)buffer;
                LastMessage++;
            }
            else if( (test = ((*(uint64_t*)"WINNERS:")+1)), (LastMessage == test) )
            {
                PCONTROL pcList = GetControl( frame, LST_WINNERS );
                TEXTCHAR *winnerlist = (TEXTCHAR*)buffer;
                TEXTCHAR *endline, lastchar;
                ResetList( pcList );
                winnerlist[size] = 0;
                Log2( WIDE("Got %d bytes of data:%s"), size, winnerlist );
                endline = winnerlist;
                do
                {
                    while( endline[0] && ( endline[0] != ',' && endline[0] != ':' ) )
                    {
                        if( endline[0] == 3 )
                            endline[0] = ' '; // space fill this...
                        endline++;
                    }
                    lastchar = endline[0];
                    //if( endline[0] )
                    {
                        endline[0] = 0;
                        AddListItem( pcList, winnerlist );
                        if( lastchar )
                        {
                            winnerlist = endline+1;
                            while( winnerlist[0] && winnerlist[0] == ' ' ) winnerlist++;
                            endline = winnerlist;
                        }
                    }
                } while( endline[0] );
                LastMessage = 0;
            }
            else if( (test = ((*(uint64_t*)"MESSAGE!")+1)), (LastMessage == test) )
            {
                Log( WIDE("(2)") );
                BasicMessageBox( WIDE("Relay Message"), DupCharToText( (char*)buffer ) );
                LastMessage = 0;
            }
            else if( LastMessage == *(uint64_t*)"MASTERIS" )
            {
                if( *(uint64_t*)buffer == *(uint64_t*)"ABSENT.." )
                {
                    SetControlText( GetControl( frame, CHK_MASTER ), WIDE("Game Master is absent") );
                }
                else if( *(uint64_t*)buffer == *(uint64_t*)"PRESENT!" )
                {
                    SetControlText( GetControl( frame, CHK_MASTER ), WIDE("Game Master is PRESENT") );
                }
                else
                {
                    BasicMessageBox( WIDE("Master Status"), WIDE("Unknown Responce...") );
                }
                LastMessage = 0;
                RemoveClient( pc );
            }
            else if( LastMessage == (*(uint64_t*)"USERLIST") )
            {
                Log( WIDE("(3)") );
                ToRead = *(uint16_t*)buffer;
                Log1( WIDE("User list with size of %d"), ToRead );
                LastMessage++;
            }
            else if(  (test = ((*(uint64_t*)"USERLIST")+1) ), (LastMessage == test) )
            {
                PCONTROL pcList = GetControl( frame, LST_USERS );
                TEXTCHAR *userlist = (TEXTCHAR*)buffer;
                TEXTCHAR *endline;
                //Log1( WIDE("Got %d bytes of data..."), size );
                ResetList( pcList );
                userlist[size] = 0;
                endline = userlist;
                do
                {
                    while( endline[0] && endline[0] != '\n' )
                    {
                        if( endline[0] == 3 )
                            endline[0] = ' '; // space fill this...
                        endline++;
                    }
                    if( endline[0] )
                    {
                        TEXTCHAR *endname;
                        TEXTCHAR *realname;
                        PLISTITEM hli;
                        endline[0] = 0;
                        hli = AddListItem( pcList, userlist );
                        endname = userlist;
                        while( endname[0] != ' ' )
                            endname++;
                        endname[0] = 0;
                        realname = NewArray( TEXTCHAR, ( endname - userlist ) + 1 );
                        StrCpyEx( realname, userlist, max( ( endname - userlist ), size ) );
                        SetItemData( hli, (uintptr_t)realname );
                        endline++;
                        userlist = endline;
                    }
                } while( endline[0] );
                LastMessage = 0;
                RemoveClient( pc );
            }
            else
            {
                Log1( WIDE("Unknonw Continuation state for %8.8s"), &LastMessage );
            }
        }
    }
    ReadTCPMsg( pc, buffer, ToRead );
}
Exemple #12
0
void main(int argc, char **argv)
{
	if(argc < 1)
		return;
	
	// get path
	int dat, l = 0, h = 0, w = 0, n = 0;
	bool prev = false;
	FILE *fs, *fd;

	char root[_MAX_PATH], file[_MAX_PATH];
	char tmp1[_MAX_PATH], tmp2[_MAX_PATH], dest[_MAX_PATH];
	GetModuleFileName(NULL, root, _MAX_PATH);
	int p = strlen(root);
	while(root[p] != '\\')
		p--;
	root[p] = '\0';

	strcpy(tmp1, argv[1]);
	p = strlen(tmp1);
	while(p != 0 && tmp1[p] != '\\')
		p--;
	if(p)
		strcpy(file, &tmp1[p + 1]);
	else
		strcpy(file, argv[1]);

	sprintf(tmp1, "%s\\tmp1.txt", root);
	sprintf(tmp2, "%s\\tmp2.txt", root);
	sprintf(dest, "%s\\dest.cas", root);
	
	if(strcmp(file, "tmp1.txt") == 0) {
		printf("skip wav->pulse\n");
		goto label1;
	}
	if(strcmp(file, "tmp2.txt") == 0) {
		printf("skip wav->pulse\n");
		printf("skip pulse->bit\n");
		goto label2;
	}
	
	// convert #1 (wav -> pulse)
	fs = fopen(argv[1], "rb");
	fd = fopen(tmp1, "w");
	
	while((dat = fgetc(fs)) != EOF) {
		bool current = dat & 0x80 ? false : true;
		if(prev && !current) {
			if(NARROW(l) && (NARROW(h) || WIDE(h)))
				fputc('N', fd);
			else if(WIDE(l) && (WIDE(h) || NARROW(h)))
				fputc('w', fd);
			else
				fprintf(fd, "[%d,%d]", l, h);
			l = h = 0;
		}
		if(current)
			h++;
		else
			l++;
		prev = current;
	}
	fclose(fd);
	fclose(fs);
	
label1:
	
	// convert #2 (pulse -> bit)
	fs = fopen(tmp1, "rb");
	fd = fopen(tmp2, "w");
	prev = true;
	
	while((dat = fgetc(fs)) != EOF) {
		if(dat != 'w' && dat != 'N') {
			fputc(dat, fd);
			continue;
		}
		bool current = (dat == 'w') ? true : false;
		if(prev != current) {
			if(w)
				fprintf(fd, "[W%d]", w);
			if(n)
				fprintf(fd, "[n%d]", n);
			w = n = 0;
		}
		prev = current;
		
		if(current)
			w++;
		else
			n++;
		if(w == 2) {
			fputc('w', fd);
			w = n = 0;
		}
		if(n == 4) {
			fputc('N', fd);
			w = n = 0;
		}
	}
	fclose(fd);
	fclose(fs);
	
label2:
	
	// convert #3 (bit -> byte)
	fs = fopen(tmp2, "rb");
	fd = fopen(dest, "wb");
	
	while((dat = fgetc2(fs)) != EOF) {
		if(dat != 'N')
			continue;
		if(fgetc2(fs) != 'N')
			continue;
label3:
		dat = fgetc2(fs);
		if(dat == EOF)
			break;
		if(dat != 'w')
			goto label3;
		int d = 0;
		d |= (fgetc2(fs) == 'N') ? 0x01 : 0;
		d |= (fgetc2(fs) == 'N') ? 0x02 : 0;
		d |= (fgetc2(fs) == 'N') ? 0x04 : 0;
		d |= (fgetc2(fs) == 'N') ? 0x08 : 0;
		d |= (fgetc2(fs) == 'N') ? 0x10 : 0;
		d |= (fgetc2(fs) == 'N') ? 0x20 : 0;
		d |= (fgetc2(fs) == 'N') ? 0x40 : 0;
		d |= (fgetc2(fs) == 'N') ? 0x80 : 0;
		fputc(d, fd);
	}
	fclose(fd);
	fclose(fs);
}
Exemple #13
0
#include "global.h"

enum {
   BTN_PASSKEY = 10000
	  , PERMISSIONS = BTN_PASSKEY + 50
	  , REQUIRED_PERMISSIONS
	  , PASSCODE
	  , CHECKBOX_REQUIRE_PARENT_LOGIN
	  , CHECKBOX_OVERRIDE_PARENT_REQUIRED
     , TEXT_EDIT_REQUIRED_PERMISSION
     , TEXT_EDIT_OVERRIDE_REQUIRED_PERMISSION
};

PRIORITY_PRELOAD( RegisterUserPasswordControls, DEFAULT_PRELOAD_PRIORITY - 2 )
{
	CTEXTSTR permission_tokens = WIDE("CREATE TABLE `permission_tokens` (")
	WIDE("`permission_id` int(11) NOT NULL AUTO_INCREMENT,")
	WIDE("`name` varchar(100) NOT NULL DEFAULT '',")
	WIDE("`log` int(11) NOT NULL DEFAULT '0',")
	WIDE("`description` varchar(255) DEFAULT '',")
	WIDE("PRIMARY KEY (`permission_id`),")
	WIDE("KEY `token` (`name`)")
	WIDE(") ENGINE=MyISAM AUTO_INCREMENT=827 DEFAULT CHARSET=latin1 COMMENT='Name detail of permission_id'");

	CTEXTSTR permission_set = WIDE("CREATE TABLE `permission_set` (")
	WIDE("`permission_group_id` int(11) NOT NULL DEFAULT '0',")
	WIDE("`permission_id` int(11) NOT NULL DEFAULT '0',")
	WIDE("PRIMARY KEY (`permission_group_id`,`permission_id`),")
	WIDE("KEY `group` (`permission_group_id`),")
	WIDE("KEY `token` (`permission_id`)")
	WIDE(") ENGINE=MyISAM DEFAULT CHARSET=latin1 COMMENT='relate permission_group_id to permission_id'");
Exemple #14
0
NTSTATUS TCOpenVolume (PDEVICE_OBJECT DeviceObject,
	       PEXTENSION Extension,
	       MOUNT_STRUCT *mount,
	       PWSTR pwszMountVolume,
	       BOOL bRawDevice)
{
	FILE_STANDARD_INFORMATION FileStandardInfo;
	FILE_BASIC_INFORMATION FileBasicInfo;
	OBJECT_ATTRIBUTES oaFileAttributes;
	UNICODE_STRING FullFileName;
	IO_STATUS_BLOCK IoStatusBlock;
	PCRYPTO_INFO cryptoInfoPtr = NULL;
	PCRYPTO_INFO tmpCryptoInfo = NULL;
	LARGE_INTEGER lDiskLength;
	__int64 partitionStartingOffset = 0;
	int volumeType;
	char *readBuffer = 0;
	NTSTATUS ntStatus = 0;
	BOOL forceAccessCheck = (!bRawDevice && !(OsMajorVersion == 5 &&OsMinorVersion == 0)); // Windows 2000 does not support OBJ_FORCE_ACCESS_CHECK attribute
	BOOL disableBuffering = TRUE;
	BOOL exclusiveAccess = mount->bExclusiveAccess;

	Extension->pfoDeviceFile = NULL;
	Extension->hDeviceFile = NULL;
	Extension->bTimeStampValid = FALSE;

	RtlInitUnicodeString (&FullFileName, pwszMountVolume);
	InitializeObjectAttributes (&oaFileAttributes, &FullFileName, OBJ_CASE_INSENSITIVE | (forceAccessCheck ? OBJ_FORCE_ACCESS_CHECK : 0) | OBJ_KERNEL_HANDLE, NULL, NULL);
	KeInitializeEvent (&Extension->keVolumeEvent, NotificationEvent, FALSE);

	if (Extension->SecurityClientContextValid)
	{
		ntStatus = SeImpersonateClientEx (&Extension->SecurityClientContext, NULL);
		if (!NT_SUCCESS (ntStatus))
			goto error;
	}

	mount->VolumeMountedReadOnlyAfterDeviceWriteProtected = FALSE;

	// If we are opening a device, query its size first
	if (bRawDevice)
	{
		PARTITION_INFORMATION pi;
		PARTITION_INFORMATION_EX pix;
		LARGE_INTEGER diskLengthInfo;
		DISK_GEOMETRY dg;
		STORAGE_PROPERTY_QUERY storagePropertyQuery = {0};
		STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR storageDescriptor = {0};

		ntStatus = IoGetDeviceObjectPointer (&FullFileName,
			FILE_READ_DATA | FILE_READ_ATTRIBUTES,
			&Extension->pfoDeviceFile,
			&Extension->pFsdDevice);

		if (!NT_SUCCESS (ntStatus))
			goto error;

		ntStatus = TCSendHostDeviceIoControlRequest (DeviceObject, Extension, IOCTL_DISK_GET_DRIVE_GEOMETRY, (char *) &dg, sizeof (dg));
		if (!NT_SUCCESS (ntStatus))
			goto error;

		lDiskLength.QuadPart = dg.Cylinders.QuadPart * dg.SectorsPerTrack * dg.TracksPerCylinder * dg.BytesPerSector;
		Extension->HostBytesPerSector = dg.BytesPerSector;

		storagePropertyQuery.PropertyId = StorageAccessAlignmentProperty;
		storagePropertyQuery.QueryType = PropertyStandardQuery;

		/* IOCTL_STORAGE_QUERY_PROPERTY supported only on Vista and above */
		if (NT_SUCCESS (TCSendHostDeviceIoControlRequestEx (DeviceObject, Extension, IOCTL_STORAGE_QUERY_PROPERTY,
			(char*) &storagePropertyQuery, sizeof(storagePropertyQuery),
			(char *) &storageDescriptor, sizeof (storageDescriptor))))
		{
			Extension->HostBytesPerPhysicalSector = storageDescriptor.BytesPerPhysicalSector;
		}
		else
		{
			Extension->HostBytesPerPhysicalSector = dg.BytesPerSector;
		}

		// Drive geometry is used only when IOCTL_DISK_GET_PARTITION_INFO fails
		if (NT_SUCCESS (TCSendHostDeviceIoControlRequest (DeviceObject, Extension, IOCTL_DISK_GET_PARTITION_INFO_EX, (char *) &pix, sizeof (pix))))
		{
			lDiskLength.QuadPart = pix.PartitionLength.QuadPart;
			partitionStartingOffset = pix.StartingOffset.QuadPart;
		}
		// Windows 2000 does not support IOCTL_DISK_GET_PARTITION_INFO_EX
		else if (NT_SUCCESS (TCSendHostDeviceIoControlRequest (DeviceObject, Extension, IOCTL_DISK_GET_PARTITION_INFO, (char *) &pi, sizeof (pi))))
		{
			lDiskLength.QuadPart = pi.PartitionLength.QuadPart;
			partitionStartingOffset = pi.StartingOffset.QuadPart;
		}
		else if (NT_SUCCESS (TCSendHostDeviceIoControlRequest (DeviceObject, Extension, IOCTL_DISK_GET_LENGTH_INFO, &diskLengthInfo, sizeof (diskLengthInfo))))
		{
			lDiskLength = diskLengthInfo;
		}

		ProbingHostDeviceForWrite = TRUE;

		if (!mount->bMountReadOnly
			&& TCSendHostDeviceIoControlRequest (DeviceObject, Extension,
				IsHiddenSystemRunning() ? TC_IOCTL_DISK_IS_WRITABLE : IOCTL_DISK_IS_WRITABLE, NULL, 0) == STATUS_MEDIA_WRITE_PROTECTED)
		{
			mount->bMountReadOnly = TRUE;
			DeviceObject->Characteristics |= FILE_READ_ONLY_DEVICE;
			mount->VolumeMountedReadOnlyAfterDeviceWriteProtected = TRUE;
		}

		ProbingHostDeviceForWrite = FALSE;

		// Some Windows tools (e.g. diskmgmt, diskpart, vssadmin) fail or experience timeouts when there is a raw device
		// open for exclusive access. Therefore, exclusive access is used only for file-hosted volumes.
		// Applications requiring a consistent device image need to acquire exclusive write access first. This is prevented
		// when a device-hosted volume is mounted.

		exclusiveAccess = FALSE;
	}
	else
	{
		// Limit the maximum required buffer size
		if (mount->BytesPerSector > 128 * BYTES_PER_KB)
		{
			ntStatus = STATUS_INVALID_PARAMETER;
			goto error;
		}

		Extension->HostBytesPerSector = mount->BytesPerSector;
		Extension->HostBytesPerPhysicalSector = mount->BytesPerPhysicalSector;

		if (Extension->HostBytesPerSector != TC_SECTOR_SIZE_FILE_HOSTED_VOLUME)
			disableBuffering = FALSE;
	}

	// Open the volume hosting file/device
	if (!mount->bMountReadOnly)
	{
		ntStatus = ZwCreateFile (&Extension->hDeviceFile,
			GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE,
			&oaFileAttributes,
			&IoStatusBlock,
			NULL,
			FILE_ATTRIBUTE_NORMAL |
			FILE_ATTRIBUTE_SYSTEM,
			exclusiveAccess ? 0 : FILE_SHARE_READ | FILE_SHARE_WRITE,
			FILE_OPEN,
			FILE_RANDOM_ACCESS |
			FILE_WRITE_THROUGH |
			(disableBuffering ? FILE_NO_INTERMEDIATE_BUFFERING : 0) |
			FILE_SYNCHRONOUS_IO_NONALERT,
			NULL,
			0);
	}

	/* 26-4-99 NT for some partitions returns this code, it is really a	access denied */
	if (ntStatus == 0xc000001b)
		ntStatus = STATUS_ACCESS_DENIED;

	mount->VolumeMountedReadOnlyAfterAccessDenied = FALSE;

	if (mount->bMountReadOnly || ntStatus == STATUS_ACCESS_DENIED)
	{
		ntStatus = ZwCreateFile (&Extension->hDeviceFile,
			GENERIC_READ | SYNCHRONIZE,
			&oaFileAttributes,
			&IoStatusBlock,
			NULL,
			FILE_ATTRIBUTE_NORMAL |
			FILE_ATTRIBUTE_SYSTEM,
			exclusiveAccess ? FILE_SHARE_READ : FILE_SHARE_READ | FILE_SHARE_WRITE,
			FILE_OPEN,
			FILE_RANDOM_ACCESS |
			FILE_WRITE_THROUGH |
			(disableBuffering ? FILE_NO_INTERMEDIATE_BUFFERING : 0) |
			FILE_SYNCHRONOUS_IO_NONALERT,
			NULL,
			0);

		if (NT_SUCCESS (ntStatus) && !mount->bMountReadOnly)
			mount->VolumeMountedReadOnlyAfterAccessDenied = TRUE;

		Extension->bReadOnly = TRUE;
		DeviceObject->Characteristics |= FILE_READ_ONLY_DEVICE;
	}
	else
		Extension->bReadOnly = FALSE;

	/* 26-4-99 NT for some partitions returns this code, it is really a
	access denied */
	if (ntStatus == 0xc000001b)
	{
		/* Partitions which return this code can still be opened with
		FILE_SHARE_READ but this causes NT problems elsewhere in
		particular if you do FILE_SHARE_READ NT will die later if
		anyone even tries to open the partition (or file for that
		matter...)  */
		ntStatus = STATUS_SHARING_VIOLATION;
	}

	if (!NT_SUCCESS (ntStatus))
	{
		goto error;
	}

	// If we have opened a file, query its size now
	if (bRawDevice == FALSE)
	{
		ntStatus = ZwQueryInformationFile (Extension->hDeviceFile,
			&IoStatusBlock,
			&FileBasicInfo,
			sizeof (FileBasicInfo),
			FileBasicInformation);

		if (NT_SUCCESS (ntStatus))
		{
			if (mount->bPreserveTimestamp)
			{
				Extension->fileCreationTime = FileBasicInfo.CreationTime;
				Extension->fileLastAccessTime = FileBasicInfo.LastAccessTime;
				Extension->fileLastWriteTime = FileBasicInfo.LastWriteTime;
				Extension->fileLastChangeTime = FileBasicInfo.ChangeTime;
				Extension->bTimeStampValid = TRUE;
			}

			ntStatus = ZwQueryInformationFile (Extension->hDeviceFile,
				&IoStatusBlock,
				&FileStandardInfo,
				sizeof (FileStandardInfo),
				FileStandardInformation);
		}

		if (!NT_SUCCESS (ntStatus))
		{
			Dump ("ZwQueryInformationFile failed while opening file: NTSTATUS 0x%08x\n",
				ntStatus);
			goto error;
		}

		lDiskLength.QuadPart = FileStandardInfo.EndOfFile.QuadPart;

		if (FileBasicInfo.FileAttributes & FILE_ATTRIBUTE_COMPRESSED)
		{
			Dump ("File \"%ls\" is marked as compressed - not supported!\n", pwszMountVolume);
			mount->nReturnCode = ERR_COMPRESSION_NOT_SUPPORTED;
			ntStatus = STATUS_SUCCESS;
			goto error;
		}

		ntStatus = ObReferenceObjectByHandle (Extension->hDeviceFile,
			FILE_ALL_ACCESS,
			*IoFileObjectType,
			KernelMode,
			&Extension->pfoDeviceFile,
			0);

		if (!NT_SUCCESS (ntStatus))
		{
			goto error;
		}

		/* Get the FSD device for the file (probably either NTFS or	FAT) */
		Extension->pFsdDevice = IoGetRelatedDeviceObject (Extension->pfoDeviceFile);
	}
	else
	{
		// Try to gain "raw" access to the partition in case there is a live filesystem on it (otherwise,
		// the NTFS driver guards hidden sectors and prevents mounting using a backup header e.g. after the user
		// accidentally quick-formats a dismounted partition-hosted TrueCrypt volume as NTFS).

		PFILE_OBJECT pfoTmpDeviceFile = NULL;

		if (NT_SUCCESS (ObReferenceObjectByHandle (Extension->hDeviceFile, FILE_ALL_ACCESS, *IoFileObjectType, KernelMode, &pfoTmpDeviceFile, NULL))
			&& pfoTmpDeviceFile != NULL)
		{
			TCFsctlCall (pfoTmpDeviceFile, FSCTL_ALLOW_EXTENDED_DASD_IO, NULL, 0, NULL, 0);
			ObDereferenceObject (pfoTmpDeviceFile);
		}
	}

	// Check volume size
	if (lDiskLength.QuadPart < TC_MIN_VOLUME_SIZE_LEGACY || lDiskLength.QuadPart > TC_MAX_VOLUME_SIZE)
	{
		mount->nReturnCode = ERR_VOL_SIZE_WRONG;
		ntStatus = STATUS_SUCCESS;
		goto error;
	}

	Extension->DiskLength = lDiskLength.QuadPart;
	Extension->HostLength = lDiskLength.QuadPart;

	readBuffer = TCalloc (max (max (TC_VOLUME_HEADER_EFFECTIVE_SIZE, PAGE_SIZE), Extension->HostBytesPerSector));
	if (readBuffer == NULL)
	{
		ntStatus = STATUS_INSUFFICIENT_RESOURCES;
		goto error;
	}

	// Go through all volume types (e.g., normal, hidden)
	for (volumeType = TC_VOLUME_TYPE_NORMAL;
		volumeType < TC_VOLUME_TYPE_COUNT;
		volumeType++)
	{
		Dump ("Trying to open volume type %d\n", volumeType);

		/* Read the volume header */

		if (!mount->bPartitionInInactiveSysEncScope
			|| (mount->bPartitionInInactiveSysEncScope && volumeType == TC_VOLUME_TYPE_HIDDEN))
		{
			// Header of a volume that is not within the scope of system encryption, or
			// header of a system hidden volume (containing a hidden OS)

			LARGE_INTEGER headerOffset;

			if (mount->UseBackupHeader && lDiskLength.QuadPart <= TC_TOTAL_VOLUME_HEADERS_SIZE)
				continue;

			switch (volumeType)
			{
			case TC_VOLUME_TYPE_NORMAL:
				headerOffset.QuadPart = mount->UseBackupHeader ? lDiskLength.QuadPart - TC_VOLUME_HEADER_GROUP_SIZE : TC_VOLUME_HEADER_OFFSET;
				break;

			case TC_VOLUME_TYPE_HIDDEN:
				if (lDiskLength.QuadPart <= TC_VOLUME_HEADER_GROUP_SIZE)
					continue;

				headerOffset.QuadPart = mount->UseBackupHeader ? lDiskLength.QuadPart - TC_HIDDEN_VOLUME_HEADER_OFFSET : TC_HIDDEN_VOLUME_HEADER_OFFSET;
				break;
			}

			Dump ("Reading volume header at %I64d\n", headerOffset.QuadPart);

			ntStatus = ZwReadFile (Extension->hDeviceFile,
			NULL,
			NULL,
			NULL,
			&IoStatusBlock,
			readBuffer,
			bRawDevice ? max (TC_VOLUME_HEADER_EFFECTIVE_SIZE, Extension->HostBytesPerSector) : TC_VOLUME_HEADER_EFFECTIVE_SIZE,
			&headerOffset,
			NULL);
		}
		else
		{
			// Header of a partition that is within the scope of system encryption

			WCHAR parentDrivePath [47+1] = {0};
			HANDLE hParentDeviceFile = NULL;
			UNICODE_STRING FullParentPath;
			OBJECT_ATTRIBUTES oaParentFileAttributes;
			LARGE_INTEGER parentKeyDataOffset;

			RtlStringCbPrintfW (parentDrivePath,
				sizeof (parentDrivePath),
				WIDE ("\\Device\\Harddisk%d\\Partition0"),
				mount->nPartitionInInactiveSysEncScopeDriveNo);

			Dump ("Mounting partition within scope of system encryption (reading key data from: %ls)\n", parentDrivePath);

			RtlInitUnicodeString (&FullParentPath, parentDrivePath);
			InitializeObjectAttributes (&oaParentFileAttributes, &FullParentPath, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,	NULL, NULL);

			ntStatus = ZwCreateFile (&hParentDeviceFile,
				GENERIC_READ | SYNCHRONIZE,
				&oaParentFileAttributes,
				&IoStatusBlock,
				NULL,
				FILE_ATTRIBUTE_NORMAL |
				FILE_ATTRIBUTE_SYSTEM,
				FILE_SHARE_READ | FILE_SHARE_WRITE,
				FILE_OPEN,
				FILE_RANDOM_ACCESS |
				FILE_WRITE_THROUGH |
				FILE_NO_INTERMEDIATE_BUFFERING |
				FILE_SYNCHRONOUS_IO_NONALERT,
				NULL,
				0);

			if (!NT_SUCCESS (ntStatus))
			{
				if (hParentDeviceFile != NULL)
					ZwClose (hParentDeviceFile);

				Dump ("Cannot open %ls\n", parentDrivePath);

				goto error;
			}

			parentKeyDataOffset.QuadPart = TC_BOOT_VOLUME_HEADER_SECTOR_OFFSET;

			ntStatus = ZwReadFile (hParentDeviceFile,
				NULL,
				NULL,
				NULL,
				&IoStatusBlock,
				readBuffer,
				max (TC_VOLUME_HEADER_EFFECTIVE_SIZE, Extension->HostBytesPerSector),
				&parentKeyDataOffset,
				NULL);

			if (hParentDeviceFile != NULL)
				ZwClose (hParentDeviceFile);
		}

		if (!NT_SUCCESS (ntStatus) && ntStatus != STATUS_END_OF_FILE)
		{
			Dump ("Read failed: NTSTATUS 0x%08x\n", ntStatus);
			goto error;
		}

		if (ntStatus == STATUS_END_OF_FILE || IoStatusBlock.Information < TC_VOLUME_HEADER_EFFECTIVE_SIZE)
		{
			Dump ("Read didn't read enough data\n");

			// If FSCTL_ALLOW_EXTENDED_DASD_IO failed and there is a live filesystem on the partition, then the
			// filesystem driver may report EOF when we are reading hidden sectors (when the filesystem is
			// shorter than the partition). This can happen for example after the user quick-formats a dismounted
			// partition-hosted TrueCrypt volume and then tries to mount the volume using the embedded backup header.
			memset (readBuffer, 0, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
		}

		/* Attempt to recognize the volume (decrypt the header) */

		ReadVolumeHeaderRecoveryMode = mount->RecoveryMode;

		if ((volumeType == TC_VOLUME_TYPE_HIDDEN) && mount->bProtectHiddenVolume)
		{
			mount->nReturnCode = ReadVolumeHeaderWCache (
				FALSE,
				mount->bCache,
				mount->bCachePim,
				readBuffer,
				&mount->ProtectedHidVolPassword,
				mount->ProtectedHidVolPkcs5Prf,
				mount->ProtectedHidVolPim,
				mount->bTrueCryptMode,
				&tmpCryptoInfo);
		}
		else
		{
			mount->nReturnCode = ReadVolumeHeaderWCache (
				mount->bPartitionInInactiveSysEncScope && volumeType == TC_VOLUME_TYPE_NORMAL,
				mount->bCache,
				mount->bCachePim,
				readBuffer,
				&mount->VolumePassword,
				mount->pkcs5_prf,
				mount->VolumePim,
				mount->bTrueCryptMode,
				&Extension->cryptoInfo);
		}

		ReadVolumeHeaderRecoveryMode = FALSE;

		if (mount->nReturnCode == 0 || mount->nReturnCode == ERR_CIPHER_INIT_WEAK_KEY)
		{
			/* Volume header successfully decrypted */

			if (!Extension->cryptoInfo)
			{
				/* should never happen */
				mount->nReturnCode = ERR_OUTOFMEMORY;
				ntStatus = STATUS_SUCCESS;
				goto error;
			}

			Dump ("Volume header decrypted\n");
			Dump ("Required program version = %x\n", (int) Extension->cryptoInfo->RequiredProgramVersion);
			Dump ("Legacy volume = %d\n", (int) Extension->cryptoInfo->LegacyVolume);

			if (IsHiddenSystemRunning() && !Extension->cryptoInfo->hiddenVolume)
			{
				Extension->bReadOnly = mount->bMountReadOnly = TRUE;
				HiddenSysLeakProtectionCount++;
			}

			Extension->cryptoInfo->bProtectHiddenVolume = FALSE;
			Extension->cryptoInfo->bHiddenVolProtectionAction = FALSE;

			Extension->cryptoInfo->bPartitionInInactiveSysEncScope = mount->bPartitionInInactiveSysEncScope;

			/* compute the ID of this volume: SHA-512 of the effective header */
			sha256 (Extension->volumeID, readBuffer, TC_VOLUME_HEADER_EFFECTIVE_SIZE);

			if (volumeType == TC_VOLUME_TYPE_NORMAL)
			{
				if (mount->bPartitionInInactiveSysEncScope)
				{
					if (Extension->cryptoInfo->EncryptedAreaStart.Value > (unsigned __int64) partitionStartingOffset
						|| Extension->cryptoInfo->EncryptedAreaStart.Value + Extension->cryptoInfo->VolumeSize.Value <= (unsigned __int64) partitionStartingOffset)
					{
						// The partition is not within the key scope of system encryption
						mount->nReturnCode = ERR_PASSWORD_WRONG;
						ntStatus = STATUS_SUCCESS;
						goto error;
					}

					if (Extension->cryptoInfo->EncryptedAreaLength.Value != Extension->cryptoInfo->VolumeSize.Value)
					{
						// Partial encryption is not supported for volumes mounted as regular
						mount->nReturnCode = ERR_ENCRYPTION_NOT_COMPLETED;
						ntStatus = STATUS_SUCCESS;
						goto error;
					}
				}
				else if (Extension->cryptoInfo->HeaderFlags & TC_HEADER_FLAG_NONSYS_INPLACE_ENC)
				{
					if (Extension->cryptoInfo->EncryptedAreaLength.Value != Extension->cryptoInfo->VolumeSize.Value)
					{
						// Non-system in-place encryption process has not been completed on this volume
						mount->nReturnCode = ERR_NONSYS_INPLACE_ENC_INCOMPLETE;
						ntStatus = STATUS_SUCCESS;
						goto error;
					}
				}
			}

			Extension->cryptoInfo->FirstDataUnitNo.Value = 0;

			if (Extension->cryptoInfo->hiddenVolume && IsHiddenSystemRunning())
			{
				// Prevent mount of a hidden system partition if the system hosted on it is currently running
				if (memcmp (Extension->cryptoInfo->master_keydata, GetSystemDriveCryptoInfo()->master_keydata, EAGetKeySize (Extension->cryptoInfo->ea)) == 0)
				{
					mount->nReturnCode = ERR_VOL_ALREADY_MOUNTED;
					ntStatus = STATUS_SUCCESS;
					goto error;
				}
			}

			switch (volumeType)
			{
			case TC_VOLUME_TYPE_NORMAL:

				Extension->cryptoInfo->hiddenVolume = FALSE;

				if (mount->bPartitionInInactiveSysEncScope)
				{
					Extension->cryptoInfo->volDataAreaOffset = 0;
					Extension->DiskLength = lDiskLength.QuadPart;
					Extension->cryptoInfo->FirstDataUnitNo.Value = partitionStartingOffset / ENCRYPTION_DATA_UNIT_SIZE;
				}
				else if (Extension->cryptoInfo->LegacyVolume)
				{
					Extension->cryptoInfo->volDataAreaOffset = TC_VOLUME_HEADER_SIZE_LEGACY;
					Extension->DiskLength = lDiskLength.QuadPart - TC_VOLUME_HEADER_SIZE_LEGACY;
				}
				else
				{
					Extension->cryptoInfo->volDataAreaOffset = Extension->cryptoInfo->EncryptedAreaStart.Value;
					Extension->DiskLength = Extension->cryptoInfo->VolumeSize.Value;
				}

				break;

			case TC_VOLUME_TYPE_HIDDEN:

				cryptoInfoPtr = mount->bProtectHiddenVolume ? tmpCryptoInfo : Extension->cryptoInfo;

				Extension->cryptoInfo->hiddenVolumeOffset = cryptoInfoPtr->EncryptedAreaStart.Value;

				Dump ("Hidden volume offset = %I64d\n", Extension->cryptoInfo->hiddenVolumeOffset);
				Dump ("Hidden volume size = %I64d\n", cryptoInfoPtr->hiddenVolumeSize);
				Dump ("Hidden volume end = %I64d\n", Extension->cryptoInfo->hiddenVolumeOffset + cryptoInfoPtr->hiddenVolumeSize - 1);

				// Validate the offset
				if (Extension->cryptoInfo->hiddenVolumeOffset % ENCRYPTION_DATA_UNIT_SIZE != 0)
				{
					mount->nReturnCode = ERR_VOL_SIZE_WRONG;
					ntStatus = STATUS_SUCCESS;
					goto error;
				}

				// If we are supposed to actually mount the hidden volume (not just to protect it)
				if (!mount->bProtectHiddenVolume)
				{
					Extension->DiskLength = cryptoInfoPtr->hiddenVolumeSize;
					Extension->cryptoInfo->hiddenVolume = TRUE;
					Extension->cryptoInfo->volDataAreaOffset = Extension->cryptoInfo->hiddenVolumeOffset;
				}
				else
				{
					// Hidden volume protection
					Extension->cryptoInfo->hiddenVolume = FALSE;
					Extension->cryptoInfo->bProtectHiddenVolume = TRUE;

					Extension->cryptoInfo->hiddenVolumeProtectedSize = tmpCryptoInfo->hiddenVolumeSize;

					Dump ("Hidden volume protection active: %I64d-%I64d (%I64d)\n", Extension->cryptoInfo->hiddenVolumeOffset, Extension->cryptoInfo->hiddenVolumeProtectedSize + Extension->cryptoInfo->hiddenVolumeOffset - 1, Extension->cryptoInfo->hiddenVolumeProtectedSize);
				}

				break;
			}

			Dump ("Volume data offset = %I64d\n", Extension->cryptoInfo->volDataAreaOffset);
			Dump ("Volume data size = %I64d\n", Extension->DiskLength);
			Dump ("Volume data end = %I64d\n", Extension->cryptoInfo->volDataAreaOffset + Extension->DiskLength - 1);

			if (Extension->DiskLength == 0)
			{
				Dump ("Incorrect volume size\n");
				continue;
			}

			// If this is a hidden volume, make sure we are supposed to actually
			// mount it (i.e. not just to protect it)
			if (volumeType == TC_VOLUME_TYPE_NORMAL || !mount->bProtectHiddenVolume)
			{
				// Validate sector size
				if (bRawDevice && Extension->cryptoInfo->SectorSize != Extension->HostBytesPerSector)
				{
					mount->nReturnCode = ERR_PARAMETER_INCORRECT;
					ntStatus = STATUS_SUCCESS;
					goto error;
				}

				// Calculate virtual volume geometry
				Extension->TracksPerCylinder = 1;
				Extension->SectorsPerTrack = 1;
				Extension->BytesPerSector = Extension->cryptoInfo->SectorSize;
				Extension->NumberOfCylinders = Extension->DiskLength / Extension->BytesPerSector;
				Extension->PartitionType = 0;

				Extension->bRawDevice = bRawDevice;

				memset (Extension->wszVolume, 0, sizeof (Extension->wszVolume));
				if (wcsstr (pwszMountVolume, WIDE ("\\??\\UNC\\")) == pwszMountVolume)
				{
					/* UNC path */
					RtlStringCbPrintfW (Extension->wszVolume,
						sizeof (Extension->wszVolume),
						WIDE ("\\??\\\\%s"),
						pwszMountVolume + 7);
				}
				else
				{
					RtlStringCbCopyW (Extension->wszVolume, sizeof(Extension->wszVolume),pwszMountVolume);
				}

				memset (Extension->wszLabel, 0, sizeof (Extension->wszLabel));
				RtlStringCbCopyW (Extension->wszLabel, sizeof(Extension->wszLabel), mount->wszLabel);
			}

			// If we are to protect a hidden volume we cannot exit yet, for we must also
			// decrypt the hidden volume header.
			if (!(volumeType == TC_VOLUME_TYPE_NORMAL && mount->bProtectHiddenVolume))
			{
				TCfree (readBuffer);

				if (tmpCryptoInfo != NULL)
				{
					crypto_close (tmpCryptoInfo);
					tmpCryptoInfo = NULL;
				}

				return STATUS_SUCCESS;
			}
		}
		else if ((mount->bProtectHiddenVolume && volumeType == TC_VOLUME_TYPE_NORMAL)
			  || mount->nReturnCode != ERR_PASSWORD_WRONG)
		{
			 /* If we are not supposed to protect a hidden volume, the only error that is
				tolerated is ERR_PASSWORD_WRONG (to allow mounting a possible hidden volume).

				If we _are_ supposed to protect a hidden volume, we do not tolerate any error
				(both volume headers must be successfully decrypted). */

			break;
		}
	}

	/* Failed due to some non-OS reason so we drop through and return NT
	   SUCCESS then nReturnCode is checked later in user-mode */

	if (mount->nReturnCode == ERR_OUTOFMEMORY)
		ntStatus = STATUS_INSUFFICIENT_RESOURCES;
	else
		ntStatus = STATUS_SUCCESS;

error:
	if (mount->nReturnCode == ERR_SUCCESS)
		mount->nReturnCode = ERR_PASSWORD_WRONG;

	if (tmpCryptoInfo != NULL)
	{
		crypto_close (tmpCryptoInfo);
		tmpCryptoInfo = NULL;
	}

	if (Extension->cryptoInfo)
	{
		crypto_close (Extension->cryptoInfo);
		Extension->cryptoInfo = NULL;
	}

	if (Extension->bTimeStampValid)
	{
		RestoreTimeStamp (Extension);
	}

	/* Close the hDeviceFile */
	if (Extension->hDeviceFile != NULL)
		ZwClose (Extension->hDeviceFile);

	/* The cryptoInfo pointer is deallocated if the readheader routines
	   fail so there is no need to deallocate here  */

	/* Dereference the user-mode file object */
	if (Extension->pfoDeviceFile != NULL)
		ObDereferenceObject (Extension->pfoDeviceFile);

	/* Free the tmp IO buffers */
	if (readBuffer != NULL)
		TCfree (readBuffer);

	return ntStatus;
}
Exemple #15
0
INDEX SrvrCreateSquareSector( uint32_t client_id, INDEX iWorld, PC_POINT pOrigin, RCOORD size )
{
	PWORLD world = GetSetMember( WORLD, &g.worlds, iWorld );
	PSECTOR pSector;
	INDEX iSector;
	_POINT o, n;
	pSector = GetFromSet( SECTOR, &world->sectors );
#ifdef OUTPUT_TO_VIRTUALITY
	pSector->facet = AddNormalPlane( world->object, VectorConst_0, VectorConst_Z, 0 );
#endif
	iSector = GetMemberIndex( SECTOR, &world->sectors, pSector );
	/*
	{
		char name[20];
		sprintf( name, "%d", SectorIDs++ );
		pSector->name = GetName( &world->names, name );
	}
	*/
	pSector->iName = INVALID_INDEX;
	pSector->iWorld = iWorld;
	/* east */
	addscaled( o, pOrigin, VectorConst_X, size/2 );
	scale( n, VectorConst_Y, 20 );
	// creates an open line....
	pSector->iWall = SrvrCreateWall( client_id, iWorld, iSector, INVALID_INDEX, FALSE, INVALID_INDEX, FALSE, o, n );
	/* south */
	addscaled( o, pOrigin, VectorConst_Y, size/2 );
	scale( n, VectorConst_X, -20 );
	// creates a wall whos start is at the start of the wall...
	SrvrCreateWall( client_id, iWorld, iSector, pSector->iWall, TRUE, INVALID_INDEX, FALSE, o, n );
	/* west */
	addscaled( o, pOrigin, VectorConst_Y, -size/2 );
	scale( n, VectorConst_X, -20 );
	SrvrCreateWall( client_id, iWorld, iSector, pSector->iWall, FALSE, INVALID_INDEX, FALSE, o, n );
	/* north */
	addscaled( o, pOrigin, VectorConst_X, -size/2 );
	scale( n, VectorConst_Y, 20 );
	{
		PWALL pWall = GetSetMember( WALL, &world->walls, pSector->iWall );
		SrvrCreateWall( client_id, iWorld, iSector
					 , pWall->iWallStart, TRUE
					 , pWall->iWallEnd, TRUE, o, n );
	}
	//ComputeSectorPointList( iWorld, iSector, NULL );
	//ComputeSectorOrigin( iWorld, iSector );
#ifdef OUTPUT_TO_VIRTUALITY
	OrderObjectLines( world->object );
#endif
	SetPoint( pSector->r.n, VectorConst_Y );
	//DumpWall( pSector->wall );
	//DumpWall( pSector->wall->wall_at_start );
	//DumpWall( pSector->wall->wall_at_end );
	//DumpWall( pSector->wall->wall_at_start->wall_at_end );
	{
		INDEX texture = SrvrMakeTexture( client_id, iWorld, SrvrMakeName( client_id, iWorld, WIDE( "Default" ) ) );
		PFLATLAND_TEXTURE pTexture = GetSetMember( FLATLAND_TEXTURE, &world->textures, texture );
		if( !pTexture->flags.bColor )
			SrvrSetSolidColor( client_id, iWorld, texture, AColor( 170, 170, 170, 0x80 ) );
		SrvrSetTexture( client_id, iWorld, iSector, texture );
	}
#ifdef WORLDSCAPE_SERVER
	/* this doesn't exist in direct library */
	MarkSectorUpdated( client_id, iWorld, iSector );
#endif
	return iSector;
}
Exemple #16
0
static PTEXT CPROC ParseCommand( PMYDATAPATH pdp, PTEXT buffer )
{
	if( buffer )
	{
		PTEXT pCommand;
     	//Log2( WIDE("buffer: %s(%d)"), GetText( buffer ), GetTextSize( buffer ) );
     	//LogBinary( buffer );
      pCommand = burst( buffer );
      LineRelease( buffer );
      if( pCommand )
      {
         PTEXT pTemp, pStart;
         int bEscaped = FALSE;
         pStart = pTemp = pCommand;
         while( pTemp )
         {
            if( TextIs( pTemp, WIDE("\\") ) )
            {
               if( !bEscaped )
               {
                  PTEXT pNext;
                  pNext = NEXTLINE( pTemp );
                  pNext->format.position.offset.spaces = pTemp->format.position.offset.spaces;
                  LineRelease( SegGrab( pTemp ) );
                  bEscaped = TRUE;
                  pTemp = pNext;
                  continue;
               }
            }
            if( !bEscaped && TextIs( pTemp, WIDE(";") ) )
            {
               PTEXT pPrior;
	           	//Log( WIDE("Splitting the line and enqueing it...") );
               pPrior = pTemp;
               SegBreak( pTemp );
               if( pStart != pTemp )
               {
               	// end of line included!
               	pStart = SegAppend( pStart, SegCreate(0) ); 
                  EnqueLink( &pdp->output, pStart );
               }
               pStart = pTemp = NEXTLINE( pTemp );
               SegBreak( pTemp );
               LineRelease( pPrior ); // remove ';'
               bEscaped = FALSE;
               continue;
            }
            bEscaped = FALSE;
            pTemp = NEXTLINE( pTemp );
         }
         if( pStart )
         {
         	PTEXT line;
         	line = BuildLine( pStart );
         	//Log1( WIDE("Enqueu: %s"), GetText( line ) );
         	LineRelease( line );
            EnqueLink( &pdp->output, pStart );
         }
      }
      else
      {
         // well what now?  I guess pLine got put into Partial...
         // next pass through this all for command recall will blow...
         Log( WIDE("No information from the burst!") );
      }
	}
	return (PTEXT)DequeLink( &pdp->output );
}
Exemple #17
0
int SrvrLoadWorldFromFile( uint32_t client_id, FILE *file, INDEX iWorld )
{
	FILE *pFile;
	PWORLD world = GetSetMember( WORLD, &g.worlds, iWorld );
	int sz = 0, cnt, version, size;
	char tag[4]; // read in make sure we're still aligned in the file...
	int linesize;
	int nlines;
	PFLATLAND_MYLINESEG *linearray;
	int wallsize;
	int nwalls;
	PWALL *wallarray;
	int sectorsize;
	int nsectors;
	PSECTOR *sectorarray;
	int namesize;
	int nnames;
	PNAME *namearray;
	int texturesize;
	int ntextures;
	PFLATLAND_TEXTURE *texturearray;

	INDEX texture;

	if( !world )
		return 0;
	{
		char buffer[256];
      GetNameText( iWorld, world->name, buffer, sizeof( buffer ) );
		Fopen( pFile, buffer, "rb" );
	}
	if( !pFile )
      return 0;
	ResetWorld( iWorld ); // make sure this thing is empty );

	sz += fread( tag, 1, 4, pFile );
	if( strncmp( tag, "FLAT", 4 ) ) 
	{
		Log( "Alignment error in file load... totally invalid file." );
		return 0;
	}
	sz += fread( &size, 1, sizeof( size ), pFile );
	if( size < 10 ) // can assume that it was a version ID
		version = size;
	else
		sz = fread( &version, 1, sizeof( version ), pFile );

	if( version < 8 )
	{
		texture = SrvrMakeTexture( client_id, iWorld, SrvrMakeName( client_id, iWorld, WIDE( "Default" ) ) );
		SrvrSetSolidColor( client_id, iWorld, texture, AColor( 43, 76, 180, 0x80 ) );
	}
	Log1( "Loading version: %d", version );

	sz += fread( tag, 1, 4, pFile );
	if( strncmp( tag, "LINE", 4 ) )
	{
		// was not LINE or FLAT tag...
		Log( "Alignment error in file line load." );
		return 0;
	}

	if( version > 9 )
		sz += fread( &linesize, 1, sizeof( linesize ), pFile );

	sz += fread( &nlines, 1, sizeof(nlines), pFile );
	linearray = (PFLATLAND_MYLINESEG*)Allocate( sizeof( PFLATLAND_MYLINESEG ) * nlines );
	for( cnt = 0; cnt < nlines; cnt++ )
	{
		PFLATLAND_MYLINESEG pls;
		LINESEGFILE lsf;
		sz += fread( &lsf, 1, sizeof(LINESEGFILE), pFile );
		pls = GetFromSet( FLATLAND_MYLINESEG, &world->lines );
#ifdef OUTPUT_TO_VIRTUALITY
		pls->pfl = CreateFacetLine( world->object, lsf.r.o, lsf.r.n, lsf.start, lsf.end );
#endif
		linearray[cnt] = pls;
		/* some sort of update line... */
		SetRay( &pls->r, &lsf.r );
		if( version < 9 )
		{
			pls->r.o[1] = -pls->r.o[1];
			pls->r.n[1] = -pls->r.n[1];
		}
		pls->dFrom = lsf.start;
		pls->dTo = lsf.end;

	}

	sz += fread( tag, 1, 4, pFile );
	if( strncmp( tag, "WALL", 4 ) )
	{
		Log( "Alignment error in file wall load." );
		return 0;
	}
	if( version > 9 )
		sz += fread( &wallsize, 1, sizeof( wallsize ), pFile );

	sz += fread( &nwalls, 1, sizeof(nwalls), pFile );
	wallarray = (PWALL*)Allocate( sizeof( PWALL ) * nwalls );
	for( cnt = 0; cnt < nwalls; cnt++ )
	{
		wallarray[cnt] = GetFromSet( WALL, &world->walls );
	}
	for( cnt = 0; cnt < nwalls; cnt++ )
	{
		FILEWALLV1 ReadWall1;
		FILEWALLV2 ReadWall2;
		PWALL pwall;
		pwall = wallarray[cnt];
		if( version < 2 )
		{
			sz += fread( &ReadWall1, 1, sizeof( FILEWALLV1 ), pFile );
			pwall->flags = ReadWall1.flags;
			pwall->iSector = ReadWall1.nSector;

			SetLineWorld( world, pwall->iLine, linearray[ReadWall1.nLine] );

			if( ReadWall1.nWallInto == -1 )
				pwall->iWallInto = INVALID_INDEX;
			else
				pwall->iWallInto = GetMemberIndex( WALL, &world->walls, wallarray[ReadWall1.nWallInto] );
			pwall->iWallStart = GetMemberIndex( WALL, &world->walls, wallarray[ReadWall1.nWallStart] );
			pwall->iWallEnd = GetMemberIndex( WALL, &world->walls, wallarray[ReadWall1.nWallEnd] );
		}
		else 
		{
			sz += fread( &ReadWall2, 1, sizeof( FILEWALLV2 ), pFile );
			pwall->flags = ReadWall2.flags;
			pwall->iSector = ReadWall2.nSector;
			if( ReadWall2.nLine != -1 )
			{
				pwall->iLine = GetMemberIndex( FLATLAND_MYLINESEG, &world->lines, linearray[ReadWall2.nLine] );
				//SetLine( pwall->line, linearray[ReadWall2.nLine] );
			}
			else
			{
				Log( "Wall without line? cant be!" );
				DebugBreak();
				pwall->iLine = INVALID_INDEX;
			}
			if( ReadWall2.nWallInto == -1 )
				pwall->iWallInto = INVALID_INDEX;
			else
				pwall->iWallInto = GetMemberIndex( WALL, &world->walls, wallarray[ReadWall2.nWallInto] );
			pwall->iWallStart = GetMemberIndex( WALL, &world->walls, wallarray[ReadWall2.nWallStart] );
			pwall->iWallEnd = GetMemberIndex( WALL, &world->walls, wallarray[ReadWall2.nWallEnd] );
		}
	}	

	sz += fread( tag, 1, 4, pFile );
	if( strncmp( tag, "SECT", 4 ) )
	{
		Log2( "Alignment error in file sector load. %s(%d)", __FILE__, __LINE__ );
		return 0;
	}
	if( version > 9 )
		sz += fread( &sectorsize, 1, sizeof( sectorsize ), pFile );
	sz += fread( &nsectors, 1, sizeof(nsectors), pFile );
	sectorarray = (PSECTOR*)Allocate( sizeof( PSECTOR ) * nsectors );
	for( cnt = 0; cnt < nsectors; cnt++ )
	{
		FILESECTORV3 ReadSector3;
		FILESECTORV4 ReadSector4;
		FILESECTORV5 ReadSector5;
		FILESECTORV8 ReadSector8;
		INDEX sector;
		sectorarray[cnt] = GetFromSet( SECTOR, &world->sectors );
#ifdef OUTPUT_TO_VIRTUALITY
		sectorarray[cnt]->facet = AddNormalPlane( world->object, VectorConst_0, VectorConst_Z, 0 );
#endif
		sector =  GetMemberIndex( SECTOR, &world->sectors, sectorarray[cnt] );
		if( version < 8 )
		{
			// one texture is sufficient...
			// in fact textures should be highly sharable.
			sectorarray[cnt]->iTexture = texture;
		}
		if( version < 4 )
		{	
			/*
			{
			char name[20];
			sprintf( name, "%d", SectorIDs++ );
			sectorarray[cnt]->name = GetName( &world->names, name );
			}
			*/
			sectorarray[cnt]->iName = INVALID_INDEX;
			sz += fread( &ReadSector3, 1, sizeof( FILESECTORV3 ), pFile );
			sectorarray[cnt]->flags = ReadSector3.flags;
			sectorarray[cnt]->iWorld = iWorld;
			SetRay( &sectorarray[cnt]->r, &ReadSector3.r );
			sectorarray[cnt]->iWall = GetMemberIndex( WALL, &world->walls, wallarray[ReadSector3.nwall] );

			if( version < 3 )
			{
				ComputeSectorOrigin( iWorld, sector);
			}
		}
		else if( version < 5 )
		{
			sz += fread( &ReadSector4, 1, sizeof( FILESECTORV4 ), pFile );
			/*
			{
			char name[20];
			sprintf( name, "%d", ReadSector4.nID );
			sectorarray[cnt]->name = GetName( &world->names, name );
			if( atoi( name ) > SectorIDs )
			SectorIDs = atoi( name );
			}
			*/
			sectorarray[cnt]->iName = INVALID_INDEX;
			sectorarray[cnt]->flags = ReadSector4.flags;
			sectorarray[cnt]->iWorld = iWorld;
			SetRay( &sectorarray[cnt]->r, &ReadSector4.r );
			sectorarray[cnt]->iWall = GetMemberIndex( WALL, &world->walls, wallarray[ReadSector4.nwall] );
		}
		else if( version < 8 )
		{
			sz += fread( &ReadSector5, 1, sizeof( FILESECTORV5 ), pFile );
			sectorarray[cnt]->iName = ReadSector5.nName;
			sectorarray[cnt]->flags = ReadSector5.flags;
			sectorarray[cnt]->iWorld = iWorld;
			SetRay( &sectorarray[cnt]->r, &ReadSector5.r );
			sectorarray[cnt]->iWall = GetMemberIndex( WALL, &world->walls, wallarray[ReadSector5.nwall] );
		}
		else
		{
			sz += fread( &ReadSector8, 1, sizeof( FILESECTORV8 ), pFile );
			sectorarray[cnt]->iName = ReadSector8.nName;
			sectorarray[cnt]->flags = ReadSector8.flags;
			sectorarray[cnt]->iWorld = iWorld;
			SetRay( &sectorarray[cnt]->r, &ReadSector8.r );
			sectorarray[cnt]->iWall = ReadSector8.nwall;
			sectorarray[cnt]->iTexture = ReadSector8.nTexture;
		}
		// walls should all be valid at this point...
		// have valid lines, and valid linkings...
		ComputeSectorPointList( iWorld, sector, NULL );
		ComputeSectorOrigin( iWorld, sector );
#ifdef OUTPUT_TO_VIRTUALITY
		OrderObjectLines( world->object );
#endif
	}

	// fix sector references in walls.
	//for( cnt = 0; cnt < nwalls; cnt++ )
	//{
	//	wallarray[cnt]->iSector = wallarray[cnt]->iSector;
	//}

	for( cnt = 0; cnt < nwalls; cnt++ )
	{
		if( wallarray[cnt]->iLine == INVALID_INDEX )
		{
			SrvrDestroySector( client_id, iWorld, wallarray[cnt]->iSector );
			Log( "attempting to fix broken walls" );
			break;
		}
	}

	if( version >= 5 )
	{
		sz += fread( tag, 1, 4, pFile );
		if( strncmp( tag, "NAME", 4 ) )
		{
			Log2( "Alignment error in name section load. %s(%d)", __FILE__, __LINE__ );
			return 0;
		}
		if( version > 9 )
			sz += fread( &namesize, 1, sizeof( namesize ), pFile );
		sz += fread( &nnames, 1, sizeof(nnames), pFile );
		namearray = (PNAME*)Allocate( sizeof( PNAME ) * nnames );
		for( cnt = 0; cnt < nnames; cnt++ )
		{  	
			namearray[cnt] = GetFromSet( NAME, &world->names );
			if( version < 6 )
			{
				uint32_t length;
 				namearray[cnt]->name = (struct name_data*)Allocate( sizeof( *namearray[cnt]->name ) );
				sz += fread( &length, 1, sizeof( length ), pFile );
            namearray[cnt]->name[0].length = length;
				namearray[cnt]->name[0].name = (TEXTSTR)Allocate( namearray[cnt]->name[0].length + 1 );
 				sz += fread( namearray[cnt]->name[0].name, 1, namearray[cnt]->name[0].length, pFile );
		      namearray[cnt]->name[0].name[namearray[cnt]->name[0].length] = 0;
		      namearray[cnt]->lines = 1;
			}
			else if( version < 7 )
			{
				int l;
				sz += fread( &namearray[cnt]->lines, 1, sizeof( namearray[cnt]->lines ), pFile );
				if( namearray[cnt]->lines )
				{
					namearray[cnt]->name = (struct name_data*)Allocate( sizeof( *namearray[cnt]->name ) * namearray[cnt]->lines );
					for( l = 0; l < namearray[cnt]->lines; l++ )
					{
						sz += fread( &namearray[cnt]->name[l].length, 1, sizeof( namearray[cnt]->name[l].length ), pFile );
						namearray[cnt]->name[l].name = (TEXTSTR)Allocate( namearray[cnt]->name[l].length + 1 );
						sz += fread( namearray[cnt]->name[l].name, 1, namearray[cnt]->name[l].length, pFile );
						namearray[cnt]->name[l].name[namearray[cnt]->name[l].length] = 0;
					}	
				}
				else
					namearray[cnt]->name = NULL;
			}
			else
			{
				int l;
				sz += fread( &namearray[cnt]->flags, 1, sizeof( namearray[cnt]->flags ), pFile );
				sz += fread( &namearray[cnt]->lines, 1, sizeof( namearray[cnt]->lines ), pFile );
				if( namearray[cnt]->lines )
				{
					namearray[cnt]->name = (struct name_data*)Allocate( sizeof( *namearray[cnt]->name ) * namearray[cnt]->lines );
					for( l = 0; l < namearray[cnt]->lines; l++ )
					{
						sz += fread( &namearray[cnt]->name[l].length, 1, sizeof( namearray[cnt]->name[l].length ), pFile );
						namearray[cnt]->name[l].name = (TEXTSTR)Allocate( namearray[cnt]->name[l].length + 1 );
						sz += fread( namearray[cnt]->name[l].name, 1, namearray[cnt]->name[l].length, pFile );
						namearray[cnt]->name[l].name[namearray[cnt]->name[l].length] = 0;
					}	
				}
				else
					namearray[cnt]->name = NULL;
			}
		}
       /*
		for( cnt = 0; cnt < nsectors; cnt++ )
		{
			if( (int)sectorarray[cnt]->iName == -1 )
				sectorarray[cnt]->iName = INVALID_INDEX;
			else
			{
				int n;
				PNAME pName = namearray[(int)sectorarray[cnt]->name];
				if( pName->name && pName->name[0].name )
					if( ( n = atoi( pName->name[0].name ) ) > SectorIDs )
						SectorIDs = n;
				sectorarray[cnt]->name = pName;
			}
	   }
      */
		if( version >= 8 )
		{
			sz += fread( tag, 1, 4, pFile );
			if( strncmp( tag, "TEXT", 4 ) )
			{
				Log2( "Alignment error in texture section load. %s(%d)", __FILE__, __LINE__ );
				return 0;
			}
			if( version > 9 )
				sz += fread( &texturesize, 1, sizeof( texturesize ), pFile );
			sz += fread( &ntextures, 1, sizeof(ntextures), pFile );
			texturearray = (PFLATLAND_TEXTURE*)Allocate( sizeof( PFLATLAND_TEXTURE ) * ntextures );
			for( cnt = 0; cnt < ntextures; cnt++ )
			{
				char flag;
				int nName;
				sz += fread( &nName, 1, sizeof( nName ), pFile );
				texturearray[cnt] = GetFromSet( FLATLAND_TEXTURE, &world->textures );
				texturearray[cnt]->iName = GetMemberIndex( NAME, &world->names, namearray[nName] );
				sz += fread( &flag, 1, sizeof( flag ), pFile );
				texturearray[cnt]->flags.bColor = flag;
				if( flag )
				{
					sz += fread( &texturearray[cnt]->data.color, 1, sizeof(CDATA), pFile );
				}
			}
		   
			//for( cnt = 0; cnt < nsectors; cnt++ )
			//{
			//	int ntexture = (int)sectorarray[cnt]->iTexture;
         //   sectorarray[cnt]->texture = NULL;
			//	SetTexture( sectorarray[cnt]->texture, texturearray[ntexture] );
			//}
			Release( texturearray );
		}

		Release( namearray );
	}

	if( version > 9 )
	{
		if( sz != size )
		{
			Log2( "Total load size %d is not %d", sz, size );
		}
	}

	//for( cnt = 0; cnt < nsectors; cnt++ )
	{
		//PSECTOR pSector = sectorarray[cnt];
		// again with the min/max fetch with
		// spacetree add
		//pSector->spacenode = AddSpaceNode( &world->spacetree, pSector, min, max );
	}

	Release( linearray );
	Release( wallarray );
	Release( sectorarray );
	ValidateWorldLinks(iWorld);
	return version;
}
Exemple #18
0
int CPROC PRIORITY( PSENTIENT ps, PTEXT parameters )
{
	// Just a note : Thread priority does not work 
	// there are MANY MANY threads involved - so only
	// process priority applies...
#if defined( WIN32 ) || defined( _WIN32 )
	PTEXT pTemp;
   HANDLE hToken, hProcess;
   TOKEN_PRIVILEGES tp;
   OSVERSIONINFO osvi;
   DWORD dwPriority = 0xA5A5A5A5;

   osvi.dwOSVersionInfoSize = sizeof( osvi );
   GetVersionEx( &osvi );
   if( osvi.dwPlatformId  == VER_PLATFORM_WIN32_NT )
   {
      // allow shutdown priviledges....
      // wonder if /shutdown will work wihtout this?
      if( DuplicateHandle( GetCurrentProcess(), GetCurrentProcess()
                        , GetCurrentProcess(), &hProcess, 0
                        , FALSE, DUPLICATE_SAME_ACCESS  ) )
         if( OpenProcessToken( hProcess, TOKEN_ADJUST_PRIVILEGES, &hToken ) )
         {
            tp.PrivilegeCount = 1;
            if( LookupPrivilegeValue( NULL
                                    , SE_SHUTDOWN_NAME
                                    , &tp.Privileges[0].Luid ) )
            {
               tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
               AdjustTokenPrivileges( hToken, FALSE, &tp, 0, NULL, NULL );
            }
            else
               GetLastError();
         }
         else
            GetLastError();
      else
         GetLastError();
   }

	if( ps->CurrentMacro )
      ps->CurrentMacro->state.flags.bSuccess = TRUE;

	pTemp = GetParam( ps, &parameters );
	if( pTemp )
	{
		if( TextLike( pTemp, WIDE("idle") ) )
		{
	      dwPriority = IDLE_PRIORITY_CLASS;
		}
		else if( TextLike( pTemp, WIDE("normal") ) )
		{
	      dwPriority = NORMAL_PRIORITY_CLASS;
		}
		else if( TextLike( pTemp, WIDE("high") ) )
		{
	      dwPriority = HIGH_PRIORITY_CLASS;
		}
		else if( TextLike( pTemp, WIDE("realtime") ) )
		{
	      dwPriority = REALTIME_PRIORITY_CLASS;
		}
		else
		{
			if( !ps->CurrentMacro )
			{
				DECLTEXT( msg, WIDE("Invalid process priority (not idle, normal, high, or realtime)") );
				EnqueLink( &ps->Command->Output, &msg );
			}
			else
			{
		      ps->CurrentMacro->state.flags.bSuccess = FALSE;
			}
		}
	}
	else
	{
		if( !ps->CurrentMacro )
		{
			DECLTEXT( msg, WIDE("No process priority specified (idle,normal,high,realtime)") );
			EnqueLink( &ps->Command->Output, &msg );
		}
		else
		{
		   ps->CurrentMacro->state.flags.bSuccess = FALSE;
		}
	}

	if( dwPriority != 0xA5A5A5A5 )
		SetPriorityClass( GetCurrentProcess(), dwPriority );

	if( !b95 )
	{
		// NT type system we opened these handles
		CloseHandle( hProcess );
		CloseHandle( hToken );
	}
#endif
	return 0;
}
Exemple #19
0
			RemoveBanner2Ex( NULL DBG_SRC  );
		}
		else
		{
			// fake an event, there was no user, so didn't do anything, just sleep more
			l.last_event_time = startTime;
		}

		// Close Connection to database
		SQLDropODBC( odbc );
	}

	return 0;
}
 
static void OnTaskLaunchComplete( WIDE("Login Monitor") )( void )
{
	// RE-Get Process List
	if ( !EnumProcesses( l.pidList1, sizeof( l.pidList1 ), &l.pidListLength1 ) )
		lprintf( WIDE(" Getting Process List 1 Failed(2)!") );
}

//----------------------------------------------------------------------------------------
// Pre-Main Event, Initialize variables
PRELOAD( InitLoginMon )
{
	if( g.flags.bInitializeLogins )
	{
		PODBC odbc;

		// Check if logging is to be turned on
Exemple #20
0
INDEX LAYER::Save( PODBC odbc )
{
	if( !this )
		return INVALID_INDEX;
	if( iLayer && iLayer != INVALID_INDEX )
	{
		lprintf( WIDE("Recovering prior layer") );
		return iLayer;
	}

	{
		INDEX iStart = route_start_layer.layer->Save( odbc );
		INDEX iEnd = route_end_layer.layer->Save( odbc );
		INDEX iPeice;
		if( pLayerData )
			iPeice = pLayerData->peice->Save( odbc, iLayer, pLayerData->psvInstance );
		else
			iPeice = INVALID_INDEX;
		SQLInsert( odbc, WIDE("board_layer")
					  ,WIDE("x") , 2, x
					  ,WIDE("y"), 2, y
					  ,WIDE("min_x"), 2, min_x
					  ,WIDE("min_y"), 2, min_y
					  ,WIDE("width"), 2, w
					  ,WIDE("height"), 2, h
					  ,WIDE("linked_from_id"), 2, iStart
					  ,WIDE("linked_from_x"), 2, route_start_layer.x
					  ,WIDE("linked_from_y"), 2, route_start_layer.y
					  ,WIDE("linked_to_id"), 2, iEnd
					  ,WIDE("linked_to_x"), 2, route_end_layer.x
					  ,WIDE("linked_to_y"),  2, route_end_layer.y
					  ,WIDE("route"), 2, flags.bRoute
					  ,WIDE("peice_info_id"), 2, iPeice
					  ,WIDE("peice_type"), 1, pLayerData->peice->name() 
					  , NULL, 0, NULL );
		iLayer = FetchLastInsertID( odbc, NULL, NULL );
		lprintf( WIDE("Saved %lu"), iLayer );
	}

	if( flags.bRoute /*&& pds_path*/ )
	{
      INDEX idx;
      PLAYER_PATH_NODE path_node;
	  for( idx = 0; path_node = (PLAYER_PATH_NODE)PeekDataEx( &pds_path, idx ); idx++ )
		{
			SQLCommandf( odbc
				, WIDE("insert into board_layer_path(board_layer_id,x,y,fore,back)values(%lu,%ld,%ld,%d,%d)")
				, iLayer
				, path_node->x, path_node->y
				, path_node->flags.ForeDir, path_node->flags.BackDir );

		}
	}
   return iLayer;
}
Exemple #21
0
//----------------------------------------------------------------------------------------
// Timer for checking the timestamp
static uintptr_t CPROC countDown( PTHREAD thread )
{
	TEXTCHAR buf[45];
	uint8_t found = 0;	
	uint32_t startTime;   
	PODBC odbc;
	
	// Loop forever
	while( 1 )
	{
		// Get Current time
		startTime = timeGetTime();

		// Sleep to next timeout
		if( l.flags.bLogSleeps )
		{
			long x =  ( l.iIdleTime*(60)*(1000) ) - ( startTime - l.last_event_time );
			lprintf( WIDE("Sleep for... %d:%02d.%03d"), x / 60000, (x / 1000 ) %60, x % 1000 );
		}

		if( ( l.iIdleTime*(60)*(1000) ) > ( startTime - l.last_event_time ) )
			WakeableSleep( ( l.iIdleTime*(60)*(1000) ) - ( startTime - l.last_event_time ) );

		startTime = timeGetTime();
		// sleep some more if we got a new event

		if( ( l.iIdleTime*(60)*(1000) ) > ( startTime - l.last_event_time ) )
			continue;

		// Make connection to database
		odbc = SQLGetODBC( l.option_dsn );

		if( l.flags.bLogSleeps )
			lprintf( WIDE("woke up and user is %p (%d)"), HaveCurrentUser( odbc ), ( startTime - l.last_event_time ) );
		// If there is current user, else there is no active logins or processes to kill

		if( HaveCurrentUser( odbc ) )
		{
			uint32_t target_tick = startTime + ( l.iScreenSaverWaitTime * 1000 );
			int32_t remaining = ( target_tick - startTime );
			// Get time

			// Check last event, if timeout not hit go back to sleep until timeout will be hit
			if( remaining < 0 )
			{
				if( l.flags.bLogSleeps )
					lprintf( WIDE("Not enough time, go back and wait...") );

				// Close Connection to database
				SQLDropODBC( odbc );

				// not enough time has really passed... sleep more
				continue;
			}

			// Let hook know to update activity flag
			l.flags.countingDown = 1;			

			// Start countdown
			do
			{
				// Update time to check against
				remaining = ( target_tick - startTime );

				// Update Banner Message
				snprintf( buf, sizeof( buf ), WIDE(" The system will logout in %d.%03d seconds...")
						  , remaining / 1000, remaining % 1000 );
				BannerTopNoWait( buf );

				// Don't eat to much cpu time
				IdleFor( 200 );
				startTime = timeGetTime();
			}
			while( l.flags.countingDown && ( target_tick > startTime ) );

			// If countdown made it to 0
			if( ( target_tick < startTime ) )
			{
				uint32_t x;
				uint32_t y;
				// Logout users
				SQLCommandf( odbc , WIDE("update login_history set logout_whenstamp=now() where logout_whenstamp=11111111111111 and system_id=%d"), g.system_id );

				// Get current process list
				if ( !EnumProcesses( l.pidList2, sizeof( l.pidList2 ), &l.pidListLength2 ) )					
						lprintf( WIDE(" Getting Process List 2 Failed!") );

				// Kill Processes
				for( x = 0; x < l.pidListLength2; x++ )
				{
					// Check if process existed originally
					for( y = 0; y < l.pidListLength1; y++ )
					{
						if( l.pidList2[x] == l.pidList1[y] )
						{
							found = 1;
							break;
						}
					}

					// If did not exist originally kill the process
					if( !found )
					{
						TEXTCHAR cmd[25];
						snprintf( cmd, sizeof( cmd ), WIDE("pskill %d"), l.pidList2[x] );
						System( cmd, LogOutput, 0 );
					}

					found = 0;
				}

				// Give extra time to see Banner
				IdleFor( 500 );

				// Reset Data				
				l.flags.countingDown  = 0;				
			}			

			// Remove Banner
			RemoveBanner2Ex( NULL DBG_SRC  );
		}
		else
		{
			// fake an event, there was no user, so didn't do anything, just sleep more
			l.last_event_time = startTime;
		}

		// Close Connection to database
		SQLDropODBC( odbc );
	}

	return 0;
}
Exemple #22
0
LAYER::LAYER( PODBC odbc, PLIST peices, INDEX iLoadLayer )
{
	if( !this )
		return;
	if( iLayer && iLayer != INVALID_INDEX )
	{
		lprintf( WIDE("Recovering prior layer") );
		return;
	}
	{
		CTEXTSTR *results;
		if( SQLRecordQueryf( odbc, NULL, &results, NULL
					  , WIDE("select x,y,min_x,min_y,width,height,linked_from_id,linked_from_x,linked_from_y,linked_to_id,linked_to_x,linked_to_y,route,peice_info_id,peice_type from board_layer where board_layer_id=%lu")
					  , iLoadLayer
					  ) && results )
		{
			PIPEICE peice_type = ::GetPeice( peices, results[14] );
			
			pLayerData->psvInstance = peice_type->Load( odbc, atoi( results[13] ) );//, pLayerData->psvInstance );
			pLayerData->SetPeice( peice_type );
			pds_path = CreateDataStack( sizeof( LAYER_PATH_NODE ) );
			x = atoi( results[0] );
			y = atoi( results[1] );
			min_x = atoi( results[2] );
			min_y = atoi( results[3] );
			w = IntCreateFromText( results[4] );
			h = IntCreateFromText( results[5] );
			flags.bRoute = atoi( results[12] );

		    iLayer = iLoadLayer;

			INDEX iStart = IntCreateFromText( results[6] );
			if( iStart != INVALID_INDEX )
			{
				int32_t x, y;
				x = atoi( results[7] );
				y = atoi( results[8] );
				PLAYER loaded_route_start_layer;
				loaded_route_start_layer = FindLayer( iStart );
				if( !loaded_route_start_layer )
					loaded_route_start_layer = GetFromSet( LAYER, pool ); //new(pool,pLayerData->pool) LAYER( odbc, peices, iStart );
				loaded_route_start_layer->pLayerData->peice->methods->ConnectBegin( loaded_route_start_layer->pLayerData->psvInstance
												, x, y // connect x, y
												, pLayerData->peice, pLayerData->psvInstance );
				loaded_route_start_layer->Link( this, LINK_VIA_START, x, y);
			}

			INDEX iEnd = IntCreateFromText( results[9] );
			if( iEnd != INVALID_INDEX )
			{
				int32_t x, y;
				x = atoi( results[10] );
				y = atoi( results[11] );
				PLAYER loaded_route_end_layer;
				loaded_route_end_layer = FindLayer( iEnd );
				if( !loaded_route_end_layer )
					loaded_route_end_layer = GetFromSet( LAYER, pool ); //new(pool,pLayerData->pool) LAYER( odbc, peices, iEnd );
				loaded_route_end_layer->pLayerData->peice->methods->ConnectEnd( loaded_route_end_layer->pLayerData->psvInstance
												, x, y // connect x, y
												, pLayerData->peice, pLayerData->psvInstance );
				loaded_route_end_layer->Link( this, LINK_VIA_END, x, y );
			}



			//}
		}
		SQLEndQuery( odbc );
		for( SQLRecordQueryf( odbc, NULL, &results, NULL, WIDE("select x,y,fore,back from board_layer_path where board_layer_id=%lu order by board_layer_path_id desc"), iLoadLayer );
			results;
			FetchSQLRecord( odbc, &results ) )
		{
			// add path node for a routed type peice
			LAYER_PATH_NODE node;
			node.x = atoi( results[0] );
			node.y = atoi( results[1] );
			node.flags.ForeDir = atoi( results[2] );
			node.flags.BackDir = atoi( results[3] );
			PushData( &pds_path, &node );
		}
	}
   //return iLayer;
}
Exemple #23
0
static genxStatus WriteBuffer( void *UserData, constUtf8 s )
{
	vtprintf( (PVARTEXT)UserData, WIDE("%s"), s );
	return GENX_SUCCESS;
}
Exemple #24
0
// result is the last node (if any... which is a peekstack)
PLAYER_PATH_NODE LAYER::UnlayPath( int nLayers )
{
	// unwind to, and including this current spot.
	// this is to handle when the line intersects itself.
	// other conditions of unlaying via pathways may require
	// other functionality.
	int n;
	PLAYER_PATH_NODE node;// = (PLAYER_PATH_NODE)PopData( &pds_path );
	lprintf( WIDE("overlapped self at path segment %d"), nLayers );
	for( n = nLayers; (n && (node = (PLAYER_PATH_NODE)PopData( &pds_path ))), n; n-- )
	{
		lprintf( WIDE("Popped node %d(%p)"), n, node );
		// grab the NEXT node...
		// if it has bForced set... then this node must exist.
		PLAYER_PATH_NODE next = (PLAYER_PATH_NODE)PeekData( &pds_path );
		if( next && next->flags.bForced )
		{
			DebugBreak();
			node->flags.ForeDir = NOWHERE;
			return node;
		}
		if( node && node->flags.bForced )
		{
			DebugBreak();
         // this is SO bad.
		}
		//if( node->x == dest_x && node->y == dest_y )
		{
			//lprintf( WIDE("And then we find the node we overlaped...") );
		}
	}
	lprintf( WIDE("Okay done popping... %d, %p"), n, node );
	if( node )
	{
		PLAYER_PATH_NODE next = (PLAYER_PATH_NODE)PeekData( &pds_path );
		// set this as nowhere, so that we can easily just step forward here..
		if( !next )
		{
			if( !node->flags.bForced )
			{
				node->flags.ForeDir = NOWHERE;
			}
			PushData( &pds_path, node );
			return node;
		}
		if( !nLayers
			&& next->flags.bForced
			&& next->flags.BackDir != NOWHERE )
		{
			// if it was forced, then this MUST be here.  There is a reason.
			// there is also a way to end this reason, and unlay 0 path.  This
			// releases the foredir to anything.  This may be used for error correction path
			// assumptions?
			DebugBreak();
			if( next->flags.bTry )
			{
				node = (PLAYER_PATH_NODE)PopData(&pds_path );
				// this is the second attempt
				if( !node->flags.bFlopped )
				{
					node->flags.bFlopped = 1;
					node->flags.ForeDir = LeftOrRight( Opposite( node->flags.BackDir ), 1 );
               return node;
				}
			}
			next->flags.bForced = 0;
		}
		else
		{
			next->flags.ForeDir = NOWHERE;
         lprintf( WIDE("this node itself is okay...") );
		}
      return next;
	}
   return NULL;
}
Exemple #25
0
void CPROC GetAnyEvent( uintptr_t psv, char *extra )
{
	printf( WIDE("Received event with extra : %s\n"), extra );
}
Exemple #26
0
int LAYER::UnlayPath( int bLoop )
{
BackTrace:   // method here to remove one peice from the trail.
		// should perhaps join this and the loop removal -
		// and do a BackTrace UNTIL _x = tx, _y = ty or we are at the start...
#ifdef DEBUG_BACKTRACE
		Log( WIDE("Start...") );
#endif
		while( bBackTrace || bLoop )
		{
#ifdef DEBUG_BACKTRACE
			Log( WIDE("BackTrace...\n") );
#endif
			if( bStarted )  // bStarted = bCompleted...
			{
				int nDir = route_current_layer->GetLastBackDirection(); // this is always correct
				// nDir will be trashed... // update position one step...
#ifdef DEBUG_BACKTRACE
				{
					BYTE byString[256];
					sprintf( (char*)byString, WIDE(" %d, %d, %d to %d, %d\n"),
							  nDir, _x, _y,
							  _x + DirDeltaMap[nDir].x,
							  _y + DirDeltaMap[nDir].y );
					Log( (char*)byString );
				}
#endif
				_x += DirDeltaMap[nDir].x;
				_y += DirDeltaMap[nDir].y;
			}
			else
			{
#ifdef DEBUG_BACKTRACE
				Log( WIDE("Not Started...") );
#endif
				if( bLoop )  // just abort cause we're sooo confused
				{
					// backup to the start....
					bStarted = TRUE;
					bFailed = TRUE;
					continue;
					//                  return;
				}
				// comment this out - and path will be predicted...
				//               if( ( (abs(wX - xStart) + abs(wY-yStart)) < 4 ) )
				//                  return;
				//    return;  // get out now... can't do a thing! - saves auto-pathing
			}
			if( _x == xStart && _y == yStart )
			{
#ifdef DEBUG_BACKTRACE
				Log( WIDE("At Beginning...") );
#endif
				bStarted = FALSE;
				bLoop = FALSE;
			}
			else if( (abs( _x - tx ) + abs( _y - ty))<2 ) // almost back at start...???
			{
#ifdef DEBUG_BACKTRACE
				Log( WIDE("Loop Removed...") );
#endif
				bLoop = FALSE;  // uhmm delayed one step...(if just now stating)
			}
			bBackTrace = FALSE;  // only one requested...
		}
		if( bFailed )
			return;
}
Exemple #27
0
void CPROC LogSQLStates( CTEXTSTR message )
{
	lprintf( WIDE("%s"), message );
}
Exemple #28
0
void LAYER::LayPath( int32_t wX, int32_t wY )
{
	int DeltaDir;
	LOGICAL bLoop = FALSE, bIsRetry;  // no looping....
	int tx, ty;
	int nPathLayed = 0;
	int nDir, nNewDir;
	LOGICAL bBackTrace = FALSE,
		bFailed = FALSE;

	PLAYER_PATH_NODE node;
	lprintf( WIDE("Laying path %p to %d,%d"), this, wX, wY );
	node = (PLAYER_PATH_NODE)PeekData( &pds_path );
	// sanity validations...
	// being done already, etc...
	wX -= LAYER::x;
	wY -= LAYER::y;
	if( node )
	{
		if( node->x == wX && node->y == wY )
		{
			lprintf( WIDE("Already at this end point, why are you telling me to end where I already did?") );
			return;
		}
		// should range check wX and wY to sane limits
		// but for now we'll trust the programmer...
		if( abs( node->x - wX ) > 100 || abs( node->y - wY ) > 100 )
		{
			DebugBreak();
			lprintf( WIDE("Laying a LONG path - is this okay?!") );
		}
	}

	#ifdef DEBUG_BACKTRACE
		Log( WIDE("Enter...") );
	#endif

		//------------ FORWARD DRAWING NOW .....
	bIsRetry = FALSE;
	DeltaDir = 0;
	{
		PLAYER_PATH_NODE node;
		// get the last node in the path.
		node = (PLAYER_PATH_NODE)PeekData( &pds_path );
		while( node )
		{
			nNewDir = FindDirection( node->x
										  , node->y
										  , wX, wY );
			if( nNewDir == NOWHERE )
			{
				// already have this node at the current spot...
				lprintf( WIDE("Node has ended here...") );
				break;
			}
			nDir = NOWHERE; // intialize this, in case we missed a path below...
			if( node->flags.BackDir == NOWHERE )
			{
				// if it is newdir, we're okay to go ahead with this plan.
				if( node->flags.ForeDir != nNewDir && flags.bForced )
				{
					lprintf( WIDE("Have a forced begin point, and no way to get there from here....") );
					DebugBreak();
					if( NearDir( node->flags.ForeDir, nNewDir ) == 10 )
					{
						lprintf( WIDE("MUST go %d , have to go %d from here.  Go nowhere."), node->flags.ForeDir, nNewDir );
						lprintf( WIDE("Okay - consider a arbitrary jump to go forward... until we can go backward.") );
					}
					else
					{
						lprintf( WIDE("It's just not quite right... return, a less radical assumption may be made.") );
					}
					return;
				}
				// else, just go ahead, we returned above here.
				node->flags.ForeDir = nNewDir;
			}
			else
			{
				// need to determine a valid foredir based on nNewDir desire, and nBackDir given.
				lprintf( WIDE("%d, %d = %d")
						 , Opposite( node->flags.BackDir )
						 , nNewDir
						 , NearDir(Opposite( node->flags.BackDir )
									 , nNewDir ) );
				lprintf( WIDE("newdir = %d backdir = %d"), nNewDir, node->flags.BackDir );
				//pold->TopLayer->ForeDir;
				if( NearDir( nNewDir, Opposite( node->flags.BackDir ) ) != 10 )
				{
					// this is a valid direction to go.
					node->flags.ForeDir = nNewDir;
				}
				else
				{
					lprintf( WIDE("Unlay path cause we can't get there from here.") );
					node = UnlayPath( nPathLayed + 1 );
					// at this point always unlay at least one more than we put down.
					nPathLayed = 1;
					continue;
#if 0
               int nBase = Opposite( node->flags.BackDir );
					nDir = ( node->flags.BackDir + 2 ) & 7;
					if( NearDir( nNewDir, nDir ) != 10 )
					{
						//node->flags.ForeDir = (nBase + 6) &7;
						node->flags.ForeDir = Right( nBase );
					}
					else if( NearDir( nNewDir, Opposite( nDir ) ) != 10 )
					{
						node->flags.ForeDir = Left(nBase);
					}
					else
					{

						// this should be a random chance to go left or right...
						// maybe tend to the lower x or higher x ?
						lprintf( WIDE("Choosing an arbitrary directino of 1, and only on1") );
						//node->flags.ForeDir = Right( nBase + 1 );
						node->flags.bFlopped = 0;
						node->flags.bTry = 1;
						node->flags.bForced = 1;
						node->flags.ForeDir = LeftOrRight( nBase, node->flags.bFlopped );
						// set a flag in this node for which way to go...
						// but a left/right node needs the ability
						// to remain forced for a single unlay, and move in a direction...

					}
#endif
				}
			}
			{
				int  n;
				tx = node->x + DirDeltaMap[node->flags.ForeDir].x;
				ty = node->y + DirDeltaMap[node->flags.ForeDir].y;
				lprintf( WIDE("New coordinate will be %d,%d"), tx, ty );
				if( n = Overlaps( tx, ty ) ) // aleady drew something here...
					// the distance of the overlap is n layers, including Nth layer
					// for( ; n; PopData(&pds_stack), n-- )
					// and some fixups which unlay path does.
				{
					lprintf( WIDE("Unlaying path %d steps to overlap") , n );
					node = UnlayPath( n );
					// at an unlay point of forced, unlay path should be 'smart' and 'wait'
					// otherwise we may unwind to our tail and be confused... specially when moving away
					// and coming back to reside at the center.
					// if the force direction to go from a forced node is excessive, that definatly
					// breaks force, and releases the path node.
					// there may be board conditions which also determine the pathing.
					// okay try this again from the top do {
					// startin laying path again.
					continue;
				}
				// otherwise we're good to go foreward.
				// at least we won't add this node if it would have
				// already been there, heck, other than that via's
				// don't exist, sometimes we'll even get the exact node
				// that this should be....
				{
					LAYER_PATH_NODE newnode;
					// this may be set intrinsically by being an excessive force
					// causing a large direction delta
					newnode.flags.bForced = FALSE;
					newnode.flags.ForeDir = NOWHERE;
					// this of course must start(?) exactly how the other ended(?)...
					newnode.flags.BackDir = Opposite( node->flags.ForeDir );
					newnode.x = tx;
					newnode.y = ty;
					{
						int xx = tx + x;
						int yy = ty + y;
						if( xx < min_x )
						{
							w += min_x - xx;
							min_x = xx;
						}
						if( xx >= ( min_x + (int32_t)w ) )
							w = xx - min_x + 1;
						if( yy < min_y )
						{
							h += min_y - yy;
							min_y = yy;
						}
						if( yy >= ( min_y + (int32_t)h ) )
							h = yy - min_y + 1;

					}
					lprintf( WIDE("Push path %d,%d  min=%d,%d size=%d,%d"), newnode.x, newnode.y, min_x, min_y, w, h );
					PushData( &pds_path, &newnode );
					nPathLayed++;
					node = (PLAYER_PATH_NODE)PeekData( &pds_path ); // okay this is now where we are.
				}
			}
		}
	}
}
Exemple #29
0
int main( int argc, char **argv )
{
	FILE *input = stdin;
	PVARTEXT pvt_cmd;
	TEXTCHAR readbuf[4096];
	TEXTCHAR *buf;
	int offset = 0;
	int no_headers = 0;
	PODBC default_odbc = NULL;
	CTEXTSTR select_into;
	PLIST output = NULL;
	PLIST outputs = NULL;
	int arg_ofs = 0;
	SQLSetFeedbackHandler( ShowSQLStates );
	//SetAllocateDebug( TRUE );
	//SetAllocateLogging( TRUE );
	if( argc < 2 )
		Usage( 1 );
	else
	{
		while( argv[1+arg_ofs] && ( argv[1+arg_ofs][0] == '-' ) )
		{
			TEXTSTR tmp;
			switch( argv[1+arg_ofs][1] )
			{
			case 'n':
				no_headers = 1;
				break;
			case 'f':
				arg_ofs++;
				input = sack_fopen( 0, tmp = DupCharToText( argv[1+arg_ofs] ), WIDE("rt") );
				if( input )
					SQLSetFeedbackHandler( LogSQLStates );
				break;
			}
			if( tmp )
			{
				Deallocate( TEXTSTR, tmp );
				tmp = NULL;
			}
			arg_ofs++;
		}
		if( argv[1+arg_ofs] )
			default_odbc = ConnectToDatabase( DupCharToText( argv[1 + arg_ofs] ) );
	}
	SetHeapUnit( 4096 * 1024 ); // 4 megs expansion if needed...
	pvt_cmd = VarTextCreateExx( 10000, 50000 );


	while( (buf = readbuf), fgets( readbuf + offset
					, sizeof( readbuf ) - offset
					, input ) )
	{
		CTEXTSTR *result = NULL;
		size_t len;
		while( buf[0] == WIDE(' ') || buf[0] == WIDE('\t') )
         buf++;
		len = strlen( buf );
		if( buf[0] == WIDE('#') )
			continue;
		if( ( len > 0 ) && buf[len-1] == WIDE('\n') )
		{
			len--;
			buf[len] = 0;
		}

		if( strcmp( buf, WIDE("\\q") ) == 0 )
			break;

		if( !buf[0] && VarTextLength( pvt_cmd ) == 0 )
			continue;

		if( ( len > 0 ) && buf[len-1] == WIDE('\\') )
		{
			buf[len-1] = 0;
			len--;
			vtprintf( pvt_cmd, WIDE("%s"), buf );
			offset = 0;
			//offset = (len - 1); // read over the slash
			continue;
		}
		else
		{
			if( len > 0 )
				vtprintf( pvt_cmd, WIDE("%s"), buf );
			offset = 0;
		}

		buf = GetText( VarTextPeek( pvt_cmd ) );

		if( buf[0] == WIDE('?') )
		{
			int fields;
			int replace = 0;
			int ofs = 1;
			CTEXTSTR *columns;
			TEXTSTR *_columns;
			PVARTEXT pvt = NULL;
			if( buf[1] == WIDE('!') )
			{
				replace = 1;
				ofs = 2;
			}
			if( output )
			{
				if( !select_into || !select_into[0] )
				{
					printf( WIDE("Table name was invalid to insert into on the destination side...\'%s\'"), select_into );
					VarTextEmpty( pvt_cmd );
					continue;
				}
				pvt = VarTextCreateExx( 10000, 50000 );
			}
			if( SQLRecordQuery( default_odbc, buf + ofs, &fields, &result, &columns ) )
			{
				int count = 0;
				int first = 1;
				_columns = NewArray( TEXTSTR, fields );
				if( !no_headers )
				{
					{
						int n;
						for( n = 0; n < fields; n++ )
						{
							_columns[n] = StrDup( columns[n] );
							if( !pvt )
								fprintf( stdout, WIDE("%s%s"), n?WIDE(","):WIDE(""), columns[n] );
						}
					}
					if( !pvt )
						fprintf( stdout, WIDE("\n") );
				}
				for( ; result; FetchSQLRecord( default_odbc, &result ) )
				{
					if( pvt && first )
					{
						vtprintf( pvt, WIDE("%s into `%s` ("), replace?WIDE("replace"):WIDE("insert ignore"), select_into );
						{
							int first = 1;
							int n;
							for( n = 0; n < fields; n++ )
							{
								vtprintf( pvt, WIDE("%s`%s`"), first?WIDE(""):WIDE(","), _columns[n] );
								first = 0;
							}
						}
						vtprintf( pvt, WIDE(") values ") );
					}
					if( pvt )
					{
						vtprintf( pvt, WIDE("%s("), first?WIDE(""):WIDE(",") );
						{
							int first = 1; // private first, sorry :) parse that, Visual studio can.
							int n;
							for( n = 0; n < fields; n++ )
							{
								TEXTSTR tmp;
								vtprintf( pvt, WIDE("%s%s")
										  , first?WIDE(""):WIDE(",")
										  , result[n]?(tmp=EscapeStringOpt( result[n], TRUE)):((tmp=NULL),WIDE("NULL"))
										  );
								Release( tmp );
								first = 0;
							}
						}
						vtprintf( pvt, WIDE(")") );
					}
					else
					{
						int n;
						int first = 1;
						for( n = 0; n < fields; n++ )
						{

							fprintf( stdout, WIDE("%s%s"), first?WIDE(""):WIDE(","),result[n]?result[n]:WIDE("NULL") );
							first = 0;
						}
						fprintf( stdout, WIDE("\n") );
					}
					first = 0;
					count++;
					if( ( VarTextLength( pvt ) ) > 100000 )
					{
						PTEXT cmd;
						first = 1; // reset first to rebuild the beginning of the insert.
						printf( WIDE("Flushing at 100k characters...%d records\n"), count );
						if( pvt )
						{
							cmd = VarTextGet( pvt );
							if( cmd )
							{
								INDEX idx;
								PODBC odbc;
								LIST_FORALL( output, idx, PODBC, odbc )
								{
									if( !SQLCommand( odbc, GetText( cmd ) ) )
										printf( WIDE("Failed command to:%s\n"), (CTEXTSTR)GetLink( &outputs, idx ) );
								}
								LineRelease( cmd );
							}
						}
					}
				}
				if( !no_headers )
				{
					int n;
					for( n = 0; n < fields; n++ )
					{
						Release( _columns[n] );
					}
				}
				Release( _columns );
			}
Exemple #30
0
int init_mib(void)
{
    char *file;//, *getenv();

		if (Mib != NULL) return (0);

    /* First, try the new parser if the variable exists.
     */

    file = getenv("MIBFILE_v2");
    if (file != NULL)
	Mib = read_mib_v2(file);

    /* Then our overrides
     */
    if (Mib == NULL)
      if ((file = getenv("MIBFILE")) != NULL)
	Mib = read_mib(file);

    /* Then the default mibfiles
     */
    if (Mib == NULL)
	Mib = read_mib_v2("mib-v2.txt");
    if (Mib == NULL)
	Mib = read_mib_v2("/etc/mib-v2.txt");

#ifndef WIN32
#define MIBDIR "."
    if (Mib == NULL) {
      char path[MAXPATHLEN];
      sprintf(path, WIDE("%s/mib-v2.txt"), MIBDIR);
      Mib = read_mib_v2(path);
    }
#endif /* WIN32 */

    /* And finally the old faithful files.
     */
    if (Mib == NULL)
	Mib = read_mib("mib.txt");
    if (Mib == NULL)
	Mib = read_mib("/etc/mib.txt");

#ifndef WIN32
    if (Mib == NULL) {
      char path[MAXPATHLEN];
      sprintf(path, WIDE("%s/mib.txt"), MIBDIR);
      Mib = read_mib(path);
    }
#endif /* WIN32 */

#ifdef WIN32

    if (Mib == NULL) {
      /* Fetch the name from the registry */
      long ret;
      HKEY   hKey;
      DWORD Type;

#define MAX_VALUE_NAME              128
#define KEY "SOFTWARE\\Carnegie Mellon\\Network Group\\SNMP Library"

      TCHAR ValueName[MAX_VALUE_NAME];
      DWORD dwcValueName = MAX_VALUE_NAME;

      ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
			 _TEXT(KEY),
			 0,
			 KEY_READ,
			 &hKey);

      if (ret == ERROR_SUCCESS) {
        /* Found this registry entry. */
        ret = RegQueryValueEx(hKey,
          _TEXT("MIB Location"),
          NULL,
          &Type,
          (LPBYTE)&ValueName,
			      &dwcValueName);

        if (ret == ERROR_SUCCESS) {

#ifdef UNICODE

          _tprintf(_TEXT("Found '%s'\n"), ValueName);

          {
            char lpszBuf[MAX_VALUE_NAME];

            if (WideCharToMultiByte(CP_ACP, 0, ValueName, WC_SEPCHARS, // -1
              lpszBuf, dwcValueName, NULL, NULL)) {
              Mib = read_mib_v2(lpszBuf);
            }
          }

#else /* UNICODE */
           Mib = read_mib_v2(ValueName);

#endif /* UNICODE */

        } else {
          /* Unable to read key */
          LPVOID lpMsgBuf;
          FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
            FORMAT_MESSAGE_IGNORE_INSERTS, NULL, ret,
            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (TCHAR *)&lpMsgBuf, 0, NULL);
#ifdef STDERR_OUTPUT
          fprintf(stderr, WIDE("Reg Read Error: %s\n"), (LPTSTR)lpMsgBuf);
#endif
        }
        /* And close the registry */
        RegCloseKey(hKey);

      } else {

        /* Unable to open key */
  	LPVOID lpMsgBuf;
	  FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
		      FORMAT_MESSAGE_IGNORE_INSERTS, NULL, ret,
		      MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (TCHAR *)&lpMsgBuf, 0, NULL);
#ifdef STDERR_OUTPUT
    fprintf(stderr, WIDE("Reg Open Error: %s\n"), (LPTSTR)lpMsgBuf);
#endif
      }
    }
#endif /* WIN32 */

    if (Mib == NULL) {
#ifdef STDERR_OUTPUT
      fprintf(stderr, WIDE("Couldn't find mib file\n"));
#endif
      return(0);
    }
    set_functions(Mib);
    return(1);
}