예제 #1
0
/*
 * doInitializeEditor - do just that
 */
static void doInitializeEditor( int argc, char *argv[] )
{
    int         i, arg, cnt, ocnt, startcnt = 0;
    srcline     sline;
    int         k, j;
    char        tmp[FILENAME_MAX], c[1];
    char        buff[MAX_STR], file[MAX_STR], **list;
    char        cmd[MAX_STR * 2];
    char        *parm;
    char        *startup[MAX_STARTUP];
    char        *startup_parms[MAX_STARTUP];
    vi_rc       rc;
    vi_rc       rc1;

    /*
     * Make sure WATCOM is setup and if it is not, make a best guess.
     */
    watcom_setup_env();

    /*
     * If EDPATH is not set, use system default %WATCOM%\EDDAT.
     */
    if( getenv( "EDPATH" ) == NULL ) {
        char *watcom;

        watcom = getenv( "WATCOM" );
        if( watcom != NULL ) {
            char edpath[FILENAME_MAX];

            sprintf( edpath, "%s%c%s", watcom, FILE_SEP, "eddat" );

            if( setenv( "EDPATH", edpath, 0 ) != 0 ) {
                /*
                 * Bail out silently on error, as we will get error message later on.
                 */
            }
        }
    }

    /*
     * misc. set up
     */
    MaxMemFree = MemSize();
    StaticStart();
    FTSInit();
    BoundDataInit();
    EditFlags.Starting = true;
    InitCommandLine();
    ChkExtendedKbd();
    SSInitBeforeConfig();

    GetCWD1( &HomeDirectory );
    GetCWD1( &CurrentDirectory );
    SetCWD( HomeDirectory );
    if( cfgFN == NULL ){
        cfgFN = DupString( CFG_NAME );
    }

    checkFlags( &argc, argv, startup, startup_parms, &startcnt );
    ScreenInit();
    SetWindowSizes();
    EditFlags.ClockActive = false;
    SetInterrupts();
#ifdef __WIN__
    InitClrPick();
    InitFtPick();
    SubclassGenericInit();
    CursorOp( COP_INIT );
#else
    InitColors();
#endif
    InitSavebufs();
    InitKeyMaps();

    /*
     * initial configuration
     */
    EditVars.Majick = MemStrDup( "()~@" );
    EditVars.FileEndString = MemStrDup( "[END_OF_FILE]" );
    MatchInit();
    SetGadgetString( NULL );
    WorkLine = MemAlloc( sizeof( line ) + EditVars.MaxLine + 2 );
    WorkLine->len = -1;

    sline = 0;
    if( cfgFN[0] != 0 ) {
        c[0] = 0;
        rc = Source( cfgFN, c, &sline );
        if( rc == ERR_FILE_NOT_FOUND ) {
#ifdef __WIN__
            CloseStartupDialog();
            MessageBox( (HWND)NULLHANDLE, "Could not locate configuration information; please make sure your EDPATH environment variable is set correctly",
                        EditorName, MB_OK );
            ExitEditor( -1 );
#else
            rc = ERR_NO_ERR;
#endif
        }
    } else {
        rc = ERR_NO_ERR;
    }
    if( wantNoReadEntireFile ) {
        EditFlags.ReadEntireFile = false;
    }
    VerifyTmpDir();
    while( LostFileCheck() );
    HookScriptCheck();

    if( EditFlags.Quiet ) {
        EditFlags.Spinning = false;
        EditFlags.Clock = false;
    }
    ExtendedMemoryInit();

    /*
     * more misc. setup
     */
    if( EditVars.WordDefn == NULL ) {
        EditVars.WordDefn = DupString( &WordDefnDefault[6] );
        InitWordSearch( EditVars.WordDefn );
    }
    if( EditVars.WordAltDefn == NULL ) {
        EditVars.WordAltDefn = DupString( WordDefnDefault );
    }
    if( EditVars.TagFileName == NULL ) {
        EditVars.TagFileName = DupString( "tags" );
    }
    DotBuffer = MemAlloc( (maxdotbuffer + 2) * sizeof( vi_key ) );
    AltDotBuffer = MemAlloc( (maxdotbuffer + 2) * sizeof( vi_key ) );
    DotCmd = MemAlloc( (maxdotbuffer + 2) * sizeof( vi_key ) );
    SwapBlockInit( EditVars.MaxSwapBlocks );
    ReadBuffer = MemAlloc( MAX_IO_BUFFER + 6 );
    WriteBuffer = MemAlloc( MAX_IO_BUFFER + 6 );
    FindHistInit( EditVars.FindHist.max );
    FilterHistInit( EditVars.FilterHist.max );
    CLHistInit( EditVars.CLHist.max );
    LastFilesHistInit( EditVars.LastFilesHist.max );
    GetClockStart();
    GetSpinStart();
    SelRgnInit();
    SSInitAfterConfig();
#if defined( VI_RCS )
    ViRCSInit();
#endif

    /*
     * create windows
     */
    StartWindows();
    InitMouse();
    rc1 = NewMessageWindow();
    if( rc1 != ERR_NO_ERR ) {
        FatalError( rc1 );
    }
    DoVersion();
    rc1 = InitMenu();
    if( rc1 != ERR_NO_ERR ) {
        FatalError( rc1 );
    }
    EditFlags.SpinningOurWheels = true;
    EditFlags.ClockActive = true;
    EditFlags.DisplayHold = true;
    rc1 = NewStatusWindow();
    if( rc1 != ERR_NO_ERR ) {
        FatalError( rc1 );
    }
    EditFlags.DisplayHold = false;

    MaxMemFreeAfterInit = MemSize();

    /*
     * look for a tag: if there is one, set it up as the file to start
     */
    EditFlags.WatchForBreak = true;
    if( cTag != NULL && !EditFlags.NoInitialFileLoad ) {
#if defined( __NT__ ) && !defined( __WIN__ )
        {
            if( !EditFlags.Quiet ) {
                SetConsoleActiveScreenBuffer( OutputHandle );
            }
        }
#endif
        rc1 = LocateTag( cTag, file, buff );
        cFN = file;
        if( rc1 != ERR_NO_ERR ) {
            if( rc1 == ERR_TAG_NOT_FOUND ) {
                Error( GetErrorMsg( rc1 ), cTag );
                ExitEditor( 0 );
            }
            FatalError( rc1 );
        }
    }

    /*
     * start specified file(s)
     */
    cmd[0] = 'e';
    cmd[1] = 0;

    arg = argc - 1;
    k = 1;
    while( !EditFlags.NoInitialFileLoad ) {

        if( cFN == nullFN && !EditFlags.UseNoName ) {
            break;
        }

#ifdef __NT__
        {
            int     k2;
            int     arg2;
            char    path[_MAX_PATH];
            int     found;
            int     fd;
            size_t  len;
            size_t  len1;
            char    *p;

            /*
             * check for the existence of a file name containing spaces, and open it if
             * there is one
             */
            len = _MAX_PATH - 1;
            found = 0;
            p = path;
            arg2 = arg;
            for( k2 = k; argv[k2] != NULL; ) {
                len1 = strlen( argv[k2] );
                if( len1 > len )
                    break;
                memcpy( p, argv[k2], len1 );
                p += len1;
                *p = '\0';
                len -= len1;
                --arg2;
                ++k2;
                fd = open( path, O_RDONLY );
                if( fd != -1 ) {
                    close( fd );
                    k = k2;
                    arg = arg2;
                    found = 1;
                    break;
                }
                *p++ = ' ';
            }
            if( found ) {
#ifndef __UNIX__
                len1 = strlen( path );
                if( path[len1 - 1] == '.' )
                    path[len1 - 1] = '\0';
#endif
                rc1 = NewFile( path, false );
                if( rc1 != ERR_NO_ERR ) {
                    FatalError( rc1 );
                }
                cFN = argv[k];
                if( arg < 1 ) {
                    break;
                }
                continue;
            }
        }
#endif

        strcat( cmd, SingleBlank );
        strcat( cmd, cFN );
        ocnt = cnt = ExpandFileNames( cFN, &list );
        if( cnt == 0 ) {
            cnt = 1;
        } else {
            cFN = list[0];
        }

        for( j = 0; j < cnt; j++ ) {
            rc1 = NewFile( cFN, false );
            if( rc1 != ERR_NO_ERR && rc1 != NEW_FILE ) {
                FatalError( rc1 );
            }
            if( EditFlags.BreakPressed ) {
                break;
            }
            if( cnt > 0 && j < cnt - 1 ) {
                cFN = list[j + 1];
            }
        }
        if( ocnt > 0 ) {
            MemFreeList( ocnt, list );
        }
        if( EditFlags.BreakPressed ) {
            ClearBreak();
            break;
        }
        k++;
        arg--;
        if( cTag != NULL || arg < 1 ) {
            break;
        }
        cFN = argv[k];
    }
    if( EditFlags.StdIOMode ) {
        rc1 = NewFile( "stdio", false );
        if( rc1 != ERR_NO_ERR ) {
            FatalError( rc1 );
        }
    }
    EditFlags.WatchForBreak = false;
    EditFlags.Starting = false;

    /*
     * if there was a tag, do the appropriate search
     */
    if( cTag != NULL && !EditFlags.NoInitialFileLoad ) {
        if( buff[0] != '/' ) {
            i = atoi( buff );
            rc1 = GoToLineNoRelCurs( i );
        } else {
            rc1 = FindTag( buff );
        }
        if( rc1 > 0 ) {
            Error( GetErrorMsg( rc1 ) );
        }
    }

    /*
     * try to run startup file
     */
    if( EditFlags.RecoverLostFiles ) {
        startcnt = 0;
    }
    for( i = 0; i < startcnt; i++ ) {
        GetFromEnv( startup[i], tmp );
        ReplaceString( &cfgFN, tmp );
        if( cfgFN[0] != 0 ) {
            if( startup_parms[i] != NULL ) {
                parm = startup_parms[i];
            } else {
                c[0] = 0;
                parm = c;
            }
#if defined( __NT__ ) && !defined( __WIN__ )
            {
                if( !EditFlags.Quiet ) {
                    SetConsoleActiveScreenBuffer( OutputHandle );
                }
            }
#endif
            sline = 0;
            rc = Source( cfgFN, parm, &sline );
        }
    }
    if( rc > ERR_NO_ERR ) {
        Error( "%s on line %u of \"%s\"", GetErrorMsg( rc ), sline, cfgFN );
    }
    if( argc == 1 ) {
        LoadHistory( NULL );
    } else {
        LoadHistory( cmd );
    }
    if( EditVars.GrepDefault == NULL ) {
        EditVars.GrepDefault = DupString( "*.(c|h)" );
    }
    if( goCmd[0] != 0 ) {
        KeyAddString( goCmd );
    }
    if( keysToPush != NULL ) {
        KeyAddString( keysToPush );
    }
#ifdef __WIN__
    if( lineToGoTo != 0 ) {
        SetCurrentLine( lineToGoTo );
        NewCursor( CurrentWindow, EditVars.NormalCursorType );
    }
#endif
    AutoSaveInit();
    HalfPageLines = WindowAuxInfo( CurrentWindow, WIND_INFO_TEXT_LINES ) / 2 - 1;
#if defined( _M_X64 )
    VarAddGlobalStr( "OSX64", "1" );
#elif defined( _M_IX86 ) && !defined( _M_I86 )
    VarAddGlobalStr( "OS386", "1" );
#endif
    if( EditVars.StatusString == NULL ) {
        EditVars.StatusString = DupString( "L:$6L$nC:$6C" );
    }
    UpdateStatusWindow();
#ifdef __WIN__
    if( CurrentInfo == NULL ) {
        // no file loaded - screen is disconcertenly empty - reassure
        DisplayFileStatus();
    }
#endif
    NewCursor( CurrentWindow, EditVars.NormalCursorType );
#if defined( __NT__ ) && !defined( __WIN__ )
    {
        SetConsoleActiveScreenBuffer( OutputHandle );
    }
#endif

} /* doInitializeEditor */
예제 #2
0
파일: delete.c 프로젝트: unizeto/bmd
/**
*Obsluzenie zadania ponownej wysylki awizo na poziomie datagramsetu
*
*@param[in] void *hDB		- wskaznik do uchwytu ustanowionego polaczenia z baza danych
*@param[in] bmdDatagramSet_t *bmdJSRequestSet	- wskaznik na datagram zadania
*@param[in] bmdDatagramSet_t **bmdJSResponseSet	- wskaznik na datagram odpowiedzi
*
*@retval BMD_OK 			- zakonczenie pomyslne.
*@retval BMD_ERR_OP_FAILED		- nieudana operacja
*@retval NO_MEMORY			- blad zasobow pamieci
*@retval BMD_ERR_PARAM1			- niepoprawny wskaznik do uchwytu ustanowionego polaczenia z baza danych
*@retval BMD_ERR_PARAM2			- niepoprawny wskaznik do lancucha znakowego z id crypto objecta
*@retval BMD_ERR_PARAM4			- niepoprawny wskaznik na GenBuf'a zawierajacego id grupy, do ktorej nalezy uzytkownik
*/
#ifndef WIN32
long JS_bmdDatagramSet_to_send_avizo(	void *hDB,
					bmdDatagramSet_t *bmdJSRequestSet,
					bmdDatagramSet_t **bmdJSResponseSet,
					server_request_data_t *req)
#else /*WIN32*/
long JS_bmdDatagramSet_to_send_avizo(	void *hDB,
					bmdDatagramSet_t *bmdJSRequestSet,
					bmdDatagramSet_t **bmdJSResponseSet,
					server_request_data_t *req,
					HANDLE *threadHandler)
#endif /*ifndef WIN32*/
{
long err		= 0;
long i			= 0;
long status		= 0;
char *hash		= NULL;
char *tmp_id		= NULL;


	PRINT_INFO("LIBBMDSQLINF Sending avizo (datagramset)\n");
	/******************************/
	/*	walidacja parametrow	*/
	/******************************/
	if (hDB==NULL)	{	BMD_FOK(BMD_ERR_PARAM1);	}
	if (bmdJSRequestSet==NULL)		{	BMD_FOK(BMD_ERR_PARAM2);	}

	/************************************************/
	/*	przygotowanie datagramsetu odpowiedzi	*/
	/************************************************/
	BMD_FOK(PR2_bmdDatagramSet_fill_with_datagrams(bmdJSRequestSet->bmdDatagramSetSize, bmdJSResponseSet));

	for(i=0; i < bmdJSRequestSet->bmdDatagramSetSize; i++, err=0)
	{
		free0(tmp_id);

		/************************************************/
		/* przepisanie zadajacego do odpowiedzi serwera */
		/************************************************/
		if (bmdJSRequestSet->bmdDatagramSetTable[i]->protocolDataOwner!=NULL)
		{
			if (bmdJSRequestSet->bmdDatagramSetTable[i]->protocolDataOwner->buf!=NULL)
			{
				(*bmdJSResponseSet)->bmdDatagramSetTable[i]->protocolDataOwner=(GenBuf_t *)malloc(sizeof(GenBuf_t));
				(*bmdJSResponseSet)->bmdDatagramSetTable[i]->protocolDataOwner->buf=(char*)malloc(bmdJSRequestSet->bmdDatagramSetTable[i]->protocolDataOwner->size+2);
				memset((*bmdJSResponseSet)->bmdDatagramSetTable[i]->protocolDataOwner->buf, 0,bmdJSRequestSet->bmdDatagramSetTable[i]->protocolDataOwner->size+1);
				memmove((*bmdJSResponseSet)->bmdDatagramSetTable[i]->protocolDataOwner->buf,bmdJSRequestSet->bmdDatagramSetTable[i]->protocolDataOwner->buf,bmdJSRequestSet->bmdDatagramSetTable[i]->protocolDataOwner->size);
				(*bmdJSResponseSet)->bmdDatagramSetTable[i]->protocolDataOwner->size=bmdJSRequestSet->bmdDatagramSetTable[i]->protocolDataOwner->size;
			}
		}

		/************************************************************************/
		/*	sprawdzenie, czy wczesniej nie wykryto bledu w datagramie zadania	*/
		/************************************************************************/
		if (bmdJSRequestSet->bmdDatagramSetTable[i]->datagramStatus<BMD_OK)
		{
			(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramStatus=bmdJSRequestSet->bmdDatagramSetTable[i]->datagramStatus;
			(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramType=bmdJSRequestSet->bmdDatagramSetTable[i]->datagramType+100;
			continue;
		}

		// sparametryzowana wysylka awizo moze odbywac sie na podstawie bmdId albo na podstawie wartosci metadanych
		if(bmdJSRequestSet->bmdDatagramSetTable[i]->datagramType == BMD_DATAGRAM_TYPE_SEND_ADVICE_WITH_PARAMETERS)
		{
			if(bmdJSRequestSet->bmdDatagramSetTable[i]->protocolDataFileId == NULL) // zadanie wywolane z podaniem bmdId
			{
				status = VerifyPermissionsForCryptoObjectByMetadata(hDB, req,
					bmdJSRequestSet->bmdDatagramSetTable[i],
					CONSIDER_CREATOR_OR_OWNER_OR_GROUPS,
					NULL/*fileName*/,
					NULL/*fileType*/,
					&tmp_id/*pointingId*/,
					NULL/*correspondingId*/,
					NULL/*forGrant*/,
					NULL/*additionalMetadataCount*/,
					NULL/*additionalMetadataValues*/);
			}
			else // zadanie wywolane z podaniem metadanych opisujacych dokument (nie bmdId)
			{
				status = VerifyPermissionsForCryptoObject(hDB, req,
					bmdJSRequestSet->bmdDatagramSetTable[i]->protocolDataFileId->buf,
					CONSIDER_CREATOR_OR_OWNER_OR_GROUPS,
					NULL/*fileName*/,
					NULL/*fileType*/,
					NULL/*pointingId*/,
					NULL/*correspondingId*/,
					NULL/*forGrant*/,
					NULL/*additionalMetadataCount*/,
					NULL/*additionalMetadataValues*/);

				tmp_id = strdup(bmdJSRequestSet->bmdDatagramSetTable[i]->protocolDataFileId->buf);
			}
		}
		else // dla innych typow zadan wysylka awizo moze odbyc sie tylko na podstawie bmdId
		{
			if(bmdJSRequestSet->bmdDatagramSetTable[i]->protocolDataFileId == NULL)
				{ BMD_FOK(BMD_ERR_PARAM2); }

			status = VerifyPermissionsForCryptoObject(hDB, req,
				bmdJSRequestSet->bmdDatagramSetTable[i]->protocolDataFileId->buf,
				CONSIDER_CREATOR_OR_OWNER_OR_GROUPS,
				NULL/*fileName*/,
				NULL/*fileType*/,
				NULL/*pointingId*/,
				NULL/*correspondingId*/,
				NULL/*forGrant*/,
				NULL/*additionalMetadataCount*/,
				NULL/*additionalMetadataValues*/);

			tmp_id = strdup(bmdJSRequestSet->bmdDatagramSetTable[i]->protocolDataFileId->buf);
		}
		
		//status=CheckIfCryptoObjectExist( hDB, bmdJSRequestSet->bmdDatagramSetTable[i], 0, &tmp_id, NULL, &tmp_location, NULL, NULL, NULL, NULL, req);
		if (status<BMD_OK)
		{
			PRINT_ERROR("LIBBMDSQLERR %s. Error=%li\n",GetErrorMsg(status), status);
			err=status;
			(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramStatus=status;
			(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramType=bmdJSRequestSet->bmdDatagramSetTable[i]->datagramType+100;
			continue;
		}


// 		/************************************************************************/
// 		/*	przepisanie id pliku z datagramu requesta do datagramu responsa	*/
// 		/************************************************************************/
// 		asprintf(&tmp_id,"%s",(char *)bmdJSRequestSet->bmdDatagramSetTable[i]->protocolDataFileId->buf);
// 		if (tmp_id==NULL)
// 		{
// 			PRINT_ERROR("LIBBMDSQLERR Memory error. Error=%i\n",NO_MEMORY);
// 			err=NO_MEMORY;
// 			PR_bmdDatagram_PrepareResponse(	&((*bmdJSResponseSet)->bmdDatagramSetTable[i]),
// 									bmdJSRequestSet->bmdDatagramSetTable[i]->datagramType+100,
// 									err);
// 			continue;
// 		}
//
// 		/************************************************/
// 		/* przepisanie id lokalizacji pliku z datagramu */
// 		/************************************************/
// 		asprintf(&tmp_location,"%s",(char *)bmdJSRequestSet->bmdDatagramSetTable[i]->protocolDataFileLocationId->buf);
// 		if (tmp_location==NULL)
// 		{
// 			PRINT_ERROR("LIBBMDSQLERR Memory error. Error=%i\n",NO_MEMORY);
// 			err=NO_MEMORY;
// 			PR_bmdDatagram_PrepareResponse(	&((*bmdJSResponseSet)->bmdDatagramSetTable[i]),
// 									bmdJSRequestSet->bmdDatagramSetTable[i]->datagramType+100,
// 									err);
// 			continue;
// 		}
//

		status = set_gen_buf2( tmp_id, (long)strlen(tmp_id), &((*bmdJSResponseSet)->bmdDatagramSetTable[i]->protocolDataFileId));
		if (status!=BMD_OK)
		{
			PRINT_ERROR("LIBBMDSQLERR Memory error. Error=%i\n",NO_MEMORY);
			err=status;
			(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramStatus=status;
			(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramType=bmdJSRequestSet->bmdDatagramSetTable[i]->datagramType+100;
			continue;
		}

		status = set_gen_buf2(_GLOBAL_bmd_configuration->location_id, (long)strlen(_GLOBAL_bmd_configuration->location_id), &((*bmdJSResponseSet)->bmdDatagramSetTable[i]->protocolDataFileLocationId));
		if (status!=BMD_OK)
		{
			PRINT_ERROR("LIBBMDSQLERR Memory error. Error=%i\n",NO_MEMORY);
			err=status;
			(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramStatus=status;
			(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramType=bmdJSRequestSet->bmdDatagramSetTable[i]->datagramType+100;
			continue;
		}

		/******************************************************/
		/*	pobranie hasha pliku na podstawienie id pliku	*/
		/******************************************************/
		status=GetHashFromId(hDB, tmp_id, _GLOBAL_bmd_configuration->location_id, &hash);
		if (status<BMD_OK)
		{
			PRINT_ERROR("LIBBMDSQLERR Error in getting recipient's e-mail\n");
			err=status;
			(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramStatus=status;
			(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramType=bmdJSRequestSet->bmdDatagramSetTable[i]->datagramType+100;
			continue;
		}

		/******************************************/
		/*	dolaczenie hasha do datagaramu	*/
		/******************************************/
		status=bmd_add_hash_to_dtg_as_data(hash,&((*bmdJSResponseSet)->bmdDatagramSetTable[i]));
		if (status<BMD_OK)
		{
			PRINT_ERROR("LIBBMDSQLERR Error adding hash to datagram. Error=%li\n",status);
			err=status;
			(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramStatus=status;
			(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramType=bmdJSRequestSet->bmdDatagramSetTable[i]->datagramType+100;
			continue;
		}

		/************************************************/
		/*	ustawienie statusu bledu datagramu	*/
		/************************************************/
		(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramStatus =(long ) err;
		(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramType = bmdJSRequestSet->bmdDatagramSetTable[i]->datagramType+100;

		/************************************************************/
		/*	pobranie metadanych pliku na podstawienie id pliku	*/
		/************************************************************/
		BMD_FOK(FillFromAllMetadata(	hDB,
						tmp_id,
						_GLOBAL_bmd_configuration->location_id,
						WITHOUT_PKI_METADATA,
						WITH_ADD_METADATA,
						WITH_SYS_METADATA,
						WITHOUT_ACTION_METADATA,
						(*bmdJSResponseSet)->bmdDatagramSetTable[i],req));

		// skopiowanie pamametrow wysylki awizo z zadania do odpowiedzi (bo wysylka odbywa sie na podstawie odpowiedzi)
		if(bmdJSRequestSet->bmdDatagramSetTable[i]->datagramType == BMD_DATAGRAM_TYPE_SEND_ADVICE_WITH_PARAMETERS)
		{
			BMD_FOK( CopySendAdviceParameters(bmdJSRequestSet->bmdDatagramSetTable[i], (*bmdJSResponseSet)->bmdDatagramSetTable[i]) );
		}
	}

	/************************************************/
	/*	wysylka maili z awizo do klientow	*/
	/************************************************/
	if(_GLOBAL_bmd_configuration->session_plugin_conf.bmd_plugin_action_post!=NULL)
	{

// 		if ((char *)_GLOBAL_bmd_configuration->additional_db_conninfo!=NULL)
// 		{
// #ifndef WIN32
//
// 			status=_GLOBAL_bmd_configuration->session_plugin_conf.bmd_plugin_action_post(	*bmdJSResponseSet,
// 																_GLOBAL_bmd_configuration->additional_db_conninfo,
// 																0,0,1,req);
// #else /*WIN32*/
//
// 			status=_GLOBAL_bmd_configuration->session_plugin_conf.bmd_plugin_action_post(	*bmdJSResponseSet,
// 																_GLOBAL_bmd_configuration->additional_db_conninfo,
// 																0,0,1,req, threadHandler);
// #endif /*ifndef WIN32*/
//
// 		}
// 		else
// 		{
#ifndef WIN32

			status=_GLOBAL_bmd_configuration->session_plugin_conf.bmd_plugin_action_post(	*bmdJSResponseSet,
																_GLOBAL_bmd_configuration->db_conninfo,
																0,0,1,req);
#else /*WIN32*/

			status=_GLOBAL_bmd_configuration->session_plugin_conf.bmd_plugin_action_post(	*bmdJSResponseSet,
																_GLOBAL_bmd_configuration->db_conninfo,
																0,0,1,req, threadHandler);

#endif /*ifndef WIN32*/
// 		}


		if (status<BMD_OK)
		{
			for(i=0; i<(long)bmdJSRequestSet->bmdDatagramSetSize; i++, err=0)
			{
				(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramStatus=status;
				(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramType=bmdJSRequestSet->bmdDatagramSetTable[i]->datagramType+100;
			}

		}

		/* rejestracja odbywa sie na zewnatrz w js.c
		// zarejestrowanie akcji w bazie danych
		if (_GLOBAL_bmd_configuration->messaging_plugin_conf.bmd_messaging_plugin_register_action)
		{
			for(i=0; i<(long)bmdJSRequestSet->bmdDatagramSetSize; i++)
			{
				status=_GLOBAL_bmd_configuration->messaging_plugin_conf.bmd_messaging_plugin_register_action(hDB, bmdJSRequestSet->bmdDatagramSetTable[i], (*bmdJSResponseSet)->bmdDatagramSetTable[i], req);
				if (status<BMD_OK)
				{
					(*bmdJSResponseSet)->bmdDatagramSetTable[i]->datagramStatus = status;
				}
			}
		}
		*/


	}
	else
	{
		BMD_FOK(PLUGIN_SESSION_NOT_RUNNING);
	}

	/************/
	/* porzadki */
	/************/
	free0(hash);
	free0(tmp_id);

	return BMD_OK;
}
예제 #3
0
/*
 * PreProcess - pre-process source file
 */
vi_rc PreProcess( const char *fn, sfile **sf, labels *lab )
{
    GENERIC_FILE        gf;
    int                 i, token, k, len;
    sfile               *tsf;
    char                tmp[MAX_SRC_LINE], tmp2[MAX_SRC_LINE];
    char                tmp3[MAX_SRC_LINE];
    bool                ret;
#ifdef VICOMP
    bool                AppendingFlag = FALSE;
#else
    #define             AppendingFlag   EditFlags.Appending
#endif

    /*
     * get source file
     */
#ifdef VICOMP
    ret = SpecialOpen( fn, &gf );
#else
    if( EditFlags.CompileScript ) {
        EditFlags.OpeningFileToCompile = TRUE;
        ret = SpecialOpen( fn, &gf, FALSE );
        EditFlags.OpeningFileToCompile = FALSE;
    } else {
        ret = SpecialOpen( fn, &gf, EditFlags.BoundData );
    }
#endif
    if( !ret ) {
        return( ERR_FILE_NOT_FOUND );
    }

    /*
     * init control
     */
    CSInit();
    CurrentSrcLine = 0L;

    tsf = MemAlloc( sizeof( sfile ) );
    tsf->next = NULL;
    tsf->prev = NULL;
    tsf->arg1 = NULL;
    tsf->arg2 = NULL;
    tsf->data = NULL;
    tsf->token = SRC_T_NULL;
    *sf = tmpTail = tsf;
    cLab = lab;

    /*
     * set up error handler
     */
    i = setjmp( genExit );
    if( i != 0 ) {
        SpecialFclose( &gf );
        return( (vi_rc)i );
    }

    /*
     * process each line
     */
    while( SpecialFgets( tmp, MAX_SRC_LINE - 1, &gf ) >= 0 ) {

        /*
         * prepare this line
         */
        CurrentSrcLine++;
#ifndef VICOMP
        if( !EditFlags.ScriptIsCompiled ) {
#endif
            RemoveLeadingSpaces( tmp );
            k = strlen( tmp );
            memcpy( tmp3, tmp, k + 1 );
            if( (len = NextWord1( tmp, tmp2 )) <= 0 ) {
                continue;
            }
            if( tmp2[0] == '#' ) {
                continue;
            }
            hasVar = FALSE;
            for( i = 0; i < k; i++ ){
                if( tmp3[i] == '%' ) {
                    hasVar = TRUE;
                    break;
                }
            }

            /*
             * if we are appending (ie, an append token was encounterd
             * before, stop tokenizing
             */
            if( !AppendingFlag ) {
                token = Tokenize( SourceTokens, tmp2, TRUE );
#ifndef VICOMP
                if( token == SRC_T_VBJ__ ) {
                    EditFlags.ScriptIsCompiled = TRUE;
                    continue;
                }
#endif
            } else {
                token = TOK_INVALID;
            }
#ifndef VICOMP
        } else {
            len = NextWord1( tmp, tmp2 );
            hasVar = (bool) tmp2[0] - '0';
            token = atoi( &tmp2[1] );
        }
#endif
        /*
         * process recognized tokens
         */
        if( token != TOK_INVALID ) {

            RemoveLeadingSpaces( tmp );
            if( token > SRC_T_NULL ) {
                genItem( token, tmp );
                continue;
            }

            /*
             * get parm
             */
            AddString( &CurrentSrcData, tmp );
            freeSrcData = TRUE;

            /*
             * process token
             */
            switch( token ) {
            case SRC_T_EXPR:
                genExpr();
                break;
            case SRC_T_LABEL:
                GenLabel( tmp );
                break;
            case SRC_T_IF:
                CSIf();
                break;
            case SRC_T_QUIF:
                CSQuif();
                break;
            case SRC_T_ELSEIF:
                CSElseIf();
                break;
            case SRC_T_ELSE:
                CSElse();
                break;
            case SRC_T_ENDIF:
                CSEndif();
                break;
            case SRC_T_LOOP:
                CSLoop();
                break;
            case SRC_T_ENDLOOP:
            case SRC_T_ENDWHILE:
                CSEndLoop();
                break;
            case SRC_T_WHILE:
                CSWhile();
                break;
            case SRC_T_UNTIL:
                CSUntil();
                break;
            case SRC_T_BREAK:
                CSBreak();
                break;
            case SRC_T_CONTINUE:
                CSContinue();
                break;
            default:
                genItem( token, NULL );
                if( token == SRC_T_GOTO ) {
#ifndef VICOMP
                    if( EditFlags.ScriptIsCompiled ) {
                        NextWord1( CurrentSrcData, tmp );
                        tmpTail->branchcond = atoi( CurrentSrcData );
                        strcpy( CurrentSrcData, tmp );
                    } else {
#endif
                        tmpTail->branchcond = COND_JMP;
#ifndef VICOMP
                    }
#endif
                }
                tmpTail->data = CurrentSrcData;
                freeSrcData = FALSE;
                break;
            }
            if( freeSrcData ) {
                MemFree( CurrentSrcData );
            }
        /*
         * set all other tokens to be processed at run time
         */
        } else {
#ifndef VICOMP
            if( EditFlags.ScriptIsCompiled ) {
                RemoveLeadingSpaces( tmp );
                genItem( token, tmp );
                continue;
            }
#endif
            if( !AppendingFlag ) {
                token = Tokenize( TokensCmdLine, tmp2, TRUE );
            } else {
                token = TOK_INVALID;
            }
            switch( token ) {
            case PCL_T_COMMANDWINDOW:
            case PCL_T_STATUSWINDOW:
            case PCL_T_COUNTWINDOW:
            case PCL_T_EDITWINDOW:
            case PCL_T_EXTRAINFOWINDOW:
            case PCL_T_FILECWINDOW:
            case PCL_T_LINENUMBERWINDOW:
            case PCL_T_DIRWINDOW:
            case PCL_T_FILEWINDOW:
            case PCL_T_SETWINDOW:
            case PCL_T_SETVALWINDOW:
            case PCL_T_MESSAGEWINDOW:
            case PCL_T_MENUWINDOW:
            case PCL_T_MENUBARWINDOW:
            case PCL_T_ENDWINDOW:
            case PCL_T_SETCOLOR:
            case PCL_T_MATCH:
            case PCL_T_DIMENSION:
            case PCL_T_BORDER:
            case PCL_T_HILIGHT:
            case PCL_T_TEXT:
            case PCL_T_ALIAS:
            case PCL_T_ABBREV:
            case PCL_T_MENU:
            case PCL_T_MENUITEM:
            case PCL_T_ENDMENU:
            case PCL_T_WHITESPACE:
            case PCL_T_SELECTION:
            case PCL_T_EOFTEXT:
            case PCL_T_KEYWORD:
            case PCL_T_OCTAL:
            case PCL_T_HEX:
            case PCL_T_INTEGER:
            case PCL_T_CHAR:
            case PCL_T_PREPROCESSOR:
            case PCL_T_SYMBOL:
            case PCL_T_INVALIDTEXT:
            case PCL_T_IDENTIFIER:
            case PCL_T_JUMPLABEL:
            case PCL_T_COMMENT:
            case PCL_T_FLOAT:
            case PCL_T_STRING:
            case PCL_T_VARIABLE:
            case PCL_T_FILETYPESOURCE:
            case PCL_T_ENDFILETYPESOURCE:
            case PCL_T_LOCATE:
            case PCL_T_MAP:
            case PCL_T_MAP_DMT:

            case PCL_T_MENUFILELIST:
            case PCL_T_MENULASTFILES:

            case PCL_T_DEFAULTWINDOW:
            case PCL_T_ACTIVEMENUWINDOW:
            case PCL_T_GREYEDMENUWINDOW:
            case PCL_T_ACTIVEGREYEDMENUWINDOW:
                RemoveLeadingSpaces( tmp );
                token += SRC_T_NULL + 1;
                genItem( token, tmp );
                break;

            case PCL_T_SET:
                token += SRC_T_NULL + 1;
#ifdef VICOMP
                WorkLine->data[0] = 0;
                Set( tmp );
                genItem( token, WorkLine->data );
#else
                if( EditFlags.CompileScript ) {
                    vi_rc   rc;

                    WorkLine->data[0] = 0;
                    rc = Set( tmp );
                    if( rc != ERR_NO_ERR ) {
                        Error( GetErrorMsg( rc ) );
                    }
                    genItem( token, WorkLine->data );
                } else {
                    genItem( token, tmp );
                }
#endif
                break;

            default:
                if( AppendingFlag ) {
                    if( tmp3[0] == '.' && tmp3[1] == 0 ) {
                        AppendingFlag = FALSE;
                    }
                } else if( token == TOK_INVALID ) {
                    /*
                     * see if the current token is a Ex token.  If
                     * it isn't, then see if the next one is
                     * (i.e., look for <n> append)
                     */
                    token = Tokenize( TokensEx, tmp2, FALSE );
                    if( token == TOK_INVALID ) {
                        if( NextWord1( tmp, tmp2 ) >= 0 ) {
                            token = Tokenize( TokensEx, tmp2, FALSE );
                            if( token == EX_T_APPEND ) {
                                AppendingFlag = TRUE;
                            }
                        }
                    }
                }
                if( tmp3[0] == '>' ) {
                    tmp3[0] = ' ';
                }
                genItem( TOK_INVALID, tmp3 );
                break;
            }
        }

    }

    SpecialFclose( &gf );
    AppendingFlag = FALSE;
    return( CSFini() );

} /* PreProcess */
예제 #4
0
static int QueryDNSListenUDP(void *ID){
	socklen_t			AddrLen;

	CompatibleAddr		ClientAddr;

	int					State;

	ThreadContext		Context;

	char				RequestEntity[1024];

	InitContext(&Context, RequestEntity);

	/* Listen and accept requests */
	while(TRUE)
	{
		memset(&ClientAddr, 0, sizeof(ClientAddr));

		GET_MUTEX(ListenMutex);

		if( Family == AF_INET )
		{
			AddrLen = sizeof(struct sockaddr);
			State = recvfrom(ListenSocketUDP,
							 RequestEntity,
							 sizeof(RequestEntity),
							 0,
							 (struct sockaddr *)&(ClientAddr.Addr4),
							 &AddrLen
							 );

		} else {
			AddrLen = sizeof(struct sockaddr_in6);
			State = recvfrom(ListenSocketUDP,
							 RequestEntity,
							 sizeof(RequestEntity),
							 0,
							 (struct sockaddr *)&(ClientAddr.Addr6),
							 &AddrLen
							 );

		}
		RELEASE_MUTEX(ListenMutex);

		if(State < 1)
		{
			if( ErrorMessages == TRUE )
			{
				int		ErrorNum = GET_LAST_ERROR();
				char	ErrorMessage[320];

				ErrorMessage[0] ='\0';

				GetErrorMsg(ErrorNum, ErrorMessage, sizeof(ErrorMessage));
				if( Family == AF_INET )
				{
					printf("An error occured while receiving from %s : %d : %s .\n",
						   inet_ntoa(ClientAddr.Addr4.sin_addr),
						   ErrorNum,
						   ErrorMessage
						   );
				} else {
					char Addr[LENGTH_OF_IPV6_ADDRESS_ASCII] = {0};

					IPv6AddressToAsc(&(ClientAddr.Addr6.sin6_addr), Addr);

					printf("An error occured while receiving from %s : %d : %s .\n",
						   Addr,
						   ErrorNum,
						   ErrorMessage
						   );

				}
			}
			continue;
		}

		Context.RequestLength = State;

		Query(&Context, &ClientAddr);
		ExtendableBuffer_Reset(Context.ResponseBuffer);

	}

	return 0;
}
예제 #5
0
/* Functions */
int QueryDNSListenUDPInit(ConfigFileInfo *ConfigInfo)
{
	CompatibleAddr ListenAddr;

	const char	*LocalAddr = ConfigGetRawString(ConfigInfo, "LocalInterface");

	int			LocalPort = ConfigGetInt32(ConfigInfo, "LocalPort");

	int			AddrLen;

	RefusingResponseCode = ConfigGetInt32(ConfigInfo, "RefusingResponseCode");

	Family = GetAddressFamily(LocalAddr);

	ListenSocketUDP = socket(Family, SOCK_DGRAM, IPPROTO_UDP);

	if(ListenSocketUDP == INVALID_SOCKET)
	{
		int		ErrorNum = GET_LAST_ERROR();
		char	ErrorMessage[320];
		ErrorMessage[0] = '\0';

		GetErrorMsg(ErrorNum, ErrorMessage, sizeof(ErrorMessage));

		ERRORMSG("Creating UDP socket failed. %d : %s\n",
				 ErrorNum,
				 ErrorMessage
				 );
		return -1;
	}

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

	if( Family == AF_INET )
	{
		FILL_ADDR4(ListenAddr.Addr4, AF_INET, LocalAddr, LocalPort);

		AddrLen = sizeof(struct sockaddr);
	} else {
		char Addr[LENGTH_OF_IPV6_ADDRESS_ASCII] = {0};

		sscanf(LocalAddr, "[%s]", Addr);

		ListenAddr.Addr6.sin6_family = Family;
		ListenAddr.Addr6.sin6_port = htons(LocalPort);
		IPv6AddressToNum(Addr, &(ListenAddr.Addr6.sin6_addr));

		AddrLen = sizeof(struct sockaddr_in6);
	}

	if(	bind(ListenSocketUDP, (struct sockaddr*)&(ListenAddr), AddrLen)
			!= 0
		)
	{
		int		ErrorNum = GET_LAST_ERROR();
		char	ErrorMessage[320];
		ErrorMessage[0] = '\0';

		GetErrorMsg(ErrorNum, ErrorMessage, sizeof(ErrorMessage));

		ERRORMSG("Opening UDP socket failed. %d : %s\n",
				 ErrorNum,
				 ErrorMessage
				 );
		return -2;
	}

	CREATE_MUTEX(ListenMutex);
	EFFECTIVE_LOCK_INIT(LockOfSendBack);

	MaximumMessageSize = GetMaximumMessageSize(ListenSocketUDP);
	if(MaximumMessageSize < 0)
	{
		MaximumMessageSize = 1000;
	}
	Inited = TRUE;

	return 0;
}
예제 #6
0
void WINAPI SVS_ServiceStart(DWORD argc , LPTSTR * argv)
{
	cout<<"Start SVS_ServiceStart"<<endl;
	WriteLog("Start SVS_ServiceStart");

	DWORD	status = 0;
	DWORD	specificError = 0;

	SVS_ServiceStatus.dwServiceType				= SERVICE_WIN32;
	SVS_ServiceStatus.dwCurrentState			= SERVICE_START_PENDING;
	SVS_ServiceStatus.dwControlsAccepted		= SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_PAUSE_CONTINUE;
	SVS_ServiceStatus.dwWin32ExitCode			= 0;
	SVS_ServiceStatus.dwServiceSpecificExitCode	= 0;
	SVS_ServiceStatus.dwCheckPoint				= 0;
	SVS_ServiceStatus.dwWaitHint				= 0;

	SVS_ServiceStatusHandle = ::RegisterServiceCtrlHandler("VALIDATESERVER" , SVS_ServiceCtrlHandler);
	if(SVS_ServiceStatusHandle == (SERVICE_STATUS_HANDLE)0)
	{
		WriteLog("RegisterServiceCtrlHandler failed!");
		char strErrMsg[1024] = {0};
		GetErrorMsg(strErrMsg);
		WriteLog(strErrMsg);
		return;
	}
	
	status = SVS_ServiceInitialization(argc,argv, &specificError); 

	if(status != NO_ERROR)
	{
		SVS_ServiceStatus.dwCurrentState       = SERVICE_STOPPED; 
        SVS_ServiceStatus.dwCheckPoint         = 0; 
        SVS_ServiceStatus.dwWaitHint           = 0; 
        SVS_ServiceStatus.dwWin32ExitCode      = status; 
        SVS_ServiceStatus.dwServiceSpecificExitCode = specificError; 
 
        SetServiceStatus (SVS_ServiceStatusHandle, &SVS_ServiceStatus); 

		WriteLog("服务初始化失败!\r\n");		
        return; 
	}

	SVS_ServiceStatus.dwCurrentState = SERVICE_RUNNING;
	SVS_ServiceStatus.dwCheckPoint = 0;
	SVS_ServiceStatus.dwWaitHint = 0;

	if (!SetServiceStatus (SVS_ServiceStatusHandle, &SVS_ServiceStatus)) 
    { 
		WriteLog("设置服务状态出错");
		char strErrMsg[1024] = {0};
		GetErrorMsg(strErrMsg);
		WriteLog(strErrMsg);
		return;
    }

	HANDLE	m_Handle = GetCurrentProcess();
	DWORD	iPriority = ::GetPriorityClass(m_Handle);
	::SetPriorityClass(m_Handle , HIGH_PRIORITY_CLASS);

	HANDLE	m_Thread = ::GetCurrentThread();
	::SetThreadPriority(m_Thread ,THREAD_PRIORITY_ABOVE_NORMAL);

	WriteLog("服务启动成功!");
    
	Run();
	MSG msg;
	while(::GetMessage(&msg,NULL,0,0))
	{
		DWORD time = msg.time;
		char strTemp[1024] = {0};
		sprintf(strTemp,"Send message time is :%ld" , time);
		WriteLog(strTemp);
		TranslateMessage(&msg);
		::DispatchMessage(&msg);
	}
}
예제 #7
0
/*
 * MainWindowProc - procedure for main (root) window
 */
WINEXPORT LRESULT CALLBACK MainWindowProc( HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam )
{
    RECT        rect;
    vi_rc       rc;
    HANDLE      hfileinfo;
    int         cnt, i;
    char        *buff;

    switch( msg ) {
    case WM_CREATE:
        Root = hwnd;
        GetClientRect( hwnd, &rect );
        EditContainer = CreateContainerWindow( &rect );
        InitWindows();
        DragAcceptFiles( hwnd, TRUE );
        timerID = SetTimer( hwnd, TIMER_ID, 60L * 1000L, NULL );
        break;
    case WM_DROPFILES:
        hfileinfo = (HANDLE) wparam;
        cnt = DragQueryFile( hfileinfo, (UINT)-1, NULL, 0 );
        buff = alloca( FILENAME_MAX + 2 );   /* we add a " at the beginning and at the end so we can handle path- and filenames with spaces */
        if( buff != NULL ) {
            buff[0] = '"';      /* one " at the beginning of the filename */
            for( i = 0; i < cnt; i++ ) {
                if( DragQueryFile( hfileinfo, i, buff + 1, FILENAME_MAX ) == (UINT)-1 ) {
                    break;
                }
                strcat( buff, SingleQuote );
                rc = EditFile( buff, false );
                if( rc > ERR_NO_ERR ) {
                    Error( GetErrorMsg( rc ) );
                }
            }
        }
        DragFinish( hfileinfo );
        break;
    case WM_TIMER:
        UpdateStatusWindow();
        break;
    case WM_KEYDOWN:
        if( WindowsKeyPush( wparam, HIWORD( lparam ) ) ) {
            return( 0 );
        }
        break;
    case WM_SIZE:
        DefFrameProc( hwnd, EditContainer, msg, wparam, lparam );
        RootState = wparam;
        if( wparam != SIZE_MINIMIZED ) {
            ResizeRoot();
            GetWindowRect( hwnd, &RootRect );
            if( wparam != SIZE_MAXIMIZED ) {
                RootState = 0;
            }
        }
        return( 0 );
    case WM_MOVE:
        DefFrameProc( hwnd, EditContainer, msg, wparam, lparam );
        if( RootState != SIZE_MINIMIZED ) {
            GetWindowRect( hwnd, &RootRect );
        }
        return( 0 );
    case WM_ACTIVATEAPP:
        if( BAD_ID( CurrentWindow ) ) {
            break;
        }
        SetFocus( Root );
#if 0
        if( !wparam ) {
            InactiveWindow( CurrentWindow );
        } else {
            SendMessage( EditContainer, WM_MDIACTIVATE, (WPARAM)CurrentWindow, 0L );
        }
#endif
        if( wparam ) {
            ResetEditWindowCursor( CurrentWindow );
        } else {
            GoodbyeCursor( CurrentWindow );
        }
        break;
    case WM_MOUSEACTIVATE:
        SetFocus( hwnd );
        return( MA_ACTIVATE );
    case WM_SETFOCUS:
        if( BAD_ID( CurrentWindow ) ) {
            break;
        }
        if( !IsIconic( CurrentWindow ) ) {
            SendMessage( EditContainer, WM_MDIACTIVATE, (WPARAM)CurrentWindow, 0L );
            DCUpdate();
            SetWindowCursor();
            SetWindowCursorForReal();
            return( 0 );
        }
        break;
    case WM_NCLBUTTONDBLCLK:
        break;
    case WM_COMMAND:
        if( LOWORD( wparam ) > 0xF000 ) {
            break;
        } else {
            rc = MenuCommand( LOWORD( wparam ) );
            if( rc != MENU_COMMAND_NOT_HANDLED ) {
                DCUpdateAll();
                if( rc > ERR_NO_ERR ) {
                    buff = GetErrorMsg( rc );
                    Error( buff );
                }
            }
            SetWindowCursor();
        }
        return( 0 );
    case WM_INITMENU:
        if( (HMENU)wparam == GetMenu( hwnd ) ) {
            HandleInitMenu( (HMENU)wparam );
        } else {
            ResetMenuBits();
        }
        break;
    case WM_MENUSELECT:
        HandleMenuSelect( wparam, lparam );
        break;
    case WM_ENDSESSION:
        if( wparam ) {
            ExitEditor( 0 );
            // will not return
        }
        return( 0 );
    case WM_QUERYENDSESSION:
        return( ExitWithPrompt( false, true ) );
    case WM_CLOSE:
        ExitWithPrompt( true, true );
        return( 0 );
#ifdef __NT__        
    case WM_MOUSEWHEEL:
        {
            int     increment;
            ULONG   linesPerNotch;
            HWND    activeWnd;

            activeWnd = (HWND)SendMessage( EditContainer, WM_MDIGETACTIVE, 0, 0 );
            SystemParametersInfo( SPI_GETWHEELSCROLLLINES, 0, &linesPerNotch, 0 );

            increment = GET_WHEEL_DELTA_WPARAM( wparam ) / 120;
                // see WM_MOUSEWHEEL-documentation for information about the "120"

            if( increment > 0 ) {
                for( i = 0; i < increment * (int)linesPerNotch; i++ ) {
                    SendMessage( activeWnd, WM_VSCROLL, SB_LINEUP, 0 );
                }
            } else {
                for( i = 0; i < (-increment) * (int)linesPerNotch; i++ ) {
                    SendMessage( activeWnd, WM_VSCROLL, SB_LINEDOWN, 0 );
                }
            }
        }
        return( 0 );
#endif
    case WM_DESTROY:
        DestroyToolBar();
        DragAcceptFiles( hwnd, FALSE );
        EditContainer = 0;
        if( timerID ) {
            KillTimer( hwnd, TIMER_ID );
        }
        return( 0 );
    }
    return( DefFrameProc( hwnd, EditContainer, msg, wparam, lparam ) );

} /* MainWindowProc */
예제 #8
0
/* Functions */
int QueryDNSListenTCPInit(void)
{
	static struct _Address	ListenAddr;

	const char	*LocalAddr = ConfigGetString(&ConfigInfo, "LocalInterface");
	int			LocalPort = ConfigGetInt32(&ConfigInfo, "LocalPort");

	int			AddrLen;

	Family = GetAddressFamily(LocalAddr);

	ListenSocketTCP = socket(Family, SOCK_STREAM, IPPROTO_TCP);
	if(ListenSocketTCP == INVALID_SOCKET)
	{
		int		ErrorNum = GET_LAST_ERROR();
		char	ErrorMessage[320];
		ErrorMessage[0] = '\0';

		GetErrorMsg(ErrorNum, ErrorMessage, sizeof(ErrorMessage));

		ERRORMSG("Creating TCP socket failed. %d : %s\n", ErrorNum, ErrorMessage);
		return -1;
	}

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

	if( Family == AF_INET )
	{
		FILL_ADDR4(ListenAddr.Addr.Addr4, AF_INET, LocalAddr, LocalPort);

		AddrLen = sizeof(struct sockaddr);
	} else {
		char Addr[LENGTH_OF_IPV6_ADDRESS_ASCII] = {0};

		sscanf(LocalAddr, "[%s]", Addr);

		ListenAddr.Addr.Addr6.sin6_family = Family;
		ListenAddr.Addr.Addr6.sin6_port = htons(LocalPort);
		IPv6AddressToNum(Addr, &(ListenAddr.Addr.Addr6.sin6_addr));

		AddrLen = sizeof(struct sockaddr_in6);
	}

	if(	bind(ListenSocketTCP, (struct sockaddr*)&(ListenAddr.Addr), AddrLen) != 0 )
	{
		int		ErrorNum = GET_LAST_ERROR();
		char	ErrorMessage[320];
		ErrorMessage[0] = '\0';

		GetErrorMsg(ErrorNum, ErrorMessage, sizeof(ErrorMessage));

		ERRORMSG("Opening TCP socket failed. %d : %s\n", ErrorNum, ErrorMessage);
		return -2;
	}

	if( listen(ListenSocketTCP, 16) == SOCKET_ERROR )
	{
		int		ErrorNum = GET_LAST_ERROR();
		char	ErrorMessage[320];
		ErrorMessage[0] = '\0';

		GetErrorMsg(ErrorNum, ErrorMessage, sizeof(ErrorMessage));

		ERRORMSG("Opening TCP socket failed. %d : %s\n", ErrorNum, ErrorMessage);
		return -3;
	}

	Inited = TRUE;

	return 0;
}
예제 #9
0
/*
 * RunCommandLine - run a command line command
 */
vi_rc RunCommandLine( const char *cmdl )
{
    int         i, x, y, x2, y2;
    bool        n1f, n2f;
    int         tkn, flag;
    bool        test1;
    linenum     n1, n2;
    char        st[FILENAME_MAX];
    info        *cinfo;
    long        val;
    jmp_buf     jmpaddr;
    vi_rc       rc;
    const char  *data;

    /*
     * parse command string
     */
    tkn = TOK_INVALID;
    rc = ParseCommandLine( cmdl, &n1, &n1f, &n2, &n2f, &tkn, &data );
    if( rc != ERR_NO_ERR ) {
        return( rc );
    }
    if( !n2f ) {
        if( !n1f ) {
            n1 = n2 = CurrentPos.line;
        } else {
            n2 = n1;
        }
    }

    /*
     * process tokens
     */
    rc = ERR_INVALID_COMMAND;
    test1 = n1f || n2f;
    switch( tkn ) {
    case PCL_T_ABOUT:
        rc = DoAboutBox();
        break;
    case PCL_T_PUSH:
        rc = PushFileStackAndMsg();
        break;
    case PCL_T_POP:
        rc = PopFileStack();
        break;
    case PCL_T_EXECUTE:
        data = SkipLeadingSpaces( data );
        if( *data != '\0' ) {
            key_map     scr;

            rc = AddKeyMap( &scr, data );
            if( rc != ERR_NO_ERR ) {
                break;
            }
            rc = RunKeyMap( &scr, 1L );
            MemFree( scr.data );
        }
        break;

    case PCL_T_DELETEMENU:
        rc = DoMenuDelete( data );
        break;
    case PCL_T_DELETEMENUITEM:
        rc = DoItemDelete( data );
        break;
    case PCL_T_ADDMENUITEM:
        rc = AddMenuItem( data );
        break;
    case PCL_T_MAXIMIZE:
        rc = MaximizeCurrentWindow();
        break;
    case PCL_T_MINIMIZE:
        rc = MinimizeCurrentWindow();
        break;
    case PCL_T_EXITFILESONLY:
        if( !ExitWithPrompt( false, false ) ) {
            rc = ERR_EXIT_ABORTED;
        } else {
            rc = ERR_NO_ERR;
        }
        break;
    case PCL_T_EXITALL:
        if( !ExitWithPrompt( true, false ) ) {
            rc = ERR_EXIT_ABORTED;
        } else {
            rc = ERR_NO_ERR;
        }
        break;
    case PCL_T_QUITALL:
        ExitWithVerify();
        rc = ERR_NO_ERR;
        break;
    case PCL_T_KEYADD:
        data = SkipLeadingSpaces( data );
        KeyAddString( data );
        rc = ERR_NO_ERR;
        break;

    case PCL_T_UNALIAS:
        rc = UnAlias( data );
        break;

    case PCL_T_UNABBREV:
        rc = UnAbbrev( data );
        break;

    case PCL_T_UNMAP:
    case PCL_T_UNMAP_DMT:
        flag = MAPFLAG_MESSAGE + MAPFLAG_UNMAP;
        if( tkn == PCL_T_UNMAP_DMT ) {
            flag |= MAPFLAG_DAMMIT;
        }
        rc = MapKey( flag, data );
        break;

    case PCL_T_EVAL:
        data = Expand( dataBuff, data, NULL );
        i = setjmp( jmpaddr );
        if( i != 0 ) {
            rc = (vi_rc)i;
        } else {
            StartExprParse( data, jmpaddr );
            val = GetConstExpr();
            ltoa( val, st, EditVars.Radix );
            Message1( "%s", st );
            rc = ERR_NO_ERR;
        }
        break;

    case PCL_T_COMPILE:
    case PCL_T_SOURCE:
    case PCL_T_LOAD:
        {
            char        *tstr;
            srcline     sline;

            data = GetNextWord1( data, st );
            if( *st == '\0' ) {
                rc = ERR_NO_FILE_SPECIFIED;
                break;
            }

            if( tkn == PCL_T_COMPILE ) {
                EditFlags.CompileScript = true;
                if( st[0] == '-' ) {
                    if( st[1] == 'a' || st[1] == 'A' ) {
                        EditFlags.CompileAssignments = true;
                        if( st[1] == 'A' ) {
                            EditFlags.CompileAssignmentsDammit = true;
                        }
                        data = GetNextWord1( data, st);
                        if( *st == '\0' ) {
                            rc = ERR_NO_FILE_SPECIFIED;
                            break;
                        }
                    }
                }
            }
            if( tkn == PCL_T_LOAD ) {
                EditFlags.LoadResidentScript = true;
            }
            sline = 0;
            rc = Source( st, data, &sline );

            EditFlags.LoadResidentScript = false;
            EditFlags.CompileScript = false;
            EditFlags.CompileAssignments = false;
            EditFlags.CompileAssignmentsDammit = false;
            if( EditFlags.SourceScriptActive ) {
                LastError = rc;
            }
            if( rc > ERR_NO_ERR ) {
                Error( "%s on line %u of \"%s\"", GetErrorMsg( rc ), sline, st );
            } else {
                if( rc != DO_NOT_CLEAR_MESSAGE_WINDOW ) {
                    if( tkn != PCL_T_SOURCE ) {
                        if( tkn == PCL_T_LOAD ) {
                            tstr = strLoad;
                        } else {
                            tstr = strCompile;
                        }
                        Message1( "Script \"%s\" %s, %u lines generated, %d errors",
                                        st, tstr, sline, SourceErrCount );
                        rc = DO_NOT_CLEAR_MESSAGE_WINDOW;
                    }
                }
            }
            break;
        }

    case PCL_T_GENCONFIG:
#ifndef __WIN__
        data = GetNextWord1( data,st );
        if( *st != '\0' ) {
            rc = GenerateConfiguration( st, true );
        } else {
            rc = GenerateConfiguration( NULL, true );
        }
#else
        {
            bool temp = EditFlags.SaveConfig;
            EditFlags.SaveConfig = true;
            WriteProfile();
            EditFlags.SaveConfig = temp;
            rc = ERR_NO_ERR;
        }
#endif
        break;

    case PCL_T_COMPRESS:
        rc = CompressWhiteSpace();
        break;

    case PCL_T_EXPAND:
        rc = ExpandWhiteSpace();
        break;

    case PCL_T_SHOVE:
        rc = Shift( n1, n2, '>', true );
        break;

    case PCL_T_SUCK:
        rc = Shift( n1, n2, '<', true );
        break;

    case PCL_T_FILES:
        if( EditFlags.LineDisplay ) {
            rc = DisplayFileStatus();
        } else {
            rc = EditFileFromList();
        }
        break;

    case PCL_T_NEXT:
        rc = RotateFileForward();
        break;

    case PCL_T_PREV:
        rc = RotateFileBackwards();
        break;

    case PCL_T_HELP:
        rc = DoHelp( data );
        break;

    case PCL_T_VIEW:
    case PCL_T_VIEW_DMT:
        EditFlags.ViewOnly = true;
    case PCL_T_EDIT:
    case PCL_T_EDIT_DMT:
        rc = EditFile( data, ( tkn == PCL_T_VIEW_DMT || tkn == PCL_T_EDIT_DMT ) );
        EditFlags.ViewOnly = false;
        break;

    case PCL_T_OPEN:
        rc = OpenWindowOnFile( data );
        break;

    case PCL_T_HIDE:
    case PCL_T_HIDE_DMT:
        rc = HideLineRange( n1, n2, ( tkn == PCL_T_HIDE_DMT ) );
        break;

    case PCL_T_DELETE:
        rc = SetSavebufNumber( data );
        if( rc != ERR_NO_ERR ) {
            break;
        }
        if( SelRgn.selected && !EditFlags.LineBased ) {
            AddSelRgnToSavebufAndDelete();
            rc = ERR_NO_ERR;
            // @ may have turned this on - it is now definitely off
            SelRgn.selected = false;
        } else {
            rc = DeleteLineRange( n1, n2, SAVEBUF_FLAG );
        }
        if( rc == ERR_NO_ERR ) {
            DCDisplayAllLines();
            LineDeleteMessage( n1, n2 );
        }
        break;

    case PCL_T_SAVEANDEXIT:
        data = GetNextWord1( data, st );
        if( *st == '\0' ) {
            rc = SaveAndExit( st );
        } else {
            rc = SaveAndExit( NULL );
        }
        break;

    case PCL_T_PUT:
    case PCL_T_PUT_DMT:
        rc = SetSavebufNumber( data );
        if( rc != ERR_NO_ERR ) {
            break;
        }
        rc = SaveAndResetFilePos( n1 );
        if( rc == ERR_NO_ERR ) {
            if( tkn == PCL_T_PUT ) {
                rc = InsertSavebufAfter();
            } else {
                rc = InsertSavebufBefore();
            }
            RestoreCurrentFilePos();
        }
        break;

    case PCL_T_YANK:
        rc = SetSavebufNumber( data );
        if( rc != ERR_NO_ERR ) {
            break;
        }
        if( SelRgn.selected && !EditFlags.LineBased ) {
            rc = YankSelectedRegion();
            // @ may have turned this on - it is now definitely off
            SelRgn.selected = false;
        } else {
            rc = YankLineRange( n1, n2 );
        }
        break;

    case PCL_T_SUBSTITUTE:
        rc = Substitute( n1, n2, data );
        break;

    case PCL_T_GLOBAL:
    case PCL_T_GLOBAL_DMT:
        if( !test1 ) {
            n1 = 1;
            rc = CFindLastLine( &n2 );
            if( rc != ERR_NO_ERR ) {
                break;
            }
        }
        rc = Global( n1,n2, data, ( tkn == PCL_T_GLOBAL_DMT ) );
        break;

    case PCL_T_WRITEQUIT:
        if( CurrentFile == NULL ) {
            rc = NextFile();
        } else {
            CurrentFile->modified = true;
            data = GetNextWord1( data, st );
            if( *st != '\0' ) {
                rc = SaveAndExit( st );
            } else {
                rc = SaveAndExit( NULL );
            }
        }
        break;

    case PCL_T_WRITE:
    case PCL_T_WRITE_DMT:
        data = GetNextWord1( data, st );
        if( test1 ) {
            if( *st == '\0' ) {
                rc = ERR_NO_FILE_SPECIFIED;
            } else {
                rc = SaveFile( st, n1, n2, ( tkn == PCL_T_WRITE_DMT ) );
            }
        } else {
            if( st[0] != '\0' ) {
#ifdef __WIN__
                if( st[0] == '?' && st[1] == '\0' ) {
                    rc = SaveFileAs();
                    break;
                } else {
                    rc = SaveFile( st, -1, -1, ( tkn == PCL_T_WRITE_DMT ) );
                }
#else
                rc = SaveFile( st, -1, -1, ( tkn == PCL_T_WRITE_DMT ) );
#endif
            } else {
                rc = SaveFile( NULL, -1, -1, ( tkn == PCL_T_WRITE_DMT ) );
                if( rc == ERR_NO_ERR ) {
                    Modified( false );
                }
            }
        }
        break;

    case PCL_T_READ:
        rc = ReadAFile( n1, data );
        break;

    case PCL_T_QUIT:
#ifdef __WIN__
        rc = CurFileExitOptionSaveChanges();
#else
        rc = NextFile();
#endif
        break;
    case PCL_T_QUIT_DMT:
        rc = NextFileDammit();
        break;

    case PCL_T_DATE:
        GetDateTimeString( st );
        Message1( st );
        rc = DO_NOT_CLEAR_MESSAGE_WINDOW;
        break;

    case PCL_T_CD:
        data = GetNextWord1( data, st );
        if( *st != '\0' ) {
            rc = SetCWD( st );
        } else {
            rc = ERR_NO_ERR;
        }
        if( rc == ERR_NO_ERR ) {
            Message1( "Current directory is %s",CurrentDirectory );
        }
        break;

    case PCL_T_SHELL:
    EVIL_SHELL:
        {
#if defined( __NT__ ) && !defined( __WIN__ )
            ExecCmd( NULL, NULL, NULL );
#else
            char foo[FILENAME_MAX];

            strcpy( foo, Comspec );
            ExecCmd( NULL, NULL, foo );
#endif
            DoVersion();
            rc = ERR_NO_ERR;
        }
        break;

    case PCL_T_SYSTEM:
        if( n1f && n2f ) {
            rc = DoGenericFilter( n1, n2, data );
        } else {
            data = SkipLeadingSpaces( data );
            if( *data == '\0' ) {
                goto EVIL_SHELL;
            }
            ExecCmd( NULL, NULL, data );
            rc = ERR_NO_ERR;
        }
        break;

    case PCL_T_RESIZE:
        rc = ResizeCurrentWindowWithKeys();
        break;

    case PCL_T_TILE:
        data = GetNextWord1( data, st );
        if( st[0] != '\0' ) {
            if( st[0] == 'v' ) {
                y = 1;
                for( x = 0, cinfo = InfoHead; cinfo != NULL; cinfo = cinfo->next ) {
                    x++;
                }
            } else if( st[0] == 'h' ) {
                x = 1;
                for( y = 0, cinfo = InfoHead; cinfo != NULL; cinfo = cinfo->next ) {
                    y++;
                }
            } else {
                x = atoi( st );
                data = GetNextWord1( data, st );
                if( *st == '\0' ) {
                    break;
                } else {
                    y = atoi( st );
                }
            }
        } else {
            x = EditVars.MaxWindowTileX;
            y = EditVars.MaxWindowTileY;
        }
        if( x > 0 && y > 0) {
            rc = WindowTile( x, y );
        }
        break;

    case PCL_T_CASCADE:
        rc = WindowCascade();
        break;

    case PCL_T_MOVEWIN:
        rc = MoveCurrentWindowWithKeys();
        break;

    case PCL_T_TAG:
        data = GetNextWord1( data, st );
        if( *st != '\0' ) {
            rc = TagHunt( st );
        }
        break;

    case PCL_T_FGREP:
        {
            bool        ci;

            data = SkipLeadingSpaces( data );
            ci = EditFlags.CaseIgnore;
            if( data[0] == '-' ) {
                if( data[1] == 'c' ) {
                    ci = false;
                    data += 2;
                    data = SkipLeadingSpaces( data );
                    rc = GetStringWithPossibleQuote( &data, st );
                } else if( data[1] == 'i' ) {
                    ci = true;
                    data += 2;
                    data = SkipLeadingSpaces( data );
                    rc = GetStringWithPossibleQuote( &data, st );
                } else if( data[1] == 'f' ) {
                    data += 2;
                    data = SkipLeadingSpaces( data );
#ifdef __WIN__
                    // call fancy grep window
                    {
                        fancy_find      *ff;
                        /* ff will be set to point at a static fancy find struct
                         * in the snoop module */
                        char snoopbuf[FILENAME_MAX];

                        if( !GetSnoopStringDialog( &ff ) ) {
                            return( ERR_NO_ERR );
                        }

                        strcpy( snoopbuf, ff->path );
                        /* assume no string means current directory */
                        if( strlen( snoopbuf ) &&
                            snoopbuf[strlen( snoopbuf ) - 1] != '\\' ){
                            strcat( snoopbuf, "\\" );
                        }
                        MySprintf( st, "%s", ff->find );
                        strcat( snoopbuf, ff->ext );
                        ci = ff->case_ignore;
                        if( !ff->use_regexp ) {
                            //MakeExpressionNonRegular( st );
                            rc = DoFGREP( snoopbuf, st, ci );
                        } else {
                            rc = DoEGREP( snoopbuf, st );
                        }
                        break;
                    }
#endif
                }
            } else {
                rc = GetStringWithPossibleQuote( &data, st );
            }
            if( rc != ERR_NO_STRING ) {
                rc = DoFGREP( data, st, ci );
            }
        }
        break;

    case PCL_T_EGREP:
        rc = GetStringWithPossibleQuote( &data, st );
        if( rc != ERR_NO_STRING ) {
            rc = DoEGREP( data, st );
        }
        break;

    case PCL_T_SIZE:
        data = GetNextWord1( data, st );
        if( *st == '\0' ) {
            break;
        }
        x = atoi( st );
        data = GetNextWord1( data, st );
        if( *st == '\0' ) {
            break;
        }
        y = atoi( st );
        data = GetNextWord1( data, st );
        if( *st == '\0' ) {
            break;
        }
        x2 = atoi( st );
        data = GetNextWord1( data, st );
        if( *st == '\0' ) {
            break;
        }
        y2 = atoi( st );
        rc = CurrentWindowResize( x, y, x2, y2 );
        break;

    case PCL_T_ECHO:
        data = GetNextWord1( data, st );
        if( *st == '\0' ) {
            break;
        }
        rc = ERR_NO_ERR;
        if( !stricmp( st, "on" ) ) {
            EditFlags.EchoOn = true;
            break;
        } else if( !stricmp( st, "off" ) ) {
            EditFlags.EchoOn = false;
            break;
        }
        x = atoi( st );
        data = SkipLeadingSpaces( data );
        /*
         * FIXME: This is not good - I will definately have to
         * fix this code up. But right now I have to get the
         * editor ready for tomorrow. Brad.
         */
        if( data[0] == '"' || data[0] == '/' ) {
            GetStringWithPossibleQuote( &data, st );
            if( x > 2 ) {
                /* this is obviously a sick individual */
                Error( "Invalid Echo" );
            } else if( x == 1 ) {
                Message1( st );
            } else if( x == 2 ) {
                Message2( st );
            }
            // DisplayLineInWindow( MessageWindow, x, st );
        } else {
            if( x > 2 ) {
                /* this is obviously a sick individual */
                Error( "Invalid Echo" );
            } else if( x == 1 ) {
                Message1( data );
            } else if( x == 2 ) {
                Message2( data );
            }
            // DisplayLineInWindow( MessageWindow, x, data );
        }
        break;
#ifdef VI_RCS
    case PCL_T_CHECKOUT:
        rc = ERR_NO_ERR;
#ifdef __WINDOWS__
        if( isOS2() ) break; // OS/2 shell returns before checkout finishes
#endif
        if( CurrentFile != NULL ) {
            rc = ViRCSCheckout( rc );
        }
        break;
    case PCL_T_CHECKIN:
        if( CurrentFile != NULL ) {
            rc = ViRCSCheckin( rc );
        }
        break;
#endif
    default:
        if( tkn >= 1000 ) {
            rc = ProcessEx( n1, n2, n2f, tkn - 1000, data );
            break;
        }
        rc = TryCompileableToken( tkn, data, true );
        if( rc != NOT_COMPILEABLE_TOKEN ) {
            break;
        }
        rc = ProcessWindow( tkn, data );
        if( rc >= ERR_NO_ERR ) {
            break;
        }
    case TOK_INVALID:
        if( n1f && !n2f ) {
            if( !n1 ) {
                n1 = 1;
            }
            MemorizeCurrentContext();
            rc = GoToLineNoRelCurs( n1 );
            if( rc == ERR_NO_ERR ) {
                GoToColumnOnCurrentLine( 1 );
                if( EditFlags.LineDisplay ) {
                    MyPrintf( "%s\n", CurrentLine->data );
                }
            }
            return( rc );
        }
        rc = ERR_INVALID_COMMAND;
        break;
    }

    if( rc == ERR_NO_ERR ) {
        rc = DO_NOT_CLEAR_MESSAGE_WINDOW;
    }
    return( rc );

} /* RunCommandLine */
예제 #10
0
bool CMySqlDatabase::BlobWriteDb( QString &strBlobFile, QString& strSql, QString& strError )
{
    QFile file( strBlobFile );
    bool bRet = false;

    if ( !file.exists( ) ) {
        return bRet;
    }

    bRet = file.open( QIODevice::ReadOnly );
    if ( !bRet ) {
        return bRet;
    }

    QByteArray byData = file.readAll( );
    file.close( );

    bRet = BlobWriteDb( byData, strSql, strError );

    return bRet;

#if false
    MYSQL_BIND bind[ 1 ];
    ulong       length = 0;

    hStmt = mysql_stmt_init( &hConnect );
    bRet = ( NULL != hStmt );
    if ( !bRet ) {
        GetErrorMsg( 0, strError, false, strSql );
        goto FileHandle;
    }

    byteSql = pCodec->fromUnicode( strSql );
    nSize = byteSql.count( );
    pSql = byteSql.data( );
    nRet = mysql_stmt_prepare( hStmt, pSql, nSize );
    bRet = ( 0 == nRet );
    if ( !bRet ){
        GetErrorMsg( nRet, strError, false, strSql );
        goto StmtHandle;
    }

    memset( bind, 0, sizeof ( bind ) );
    bind[ 0 ].buffer_type = MYSQL_TYPE_LONG_BLOB;
    bind[ 0 ].length = &length;
    bind[ 0 ].is_null = 0; /* Bind the buffers */
    //bind[ 0 ].buffer
    //bind[ 0 ].buffer_length

    bRet = ( 0 == mysql_stmt_bind_param( hStmt, bind ) );
    if ( !bRet ) {
        GetErrorMsg( 0, strError, false, strSql );
        goto StmtHandle;
    }

    byteSql = file.readAll( );
    nSize = byteSql.count( );
    pSql = byteSql.data( );
    if ( 0 < nSize ) {
        nRet = mysql_stmt_send_long_data( hStmt, 0, pSql, nSize );
        bRet = ( 0 == nRet );
        if ( !bRet ) {
            GetErrorMsg( nRet, strError, false, strSql );
            goto StmtHandle;
        }
    }

    nRet = mysql_stmt_execute( hStmt );
    bRet = ( 0 == nRet );
    if ( !bRet ) {
        GetErrorMsg( nRet, strError, false, strSql );
    }

    StmtHandle:
    bRet = ( 0 == mysql_stmt_close( hStmt ) );
    if ( !bRet ) {
        GetErrorMsg( 0, strError, false, strSql );
    }

    FileHandle:
    file.close( );

    return bRet;
#endif
}
예제 #11
0
static int Query(	SOCKET				*PrimarySocket,
					SOCKET				*SecondarySocket,
					DNSQuaryProtocol	PrimaryProtocol,
					char				*QueryContent,
					int					QueryContentLength,

					SOCKET				*ClientSocket,
					CompatibleAddr		*ClientAddr,
					ExtendableBuffer	*Buffer
					)
{
	int					State;

	DNSRecordType		SourceType;
	char				*DNSBody = DNSGetDNSBody(QueryContent);

	char				ProtocolCharacter = ' ';

	char				QueryDomain[256];

	char				DateAndTime[32];

	QueryContext		Context;

	GetCurDateAndTime(DateAndTime, sizeof(DateAndTime));

	QueryDomain[0] = '\0';
	DNSGetHostName(DNSBody, DNSJumpHeader(DNSBody), QueryDomain);

	SourceType = (DNSRecordType)DNSGetRecordType(DNSJumpHeader(DNSBody));

	Context.PrimarySocket = PrimarySocket;
	Context.SecondarySocket = SecondarySocket;
	Context.PrimaryProtocolToServer = PrimaryProtocol;
	Context.ProtocolToSrc = DNS_QUARY_PROTOCOL_TCP;
	Context.Compress = TRUE;

	State = QueryBase(&Context,

					  QueryContent,
					  QueryContentLength,

					  Buffer,
					  QueryDomain,
					  SourceType,
					  &ProtocolCharacter
					  );

	switch( State )
	{
		case QUERY_RESULT_DISABLE:
			((DNSHeader *)DNSBody) -> Flags.Direction = 1;
			((DNSHeader *)DNSBody) -> Flags.ResponseCode = 5;
			send(*ClientSocket, QueryContent, QueryContentLength, 0);
			if( Family == AF_INET )
			{
				PRINT("%s[R][%s:%d][%s][%s] Refused.\n", DateAndTime, inet_ntoa(ClientAddr -> Addr4.sin_addr), ClientAddr -> Addr4.sin_port, DNSGetTypeName(SourceType), QueryDomain);
			} else {
				char Addr[LENGTH_OF_IPV6_ADDRESS_ASCII] = {0};

				IPv6AddressToAsc(&(ClientAddr -> Addr6.sin6_addr), Addr);

				PRINT("%s[R][%s:%d][%s][%s] Refused.\n", DateAndTime, Addr, ClientAddr -> Addr6.sin6_port, DNSGetTypeName(SourceType), QueryDomain);

			}
			return -1;
			break;

		case QUERY_RESULT_ERROR:
			if( ErrorMessages == TRUE )
			{
				int		ErrorNum = GET_LAST_ERROR();
				char	ErrorMessage[320];

				ErrorMessage[0] ='\0';

				GetErrorMsg(ErrorNum, ErrorMessage, sizeof(ErrorMessage));
				if( Family == AF_INET )
				{
					printf("%s[%c][%s][%s][%s] Error occured : %d : %s .\n",
						   DateAndTime,
						   ProtocolCharacter,
						   inet_ntoa(ClientAddr -> Addr4.sin_addr),
						   DNSGetTypeName(SourceType),
						   QueryDomain,
						   ErrorNum,
						   ErrorMessage
						   );
				} else {
					char Addr[LENGTH_OF_IPV6_ADDRESS_ASCII] = {0};

					IPv6AddressToAsc(&(ClientAddr -> Addr6.sin6_addr), Addr);

					printf("%s[%c][%s][%s][%s] Error occured : %d : %s .\n",
						   DateAndTime,
						   ProtocolCharacter,
						   Addr,
						   DNSGetTypeName(SourceType),
						   QueryDomain,
						   ErrorNum,
						   ErrorMessage
						   );
				}
			}
			return -1;
			break;

		default: /* Succeed */
			send(*ClientSocket, ExtendableBuffer_GetData(Buffer), State, 0);

			if( ShowMassages == TRUE )
			{
				char InfoBuffer[3072];
				InfoBuffer[0] = '\0';
				GetAllAnswers(DNSGetDNSBody(ExtendableBuffer_GetData(Buffer)), InfoBuffer);

				if( Family == AF_INET )
				{
					PRINT("%s[%c][%s][%s][%s] :\n%s", DateAndTime, ProtocolCharacter, inet_ntoa(ClientAddr ->Addr4.sin_addr), DNSGetTypeName(SourceType), QueryDomain, InfoBuffer);
				} else {
					char Addr[LENGTH_OF_IPV6_ADDRESS_ASCII] = {0};

					IPv6AddressToAsc(&(ClientAddr -> Addr6.sin6_addr), Addr);

					PRINT("%s[%c][%s][%s][%s] :\n%s", DateAndTime, ProtocolCharacter, Addr, DNSGetTypeName(SourceType), QueryDomain, InfoBuffer);
				}
			}
			return 0;
			break;

	}
}
예제 #12
0
bool CMySqlDatabase::BlobWriteDb( QByteArray &byData, QString &strSql, QString &strError )
{
    MYSQL_BIND bind[ 1 ];
    ulong       length = 0;
    QByteArray byteSql;
    int nRet = 0;
    int nSize = 0;
    const char* pSql = NULL;

    hStmt = mysql_stmt_init( &hConnect );
    bool bRet = ( NULL != hStmt );
    if ( !bRet ) {
        GetErrorMsg( 0, strError, false, strSql );
        goto FileHandle;
    }

    byteSql = pCodec->fromUnicode( strSql );
    nSize = byteSql.count( );
    pSql = byteSql.data( );
    nRet = mysql_stmt_prepare( hStmt, pSql, nSize );
    bRet = ( 0 == nRet );
    if ( !bRet ){
        GetErrorMsg( nRet, strError, false, strSql );
        goto StmtHandle;
    }

    memset( bind, 0, sizeof ( bind ) );
    bind[ 0 ].buffer_type = MYSQL_TYPE_LONG_BLOB;
    bind[ 0 ].length = &length;
    bind[ 0 ].is_null = 0; /* Bind the buffers */
    //bind[ 0 ].buffer
    //bind[ 0 ].buffer_length

    bRet = ( 0 == mysql_stmt_bind_param( hStmt, bind ) );
    if ( !bRet ) {
        GetErrorMsg( 0, strError, false, strSql );
        goto StmtHandle;
    }

    nSize = byData.count( );
    pSql = byData.data( );
    if ( 0 < nSize ) {
        nRet = mysql_stmt_send_long_data( hStmt, 0, pSql, nSize );
        bRet = ( 0 == nRet );
        if ( !bRet ) {
            GetErrorMsg( nRet, strError, false, strSql );
            goto StmtHandle;
        }
    }

    nRet = mysql_stmt_execute( hStmt );
    bRet = ( 0 == nRet );
    if ( !bRet ) {
        GetErrorMsg( nRet, strError, false, strSql );
    }

    StmtHandle:
    bRet = ( 0 == mysql_stmt_close( hStmt ) );
    if ( !bRet ) {
        GetErrorMsg( 0, strError, false, strSql );
    }

    FileHandle:

    return bRet;
}
예제 #13
0
bool CMySqlDatabase::BlobReadDb( QString &strBlobFile, QString& strSql, QString& strError )
{
    //http://www.cplusplus.com
    QByteArray byData;
    bool bRet = BlobReadDb( byData, strSql, strError );
    if ( false == bRet ) {
        return bRet;
    }

    QFile file( strBlobFile );
    bRet = file.open( QIODevice::WriteOnly );
    if ( !bRet ) {
        return bRet;
    }

    file.write( byData );
    file.close( );

    return bRet;

#if false
    MYSQL_BIND bind[ 1 ];
    ulong       length = 0;
    QByteArray byteSql;
    int nSize = 0;
    const char* pSql = NULL;
    char* bufData = NULL;
    quint32 nData = 1024 * 1024 * 2;
    int nRet = 0;
    MYSQL_RES* res = NULL;
    my_bool bGetMaxLen = 1;

    hStmt = mysql_stmt_init( &hConnect );
    bRet = ( NULL != hStmt );
    if ( !bRet ) {
        GetErrorMsg( 0, strError, false, strSql );
        goto FileHandle;
    }

    byteSql = pCodec->fromUnicode( strSql );
    nSize = byteSql.count( );
    pSql = byteSql.data( );

    bRet = ( 0 == mysql_stmt_prepare( hStmt, pSql, nSize ) );
    if ( !bRet ){
        GetErrorMsg( 0, strError, false, strSql );
        goto StmtHandle;
    }

    bRet = ( 0 == mysql_stmt_execute( hStmt ) );
    if ( !bRet ) {
        GetErrorMsg( 0, strError, false, strSql );
        goto StmtHandle;
    }

    // max_allowed_packet 16M
    // write_timeout 120
    // Net Buffer 16M
    bufData = ( char* ) malloc( nData );
    memset( bind, 0, sizeof ( bind ) );
    bind[ 0 ].buffer_type = MYSQL_TYPE_LONG_BLOB;
    bind[ 0 ].length = &length; // Return Real Data Length
    bind[ 0 ].is_null = 0; /* Bind the buffers */
    bind[ 0 ].buffer = bufData; // Bind data buffer
    bind[ 0 ].buffer_length = nData; // Buffer Length

    bRet = ( 0 == mysql_stmt_bind_result( hStmt, bind ) );
    if ( !bRet ) {
        GetErrorMsg( 0, strError, false, strSql );
        goto NewHandle;
    }

    bRet = ( 0 == mysql_stmt_attr_set( hStmt, STMT_ATTR_UPDATE_MAX_LENGTH, &bGetMaxLen ) );
    bRet = ( 0 == mysql_stmt_store_result( hStmt ) );
    if ( !bRet ) {
        GetErrorMsg( 0, strError, false, strSql );
        goto NewHandle;
    }

    /////////////////////////////////// Get Meta Data
    res = mysql_stmt_result_metadata( hStmt );
    if ( NULL != res && 0 < res->field_count &&
        nData < res->fields[ 0 ].max_length ) {
        nData = res->fields[ 0 ].max_length; // Data Real Length
        mysql_free_result( res );

        bind[ 0 ].buffer_length = nData;
        bufData = ( char* ) realloc( bufData, nData );
        bind[ 0 ].buffer = bufData;
        bRet = ( 0 == mysql_stmt_bind_result( hStmt, bind ) );
        if ( !bRet ) {
            GetErrorMsg( 0, strError, false, strSql );
            goto NewHandle;
        }
    }
    ///////////////////////////////////

    nRet = mysql_stmt_fetch( hStmt );
    if ( MYSQL_DATA_TRUNCATED == nRet ) {
        ;
    } else {
        bRet = ( 0 == nRet );
        if ( !bRet ) {
            GetErrorMsg( 0, strError, false, strSql );
            goto NewHandle;
        }
    }

    file.write( ( const char* ) bufData, length );

    NewHandle:
    if ( NULL != bufData ) {
        free( bufData );
    }

    bRet = ( 0  == mysql_stmt_free_result( hStmt ) );
    if ( !bRet ) {
        GetErrorMsg( 0, strError, false, strSql );
    }

    StmtHandle:
    bRet = ( 0 == mysql_stmt_close( hStmt ) );
    if ( !bRet ) {
        GetErrorMsg( 0, strError, false, strSql );
    }

    FileHandle:
    file.close( );

    return bRet;
#endif
}
예제 #14
0
int _tmain(int argc, _TCHAR* argv[])
{
	WriteLog("========SipDownload Start========");

	g_mcPName = argv[0];
//	g_account = _strdup("Test");
//	g_password = _strdup("test");

    
	if(argc > 1)
	{
		if(stricmp(argv[1] , "-install") == 0)
		{
			g_account = _strdup("Test");
			g_password = _strdup("test");
			if(argc == 4)
			{
				g_account = _strdup(argv[2]);
				g_password = _strdup(argv[3]);
			}
			if(Install())
			{
				cout<<"install service successful!"<<endl;
			}
			else
			{
				cout<<"install service failed!"<<endl;
			}
		}
		else if(stricmp(argv[1] , "-uninstall") == 0)
		{
			UnInstall();
		}
		else if(stricmp(argv[1] , "-service") == 0)
		{
			SERVICE_TABLE_ENTRY ste[] =
			{
				{"SipDownload" , SVS_ServiceStart},
				{NULL , NULL}
			};
			if(::StartServiceCtrlDispatcher(ste))
			{
				cout<<"start service ctrl dispatcher "<<endl;
				WriteLog("start service ctrl dispatcher successful!");
			}
			else
			{
				cout<<"start service ctrl dispatcher failed"<<endl;
				char strMSG[1024] = {0};
				GetErrorMsg(strMSG);
				cout<<strMSG<<endl;
				WriteLog(strMSG);
			}

        
		}
		else
		{
			WriteLog("Error parameters!");
			return -1;
		}
	}

	MSG msg;
	while(::GetMessage(&msg,NULL,0,0))
	{
		DWORD time = msg.time;
		char strTemp[1024] = {0};
		sprintf(strTemp,"(_tmain)Send message time is :%ld" , time);
		WriteLog(strTemp);

		puts("Got Message");
		TranslateMessage(&msg);
		::DispatchMessage(&msg);
	}
	::Sleep(100000);

	return 0;
}
예제 #15
0
bool wxRegExImpl::Compile(const wxString& expr, int flags)
{
    Reinit();

#ifdef WX_NO_REGEX_ADVANCED
#   define FLAVORS wxRE_BASIC
#else
#   define FLAVORS (wxRE_ADVANCED | wxRE_BASIC)
    wxASSERT_MSG( (flags & FLAVORS) != FLAVORS,
                  wxT("incompatible flags in wxRegEx::Compile") );
#endif
    wxASSERT_MSG( !(flags & ~(FLAVORS | wxRE_ICASE | wxRE_NOSUB | wxRE_NEWLINE)),
                  wxT("unrecognized flags in wxRegEx::Compile") );

    // translate our flags to regcomp() ones
    int flagsRE = 0;
    if ( !(flags & wxRE_BASIC) )
    {
#ifndef WX_NO_REGEX_ADVANCED
        if (flags & wxRE_ADVANCED)
            flagsRE |= REG_ADVANCED;
        else
#endif
            flagsRE |= REG_EXTENDED;
    }
    if ( flags & wxRE_ICASE )
        flagsRE |= REG_ICASE;
    if ( flags & wxRE_NOSUB )
        flagsRE |= REG_NOSUB;
    if ( flags & wxRE_NEWLINE )
        flagsRE |= REG_NEWLINE;

    // compile it
#ifdef WXREGEX_USING_BUILTIN
    bool conv = true;
    // FIXME-UTF8: use wc_str() after removing ANSI build
    int errorcode = wx_re_comp(&m_RegEx, expr.c_str(), expr.length(), flagsRE);
#else
    // FIXME-UTF8: this is potentially broken, we shouldn't even try it
    //             and should always use builtin regex library (or PCRE?)
    const wxWX2MBbuf conv = expr.mbc_str();
    int errorcode = conv ? regcomp(&m_RegEx, conv, flagsRE) : REG_BADPAT;
#endif

    if ( errorcode )
    {
        wxLogError(_("Invalid regular expression '%s': %s"),
                   expr.c_str(), GetErrorMsg(errorcode, !conv).c_str());

        m_isCompiled = false;
    }
    else // ok
    {
        // don't allocate the matches array now, but do it later if necessary
        if ( flags & wxRE_NOSUB )
        {
            // we don't need it at all
            m_nMatches = 0;
        }
        else
        {
            // we will alloc the array later (only if really needed) but count
            // the number of sub-expressions in the regex right now

            // there is always one for the whole expression
            m_nMatches = 1;

            // and some more for bracketed subexperessions
            for ( const wxChar *cptr = expr.c_str(); *cptr; cptr++ )
            {
                if ( *cptr == wxT('\\') )
                {
                    // in basic RE syntax groups are inside \(...\)
                    if ( *++cptr == wxT('(') && (flags & wxRE_BASIC) )
                    {
                        m_nMatches++;
                    }
                }
                else if ( *cptr == wxT('(') && !(flags & wxRE_BASIC) )
                {
                    // we know that the previous character is not an unquoted
                    // backslash because it would have been eaten above, so we
                    // have a bare '(' and this indicates a group start for the
                    // extended syntax. '(?' is used for extensions by perl-
                    // like REs (e.g. advanced), and is not valid for POSIX
                    // extended, so ignore them always.
                    if ( cptr[1] != wxT('?') )
                        m_nMatches++;
                }
            }
        }

        m_isCompiled = true;
    }

    return IsValid();
}
예제 #16
0
/**
 * (Un)Installs a driver from/to the system.
 *
 * @return  Exit code (EXIT_OK, EXIT_FAIL)
 * @param   fInstall            Flag indicating whether to install (TRUE) or uninstall (FALSE) a driver.
 * @param   pszDriverPath       Pointer to full qualified path to the driver's .INF file (+ driver files).
 * @param   fSilent             Flag indicating a silent installation (TRUE) or not (FALSE).
 * @param   pszLogFile          Pointer to full qualified path to log file to be written during installation.
 *                              Optional.
 */
int VBoxInstallDriver(const BOOL fInstall, const _TCHAR *pszDriverPath, BOOL fSilent,
                      const _TCHAR *pszLogFile)
{
    HRESULT hr = S_OK;
    HMODULE hDIFxAPI = loadInstalledDll(L"DIFxAPI.dll");
    if (NULL == hDIFxAPI)
    {
        _tprintf(_T("ERROR: Unable to locate DIFxAPI.dll!\n"));
        hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
    }
    else
    {
        if (fInstall)
        {
            g_pfnDriverPackageInstall = (fnDriverPackageInstall)GetProcAddress(hDIFxAPI, "DriverPackageInstallW");
            if (g_pfnDriverPackageInstall == NULL)
            {
                _tprintf(_T("ERROR: Unable to retrieve entry point for DriverPackageInstallW!\n"));
                hr = HRESULT_FROM_WIN32(ERROR_PROC_NOT_FOUND);
            }
        }
        else
        {
            g_pfnDriverPackageUninstall = (fnDriverPackageUninstall)GetProcAddress(hDIFxAPI, "DriverPackageUninstallW");
            if (g_pfnDriverPackageUninstall == NULL)
            {
                _tprintf(_T("ERROR: Unable to retrieve entry point for DriverPackageUninstallW!\n"));
                hr = HRESULT_FROM_WIN32(ERROR_PROC_NOT_FOUND);
            }
        }

        if (SUCCEEDED(hr))
        {
            g_pfnDIFXAPISetLogCallback = (fnDIFXAPISetLogCallback)GetProcAddress(hDIFxAPI, "DIFXAPISetLogCallbackW");
            if (g_pfnDIFXAPISetLogCallback == NULL)
            {
                _tprintf(_T("ERROR: Unable to retrieve entry point for DIFXAPISetLogCallbackW!\n"));
                hr = HRESULT_FROM_WIN32(ERROR_PROC_NOT_FOUND);
            }
        }
    }

    if (SUCCEEDED(hr))
    {
        FILE *phFile = NULL;
        if (pszLogFile)
        {
            phFile = _wfopen(pszLogFile, _T("a"));
            if (!phFile)
                _tprintf(_T("ERROR: Unable to create log file!\n"));
            g_pfnDIFXAPISetLogCallback(LogCallback, phFile);
        }

        INSTALLERINFO instInfo =
        {
            TEXT("{7d2c708d-c202-40ab-b3e8-de21da1dc629}"), /* Our GUID for representing this installation tool. */
            TEXT("VirtualBox Guest Additions Install Helper"),
            TEXT("VirtualBox Guest Additions"), /** @todo Add version! */
            TEXT("Oracle Corporation")
        };

        _TCHAR szDriverInf[MAX_PATH + 1];
        if (0 == GetFullPathNameW(pszDriverPath, MAX_PATH, szDriverInf, NULL))
        {
            _tprintf(_T("ERROR: INF-Path too long / could not be retrieved!\n"));
            hr = HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER);
        }
        else
        {
            if (fInstall)
                _tprintf(_T("Installing driver ...\n"));
            else
                _tprintf(_T("Uninstalling driver ...\n"));
            _tprintf(_T("INF-File: %ws\n"), szDriverInf);

            DWORD dwFlags = DRIVER_PACKAGE_FORCE;
            if (!fInstall)
                dwFlags |= DRIVER_PACKAGE_DELETE_FILES;

            OSVERSIONINFO osi;
            memset(&osi, 0, sizeof(OSVERSIONINFO));
            osi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
            if ( (GetVersionEx(&osi) != 0)
              && (osi.dwPlatformId == VER_PLATFORM_WIN32_NT)
              && (osi.dwMajorVersion < 6))
            {
                if (fInstall)
                {
                    _tprintf(_T("Using legacy mode for install ...\n"));
                    dwFlags |= DRIVER_PACKAGE_LEGACY_MODE;
                }
            }

            if (fSilent)
            {
                _tprintf(_T("Installation is silent ...\n"));
                /*
                 * Don't add DRIVER_PACKAGE_SILENT to dwFlags here, otherwise
                 * installation will fail because we (still) don't have WHQL certified
                 * drivers. See CERT_E_WRONG_USAGE on MSDN for more information.
                 */
            }

            BOOL fReboot;
            DWORD dwRet = fInstall ?
                            g_pfnDriverPackageInstall(szDriverInf, dwFlags, &instInfo, &fReboot)
                          : g_pfnDriverPackageUninstall(szDriverInf, dwFlags, &instInfo, &fReboot);
            if (dwRet != ERROR_SUCCESS)
            {
                switch (dwRet)
                {
                    case CRYPT_E_FILE_ERROR:
                        _tprintf(_T("ERROR: The catalog file for the specified driver package was not found!\n"));
                        break;

                    case ERROR_ACCESS_DENIED:
                        _tprintf(_T("ERROR: Caller is not in Administrators group to (un)install this driver package!\n"));
                        break;

                    case ERROR_BAD_ENVIRONMENT:
                        _tprintf(_T("ERROR: The current Microsoft Windows version does not support this operation!\n"));
                        break;

                    case ERROR_CANT_ACCESS_FILE:
                        _tprintf(_T("ERROR: The driver package files could not be accessed!\n"));
                        break;

                    case ERROR_DEPENDENT_APPLICATIONS_EXIST:
                        _tprintf(_T("ERROR: DriverPackageUninstall removed an association between the driver package and the specified application but the function did not uninstall the driver package because other applications are associated with the driver package!\n"));
                        break;

                    case ERROR_DRIVER_PACKAGE_NOT_IN_STORE:
                        _tprintf(_T("ERROR: There is no INF file in the DIFx driver store that corresponds to the INF file %ws!\n"), szDriverInf);
                        break;

                    case ERROR_FILE_NOT_FOUND:
                        _tprintf(_T("ERROR: File not found! File = %ws\n"), szDriverInf);
                        break;

                    case ERROR_IN_WOW64:
                        _tprintf(_T("ERROR: The calling application is a 32-bit application attempting to execute in a 64-bit environment, which is not allowed!\n"));
                        break;

                    case ERROR_INVALID_FLAGS:
                        _tprintf(_T("ERROR: The flags specified are invalid!\n"));
                        break;

                    case ERROR_INSTALL_FAILURE:
                        _tprintf(_T("ERROR: The (un)install operation failed! Consult the Setup API logs for more information.\n"));
                        break;

                    case ERROR_NO_MORE_ITEMS:
                        _tprintf(
                                 _T(
                                    "ERROR: The function found a match for the HardwareId value, but the specified driver was not a better match than the current driver and the caller did not specify the INSTALLFLAG_FORCE flag!\n"));
                        break;

                    case ERROR_NO_DRIVER_SELECTED:
                        _tprintf(_T("ERROR: No driver in .INF-file selected!\n"));
                        break;

                    case ERROR_SECTION_NOT_FOUND:
                        _tprintf(_T("ERROR: Section in .INF-file was not found!\n"));
                        break;

                    case ERROR_SHARING_VIOLATION:
                        _tprintf(_T("ERROR: A component of the driver package in the DIFx driver store is locked by a thread or process\n"));
                        break;

                    /*
                     * !    sig:           Verifying file against specific Authenticode(tm) catalog failed! (0x800b0109)
                     * !    sig:           Error 0x800b0109: A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider.
                     * !!!  sto:           No error message will be displayed as client is running in non-interactive mode.
                     * !!!  ndv:           Driver package failed signature validation. Error = 0xE0000247
                     */
                    case ERROR_DRIVER_STORE_ADD_FAILED:
                        _tprintf(_T("ERROR: Adding driver to the driver store failed!!\n"));
                        break;

                    case ERROR_UNSUPPORTED_TYPE:
                        _tprintf(_T("ERROR: The driver package type is not supported of INF %ws!\n"), szDriverInf);
                        break;

                    default:
                    {
                        /* Try error lookup with GetErrorMsg(). */
                        TCHAR szErrMsg[1024];
                        GetErrorMsg(dwRet, szErrMsg, sizeof(szErrMsg));
                        _tprintf(_T("ERROR (%08x): %ws\n"), dwRet, szErrMsg);
                        break;
                    }
                }
                hr = HRESULT_FROM_WIN32(dwRet);
            }
            g_pfnDIFXAPISetLogCallback(NULL, NULL);
            if (phFile)
                fclose(phFile);
            if (SUCCEEDED(hr))
            {
                _tprintf(_T("Driver was installed successfully!\n"));
                if (fReboot)
                    _tprintf(_T("A reboot is needed to complete the driver (un)installation!\n"));
            }
        }
    }

    if (NULL != hDIFxAPI)
       FreeLibrary(hDIFxAPI);

    return SUCCEEDED(hr) ? EXIT_OK : EXIT_FAIL;
}
예제 #17
0
int wxRegExImpl::Replace(wxString *text,
                         const wxString& replacement,
                         size_t maxMatches) const
{
    wxCHECK_MSG( text, wxNOT_FOUND, wxT("NULL text in wxRegEx::Replace") );
    wxCHECK_MSG( IsValid(), wxNOT_FOUND, wxT("must successfully Compile() first") );

    // the input string
#ifndef WXREGEX_CONVERT_TO_MB
    const wxChar *textstr = text->c_str();
    size_t textlen = text->length();
#else
    const wxWX2MBbuf textstr = WXREGEX_CHAR(*text);
    if (!textstr)
    {
        wxLogError(_("Failed to find match for regular expression: %s"),
                   GetErrorMsg(0, true).c_str());
        return 0;
    }
    size_t textlen = strlen(textstr);
    text->clear();
#endif

    // the replacement text
    wxString textNew;

    // the result, allow 25% extra
    wxString result;
    result.reserve(5 * textlen / 4);

    // attempt at optimization: don't iterate over the string if it doesn't
    // contain back references at all
    bool mayHaveBackrefs =
        replacement.find_first_of(wxT("\\&")) != wxString::npos;

    if ( !mayHaveBackrefs )
    {
        textNew = replacement;
    }

    // the position where we start looking for the match
    size_t matchStart = 0;

    // number of replacement made: we won't make more than maxMatches of them
    // (unless maxMatches is 0 which doesn't limit the number of replacements)
    size_t countRepl = 0;

    // note that "^" shouldn't match after the first call to Matches() so we
    // use wxRE_NOTBOL to prevent it from happening
    while ( (!maxMatches || countRepl < maxMatches) &&
             Matches(
#ifndef WXREGEX_CONVERT_TO_MB
                    textstr + matchStart,
#else
                    textstr.data() + matchStart,
#endif
                    countRepl ? wxRE_NOTBOL : 0
                    WXREGEX_IF_NEED_LEN(textlen - matchStart)) )
    {
        // the string possibly contains back references: we need to calculate
        // the replacement text anew after each match
        if ( mayHaveBackrefs )
        {
            mayHaveBackrefs = false;
            textNew.clear();
            textNew.reserve(replacement.length());

            for ( const wxChar *p = replacement.c_str(); *p; p++ )
            {
                size_t index = (size_t)-1;

                if ( *p == wxT('\\') )
                {
                    if ( wxIsdigit(*++p) )
                    {
                        // back reference
                        wxChar *end;
                        index = (size_t)wxStrtoul(p, &end, 10);
                        p = end - 1; // -1 to compensate for p++ in the loop
                    }
                    //else: backslash used as escape character
                }
                else if ( *p == wxT('&') )
                {
                    // treat this as "\0" for compatbility with ed and such
                    index = 0;
                }

                // do we have a back reference?
                if ( index != (size_t)-1 )
                {
                    // yes, get its text
                    size_t start, len;
                    if ( !GetMatch(&start, &len, index) )
                    {
                        wxFAIL_MSG( wxT("invalid back reference") );

                        // just eat it...
                    }
                    else
                    {
                        textNew += wxString(
#ifndef WXREGEX_CONVERT_TO_MB
                                textstr
#else
                                textstr.data()
#endif
                                + matchStart + start,
                                *wxConvCurrent, len);

                        mayHaveBackrefs = true;
                    }
                }
                else // ordinary character
                {
                    textNew += *p;
                }
            }
        }

        size_t start, len;
        if ( !GetMatch(&start, &len) )
        {
            // we did have match as Matches() returned true above!
            wxFAIL_MSG( wxT("internal logic error in wxRegEx::Replace") );

            return wxNOT_FOUND;
        }

        // an insurance against implementations that don't grow exponentially
        // to ensure building the result takes linear time
        if (result.capacity() < result.length() + start + textNew.length())
            result.reserve(2 * result.length());

#ifndef WXREGEX_CONVERT_TO_MB
        result.append(*text, matchStart, start);
#else
        result.append(wxString(textstr.data() + matchStart, *wxConvCurrent, start));
#endif
        matchStart += start;
        result.append(textNew);

        countRepl++;

        matchStart += len;
    }

#ifndef WXREGEX_CONVERT_TO_MB
    result.append(*text, matchStart, wxString::npos);
#else
    result.append(wxString(textstr.data() + matchStart, *wxConvCurrent));
#endif
    *text = result;

    return countRepl;
}
예제 #18
0
void WINAPI SVS_ServiceCtrlHandler(DWORD opcode)
{
	switch(opcode)
	{
	case SERVICE_CONTROL_PAUSE:
		{
			SVS_ServiceStatus.dwCurrentState=SERVICE_PAUSED;
			break;  
		}
	case SERVICE_CONTROL_CONTINUE:
		{
			SVS_ServiceStatus.dwCurrentState=SERVICE_RUNNING;
			break; 
		}
	case SERVICE_CONTROL_STOP: 
	case SERVICE_CONTROL_SHUTDOWN:
		{
			SVS_ServiceStatus.dwWin32ExitCode = 0; 
            SVS_ServiceStatus.dwCurrentState  = SERVICE_STOPPED; 
            SVS_ServiceStatus.dwCheckPoint    = 0; 
            SVS_ServiceStatus.dwWaitHint      = 0; 

			g_SubProcessState=FALSE;

		//	::SetEvent(g_hExit);
		//	::SetEvent(g_hCom);
			::Sleep(1000);
		   ::PostThreadMessage(g_alertpi.dwThreadId,WM_QUIT,0,0);
		    ::PostThreadMessage(g_reportpi.dwThreadId,WM_QUIT,0,0);

			::PostThreadMessage(g_pi.dwThreadId,WM_QUIT,0,0);
			::Sleep(1000);
			::TerminateProcess(g_pi.hProcess,3);
			::TerminateProcess(g_alertpi.hProcess,3);

			WriteLog("服务退出,正终止子进程...");

 
            if(!SetServiceStatus(SVS_ServiceStatusHandle, &SVS_ServiceStatus))
            { 
				WriteLog("设置服务状态出错:");
				char strErrorMsg[1024] = {0};
				GetErrorMsg(strErrorMsg);
				WriteLog(strErrorMsg);
            }
            return; 
		}
	case SERVICE_CONTROL_INTERROGATE:
		{
			//Fall through to send current status. 
			//AddToErrorLog("Service Control Interrogate\r\n");
            break;
		}
	default:
		{
			WriteLog("Unrecognized opcode");
			char strErrorMsg[1024] = {0};
			GetErrorMsg(strErrorMsg);
			WriteLog(strErrorMsg);
			break;
		}
	}
	if (!SetServiceStatus (SVS_ServiceStatusHandle,  &SVS_ServiceStatus)) 
	{
		WriteLog("设置服务状态出错:");
		char strErrorMsg[1024] = {0};
		GetErrorMsg(strErrorMsg);
		WriteLog(strErrorMsg);
    } 
}