// main function for xml parsing
void ParseXMLStr(char* szXMLStr, PT_NODE ptHead)
{
    T_STRING_OBJ tXmlStr;
    T_XML_PARSE_STATE_MACHINE tXmlMachine;
    PT_XML_PARSE_STATE_MACHINE ptXmlMachine = &tXmlMachine;
    int iIndex = 0;
    char cChar = '\0';
    
    InitStrObjStruct(&tXmlStr, szXMLStr, FALSE);
    InitXMLParseStateMachine(&tXmlMachine);
    
    while( (cChar = GetCharFromStr(&tXmlStr)) )
    {
        MyPrintf("current eParseState = %d", ptXmlMachine->eParseState);
        MyPrintf("input char = %c", cChar);
        
        iIndex = GetStateChangeRuleIndex(ptXmlMachine->eParseState, cChar);
        MyPrintf("machine rule iIndex=%d", iIndex);
        if ( -1 != iIndex )
        {
            ptXmlMachine->eParseState = g_stateChangeTable[iIndex].eTransferState;
            MyPrintf("changed eParseState = %d\n", ptXmlMachine->eParseState);
            
            g_stateChangeTable[iIndex].eventhandler(cChar, ptXmlMachine, ptHead);
        }
        else
        {
            StopWithMsg("state machine run encounter error!");
        }
    }

    FreeXMLParseStateMachine(ptXmlMachine);
}
void PrintUsage()
{
    MyPrintf(_T("RSACert [</e>|</d>] <CertName> <StoreName> [</u>|</m>] <InputFile> <OutputFile>\n"));
    MyPrintf(_T("/e for Encryption\n"));
    MyPrintf(_T("/d for Decryption\n"));
    MyPrintf(_T("/u for current user certificate store\n"));
    MyPrintf(_T("/m for local machine certificate store\n"));
}
void PrintUsage()
{
   MyPrintf(_T("SignHash [md5|sha1] [</s>|</v>] <DataFile> <SigFile> [</cert>|</key>]\n"));
   MyPrintf(_T("/s to Sign.\n"));
   MyPrintf(_T("/v to Verify.\n"));
   MyPrintf(_T("/cert <CertName> <StoreName> [<u>|<m>] - use a certificate.\n"));
   MyPrintf(_T("/key <ContainerName> [<u>|<m>] [<x>|<s>] use container with exchange or signature key.\n"));
}
BOOL GetRSAKeyFromContainer(LPTSTR szContainerName,
                            DWORD dwAcquireFlags,
                            DWORD dwKeySpec,
                            HCRYPTPROV *hProv,                            
                            HCRYPTKEY *hPubKey)
{
   BOOL fResult;
   BOOL fReturn = FALSE;

   __try
   {
      if (hProv == NULL || hPubKey == NULL)
      {
         __leave;
      }

      // acquire crypto context using container name
      fResult = CryptAcquireContext(hProv, 
                                    szContainerName, 
                                    MS_DEF_PROV, 
                                    PROV_RSA_FULL, 
                                    dwAcquireFlags);
      if (!fResult)
      {
         MyPrintf(_T("CryptAcquireContext failed with %x\n"), GetLastError());
         __leave;
      }
      
      // Get the key handle for verification
      fResult = CryptGetUserKey(*hProv, dwKeySpec, hPubKey);
      if (!fResult)
      {
         MyPrintf(_T("CryptGetUserKey failed with %x\n"), GetLastError());
         __leave;
      }

      fReturn = TRUE;
   }
   __finally
   {
      if (!fReturn)
      {
         if (*hPubKey != NULL) 
         {
            CryptDestroyKey(*hPubKey);
            *hPubKey = NULL;
         }

         if (*hProv != NULL) 
         {
            CryptReleaseContext(*hProv, 0);
            *hProv = NULL;
         }
      }
   }

   return fReturn;
}
Exemple #5
0
/*
 * EnterExMode - start Ex emulation mode
 */
vi_rc EnterExMode( void )
{
    int         i;
    window_id   wid;
    char        *st;
    char        *prompt;
    vi_rc       rc;
    bool        ret;

    if( EditFlags.InputKeyMapMode ) {
        return( ERR_NO_ERR );
    }
    i = EditVars.WindMaxHeight - 1;
    exwInfo.area.y1 = exwInfo.area.y2 = i;
    exwInfo.area.x2 = EditVars.WindMaxWidth - 1;
    SetPosToMessageLine();
    EditFlags.ExMode = true;
    EditFlags.LineDisplay = true;
    EditFlags.ClockActive = false;
    MyPrintf( "\nEntering EX mode (type vi to return)\n" );
    rc = NewWindow2( &wid, &exwInfo );
    if( rc != ERR_NO_ERR ) {
        return( rc );
    }
    st = MemAlloc( EditVars.MaxLine );

    for( ;; ) {
        if( EditFlags.Appending ) {
            prompt = "";
        } else {
            prompt = ":";
        }
        ret = ReadStringInWindow( wid, 1, prompt, st, EditVars.MaxLine, &EditVars.CLHist );
        MyPrintf( "\n" );
        if( !ret ) {
            continue;
        }
        ScreenPage( 1 );
        if( EditFlags.Appending ) {
            AppendAnother( st );
            ScreenPage( -1 );
            continue;
        }
        rc = RunCommandLine( st );
        if( !EditFlags.ExMode ) {
            break;
        }
        if( rc > ERR_NO_ERR ) {
            Error( GetErrorMsg( rc ) );
        }
        ScreenPage( -1 );
    }
    MemFree( st );
    return( ERR_NO_ERR );

} /* EnterExMode */
Exemple #6
0
int
Test_CardConnecting()
{
	int trycnt;
	long result;

	printf("==============================================================\n");
	printf("Part B : Card Connect/Disconnect\n");
	printf("==============================================================\n");
	trycnt = 0;
	printf("Testing");
	while(trycnt < 5)
	{
		trycnt++;
		printf("...");
#ifdef LINUX_OS
		fflush(stdout);
#endif
		result = SCardConnect(	 ScardContext,
							 ScardReaderState[CurrentReader].szReader,
							 SCARD_SHARE_EXCLUSIVE,
							 SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1,
							 &ScardHandle[CurrentReader],
							 &ScardProtocol[CurrentReader]);

		if(result != SCARD_S_SUCCESS)
		{
			MyPrintf(strlen("Testing"), strlen("..."), trycnt * 2 - 1, "Failed\n");
			PRINTERR(("SCardConnect Fail : %08X\n", result));
			return FALSE;
		}
		
		printf("...");
#ifdef LINUX_OS
		fflush(stdout);
#endif
		result = SCardDisconnect(ScardHandle[CurrentReader],
										   SCARD_UNPOWER_CARD);

		if(result != SCARD_S_SUCCESS)
		{
			MyPrintf(strlen("Testing"), strlen("..."), trycnt * 2, "Failed\n");
			PRINTERR(("SCardDisconnect Fail : %08X\n", result));
			return FALSE;
		}
	}
	MyPrintf(strlen("Testing"), strlen("..."), trycnt * 2, "Passed\n");

	printf("\n                Part B Test Successfully\n\n");

	return TRUE;
}
PCCERT_CONTEXT GetCertificateContextFromName(
    LPTSTR lpszCertificateName,
    LPTSTR lpszCertificateStoreName,
    DWORD  dwCertStoreOpenFlags)
{
    PCCERT_CONTEXT pCertContext = NULL;
    HCERTSTORE hCertStore = NULL;
    LPSTR szStoreProvider;
    DWORD dwFindType;

#ifdef UNICODE
    szStoreProvider = (LPSTR)CERT_STORE_PROV_SYSTEM_W;
#else
    szStoreProvider = (LPSTR)CERT_STORE_PROV_SYSTEM_A;
#endif

    // Open the specified certificate store
    hCertStore = CertOpenStore(szStoreProvider,
                               0,
                               NULL,
                               CERT_STORE_READONLY_FLAG|
                               dwCertStoreOpenFlags,
                               lpszCertificateStoreName);
    if (hCertStore == NULL)
    {
        MyPrintf(_T("CertOpenStore failed with %X\n"), GetLastError());
        return pCertContext;
    }

#ifdef UNICODE
    dwFindType = CERT_FIND_SUBJECT_STR_W;
#else
    dwFindType = CERT_FIND_SUBJECT_STR_A;
#endif

    // Find the certificate by CN.
    pCertContext = CertFindCertificateInStore(
                       hCertStore,
                       MY_ENCODING,
                       0,
                       dwFindType,
                       lpszCertificateName,
                       NULL);
    if (pCertContext == NULL)
    {
        MyPrintf(_T("CertFindCertificateInStore failed with %X\n"), GetLastError());
    }

    CertCloseStore(hCertStore, 0);

    return pCertContext;
}
Exemple #8
0
/*
 * Die - unusual termination
 */
void Die( const char *str, ... )
{
    va_list     al;

    SetPosToMessageLine();
    MyPrintf( "Failure: " );
    va_start( al, str );
    MyVPrintf( str, al );
    va_end( al );
    MyPrintf( "\n" );
    ExitEditor( -1 );

} /* Die */
void PrintList(PT_NODE ptHeadNode)
{
    PT_NODE ptCurNode = NULL;
    MyPrintf("---- list printing begin -----");
 
     ptCurNode = ptHeadNode->next;
    while(ptCurNode)
    {
        MyPrintf("node tagname is %s", ptCurNode->tagName);
        MyPrintf("node content is %s", ptCurNode->content);
        
        ptCurNode = ptCurNode->next;
    }
   
    MyPrintf("---- list printing end -----");
}
Exemple #10
0
/*
 * ErrorBox - show an error message in a dialog box
 */
void ErrorBox( char *str, ... )
{
    va_list     al;
    char        tmp[MAX_STR];

    if( MessageWindow != NO_WINDOW ) {
        WindowAuxUpdate( MessageWindow, WIND_INFO_TEXT_COLOR,
                            messagew_info.hilight.foreground );
        WindowAuxUpdate( MessageWindow, WIND_INFO_BACKGROUND_COLOR,
                            messagew_info.hilight.background );
        va_start( al, str );
        MyVSprintf( tmp, str, al );
        va_end( al );

        SourceError( tmp );
        Message1Box( "%s", tmp );

        WindowAuxUpdate( MessageWindow, WIND_INFO_TEXT_COLOR,
                            messagew_info.text.foreground );
        WindowAuxUpdate( MessageWindow, WIND_INFO_BACKGROUND_COLOR,
                            messagew_info.text.background );
        MyBeep();
    } else {
        va_start( al, str );
#ifndef __WIN__
        MyVPrintf( str, al );
        MyPrintf( "\n" );
#endif
        va_end( al );
    }

} /* Error */
// current is state starttag, jump2Content event is triggered, now do some action
E_RETURN_TYPE EventHandler_StateEndTag_Jump2Null(char cCurrentChar, PT_XML_PARSE_STATE_MACHINE ptStateMachine, PT_NODE ptHead)
{
MyPrintf("EventHandler_StateEndTag_Jump2Null enter");
    // discard current char, compare starttag with endtag
    // if starttag equals to endtag, add tagName-content into list
    if ( !strcmp(ptStateMachine->tStartTag.szStr, ptStateMachine->tEndTag.szStr) )
    {
        Insert2List(ptHead, ptStateMachine->tStartTag.szStr, ptStateMachine->tContent.szStr);
    }
    else
    {
        MyPrintf("start tag(%s) do not match end tag(%s), ", ptStateMachine->tStartTag.szStr, ptStateMachine->tEndTag.szStr);
    }

    FreeXMLParseStateMachine(ptStateMachine);
    InitXMLParseStateMachine(ptStateMachine);
}
Exemple #12
0
/*
 * GetFromEnvAndOpen - search env and fopen a file
 */
static FILE *GetFromEnvAndOpen( char *inpath )
{
    char tmppath[_MAX_PATH];

    GetFromEnv( inpath, tmppath );
    if( tmppath[0] != 0 ) {
        MyPrintf( " %s...", tmppath );
        return( fopen( tmppath, "r" ) );
    }
    return( NULL );

} /* GetFromEnvAndOpen */
Exemple #13
0
/*
 * FatalError - process fatal error
 */
void FatalError( vi_rc err )
{
    char *str;

    SetPosToMessageLine();
    if( err == ERR_NO_MEMORY ) {
        str = "Out of memory";
    } else {
        str = GetErrorMsg( err );
    }
    MyPrintf( "%s (fatal)\n", str );
    ExitEditor( -1 );

} /* FatalError */
// test xml parsing result
void TestXMLPasring(char* szXMLStr, T_XML_NODE xmlArr[])
{
    T_NODE tHead = {
        NULL,
        NULL,
        NULL
    };
    
    ParseXMLStr(szXMLStr, &tHead);

    PrintList(&tHead);
    
    AssertList(&tHead, xmlArr);
    
    MyPrintf("szXMLStr(%s) test ok!-----------------\n\n", szXMLStr);
}
Exemple #15
0
/*
 * StartupError - process fatal startup error
 */
void StartupError( vi_rc err )
{
    char    *str;

    if( err == ERR_NO_MEMORY ) {
        str = "Out of memory";
    } else {
        str = GetErrorMsg( err );
    }
    MyPrintf( "%s (fatal)\n", str );

    FiniMem();

    /* Do not call ExitEditor() because almost nothing is initialized yet. */
    exit( -1 );
} /* StartupError */
Exemple #16
0
/*
 * Quit - print usage messages
 */
void Quit( const char **usage_msg, const char *str, ... )
{
    va_list     al;

    usage_msg = usage_msg;
#ifdef __WIN__
    {
        char    buff[MAX_STR];

        if( str != NULL ) {
            va_start( al, str );
            MyVSprintf( buff, str, al );
            va_end( al );
        } else {
            buff[0] = 0;
        }
        CloseStartupDialog();
        UsageDialog( UsageMsg, buff,  sizeof( UsageMsg ) / sizeof( char *) );
    }
#else
    {
        int     i;
        int     cnt;

        if( str != NULL ) {
            va_start( al, str );
            MyVPrintf( str, al );
            va_end( al );
            cnt = 1;
        } else {
            cnt = sizeof( UsageMsg ) / sizeof( char *);
        }

        for( i = 0; i < cnt; i++ ) {
            MyPrintf( "%s\n", UsageMsg[i] );
        }
    }
#endif
    // can't do an ExitEditor because we will not have initialized anything
    // yet (this is always called from checkFlags)
    // ExitEditor( 0 );
    ChangeDirectory( HomeDirectory );
    FiniMem();
    exit( 0 );

} /* Usage */
Exemple #17
0
/*
 * Message2 - display message on line 2
 */
void Message2( const char *str, ... )
{
    va_list     al;
    char        tmp[MAX_STR];

    if( !EditFlags.EchoOn || BAD_ID( message_window_id ) ) {
        return;
    }
    va_start( al, str );
    MyVSprintf( tmp,str, al );
    va_end( al );
    tmp[EditVars.WindMaxWidth - 1] = '\0';

    if( !EditFlags.LineDisplay ) {
        DisplayLineInWindow( message_window_id, 2, tmp );
    } else {
        MyPrintf( "%s\n", tmp );
    }

} /* Message2 */
Exemple #18
0
/*
 * Message2 - display message on line 2
 */
void Message2( char *str, ... )
{
    va_list     al;
    char        tmp[MAX_STR];

    if( !EditFlags.EchoOn || MessageWindow == NO_WINDOW ) {
        return;
    }
    va_start( al, str );
    MyVSprintf( tmp,str, al );
    va_end( al );
    tmp[EditVars.WindMaxWidth - 1] = 0;

    if( !EditFlags.LineDisplay ) {
        DisplayLineInWindow( MessageWindow, 2, tmp );
    } else {
        MyPrintf( "%s\n", tmp );
    }

} /* Message2 */
Exemple #19
0
static void postSpawn( long rc )
{
    restorePrompt();
    VarAddGlobalLong( "Sysrc", rc );
    UpdateCurrentDirectory();

#ifndef __WIN__
    ResetColors();
    // if( (EditFlags.PauseOnSpawnErr && rc != 0 ) ||
    //          !EditFlags.SourceScriptActive ) {
    if( EditFlags.PauseOnSpawnErr && rc != 0 ) {
        MyPrintf( "[%s]\n", MSG_PRESSANYKEY );
        GetNextEvent( false );
    }
    ResetSpawnScreen();
    if( !EditFlags.LineDisplay ) {
        ReDisplayScreen();
    }
#endif
    EditFlags.ClockActive = clockActive;
}
Exemple #20
0
int main( int argc, char *argv[] )
{
    char                *buff = NULL;
    char                *buff2, *buff3;
    char                *buffn, *buffs;
    char                *ptr;
    int                 i, bytes, j, k, sl;
    FILE                *f;
    struct stat         fs;
    char                drive[_MAX_DRIVE], dir[_MAX_DIR];
    char                fname[_MAX_FNAME], ext[_MAX_EXT];
    char                path[_MAX_PATH];
    char                tmppath[_MAX_PATH];
    char                tmpfname[_MAX_FNAME], tmpext[_MAX_EXT];
    unsigned            cnt;
    unsigned            lines;
    bind_size           *index;
    bind_size           *entries;

    for( j = argc - 1; j > 0; --j ) {
        if( argv[j][0] == '/' || argv[j][0] == '-' ) {
            sl = strlen( argv[j] );
            for( i = 1; i < sl; i++ ) {
                switch( argv[j][i] ) {
                case 's': sflag = true; break;
                case 'q': qflag = true; break;
                case 'd':
                    bindfile = &argv[j][i + 1];
                    i = sl;
                    break;
                case '?':
                    Banner();
                    Usage( NULL );
                default:
                    Banner();
                    Usage( "Invalid option" );
                }
            }
            for( i = j; i < argc; i++ ) {
                argv[i]= argv[i + 1];
            }
            argc--;
        }
    }
    Banner();

    /*
     * now, check for null file name
     */
    if( argc < 2 ) {
        Usage( "No executable to bind" );
    }
    _splitpath( argv[1], drive, dir, fname, ext );
    if( ext[0] == 0 ) {
        _makepath( path, drive, dir, fname, ".exe" );
    } else {
        strcpy( path, argv[1] );
    }
    if( stat( path, &fs ) == -1 ) {
        Abort( "Could not find executable \"%s\"", path );
    }

    cnt = 0;
    if( !sflag ) {

        buff = MyAlloc( 65000 );
        buff2 = MyAlloc( 32000 );
        buff3 = MyAlloc( MAX_LINE_LEN );

        /*
         * read in all data files
         */
        MyPrintf( "Getting data files from" );
        f = GetFromEnvAndOpen( bindfile );
        MyPrintf( "\n" );
        if( f == NULL ) {
            Abort( "Could not open %s", bindfile );
        }
        while( (ptr = fgets( buff3, MAX_LINE_LEN, f )) != NULL ) {
            for( i = strlen( ptr ); i && isWSorCtrlZ( ptr[i - 1] ); --i ) {
                ptr[i - 1] = '\0';
            }
            if( ptr[0] == '\0' ) {
                continue;
            }
            ptr = SkipLeadingSpaces( ptr );
            if( ptr[0] == '#' ) {
                continue;
            }
            dats[FileCount] = MyAlloc( strlen( ptr ) + 1 );
            strcpy( dats[FileCount], ptr );
            FileCount++;
            if( FileCount >= MAX_DATA_FILES ) {
                Abort( "Too many files to bind!" );
            }
        }
        fclose( f );
        index = MyAlloc( FileCount * sizeof( bind_size ) );
        entries = MyAlloc( FileCount * sizeof( bind_size ) );

        buffn = buff;

        *(bind_size *)buffn = FileCount;
        buffn += sizeof( bind_size );
        cnt += sizeof( bind_size );
        buffs = buffn;
        buffn += sizeof( bind_size );
        cnt += sizeof( bind_size );
        k = 0;
        for( i = 0; i < FileCount; i++ ) {
//          j = strlen( dats[i] ) + 1;
//          memcpy( buffn, dats[i], j );
            _splitpath( dats[i], NULL, NULL, tmpfname, tmpext );
            _makepath( tmppath, NULL, NULL, tmpfname, tmpext );
            j = strlen( tmppath ) + 1;
            memcpy( buffn, tmppath, j );
            buffn += j;
            cnt += j;
            k += j;
        }
        *(bind_size *)buffs = k + 1;  /* size of token list */
        *buffn = 0;                             /* trailing zero */
        buffn++;
        cnt++;
        buffs = buffn;
        buffn += FileCount * ( sizeof( bind_size ) + sizeof( bind_size ) );
        cnt += FileCount * ( sizeof( bind_size ) + sizeof( bind_size ) );

        for( j = 0; j < FileCount; j++ ) {
            MyPrintf( "Loading" );
            f = GetFromEnvAndOpen( dats[j] );
            if( f == NULL ) {
                Abort( "\nLoad of %s failed!", dats[j] );
            }
            setvbuf( f, buff2, _IOFBF, 32000 );
            bytes = lines = 0;
            index[j] = cnt;
            while( (ptr = fgets( buff3, MAX_LINE_LEN, f )) != NULL ) {
                unsigned    len;

                for( len = strlen( ptr ); len && isWSorCtrlZ( ptr[len - 1] ); --len )
                    ptr[len - 1] = '\0';
                if( ptr[0] == '\0' ) {
                    continue;
                }
                ptr = SkipLeadingSpaces( ptr );
                if( ptr[0] == '#' ) {
                    continue;
                }
                len = strlen( ptr );
                *buffn = (char)len;
                buffn++;
                memcpy( buffn, ptr, len );
                buffn += len;
                cnt += len + 1;
                lines++;
                bytes += len;
            }
            fclose( f );
            entries[j] = lines;
            MyPrintf( "Added %d lines (%d bytes)\n", lines, bytes );
        }
        memcpy( buffs, index, FileCount * sizeof( bind_size ) );
        buffs += FileCount * sizeof( bind_size );
        memcpy( buffs, entries, FileCount * sizeof( bind_size ) );
    }

    AddDataToEXE( path, buff, cnt, fs.st_size );
    if( !sflag ) {
        MyPrintf( "Added %d bytes to \"%s\"\n", cnt, path );
    } else {
        MyPrintf( "\"%s\" has been stripped of configuration information\n", path );
    }
    return( 0 );

} /* main */
Exemple #21
0
int main(void){
	MyPrintf("teste: %c, %i", 'a', summate(4, 1, NULL, 3, 2));
	return 0;
}
Exemple #22
0
/*
 * ProcessEx - process an ex command
 */
vi_rc ProcessEx( linenum n1, linenum n2, bool n2f, int tkn, const char *data )
{
    vi_rc       rc = ERR_INVALID_COMMAND, i;
    char        word[MAX_STR];
    linenum     addr, tlines;
    fcb         *cfcb;
    line        *cline;
    fcb_list    fcblist;

    GetNextWord1( data, word );
    data = word;
    if( GetAddress( &data, &addr ) != ERR_NO_ERR ) {
        addr = -1;
    }
    tlines = n2 - n1 + 1;

    switch( tkn ) {
    case EX_T_APPEND:
        if( !EditFlags.ExMode ) {
            return( ERR_ONLY_VALID_IN_EX_MODE );
        }
        if( !n2f ) {
            rc = Append( n1, true );
        }
        break;
    case EX_T_CHANGE:
        if( !EditFlags.ExMode ) {
            return( ERR_ONLY_VALID_IN_EX_MODE );
        }
        StartUndoGroup( UndoStack );
        rc = DeleteLineRange( n1, n2, 0 );
        if( rc != ERR_NO_ERR ) {
            EndUndoGroup( UndoStack );
            break;
        }
        rc = Append( n1 - 1, false );
        if( rc != ERR_NO_ERR ) {
            EndUndoGroup( UndoStack );
            break;
        }
        break;
    case EX_T_COPY:
        if( addr < 0 || IsPastLastLine( addr ) ) {
            return( ERR_INVALID_ADDRESS );
        }
        i = GetCopyOfLineRange( n1, n2, &fcblist );
        if( i ) {
            break;
        }
        rc = InsertLines( addr, &fcblist, UndoStack );
        GoToLineNoRelCurs( addr );
        if( rc == ERR_NO_ERR ) {
            Message1( strCmmsg, tlines, "copied", addr );
        }
        break;
    case EX_T_INSERT:
        if( !EditFlags.ExMode ) {
            return( ERR_ONLY_VALID_IN_EX_MODE );
        }
        if( !n2f ) {
            rc = Append( n1 - 1, true );
        }
        break;
    case EX_T_JOIN:
        if( SaveAndResetFilePos( n1 ) != ERR_NO_ERR ) {
            rc = ERR_NO_SUCH_LINE;
            break;
        }
        if( tlines == 1 ) {
            n2 = n1 + 1;
            tlines = 2;
        }
        SetRepeatCount( tlines - 1 );
        rc = JoinCurrentLineToNext();
        RestoreCurrentFilePos();
        GoToLineNoRelCurs( n1 );
        if( rc == ERR_NO_ERR ) {
            Message1( "lines %l to %l joined", n1, n2 );
        }
        break;
    case EX_T_LIST:
        if( !EditFlags.ExMode ) {
            return( ERR_ONLY_VALID_IN_EX_MODE );
        }
        for( rc = CGimmeLinePtr( n1, &cfcb, &cline ); rc == ERR_NO_ERR; rc = CGimmeNextLinePtr( &cfcb, &cline ) ) {
            if( EditFlags.LineNumbers ) {
                MyPrintf( "%M %s\n", n1, cline->data );
            } else {
                MyPrintf( "%s\n", cline->data );
            }
            if( n1 >= n2 ) {
                break;
            }
            n1++;
        }
        break;
    case EX_T_MARK:
        rc = SetGenericMark( n1, 1, C2VIKEY( word[0] ) );
        break;
    case EX_T_MOVE:
        if( addr < 0 || IsPastLastLine( addr ) ) {
            return( ERR_INVALID_ADDRESS );
        }
        SavebufNumber = WORK_SAVEBUF;
        StartUndoGroup( UndoStack );
        rc = DeleteLineRange( n1, n2, SAVEBUF_FLAG );

        if( SavebufNumber != WORK_SAVEBUF ) {
            /* if this changes, the command will fail
             * this could be caused by checking out a read-only file
             * so fix the deleted text and give an error message
             */
            DoUndo();
            return( ERR_INVALID_COMMAND );
        }
        if( rc != ERR_NO_ERR ) {
            EndUndoGroup( UndoStack );
            break;
        }
        if( addr > n2 ) {
            addr -= tlines;
        } else if( addr >= n1 && addr <= n2 ) {
            addr = n1;
        }
        rc = InsertLines( addr, &WorkSavebuf->u.fcbs, UndoStack );
        EndUndoGroup( UndoStack );
        GoToLineNoRelCurs( addr );
        if( rc == ERR_NO_ERR ) {
            Message1( strCmmsg, tlines, "moved", addr );
        }
        break;
    case EX_T_UNDO:
        rc = DoUndo();
        break;
    case EX_T_UNDO_DMT:
        rc = DoUndoUndo();
        break;
    case EX_T_EQUALS:
        Message1( "%l", n1 );
        rc = ERR_NO_ERR;
        break;
    case EX_T_VERSION:
        rc = DoVersion();
        break;
    case EX_T_VISUAL:
    case EX_T_VISUAL_DMT:
        if( EditFlags.LineDisplay ) {
            ScreenPage( -1 );
            EditFlags.ExMode = false;
            EditFlags.LineDisplay = false;
            EditFlags.ClockActive = true;
            ReDisplayScreen();
            DoVersion();
        }
        if( word[0] != '\0' ) {
            rc = EditFile( word, ( tkn == EX_T_VISUAL_DMT ) );
        } else {
            rc = ERR_NO_ERR;
        }
        break;
    }
    return( rc );

} /* ProcessEx */
Exemple #23
0
int
Test_CardTransmiting()
{
	int trycnt,i;
	long result;

	printf("==============================================================\n");
	printf("Part C : Card Transmiting\n");
	printf("==============================================================\n");
	trycnt = 0;

	result = SCardConnect(	 ScardContext,
							 ScardReaderState[CurrentReader].szReader,
							 SCARD_SHARE_EXCLUSIVE,
							 SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1,
							 &ScardHandle[CurrentReader],
							 &ScardProtocol[CurrentReader]);

	if(result != SCARD_S_SUCCESS)
	{		
		PRINTERR(("SCardConnect Fail : %08X\n", result));
		return FALSE;
	}

	printf("Transmit");
	while(trycnt < 10)
	{
		trycnt++;
		ScardIoRequest[CurrentReader].dwProtocol = ScardProtocol[CurrentReader];
		ScardIoRequest[CurrentReader].cbPciLength = sizeof(SCARD_IO_REQUEST);

		RecvLength = MAX_RECV_BUFFER_SIZE;

		printf("...");
#ifdef LINUX_OS
		fflush(stdout);
#endif
		result = SCardTransmit(ScardHandle[CurrentReader],
								&ScardIoRequest[CurrentReader],
								ReadMEMCommand,
								sizeof(ReadMEMCommand),
								&ScardIoRequest[CurrentReader],
								RecvBuffer,
								&RecvLength);

		if(result != SCARD_S_SUCCESS)
		{
			MyPrintf(strlen("Transmit"), strlen("..."), trycnt, "Failed\n");
			PRINTERR(("SCardTransmit Fail : %08X\n", result));
			return FALSE;	
		}


		if(RecvLength != 18)
		{
			isexception = 1;
		}
	}

	if(isexception)
	{
		MyPrintf(strlen("Transmit"), strlen("..."), trycnt, "*Passed\n");
	}
	else
	{
		MyPrintf(strlen("Transmit"), strlen("..."), trycnt, "Passed\n");
	}
	
	printf("\n                Part C Test Successfully\n\n");

	return TRUE;
}
Exemple #24
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 */
BOOL EncryptDecryptFile(LPTSTR lpszCertificateName,
                        LPTSTR lpszCertificateStoreName,
                        DWORD  dwCertStoreOpenFlags,
                        LPTSTR lpszInputFileName,
                        LPTSTR lpszOutputFileName,
                        BOOL fEncrypt)
{
    BOOL fResult = FALSE;
    HCRYPTPROV hProv = NULL;
    HCRYPTKEY hRSAKey = NULL;
    HCRYPTKEY hSessionKey = NULL;
    HANDLE hInFile = INVALID_HANDLE_VALUE;
    HANDLE hOutFile = INVALID_HANDLE_VALUE;
    BOOL finished = FALSE;
    BYTE pbBuffer[OUT_BUFFER_SIZE];
    DWORD dwByteCount = 0;
    DWORD dwBytesRead = 0;
    DWORD dwBytesWritten = 0;
    LPBYTE pbSessionKeyBlob = NULL;
    DWORD dwSessionKeyBlob = 0;
    BOOL fCallerFreeProv = FALSE;
    PCCERT_CONTEXT pCertContext = NULL;
    BOOL fSuccess = FALSE;

    __try
    {
        pCertContext = GetCertificateContextFromName(lpszCertificateName,
                       lpszCertificateStoreName,
                       dwCertStoreOpenFlags);
        if (pCertContext == NULL)
        {
            __leave;
        }

        fResult = AcquireAndGetRSAKey(pCertContext,
                                      &hProv,
                                      &hRSAKey,
                                      fEncrypt,
                                      &fCallerFreeProv);
        if (fResult == FALSE)
        {
            __leave;
        }

        // Open the input file to be encrypted or decrypted
        hInFile = CreateFile(lpszInputFileName,
                             GENERIC_READ,
                             0,
                             NULL,
                             OPEN_EXISTING,
                             FILE_ATTRIBUTE_NORMAL,
                             NULL);
        if (hInFile == INVALID_HANDLE_VALUE)
        {
            MyPrintf(_T("CreateFile failed with %d\n"), GetLastError());
            __leave;
        }

        // Open the output file to write the encrypted or decrypted data
        hOutFile = CreateFile(lpszOutputFileName,
                              GENERIC_WRITE,
                              0,
                              NULL,
                              CREATE_ALWAYS,
                              FILE_ATTRIBUTE_NORMAL,
                              NULL);
        if (hOutFile == INVALID_HANDLE_VALUE)
        {
            MyPrintf(_T("CreateFile failed with %d\n"), GetLastError());
            __leave;
        }

        if (fEncrypt)
        {
            fResult = CryptGenKey(hProv, CALG_RC4, CRYPT_EXPORTABLE, &hSessionKey);
            if (!fResult)
            {
                MyPrintf(_T("CryptGenKey failed with %X\n"), GetLastError());
                __leave;
            }

            // The first call to ExportKey with NULL gets the key size.
            dwSessionKeyBlob = 0;
            fResult = CryptExportKey(hSessionKey, hRSAKey, SIMPLEBLOB, 0,
                                     NULL, &dwSessionKeyBlob);
            if (!fResult)
            {
                MyPrintf(_T("CryptExportKey failed with %X\n"), GetLastError());
                __leave;
            }

            // Allocate memory for Encrypted Session key blob
            pbSessionKeyBlob = (LPBYTE)LocalAlloc(LPTR, dwSessionKeyBlob);
            if (!pbSessionKeyBlob)
            {
                MyPrintf(_T("LocalAlloc failed with %d\n"), GetLastError());
                __leave;
            }

            fResult = CryptExportKey(hSessionKey, hRSAKey, SIMPLEBLOB, 0,
                                     pbSessionKeyBlob, &dwSessionKeyBlob);
            if (!fResult)
            {
                MyPrintf(_T("CryptExportKey failed with %X\n"), GetLastError());
                __leave;
            }

            // Write the size of key blob, then the key blob itself, to output file.
            fResult = WriteFile(hOutFile, &dwSessionKeyBlob,
                                sizeof(dwSessionKeyBlob),
                                &dwBytesWritten, NULL);
            if (!fResult)
            {
                MyPrintf(_T("WriteFile failed with %d\n"), GetLastError());
                __leave;
            }
            fResult = WriteFile(hOutFile, pbSessionKeyBlob,
                                dwSessionKeyBlob,
                                &dwBytesWritten, NULL);
            if (!fResult)
            {
                MyPrintf(_T("WriteFile failed with %d\n"), GetLastError());
                __leave;
            }
        }
        else
        {
            // Read in key block size, then key blob itself from input file.
            fResult = ReadFile(hInFile, &dwByteCount, sizeof(dwByteCount),
                               &dwBytesRead, NULL);
            if (!fResult)
            {
                MyPrintf(_T("ReadFile failed with %d\n"), GetLastError());
                __leave;
            }

            fResult = ReadFile(hInFile, pbBuffer, dwByteCount, &dwBytesRead, NULL);
            if (!fResult)
            {
                MyPrintf(_T("ReadFile failed with %d\n"), GetLastError());
                __leave;
            }

            // import key blob into "CSP"
            fResult = CryptImportKey(hProv, pbBuffer, dwByteCount, hRSAKey, 0, &hSessionKey);
            if (!fResult)
            {
                MyPrintf(_T("CryptImportKey failed with %X\n"), GetLastError());
                __leave;
            }
        }

        do
        {
            dwByteCount = 0;

            // Now read data from the input file 64K bytes at a time.
            fResult = ReadFile(hInFile, pbBuffer, IN_BUFFER_SIZE, &dwByteCount, NULL);

            // If the file size is exact multiple of 64K, dwByteCount will be zero after
            // all the data has been read from the input file. In this case, simply break
            // from the while loop. The check to do this is below
            if (dwByteCount == 0)
                break;

            if (!fResult)
            {
                MyPrintf(_T("ReadFile failed with %d\n"), GetLastError());
                __leave;
            }

            finished = (dwByteCount < IN_BUFFER_SIZE);

            // Encrypt/Decrypt depending on the required action.
            if (fEncrypt)
            {
                fResult = CryptEncrypt(hSessionKey, 0, finished, 0, pbBuffer, &dwByteCount,
                                       OUT_BUFFER_SIZE);
                if (!fResult)
                {
                    MyPrintf(_T("CryptEncrypt failed with %X\n"), GetLastError());
                    __leave;
                }
            }
            else
            {
                fResult = CryptDecrypt(hSessionKey, 0, finished, 0, pbBuffer, &dwByteCount);
                if (!fResult)
                {
                    MyPrintf(_T("CryptDecrypt failed with %X\n"), GetLastError());
                    __leave;
                }
            }

            // Write the encrypted/decrypted data to the output file.
            fResult = WriteFile(hOutFile, pbBuffer, dwByteCount,
                                &dwBytesWritten, NULL);
            if (!fResult)
            {
                MyPrintf(_T("WriteFile failed with %d\n"), GetLastError());
                __leave;
            }

        } while (!finished);

        if (fEncrypt)
            MyPrintf(_T("File %s is encrypted successfully!\n"), lpszInputFileName);
        else
            MyPrintf(_T("File %s is decrypted successfully!\n"), lpszInputFileName);

        fSuccess = TRUE;
    }
    __finally
    {
        /* Cleanup */
        CheckAndLocalFree(pbSessionKeyBlob);
        if (pCertContext != NULL) CertFreeCertificateContext(pCertContext);
        if (hRSAKey != NULL) CryptDestroyKey(hRSAKey);
        if (hSessionKey != NULL) CryptDestroyKey(hSessionKey);
        if (fCallerFreeProv && hProv != NULL) CryptReleaseContext(hProv, 0);
        if (hInFile != INVALID_HANDLE_VALUE) CloseHandle(hInFile);
        if (hOutFile != INVALID_HANDLE_VALUE) CloseHandle(hOutFile);
    }

    return fSuccess;
}
BOOL AcquireAndGetRSAKey(PCCERT_CONTEXT pCertContext,
                         HCRYPTPROV *phProv,
                         HCRYPTKEY *phRSAKey,
                         BOOL fEncrypt,
                         BOOL *pfCallerFreeProv)
{
    BOOL fSuccess = FALSE;
    DWORD dwKeySpec = 0;

    __try
    {
        *phProv = NULL;
        *phRSAKey = NULL;
        *pfCallerFreeProv = FALSE;

        if (fEncrypt)
        {
            // Acquire context for RSA key
            fSuccess = CryptAcquireContext(phProv,
                                           NULL,
                                           MS_DEF_PROV,
                                           PROV_RSA_FULL,
                                           CRYPT_VERIFYCONTEXT);
            if (!fSuccess)
            {
                MyPrintf(_T("CryptAcquireContext failed with %X\n"), GetLastError());
                __leave;
            }

            // Import the RSA public key from the certificate context
            fSuccess = CryptImportPublicKeyInfo(*phProv,
                                                MY_ENCODING,
                                                &(pCertContext->pCertInfo->SubjectPublicKeyInfo),
                                                phRSAKey);
            if (!fSuccess)
            {
                MyPrintf(_T("CryptImportPublicKeyInfo failed with %X\n"), GetLastError());
                __leave;
            }

            *pfCallerFreeProv = TRUE;
        }
        else
        {
            // Acquire the RSA private key
            fSuccess = CryptAcquireCertificatePrivateKey(pCertContext,
                       CRYPT_ACQUIRE_USE_PROV_INFO_FLAG|CRYPT_ACQUIRE_COMPARE_KEY_FLAG,
                       NULL, phProv, &dwKeySpec, pfCallerFreeProv);
            if (!fSuccess)
            {
                MyPrintf(_T("CryptAcquireCertificatePrivateKey failed with %X\n"), GetLastError());
                __leave;
            }

            // Get the RSA key handle
            fSuccess = CryptGetUserKey(*phProv, dwKeySpec, phRSAKey);
            if (!fSuccess)
            {
                MyPrintf(_T("CryptGetUserKey failed with %X\n"), GetLastError());
                __leave;
            }
        }
    }
    __finally
    {
        if (fSuccess == FALSE)
        {
            if (phProv && *phProv != NULL)
            {
                CryptReleaseContext(*phProv, 0);
                *phProv = NULL;
            }
            if (phRSAKey && *phRSAKey != NULL)
            {
                CryptDestroyKey(*phRSAKey);
                *phRSAKey = NULL;
            }
        }
    }

    return fSuccess;
}
Exemple #27
0
/*
 * LostFileCheck - check if there are any lost files out there
 */
bool LostFileCheck( void )
{
    char        path[FILENAME_MAX];
    vi_key      key;
    char        ch;
    int         off;
    int         handle;

    MakeTmpPath( path, lockFileName );
    off = strlen( path ) - 5;
    for( ch = START_CHAR; ch <= END_CHAR; ch++ ) {
        path[off] = ch;
        handle = sopen3( path, O_RDONLY | O_TEXT, SH_DENYRW );
        if( handle > 0 ) {
            MakeTmpPath( path, checkFileName );
            path[off] = ch;
            if( access( path, F_OK ) == -1 ) {
                MakeTmpPath( path, lockFileName );
                path[off] = ch;
                close( handle );
                handle = -1;
                remove( path );
            } else {
                break;
            }
        }
    }
    if( handle > 0 ) {
        close( handle );
        if( !EditFlags.RecoverLostFiles ) {
            if( !EditFlags.IgnoreLostFiles ) {
#ifdef __WIN__
                CloseStartupDialog();
                key = GetAutosaveResponse();
                handleKey( key );
                ShowStartupDialog();
                return( TRUE );
#else
                SetPosToMessageLine();
                MyPrintf( "Files have been lost since your last session, do you wish to:\n" );
                MyPrintf( "\ti)gnore\n\tr)ecover\n\tq)uit\n" );
                for( ;; ) {
                    key = GetKeyboard();
                    if( handleKey( key ) ) {
                        return( TRUE );
                    }
                }
#endif
            } else {
                remove( path );
                return( FALSE );
            }
        }
    } else {
        if( EditFlags.RecoverLostFiles ) {
            EditFlags.RecoverLostFiles = FALSE;
            EditFlags.NoInitialFileLoad = FALSE;
        }
    }
    return( FALSE );

} /* LostFileCheck */
void _tmain(int argc, TCHAR *argv[])
{
   HCRYPTPROV hProv = NULL;
   HCRYPTKEY hPubKey = NULL;   
   PCCERT_CONTEXT pCertContext = NULL;
   LPTSTR szCertificateName = NULL;
   LPTSTR szStoreName = NULL;
   LPTSTR szContainerName = NULL;   
   LPTSTR szFileToSign = NULL;
   LPTSTR szSigFile = NULL;
   DWORD dwOpenFlags = CERT_SYSTEM_STORE_CURRENT_USER;
   DWORD dwAcquireFlags = 0;
   DWORD dwKeySpec = AT_SIGNATURE;
   ALG_ID AlgId;   
   BOOL fSign = FALSE;
   BOOL fResult = FALSE;
   BOOL fUseCert = FALSE;
   BOOL fFreeProv = FALSE;

   if (argc != 9)
   {
      PrintUsage();
      return;
   }

   __try
   {  
      // Determine hash algorithm
      if (lstrcmpi(argv[1], _T("sha1")) == 0)
      {
         AlgId = CALG_SHA1;
      }
      else if (lstrcmpi(argv[1], _T("md5")) == 0)
      {
         AlgId = CALG_MD5;
      }
      else
      {
         PrintUsage();
         return;
      }

      /* Check whether the action to be performed is to sign or verify */
      if (lstrcmpi(argv[2], _T("/s")) == 0)
      {
         fSign = TRUE;
      }
      else if (lstrcmpi(argv[2], _T("/v")) == 0)
      {
         fSign = FALSE;
      }
      else
      {
         PrintUsage();
         return;
      }

      szFileToSign = argv[3];
      szSigFile = argv[4];

      // check to see if user wants to use a certificate
      if (lstrcmpi(argv[5], _T("/cert")) == 0)
      {
         fUseCert = TRUE;
         
         szCertificateName = argv[6];
         szStoreName = argv[7];

         // Determine if we have to use user or machine store
         if (lstrcmpi(argv[8], _T("u")) == 0)
         {
            dwOpenFlags = CERT_SYSTEM_STORE_CURRENT_USER;
         }
         else if (lstrcmpi(argv[8], _T("m")) == 0)
         {
            dwOpenFlags = CERT_SYSTEM_STORE_LOCAL_MACHINE;
         }
         else
         {
            PrintUsage();
            return;
         }
      }
      else if (lstrcmpi(argv[5], _T("/key")) == 0)
      {
         fUseCert = FALSE;

         szContainerName = argv[6];

         if (lstrcmpi(argv[7], _T("u")) == 0)
         {
            dwAcquireFlags = 0;
         }
         else if (lstrcmpi(argv[7], _T("m")) == 0)
         {
            dwAcquireFlags = CRYPT_MACHINE_KEYSET;
         }
         else
         {
            PrintUsage();
            return;
         }

         // Use exchange key or signature key
         if (lstrcmpi(argv[8], _T("x")) == 0)
         {
            dwKeySpec = AT_KEYEXCHANGE;
         }
         else if (lstrcmpi(argv[8], _T("s")) == 0)
         {
            dwKeySpec = AT_SIGNATURE;
         }
         else
         {
            PrintUsage();
            return;
         }
      }
      else
      {
         PrintUsage();
         return;
      }

      if (fUseCert)
      {
         pCertContext = GetCertificateContextFromName(szCertificateName,
                                                      szStoreName,
                                                      dwOpenFlags);
         if (!pCertContext) __leave;
         
         fResult = GetRSAKeyFromCert(pCertContext,
                                     fSign,
                                     &hProv,
                                     &hPubKey,
                                     &dwKeySpec,
                                     &fFreeProv);
         if (!fResult) __leave;
      }
      else
      {
         fResult = GetRSAKeyFromContainer(szContainerName,
                                          dwAcquireFlags,
                                          dwKeySpec,
                                          &hProv,                            
                                          &hPubKey);         
         if (!fResult) __leave;

         fFreeProv = TRUE;
      }
      
      fResult = SignVerifyFile(hProv,
                               hPubKey,
                               dwKeySpec,
                               AlgId,
                               szFileToSign,
                               szSigFile,
                               fSign);
      if (!fResult) __leave;
      
      if (fSign)
      {
         MyPrintf(_T("File %s hashed and signed successfully!\n"), szFileToSign);
      }
      else
      {
         MyPrintf(_T("File %s verified successfully!\n"), szSigFile);
      }
   }
   __finally
   {
      // Clean up      
      if (hPubKey != NULL) CryptDestroyKey(hPubKey);
      if (fFreeProv && (hProv != NULL)) CryptReleaseContext(hProv, 0);
      if (pCertContext != NULL) CertFreeCertificateContext(pCertContext);      
   }
}
Exemple #29
0
/*
 * AutoSaveInit - initialize for auto-save
 */
void AutoSaveInit( void )
{
    char        path[FILENAME_MAX];
    char        path2[FILENAME_MAX];
    char        as_path[FILENAME_MAX];
    char        asl_path[FILENAME_MAX];
    int         len;
    int         cnt;
    FILE        *f;
    int         pid;
    int         ch;
    int         handle;
    int         off;
//    int         old_len;
    int         i;

    /*
     * initialize tmpname
     */
#ifdef __UNIX__
    strcpy( currTmpName,"aaaaaaaaaaaa.tmp" );
#else
    strcpy( currTmpName,"aaaaaaaa.tmp" );
#endif
    pid = getpid();
    itoa( pid, path, 36 );
    len = strlen( path );
    memcpy( &currTmpName[TMP_FNAME_LEN - len], path, len );
#ifdef __QNX__
    {
        int     len2, len3;
        int     nid, uid;

        nid = getnid();
        itoa( nid, path, 36 );
        len2 = strlen( path );
        memcpy( &currTmpName[TMP_FNAME_LEN - len - len2], path, len2 );

        uid = getuid();
        itoa( uid, path, 36 );
        len3 = strlen( path );
        memcpy( &currTmpName[TMP_FNAME_LEN - len - len2 - len3], path, len3 );
        memcpy( &checkFileName[EXTRA_EXT_OFF], path, len3 );
        memcpy( &checkFileTmpName[EXTRA_EXT_OFF], path, len3 );
        memcpy( &lockFileName[EXTRA_EXT_OFF], path, len3 );
    }
#endif

    /*
     * check if we need to recover lost files
     */
    if( EditFlags.RecoverLostFiles ) {
        cnt = 0;
        MakeTmpPath( as_path, checkFileName );
        MakeTmpPath( asl_path, lockFileName );
        off = strlen( as_path ) - 5;
        for( ch = START_CHAR; ch <= END_CHAR; ch++ ) {
            as_path[off] = ch;
            asl_path[off] = ch;
            handle = sopen3( as_path, O_RDONLY | O_TEXT, SH_DENYRW );
            if( handle < 0 ) {
                continue;
            }
            f = fdopen( handle, "r" );
            if( f != NULL ) {
                while( fgets( path2, FILENAME_MAX, f ) != NULL ) {
                    for( i = strlen( path2 ); i && isWSorCtrlZ( path2[i - 1] ); --i ) {
                        path2[i - 1] = '\0';
                    }
                    NextWord1( path2, path );
                    RemoveLeadingSpaces( path2 );
                    NewFile( path, FALSE );
                    AddString2( &(CurrentFile->name), path2 );
                    SetFileWindowTitle( CurrentWindow, CurrentInfo, TRUE );
                    FileSPVAR();
                    CurrentFile->modified = TRUE;
                    CurrentFile->check_readonly = TRUE;
                    FTSRunCmds( path2 );
                    cnt++;
                }
                fclose( f );
                remove( as_path );
            } else {
                close( handle );
            }
            remove( asl_path );
        }
        if( cnt == 0 ) {
            MyPrintf( "No files recovered!\n" );
            ExitEditor( -1 );
        }
        Message1( "%d files recovered", cnt );

    }
    if( EditVars.AutoSaveInterval == 0 ) {
        return;
    }

//    old_len = strlen( lockFileName );
    MakeTmpPath( path, lockFileName );
    len = strlen( path ) - strlen( lockFileName );
    off = len + CHAR_OFF;
    for( ch = START_CHAR; ch <= END_CHAR; ch++ ) {
        path[off] = ch;
        lockFileHandle = sopen4( path, O_CREAT | O_TRUNC | O_RDWR | O_TEXT, SH_DENYRW, PMODE_RW );
        if( lockFileHandle > 0 ) {
            break;
        }
    }
    if( lockFileHandle < 0 ) {
        // MyPrintf( "Too many editors running!\n" );
        MyPrintf( "Error opening temp file - '%s'\n", strerror( errno ) );
        ExitEditor( -1 );
    }
    lockFileName[CHAR_OFF] = ch;
    checkFileName[CHAR_OFF] = ch;
    checkFileTmpName[CHAR_OFF] = ch;

} /* AutoSaveInit */
BOOL GetRSAKeyFromCert(PCCERT_CONTEXT pCertContext,
                       BOOL fSign,
                       HCRYPTPROV *hProv,
                       HCRYPTKEY *hPubKey,
                       DWORD *dwKeySpec,
                       BOOL *fFreeProv)
{   
   BOOL fResult;
   BOOL fReturn = FALSE;
   
   __try
   {  
      if (hProv == NULL || hPubKey == NULL || 
          dwKeySpec == NULL || fFreeProv == NULL)
      {
         __leave;
      }

      *hProv = 0;
      *hPubKey = 0;
      *fFreeProv = FALSE;
    
      if (fSign)
      {
         // Acquire the certificate's private key
         fResult = CryptAcquireCertificatePrivateKey(pCertContext,
                                                     CRYPT_ACQUIRE_USE_PROV_INFO_FLAG|
                                                     CRYPT_ACQUIRE_COMPARE_KEY_FLAG,
                                                     NULL,
                                                     hProv,
                                                     dwKeySpec,
                                                     fFreeProv);
         if (!fResult)
         {
            MyPrintf(_T("CryptAcquireCertificatePrivateKey failed with %x\n"), GetLastError());
            __leave;
         }
      }
      else
      {
         fResult = CryptAcquireContext(hProv, 
                                       NULL, 
                                       MS_DEF_PROV,
                                       PROV_RSA_FULL, 
                                       CRYPT_VERIFYCONTEXT);
         if (!fResult)
         {
            MyPrintf(_T("CryptAcquireContext failed with %x\n"), GetLastError());
            __leave;
         }

         *fFreeProv = TRUE;

         // Import the public key from the certificate so we can verify
         fResult = CryptImportPublicKeyInfo(*hProv,
                                            ENCODING,
                                            &(pCertContext->pCertInfo->SubjectPublicKeyInfo),
                                            hPubKey);
         if (!fResult)
         {
            MyPrintf(_T("CryptImportPublicKeyInfo failed with %x\n"), GetLastError());
            __leave;
         }         
      }

      fReturn = TRUE;
   }
   __finally
   {
      if (!fReturn)
      {
         if (*hPubKey != NULL) 
         {
            CryptDestroyKey(*hPubKey);
            *hPubKey = NULL;
         }

         if ((*fFreeProv == TRUE) && (*hProv != NULL)) 
         {
            CryptReleaseContext(*hProv, 0);
            *hProv = NULL;
            *fFreeProv = FALSE;
         }
      }
   }

   return fReturn;
}