Example #1
0
bool CTlsSocket::Init()
{
	// This function initializes GnuTLS
	m_initialized = true;
	int res = gnutls_global_init();
	if (res) {
		LogError(res, _T("gnutls_global_init"));
		Uninit();
		return false;
	}

#if TLSDEBUG
	if (!pLoggingControlSocket) {
		pLoggingControlSocket = m_pOwner;
		gnutls_global_set_log_function(log_func);
		gnutls_global_set_log_level(99);
	}
#endif
	res = gnutls_certificate_allocate_credentials(&m_certCredentials);
	if (res < 0) {
		LogError(res, _T("gnutls_certificate_allocate_credentials"));
		Uninit();
		return false;
	}

	if (!InitSession())
		return false;

	m_shutdown_requested = false;

	// At this point, we can start shaking hands.

	return true;
}
Example #2
0
CQuickSyncDecoder::CQuickSyncDecoder(const CQsConfig& cfg, mfxStatus& sts) :
    m_mfxVideoSession(NULL),
    m_mfxImpl(MFX_IMPL_UNSUPPORTED),
    m_Config(cfg),
    m_pmfxDEC(0),
    m_pVideoParams(0),
    m_pFrameAllocator(NULL),
    m_pFrameSurfaces(NULL),
    m_nRequiredFramesNum(0),
    m_nAuxFrameCount(0),
    m_pRendererD3dDeviceManager(NULL),
    m_HwDevice(NULL)
{
    MSDK_ZERO_VAR(m_AllocResponse);

    m_ApiVersion.Major = MIN_REQUIRED_API_VER_MAJOR;
    m_ApiVersion.Minor = MIN_REQUIRED_API_VER_MINOR;
    mfxIMPL impl = MFX_IMPL_AUTO_ANY;

    // Uncomment for SW emulation (Media SDK software DLL must be present)
    //impl = MFX_IMPL_SOFTWARE;

    int d3d9IntelAdapter = 0;
    if (impl != MFX_IMPL_SOFTWARE)
    {
        d3d9IntelAdapter = GetIntelAdapterIdD3D9(NULL);

        // select d3d9 or d3d11 HW implementation base on config and GPU/OS capabilities
        if (d3d9IntelAdapter >= 0 && !m_Config.bDefaultToD3D11)
        {
            impl |= MFX_IMPL_VIA_D3D9;
        }
        else if (m_Config.bEnableD3D11)
        {
            impl |= MFX_IMPL_VIA_D3D11;
        }
        else
        {
            MSDK_TRACE("QsDecoder: Can't create HW decoder, the iGPU is not connected to a screen!\n");
            sts = MFX_ERR_UNSUPPORTED;
            return;
        }
    }

    sts = InitSession(impl);
    if (MSDK_SUCCEEDED(sts) && !m_Config.bEnableD3D11 && 0 > d3d9IntelAdapter)
    {
        MSDK_TRACE("QsDecoder: can't create HW decoder, the iGPU is not connected to a screen!\n");
        sts = MFX_ERR_UNSUPPORTED;
    }
}
Example #3
0
void MetainfoSocket::OnDelete()
{
	if (m_fil)
	{
		fclose(m_fil);
		m_fil = NULL;
		if (m_sz_read == m_sz)
		{
			InitSession();
		}
		else
		{
			
		}
	}
}
Example #4
0
CNetCom* CNetMgr::CreateNewSession()
{_STT();
	// Acquire lock
	CTlLocalLock ll( *this );
	if ( !ll.IsLocked() ) return NULL;

	// Delete invalid connections
	Cleanup();

	// Create specialized session object
	CNetCom* pNc = CreateSessionObject();
	if ( pNc == NULL ) return FALSE;

	// Initialize
	InitSession( pNc );

	return pNc;
}
bool
JabberProtocol::BeginSession() 
{
	if (host == "" || domain == "" || user == "" || pass == "" || port <= 0)
		return false;

	socketAdapter->Create();
	socketAdapter->Open(host, port);
	
	if (secure)
		socketAdapter->StartTLS();
		
	if (socketAdapter->IsConnected())
	{
		InitSession();
		return true;
	}

	return false;
}
Example #6
0
void CIVConnection::OnPostRequest	(WPARAM wParam, LPARAM lParam)
{
	ASSERT (!m_strRequest.IsEmpty());
	try
	{
		InitSession();

		CString strSID = Login();

		CString strRequest;
		strRequest.Format (m_strRequest, (LPCTSTR) strSID );

		GetHTTPData (strRequest, m_strResult);
	}
	catch (CException * e )
	{
		e->Delete();
	}

	CloseSession();
	SetReady (true);	
}
Example #7
0
bool CTlsSocket::CopySessionData(const CTlsSocket* pPrimarySocket)
{
	gnutls_datum_t d;
	int res = gnutls_session_get_data2(pPrimarySocket->m_session, &d);
	if (res) {
		m_pOwner->LogMessage(MessageType::Debug_Warning, _T("gnutls_session_get_data2 on primary socket failed: %d"), res);
		return true;
	}

	// Set session data
	res = gnutls_session_set_data(m_session, d.data, d.size );
	gnutls_free(d.data);
	if (res) {
		m_pOwner->LogMessage(MessageType::Debug_Info, _T("gnutls_session_set_data failed: %d. Going to reinitialize session."), res);
		UninitSession();
		if (!InitSession())
			return false;
	}
	else
		m_pOwner->LogMessage(MessageType::Debug_Info, _T("Trying to resume existing TLS session."));

	return true;
}
Example #8
0
bool CTlsSocket::CopySessionData(const CTlsSocket* pPrimarySocket)
{
	size_t session_data_size = 0;

	// Get buffer size
	int res = gnutls_session_get_data(pPrimarySocket->m_session, 0, &session_data_size);
	if (res && res != GNUTLS_E_SHORT_MEMORY_BUFFER )
	{
		m_pOwner->LogMessage(Debug_Warning, _T("gnutls_session_get_data on primary socket failed: %d"), res);
		return true;
	}

	// Get session data
	char *session_data = new char[session_data_size];
	res = gnutls_session_get_data(pPrimarySocket->m_session, session_data, &session_data_size);
	if (res)
	{
		delete [] session_data;
		m_pOwner->LogMessage(Debug_Warning, _T("gnutls_session_get_data on primary socket failed: %d"), res);
		return true;
	}

	// Set session data
	res = gnutls_session_set_data(m_session, session_data, session_data_size );
	delete [] session_data;
	if (res)
	{
		m_pOwner->LogMessage(Debug_Info, _T("gnutls_session_set_data failed: %d. Going to reinitialize session."), res);
		UninitSession();
		if (!InitSession())
			return false;
	}
	else
		m_pOwner->LogMessage(Debug_Info, _T("Trying to resume existing TLS session."));

	return true;
}
Example #9
0
int
main (int argc, char *argv[])
{
	ASFlagType flags = 0 ; 
	int i;
	char * initial_command = NULL ;
	static char *deleted_arg = "_deleted_arg_" ;

	memset( &AppState, 0x00, sizeof(AppState));

	InitMyApp (CLASS_ASMOUNT, argc, argv, NULL, NULL, 0 );
	for( i = 1 ; i < argc ; ++i ) 
		if( argv[i] == NULL ) 
			argv[i] = strdup(deleted_arg) ;
 	LinkAfterStepConfig();
 	InitSession();

	g_type_init();
#if 0
	ConnectXDisplay (gdk_x11_display_get_xdisplay(gdk_display_open(NULL)), NULL, False);
#else	
	ConnectX( ASDefaultScr, EnterWindowMask|PropertyChangeMask );
#endif
	
	ReloadASEnvironment( NULL, NULL, NULL, False, True );

	ConnectAfterStep(0,0);
	Config = AS_ASMOUNT_CONFIG(parse_asmodule_config_all( getASMountConfigClass() )/*asm_config*/);
	CheckASMountConfigSanity(Config, &TileSize);

	SetASMountLook();
	
	init_ASMount( flags, initial_command);
	mainLoop();	
 	return 0;
}
Example #10
0
int
main (int argc, char **argv)
{
	int i ; 
	char *source_dir = NULL ;
	const char *destination_dir = NULL ;
	Bool do_data = False;
	ASDocType target_type = DocType_Source ;
	/* Save our program name - for error messages */
	set_DeadPipe_handler(DeadPipe);
    InitMyApp (CLASS_ASDOCGEN, argc, argv, NULL, asdocgen_usage, 0 );
	LinkAfterStepConfig();
	InitSession();
    for( i = 1 ; i< argc ; ++i)
	{
		LOCAL_DEBUG_OUT( "argv[%d] = \"%s\", original argv[%d] = \"%s\"", i, argv[i]?argv[i]:"(null)", i, MyArgs.saved_argv[i]);	  
		if( argv[i] != NULL  )
		{
			if( (strcmp( argv[i], "-t" ) == 0 || strcmp( argv[i], "--target" ) == 0) && i+1 < argc && argv[i+1] != NULL ) 
			{
				++i ;
				if( mystrcasecmp( argv[i], "plain" ) == 0 || mystrcasecmp( argv[i], "text" ) == 0) 
					target_type = DocType_Plain ; 														   
				else if( mystrcasecmp( argv[i], "html" ) == 0 ) 
					target_type = DocType_HTML ; 														   
				else if( mystrcasecmp( argv[i], "php" ) == 0 ) 
					target_type = DocType_PHP ; 														   
				else if( mystrcasecmp( argv[i], "xml" ) == 0 ) 
					target_type = DocType_XML ; 														   
				else if( mystrcasecmp( argv[i], "nroff" ) == 0 ) 
					target_type = DocType_NROFF ; 														   
				else if( mystrcasecmp( argv[i], "source" ) == 0 ) 
					target_type = DocType_Source ; 														   
				else
					show_error( "unknown target type \"%s\"" );
			}else if( (strcmp( argv[i], "-s" ) == 0 || strcmp( argv[i], "--css" ) == 0) && i+1 < argc && argv[i+1] != NULL ) 
			{
				++i ;				
				HTML_CSS_File = argv[i] ;
			}else if( strcmp( argv[i], "--faq-css" ) == 0 && i+1 < argc && argv[i+1] != NULL ) 
			{
				++i ;				
				FAQ_HTML_CSS_File = argv[i] ;
			}else if( strcmp( argv[i], "--html-data-back" ) == 0 && i+1 < argc && argv[i+1] != NULL ) 
			{
				++i ;				
				if( strcasecmp( argv[i], "none") == 0 ) 
					HTML_DATA_BACKGROUND_File = NULL ;
				else
					HTML_DATA_BACKGROUND_File = argv[i] ;
			}else if( (strcmp( argv[i], "-d" ) == 0 || strcmp( argv[i], "--data" ) == 0) ) 
			{
				do_data = True ;
			}else if( (strcmp( argv[i], "-S" ) == 0 || strcmp( argv[i], "--source" ) == 0) && i+1 < argc && argv[i+1] != NULL ) 
			{
				++i ;				
				source_dir = argv[i] ;
			}else if( (strcmp( argv[i], "-D" ) == 0 || strcmp( argv[i], "--dst" ) == 0) && i+1 < argc && argv[i+1] != NULL ) 
			{
				++i ;				
				destination_dir = argv[i] ;
			}
		}
	}		  
	if( destination_dir == NULL ) 
		destination_dir = do_data?"data":ASDocTypeExtentions[target_type] ;
	if( source_dir == NULL ) 
		source_dir = do_data?"../../afterstep":"source" ;

#if 0

    ConnectAfterStep ( mask_reg, 0);
	
  	SendInfo ( "Nop \"\"", 0);
#endif
	ProcessedSyntaxes = create_ashash( 7, pointer_hash_value, NULL, NULL );
	Glossary = create_ashash( 4096, string_hash_value, string_compare, string_destroy );
	Index = create_ashash( 4096, string_hash_value, string_compare, string_destroy );
	UserLinks = create_ashash( 4096, string_hash_value, string_compare, string_destroy );
	APILinks = create_ashash( 4096, string_hash_value, string_compare, string_destroy );

	Links = UserLinks;

	GlossaryName = UserGlossaryName ; 
	TopicIndexName = UserTopicIndexName ; 

	if( target_type < DocType_Source )
	{	
		time_t curtime;
    	struct tm *loctime;
		
		DocBookVocabulary = create_ashash( 7, casestring_hash_value, casestring_compare, string_destroy_without_data );
		for( i = 1 ; i < DOCBOOK_SUPPORTED_IDS ; ++i )
			add_hash_item( DocBookVocabulary, AS_HASHABLE(SupportedDocBookTagInfo[i].tag), (void*)(SupportedDocBookTagInfo[i].tag_id));
		
		/* Get the current time. */
		curtime = time (NULL);
     	/* Convert it to local time representation. */
		loctime = localtime (&curtime);
		strftime(CurrentDateLong, DATE_SIZE, "%b %e %Y", loctime);
		strftime(CurrentDateShort, DATE_SIZE, "%m/%d/%Y", loctime);
	}
	i = 0 ; 
	LOCAL_DEBUG_OUT( "Starting main action... %s", "" );
	
	if( target_type >= DocType_Source ) /* 1) generate HTML doc structure */
	{
		while( TopLevelSyntaxes[i] )
		{	/* create directory structure for source docs and all the missing files */
			check_syntax_source( source_dir, TopLevelSyntaxes[i], (i >= MODULE_SYNTAX_START) );
			++i ;	
		}
		check_syntax_source( source_dir, NULL, True );
	}else if( do_data )
	{	
		char *env_path1 = NULL, *env_path2 = NULL ;
		ASColorScheme *cs = NULL ;
		
	    if ((dpy = XOpenDisplay (MyArgs.display_name)))
		{
			set_current_X_display (dpy);
			Scr.MyDisplayWidth = DisplayWidth (dpy, Scr.screen);
			Scr.MyDisplayHeight = DisplayHeight (dpy, Scr.screen);

		    Scr.asv = create_asvisual (dpy, Scr.screen, DefaultDepth(dpy,Scr.screen), NULL);
		}else
		{		    
			Scr.asv = create_asvisual(NULL, 0, 32, NULL);
		}
		
		asxml_var_insert("xroot.width", 640);
    	asxml_var_insert("xroot.height", 480);
		
		env_path1 = getenv( "IMAGE_PATH" ) ;
		env_path2 = getenv( "PATH" );
		if( env_path1 == NULL ) 
		{
			env_path1 = env_path2;
			env_path2 = NULL ;
		}
	    Scr.image_manager = create_image_manager( NULL, 2.2, env_path1, env_path2, NULL );
		set_xml_image_manager( Scr.image_manager );
        
		env_path1 = getenv( "FONT_PATH" ) ;
		Scr.font_manager = create_font_manager( dpy, env_path1, NULL );
		set_xml_font_manager( Scr.font_manager );

		/*ReloadASEnvironment( NULL, NULL, NULL, False ); */
		cs = make_default_ascolor_scheme();
		populate_ascs_colors_rgb( cs );
		populate_ascs_colors_xml( cs );
		free( cs );

		TopicIndexName = NULL ;
		
		CurrHtmlBackFile = HTML_DATA_BACKGROUND_File ;
		gen_data_doc( 	source_dir, destination_dir?destination_dir:"data", "",
			  		  	"Installed data files - fonts, images and configuration",
			  			target_type );

		flush_ashash( Glossary );
		flush_ashash( Index );
	}else
	{
		char *api_dest_dir ;
		api_dest_dir = make_file_name( destination_dir, "API" );
		
		GlossaryName = UserGlossaryName ; 
		TopicIndexName = UserTopicIndexName ; 
		Links = UserLinks;

		DocGenerationPass = 2 ;
		while( --DocGenerationPass >= 0 ) 
		{
			gen_code_doc( "../../libAfterImage", destination_dir, 
			  		  	"asimagexml.c", 
			  		  	"AfterImage XML",
			  		  	"XML schema to be used for scripting image manipulation by AfterStep and ascompose",
			  		  	target_type );
		
			/* we need to generate some top level files for afterstep itself : */
			gen_syntax_doc( source_dir, destination_dir, NULL, target_type );
		
			for( i = 0 ; TopLevelSyntaxes[i] ; ++i )
				gen_syntax_doc( source_dir, destination_dir, TopLevelSyntaxes[i], target_type );
			
			if( DocGenerationPass == 0 ) 
			{	
				gen_faq_doc( source_dir, destination_dir, target_type );
				gen_glossary( destination_dir, "Glossary", target_type );
				gen_index( destination_dir, "index", target_type, True );
			}
			flush_ashash( ProcessedSyntaxes );
		}
		flush_ashash( Glossary );
		flush_ashash( Index );
		
		GlossaryName = APIGlossaryName ; 
		TopicIndexName = APITopicIndexName ; 
		Links = APILinks;
		DocGenerationPass = 2 ;
		
		CurrentManType = 3 ;
		
		while( --DocGenerationPass >= 0 ) 
		{
			int s ;
			for( s = 0 ; libAfterImage_Sources[s].src_file != NULL ; ++s ) 
			{	
				gen_code_doc( 	"../../libAfterImage", api_dest_dir, 
			  			  		libAfterImage_Sources[s].src_file, 
			  			  		libAfterImage_Sources[s].descr_short,
			  		  			libAfterImage_Sources[s].descr_long,
			  		  			target_type );
			}
			if( DocGenerationPass == 0 ) 
			{	
				gen_glossary( api_dest_dir, "Glossary", target_type );
				gen_index( api_dest_dir, "index", target_type, False );
			}
			flush_ashash( Glossary );
			flush_ashash( Index );
		}		  


	}		 
	
	if( dpy )   
    	XCloseDisplay (dpy);
    return 0;
}
Example #11
0
void	HandleQuery(Host Session_SN, uchar *Query, int Size)
{
    uchar		*Browser;
    SResponse	Response;
    CLocation	TesterLocation;
    Host		Tested;
    SessProp	*SessionProposal;
    uint Idx = 0;
    uint Rank = 0;

    Browser = Query;

    while (Size > 0)
    {
        Response.Objs = NULL;
        Response.NbObj = 0;
        TCPResponseManager(&Browser, (uint *)&Size, &Response);
        uint Idx = 0;

        switch (Response.Cmd / 8)
        {
        case CMD_QUERY_IPING:
            printf("Received Incoming Initial Ping..\n");
            for (Idx = 0; Idx < Response.NbObj; Idx++)
            {
                switch (Response.Objs[Idx].Id)
                {
                case OBJ_ID_PINGER:
                    printf("Ping Coming From : %s.. Let's Reply..\n", Response.Objs[Idx].Value.Memory.Memory);
                    PingReply(Session_SN, Response.Reply2ID);
                    break;
                default:
                    break;
                }
            }
            break;
        case CMD_QUERY_SESSION:
            printf("Received session proposal..\n");

            SessionProposal = (SessProp *)malloc(sizeof(SessProp));
            SessionProposal->Relays = new queue<Host>;
            SessionProposal->SessID = BytesRandomWord() % 0x7FFF;
            *(uint *)(SessionProposal->PeerChallenge) = BytesRandom();
            *(uint *)(SessionProposal->PeerChallenge + 4) = BytesRandom();

            printf("Challenge to propose to Peer : ");
            showmem((uchar *)SessionProposal->PeerChallenge, 0x08);

            SessionProposal->CreatedSID = 0x00;
            SessionProposal->LocalCreatedSID = 0x00;

            for (Idx = 0; Idx < Response.NbObj; Idx++)
            {
                if (Response.Objs[Idx].ObjListInfos.Id == -1)
                {
                    switch(Response.Objs[Idx].Id)
                    {
                    case OBJ_ID_SESPROPOSER:
                        LocationBlob2Location(Response.Objs[Idx].Value.Memory.Memory, &(SessionProposal->ProposerLocation), Response.Objs[Idx].Value.Memory.MsZ);
                        printf("Proposer Node : ");
                        DumpLocation(&(SessionProposal->ProposerLocation));
                        break;
                    case OBJ_ID_SESCHALLENG:
                        printf("Session Challenge : ");
                        showmem(Response.Objs[Idx].Value.Table, sizeof(Response.Objs[Idx].Value.Table));
                        memcpy_s(SessionProposal->Challenge, sizeof(SessionProposal->Challenge), Response.Objs[Idx].Value.Table, sizeof(SessionProposal->Challenge));
                        break;
                    case OBJ_ID_PEERSESSID:
                        printf("Peer Choosen Session ID : 0x%x\n", Response.Objs[Idx].Value.Nbr);
                        SessionProposal->PeerSessID = Response.Objs[Idx].Value.Nbr;
                    default:
                        break;
                    }
                }
            }

            uint		NbObjLists;
            Memory_U	RelaysInfos;

            RelaysInfos.Memory = (uchar *)malloc(0xFF);
            ZeroMemory(RelaysInfos.Memory, 0xFF);
            RelaysInfos.MsZ = 0xFF;
            Browser = RelaysInfos.Memory;

            NbObjLists = DefNbObjList(Response);
            for (Rank = 0; Rank < NbObjLists + 1; Rank++)
            {
                Host	Relay;
                uint	State, ObjOccur;

                State = ObjOccur = 0;
                for (uint Idx = 0; Idx < Response.NbObj; Idx++)
                {
                    if ((Response.Objs[Idx].ObjListInfos.Id == 0x07) && (Response.Objs[Idx].ObjListInfos.Rank == Rank))
                    {
                        if (!ObjOccur)
                        {
                            memcpy_s(Browser, 0xFF, "\x05\x07\x41\x03", 0x04);
                            Browser += 0x04;
                            ObjOccur = 1;
                        }
                        WriteObject(&Browser, Response.Objs[Idx]);
                        switch(Response.Objs[Idx].Id)
                        {
                        case OBJ_ID_RELAY:
                            printf("Proposed Relay : %s:%d\n", Response.Objs[Idx].Value.Addr.ip, Response.Objs[Idx].Value.Addr.port);
                            strcpy_s(Relay.ip, MAX_IP_LEN + 1, Response.Objs[Idx].Value.Addr.ip);
                            Relay.port = Response.Objs[Idx].Value.Addr.port;
                            State += 1;
                            break;
                        case OBJ_ID_SID2DEC:
                            printf("Session To Declare on this relay : 0x%x\n", Response.Objs[Idx].Value.Nbr);
                            Relay.SessionID2Declare = Response.Objs[Idx].Value.Nbr;
                            State += 1;
                        default:
                            break;
                        }
                    }
                }
                if (State == 2)
                    SessionProposal->Relays->push(Relay);
            }
            RelaysInfos.MsZ = (uint)(Browser - RelaysInfos.Memory);
            SessionProposal->RelaysInfos = RelaysInfos;

            printf("Accepted session.. Let's initialize..\n");

            uchar	RecvCopy[0xFFFF];
            int		RecvSzCopy;

            ZeroMemory(RecvCopy, 0xFFFF);
            memcpy_s(RecvCopy, 0xFFFF, Query, Size);
            RecvSzCopy = Size;

            SessionPropReply(Session_SN, Response.Reply2ID);
            InitSession(SessionProposal);

            ZeroMemory(RecvBuffer, 0xFFFF);
            memcpy_s(Query, 0xFFFF, RecvCopy, RecvSzCopy);
            Size = RecvSzCopy;
            break;
        case CMD_QUERY_UDPTEST:
            printf("Received UDP Test report..\n");
            Tested.port = 0;
            for (Idx = 0; Idx < Response.NbObj; Idx++)
            {
                switch(Response.Objs[Idx].Id)
                {
                case OBJ_ID_TESTED:
                    printf("Peer Tested my UDP Address : %s:%d\n", Response.Objs[Idx].Value.Addr.ip, Response.Objs[Idx].Value.Addr.port);
                    if (Tested.port == 0)
                        Tested = Response.Objs[Idx].Value.Addr;
                    break;
                case OBJ_ID_TESTER:
                    LocationBlob2Location(Response.Objs[Idx].Value.Memory.Memory, &TesterLocation, Response.Objs[Idx].Value.Memory.MsZ);
                    printf("Tester Node : ");
                    DumpLocation(&TesterLocation);
                    printf("Should UDP Test %s:%d\n", TesterLocation.PVAddr.ip, TesterLocation.PVAddr.port);
                    break;
                default:
                    break;
                }
            }
            UDPTestReply(Session_SN, Response.Reply2ID, Tested);
            break;
        default:
            printf("Unhandled Query.. Sending ACK..\n");
            SendACK(Response.PacketID, Session_SN.socket, Session_SN, HTTPS_PORT, &(Session_SN.Connected), &Keys);
            break;
        }
        printf("\n");
    }
}
Example #12
0
int main (int argc, char *argv[]) {
	int c;
	unsigned long hostaddr;
	FILE *cmdfile;
	char *cmdline = NULL;
	char *cmdtok = NULL;
	char *filename = NULL;
	char line[MAXLEN];
	char tmpcmd[MAXLEN];
	debug=0;verbose=0;errpause=0;skiperr=0;allocpty=0;envfl=0;
	timeout=5;
	enable_trace=0;
	tracelvl=0;
	errfile=NULL;
	envfilenm=NULL;
	appname = basename(argv[0]);
	while ((c = getopt (argc, argv, "dhpvP :c:f:t:s:e:T:")) != -1) {
		switch (c) {
			case 'c':
				cmdline = optarg;
				break;
				
			case 'd':
				debug++;
				break;
				
			case 'f':
				filename = optarg;
				break;
				
			case 'h':
				PrintUsage();
				break;
				
			case 'p':
				errpause++;
				break;
				
			case 'P':
				allocpty++;
				break;
				
			case 'e':
				envfl++;
				envfilenm = optarg;
				break;
				
			case 's':
				skiperr++;
				errfile = optarg;
				break;
				
			case 't':
				timeout = (int) strtol(optarg, (char **)NULL, 10);
				break;
				
			case 'T':
				enable_trace++;
				tracelvl = (int) strtol(optarg, (char **)NULL, 10);
				break;
				
			case 'v':
				verbose++;
				break;
				
			case '?':
				PrintUsage();
				break;
		}
	}
	
	ValidateOptions(cmdline,filename);
	
	if ((argc - optind) == 1) {
		hostaddr = GetHostInfo((char *)argv[optind]);
	} else {
        fprintf(stderr, "Hostname or IP is required\n\n");
        PrintUsage();
	}
	
	/* Get Username from effecive user id running the program */
	GetUserInfo();
	
	/* Initialize the Session */
	InitSession(hostaddr);
	
	if (cmdline != NULL) {
		RunCommand(cmdline);
	} else {
		if ((cmdfile = fopen(filename, "r")) == 0) {
			fprintf(stderr, "Could not open file %s:%s\n",
					filename ,strerror(errno));
			exit(-1);
		}
		
		strcpy(tmpcmd,"");
		while (fgets(line, sizeof(line), cmdfile) != NULL) {
			cmdtok = strdup(line);
			if (CheckLine(trim(cmdtok))) {
				sprintf(tmpcmd,"%s%s",tmpcmd,cmdtok);
			} else {
				if ( strcmp(tmpcmd,"") != 0 ) {
					sprintf(tmpcmd,"%s%s",tmpcmd,cmdtok);
					free(cmdtok);
					cmdtok = strdup(tmpcmd);
				}
				if (strlen(cmdtok) > 1 && SkipComments(cmdtok) ) {
					RunCommand(cmdtok);
				}
				strcpy(tmpcmd,"");
			}
			free(cmdtok);
		}
		if (strcmp(tmpcmd,"") != 0) {
			RunCommand(tmpcmd);
			strcpy(tmpcmd,"");
		}
	}
	CleanupSession(session,username);
	return 0;
}
void
JabberProtocol::OnTag(XMLEntity *entity)
{
	char buffer[4096]; // general buffer space
	static int seen_streams = 0;

	if (entity->IsCompleted() && !strcasecmp(entity->Name(), "iq"))
	{
		
		// handle roster retrival
		if (entity->Child("query") && entity->Child("query")->Attribute("xmlns") &&
			!strcasecmp(entity->Child("query")->Attribute("xmlns"),"jabber:iq:roster"))
		{
			ParseRosterList(entity);
			return;
		}
		
		// handle session retrival
		if (entity->Attribute("id") && entity->Attribute("type") &&
			!strcasecmp(entity->Attribute("type"), "result") &&
			!strcasecmp(entity->Attribute("id"), "sess_1"))
		{
			release_sem(logged);
		
			mainWindow->Lock();
			mainWindow->PostMessage(JAB_LOGGED_IN);
			mainWindow->Unlock();
			
			return;
		}
		
		// handle binding retrival
		if (entity->Attribute("id") && entity->Attribute("type") &&
			!strcasecmp(entity->Attribute("type"), "result") &&
			!strcasecmp(entity->Attribute("id"), "bind_0"))
		{
			jid = BString(entity->Child("bind")->Child("jid")->Data());

			fprintf(stderr, "JID: %s.\n", jid.String());

			Session();
			
			return;
		}
		
		if (entity->Attribute("type") && entity->Child("query") &&
			!strcasecmp(entity->Attribute("type"), "result") &&
			entity->Child("query", "xmlns", "jabber:iq:register"))
		{
			Authorize();
			
			return;
		}
		
		if (entity->Attribute("type") && entity->Attribute("id") &&
			!strcasecmp(entity->Attribute("type"), "result") &&
			!strcasecmp(entity->Attribute("id"), "request_room_info"))
		{
			BMessage msg(JAB_PREFERENCES_DATAFORM);
			msg.AddPointer("XMLEntity", entity);
			MessageRepeater::Instance()->PostMessage(&msg);
			
			return;
		}
		
		if (entity->Attribute("type") && entity->Attribute("id") &&
			!strcasecmp(entity->Attribute("type"), "error"))
		{
			if (!strcasecmp(entity->Attribute("id"), "storage_request"))
			{
				_storage_supported = false;
				return;
			}
			else if (!strcasecmp(entity->Attribute("id"), "save_conferences"))
			{
				_storage_supported = false;
				sprintf(buffer, "Storage XEP-0049 is not supported on server. Cannot save conferences.\n\nNext time will try save to roster.");
				ModalAlertFactory::Alert(buffer, "Pity", NULL, NULL, B_WIDTH_AS_USUAL, B_STOP_ALERT); 
				return;
			}
			else if (!strcasecmp(entity->Attribute("id"), "request_room_info"))
			{
				
				if (entity->Child("error") &&
					entity->Child("error")->Child("text") &&
					entity->Child("error")->Attribute("code"))
					sprintf(buffer, "Error %s:\n\n%s", entity->Child("error")->Attribute("code"),
							entity->Child("error")->Child("text")->Data());
				else
					sprintf(buffer, "Error %s", entity->Child("error")->Attribute("code"));
			
				ModalAlertFactory::Alert(buffer, "OK", NULL, NULL, B_WIDTH_AS_USUAL, B_STOP_ALERT); 
			
				return;
			}
				
			if (entity->Child("error") &&
				entity->Child("error")->Child("text") &&
				entity->Child("error")->Attribute("code"))
				sprintf(buffer, "Error %s:\n\n%s", entity->Child("error")->Attribute("code"),
					entity->Child("error")->Child("text")->Data());
			else
				sprintf(buffer, "Error %s", entity->Child("error")->Attribute("code"));
			
			ModalAlertFactory::Alert(buffer, "OK", NULL, NULL, B_WIDTH_AS_USUAL, B_STOP_ALERT); 
			
			Disconnect();
			
			return;
			
		}
		
		if (entity->Attribute("id") && entity->Child("query") && entity->Child("query")->Attribute("xmlns") &&
			entity->Attribute("type") &&
			!strcasecmp(entity->Attribute("id"), "storage_request") &&
			!strcasecmp(entity->Attribute("type"), "result") &&
			!strcasecmp(entity->Child("query")->Attribute("xmlns"), "jabber:iq:private"))
		{
			if (entity->Child("query")->Child("storage"))
				ParseStorage(entity->Child("query")->Child("storage"));
				
			return;
		}
		
		if (entity->Attribute("type") && !strcasecmp(entity->Attribute("type"), "get"))
		{
			BString iq_from;
			BString iq_id;   
			
			if (entity->Attribute("from")) {
				iq_from = BString(entity->Attribute("from"));
			}
			
			if (entity->Attribute("id")) {
				iq_id = BString(entity->Attribute("id"));
			}
			
			// handle version request
			XMLEntity *query = entity->Child("query");
			if (query && query->Attribute("xmlns")) {
				if (!strcasecmp(query->Attribute("xmlns"), "jabber:iq:version")) {
					ProcessVersionRequest(iq_id, iq_from);
				}
			}
			
			// handle version request
			query = entity->Child("ping");
			if (query && query->Attribute("xmlns")) {
				if (!strcasecmp(query->Attribute("xmlns"), "urn:xmpp:ping"))
				{
					Pong(iq_id, iq_from);
				}
			}
			
			return;
		}
		
		fprintf(stderr, "Unknown IQ message.\n");
		return;
	}
	
	// handle authorization success
	if (entity->IsCompleted() && !strcasecmp(entity->Name(), "success"))
	{
		InitSession();
		
		return;
		
	}
	
	// handle presence messages
	if (entity->IsCompleted() && !strcasecmp(entity->Name(), "presence"))
	{
		ProcessPresence(entity);
		
		return;
	}
	
	// handle stream error
	if (entity->IsCompleted() && !strcasecmp(entity->Name(), "stream:error")) {
		sprintf(buffer, "An stream error has occurred.");
		ModalAlertFactory::Alert(buffer, "Sorry", NULL, NULL, B_WIDTH_AS_USUAL, B_STOP_ALERT); 
		
		Disconnect();
		
		return;
	}
	
	// handle stream error
	if (entity->IsCompleted() && !strcasecmp(entity->Name(), "stream:features"))
	{
		mainWindow->Lock();
		int wantRegister = mainWindow->_login_new_account->Value();
		mainWindow->Unlock();
		
		if (wantRegister == B_CONTROL_ON)
		{
			if (entity->Child("register"))
			{
				mainWindow->Lock();
				mainWindow->_login_new_account->SetValue(B_CONTROL_OFF);
				mainWindow->Unlock();
				
				SendUserRegistration(user, pass, "haiku");
			} else
			{
				sprintf(buffer, "Registration not supported on this server.");
				ModalAlertFactory::Alert(buffer, "Sorry", NULL, NULL, B_WIDTH_AS_USUAL, B_STOP_ALERT); 
				
				Disconnect();
			}
		}
		else if (entity->Child("mechanisms"))
			Authorize();
		else if (entity->Child("bind"))
			Bind();
		else if (entity->Child("session"))
			Session();
			
		return;
		
	}
	
	// handle failures
	if (entity->IsCompleted() && !strcasecmp(entity->Name(), "failure")) {
		if (entity->Child("not-authorized") != NULL)
			sprintf(buffer, "Not authorized failure.");
		else if (entity->Child("invalid-mechanism") != NULL)
			sprintf(buffer, "Invalid mechanism failure.");
		else if (entity->Child("invalid-authzid") != NULL)
			sprintf(buffer, "Invalid authorization Id.");
		else
			sprintf(buffer, "An failure occured.");
			
		ModalAlertFactory::Alert(buffer, "Sorry", NULL, NULL, B_WIDTH_AS_USUAL, B_STOP_ALERT); 
		
		Disconnect();
		
		return;
	}
	
	// handle disconnection
	if (entity->IsCompleted() && !strcasecmp(entity->Name(), "stream:stream"))
	{
		++seen_streams;
		if (seen_streams % 2 == 1)
			Disconnect();
			
		return;
	}
	
	// handle incoming messages
	if (entity->IsCompleted() && !strcasecmp(entity->Name(), "message"))
	{
		//TalkManager::Instance()->Lock();
		TalkManager::Instance()->ProcessMessageData(entity);
		//TalkManager::Instance()->Unlock();
		
		return;
	}
	
	//delete entity;
}
Example #14
0
int main(int argc, char **argv)
{
  LCHAR phrase[MAX_LINE_LENGTH];
  SR_Vocabulary *vocab = 0;
  LCHAR vocabfile[MAX_LINE_LENGTH];
  LCHAR outfilename[MAX_LINE_LENGTH];
  LCHAR testfilename[MAX_LINE_LENGTH];
  LCHAR parfilename[MAX_LINE_LENGTH];
  LCHAR wordfile[MAX_LINE_LENGTH];
  LCHAR locale[MAX_LINE_LENGTH];
  LCHAR ptemp[MAX_LINE_LENGTH];
  LCHAR* p;
  ESR_ReturnCode rc;
  int i;
  PFile* fin = 0;
  FILE* fout = stdout;
  size_t len;
  ESR_BOOL bSession = ESR_FALSE;

  LCHAR *env_sdk_path;
  LCHAR *env_lang;

  CHKLOG(rc, PMemInit());
/*  CHKLOG(rc, PFileSystemCreate());
    CHKLOG(rc, PANSIFileSystemCreate());
    CHKLOG(rc, PANSIFileSystemAddPath(L("/dev/ansi"), L("/")));*/

    /* Set ANSI file-system as default file-system */
/*  CHKLOG(rc, PANSIFileSystemSetDefault(ESR_TRUE));*/
    /* Set virtual current working directory to native current working directory */
/*  len = P_PATH_MAX;
    CHKLOG(rc, PANSIFileSystemGetcwd(cwd, &len));
    CHKLOG(rc, PFileSystemChdir(cwd));*/

    fout = stdout;
  *vocabfile = 0;
  *wordfile = 0;
  *locale = 0;
  *outfilename = 0;
  *testfilename = 0;
  *parfilename = 0;

  /* get some phrases from the user */
  LPRINTF("\nDictation Test Program for esr (Nuance Communications, 2007)\n");

  if(argc != 1 && argc != 3 && argc != 5 && argc != 7 && argc != 9)
  {
    usage();
        rc = 1;
    goto CLEANUP;
  }

  for(i=1; i<argc; i++)
  {
    if(!LSTRCMP(argv[i], L("-words")))
      LSTRCPY(wordfile, argv[++i]);
    else if(!LSTRCMP(argv[i], L("-vocab")))
      LSTRCPY(vocabfile, argv[++i]);
    else if(!LSTRCMP(argv[i], L("-locale")))
      LSTRCPY(locale, argv[++i]);
    else if(!LSTRCMP(argv[i], L("-out")))
      LSTRCPY(outfilename, argv[++i]);
    else if(!LSTRCMP(argv[i], L("-itest")))
      LSTRCPY(testfilename, argv[++i]);
    else if(!LSTRCMP(argv[i], L("-parfile")) || !LSTRCMP(argv[i], L("-par")) )
      LSTRCPY(parfilename, argv[++i]);
    else {
      usage();
      rc = 1;
      goto CLEANUP;
    }
  }

  if ( *parfilename == L('\0') )
  {
    LPRINTF ( "Warning: No parfile defined in the command line.\n" );
    LPRINTF ( "Looking for the default parfile, $ESRSDK/config/$ESRLANG/baseline.par...\n" );

    env_sdk_path =  LGETENV(L("ESRSDK"));
    if ( env_sdk_path != NULL )
    {
      LSPRINTF ( parfilename, L("%s/config/"), env_sdk_path );
      env_lang = LGETENV(L("ESRLANG"));
      if ( env_lang != NULL )
      {
         LSTRCAT ( parfilename, env_lang );
         LSTRCAT ( parfilename, L("/baseline.par") );
      }
      else
      {
        LPRINTF("Error: An environment variable ESRLANG should be defined.\n");
        goto CLEANUP;
      }
    }
    else
    {
      LPRINTF("Error: An environment variable ESRSDK should be defined.\n");
      goto CLEANUP;
    }
  }

  rc = InitSession( parfilename );
  if ( rc != ESR_SUCCESS )
  {
    LPRINTF("Error: %s\n", ESR_rc2str(rc));
    goto CLEANUP;
  }
  bSession = ESR_TRUE;

  if (*vocabfile == 0)
  {
    len = sizeof(vocabfile);
    rc = ESR_SessionGetLCHAR ( L("cmdline.vocabulary"), vocabfile, &len );
    env_sdk_path =  LGETENV(L("ESRSDK"));
    if ( env_sdk_path != NULL )
      {
	LSPRINTF ( parfilename, L("%s/config/"), env_sdk_path );
	env_lang = LGETENV(L("ESRLANG"));
	if ( env_lang != NULL )
	  {
	    LSTRCAT ( parfilename, env_lang );
	    LSTRCAT ( parfilename, L("/baseline.par") );
	  }
	else
	  {
	    LPRINTF("Error: An environment variable ESRLANG should be defined.\n");
	    goto CLEANUP;
	  }
      }
    else
      {
	LPRINTF("Error: An environment variable ESRSDK should be defined.\n");
	goto CLEANUP;
      }

    strcpy(ptemp, env_sdk_path);
    strcat(ptemp,"/config/");
    strcat(ptemp,env_lang);
    strcat(ptemp,"/");
    strcat(ptemp,vocabfile);
    strcpy(vocabfile,ptemp);
    if ( rc == ESR_SUCCESS )
    {
      len = sizeof(vocabfile);
       rc = ESR_SessionPrefixWithBaseDirectory(vocabfile, &len);
    }
    else
    {
       *vocabfile = 0;
    }
  }

  if (*vocabfile)
    rc = SR_VocabularyLoad(vocabfile, &vocab);
  else if (*locale)
  {
    ESR_Locale localeTag;

    rc = ESR_str2locale(locale, &localeTag);
    if (rc != ESR_SUCCESS)
    {
      LPRINTF("Error: %s\n",ESR_rc2str(rc));
      goto CLEANUP;
    }
    rc = SR_VocabularyCreate(localeTag, &vocab);
  }
  else
    rc = SR_VocabularyCreate(ESR_LOCALE_EN_US, &vocab);

  if (rc != ESR_SUCCESS)
  {
    LPRINTF("Error: %s\n",ESR_rc2str(rc));
    goto CLEANUP;
  }

  if (*outfilename) /* output file */
  {
    if  ((fout = fopen(outfilename,"w")) == NULL)
    {
      LPRINTF("Could not open file: %s\n",outfilename);
      rc = 1;
      goto CLEANUP;
    }
  }

  if (*wordfile) /* file mode */
  {
    if ((fin = pfopen(wordfile,"r")) == NULL)
    {
      LPRINTF("Could not open file: %s\n", wordfile);
      goto CLEANUP;
    }
    while (pfgets(phrase, MAX_LINE_LENGTH, fin)!=NULL)
    {
      lstrtrim(phrase);
      doGetProns(vocab, phrase, MAX_PRONS_LENGTH, fout);
    }

  }
  else if (*testfilename) /* test file mode */
  {
    if ((fin = pfopen(testfilename,"r")) == NULL)
    {
      LPRINTF("Could not open file: %s\n", testfilename);
      rc = 1;
      goto CLEANUP;
    }
    doInputTestPhonemes(vocab, fin, fout);
  }
  else /* interactive mode */
  {
    LPRINTF("'qqq' to quit\n");
    while (ESR_TRUE)
    {
      LPRINTF("> ");
      if(! pfgets(phrase, MAX_LINE_LENGTH, PSTDIN ))
        break;
      // remove trailing whitespace
      for(p=&phrase[0]; *p!=0 && *p!='\n' && *p!='\r'; p++) {}
      *p=0;
      lstrtrim(phrase);
      if(!LSTRCMP("qqq",phrase))
        break;
      else
        doGetProns(vocab, phrase, MAX_PRONS_LENGTH, fout);
     }
  }

CLEANUP:
  if(vocab)
    vocab->destroy(vocab);

  if(bSession)
    ShutdownSession();

  if(fin)
    pfclose(fin);

  if(fout && fout != stdout)
    fclose(fout);

/*  PANSIFileSystemDestroy();
  PFileSystemDestroy();*/
  PMemShutdown();
  return rc;
}
Example #15
0
void InitBCI() {
    concurrency::critical_section::scoped_lock lock(bci_mutex);

    std::cout << "Initializing BCI" << std::endl;

    if (StopAcquisition() != ID_WRONG_SEQUENCY_OF_COMMAND) {
        std::cerr << "Stopped previous data acquisition" << std::endl;
    }

    _DEVICE_INFO *devInfo;
    if (!(devInfo = GetDeviceInfo())) {
        throw("GetDeviceInfo() failed");
    }

    std::cout << "ABM Device Info:" << std::endl;
    std::cout << "Device name: " << devInfo->chDeviceName << std::endl;
    std::cout << "COM Port: " << devInfo->nCommPort << std::endl;
    std::cout << "ECG Channel: " << devInfo->nECGPos << std::endl;
    std::cout << "Number of channels: " << devInfo->nNumberOfChannel << std::endl;

    num_channels = devInfo->nNumberOfChannel;

    if (num_channels < 0) {
        std::cerr << "ABM X10 not connected" << std::endl;
        ExitProcess(1);
    }

    std::stringstream destfilepath;
    SYSTEMTIME stime;
    GetLocalTime(&stime);

    int err;


    destfilepath << "data\\" << stime.wYear << "_" << stime.wMonth << "_" << stime.wDay << "_" << stime.wHour << "_" << stime.wMinute << "_" << stime.wSecond << ".ebs";
    std::string dfp = destfilepath.str();

    char fullpath[4096] = "";
    char *pszfn = NULL;

    err = GetFullPathNameA(dfp.c_str(), sizeof(fullpath), fullpath, &pszfn);

    std::cout << "Setting destination file path to " << fullpath << std::endl;

    if (!(err = SetDestinationFile(fullpath))) {
        std::cerr << "SetDestinationFile failed! err " << err << std::endl;
        ExitProcess(1);
    }

    std::cout << "Initiating session..." << std::endl;
    if ((err = InitSession(ABM_DEVICE_X10Standard, ABM_SESSION_RAW, -1, FALSE)) != INIT_SESSION_OK) {
        std::cerr << "InitSession failed! err " << err << std::endl;
        switch (err) {
        case ID_WRONG_SEQUENCY_OF_COMMAND:
            std::cerr << "Wrong command sequence" << std::endl;
            break;
        case INIT_SESSION_NO:
            std::cerr << "Session initiation failed" << std::endl;
            break;
        case INIT_SESSION_NO_DESTFILE_FAILED:
            std::cerr << "No destination file!" << std::endl;
            break;
        }
        ExitProcess(1);
    }

    std::cout << "Getting channel map info" << std::endl;
    _CHANNELMAP_INFO channelMap;
    if (!GetChannelMapInfo(channelMap)) {
        std::cerr << "GetChannelMapInfo failed!" << std::endl;
        ExitProcess(1);
    }

    if (channelMap.nDeviceTypeCode != 0) {
        std::cerr << "ABM X10 not found! :(" << std::endl;
        ExitProcess(1);
    }

    _EEGCHANNELS_INFO& eegChannels = channelMap.stEEGChannels;
    for (int i = 0; i < channelMap.nSize; ++i) {
        std::cout << eegChannels.cChName[i] << " " << eegChannels.bChUsed[i] << " " << eegChannels.bChUsedInQualityData[i] << std::endl;
    }

    std::cout << "Starting acquisition..." << std::endl;
    if (StartAcquisition() != ACQ_STARTED_OK) {
        std::cerr << "StartAcquisition failed!" << std::endl;
        ExitProcess(1);
    }

    running = true;

    std::cout << "BCI initialization done!" << std::endl;

}
Example #16
0
void MainServer()
{
	InitInterfaceLocks(); 
	
	InitInterface(); /* starts a thread with the window */

   WrapInit();
	
	InitMemory(); /* memory needs channels in general, but need to start before config,
	so just be careful. */
	
	InitConfig();
	LoadConfig();		/* must be nearly first since channels use it */
	
	InitDebug();
	
	InitChannelBuffer();
	
	OpenDefaultChannels();
	
	lprintf("Starting %s\n",BlakServLongVersionString());
	
	InitClass();
	InitMessage();
	InitObject();
	InitList();
	InitTimer();
	InitSession();
	InitResource();
	InitRoomData();
	InitString();
	InitUser();
	InitAccount();
	InitNameID();
	InitDLlist();   
	InitSysTimer();
	InitMotd();
	InitLoadBof();
	InitTime();
	InitGameLock();
	InitBkodInterpret();
	InitBufferPool();
	InitTable();
	AddBuiltInDLlist();
	
	LoadMotd();
	LoadBof();
	LoadRsc();
	LoadKodbase();
	
	LoadAdminConstants();
	
	PauseTimers();
	
	if (LoadAll() == True)
	{
	/* this loaded_game_msg tells it to disconnect all blakod info about sessions,
		* that were logged on when we saved */
		
		SendTopLevelBlakodMessage(GetSystemObjectID(),LOADED_GAME_MSG,0,NULL);
		DoneLoadAccounts();
	}
	
	/* these must be after LoadAll and ClearList */
	InitCommCli(); 
	InitParseClient(); 
	InitProfiling();
	InitAsyncConnections();
	
	UpdateSecurityRedbook();
	
	UnpauseTimers();

	

	ServiceTimers();
	/* returns if server termiated */
	
	MainExitServer();
   WrapShutdown();
}
Example #17
0
int
ConnectAfterStep (send_data_type message_mask, send_data_type lock_on_send_mask)
{
	char *temp;
	int   fd;

	/* connect to AfterStep */
	/* Dead pipe == AS died */
	signal (SIGPIPE, ASDeadPipe);
	fd = ASDefaultScr->wmprops?socket_connect_client(ASDefaultScr->wmprops->as_socket_filename):-1;

	set_module_in_fd( fd );
	set_module_out_fd( fd );

	if (fd < 0)
	{
		show_error("unable to establish connection to AfterStep");
	}else
	{	
		int arg_len = 0 ; 
		int i ; 
		char *ptr ;
		char *exec_name = strrchr (MyArgs.saved_argv[0], '/');
		int exec_name_len ; 
		send_signed_data_type masks[2] ; 

		masks[0] = message_mask ;
		masks[1] = lock_on_send_mask ;

		if( exec_name == NULL ) 
			exec_name = MyArgs.saved_argv[0] ;
		else
			++exec_name ;

		exec_name_len = strlen(exec_name);
		arg_len = exec_name_len ;
		for( i = 1 ; i < MyArgs.saved_argc ; ++i )
			arg_len += 1+1+strlen( MyArgs.saved_argv[i] )+1 ;	


		/* assuming that unsigned long will be limited to 32 chars : */
		temp = safemalloc (arg_len+1);
		strcpy(temp, exec_name);
		ptr = temp + exec_name_len; 
		for( i = 1 ; i < MyArgs.saved_argc ; ++i )
		{
			Bool quote = False ; 
			if( MyArgs.saved_argv[i][0] != '-' ) 
			{
				int k = 0;
				int c = MyArgs.saved_argv[i][k] ; 
				while( isalnum(c) || c == '-' || c == '+' || c == '.' || c == '_' ) 
					c = MyArgs.saved_argv[i][++k] ; 
				quote = ( c != '\0' ) ;
			}	 
			sprintf( ptr, quote?" \"%s\"":" %s", MyArgs.saved_argv[i] );	
			while( *ptr ) ++ptr;
		}
		SendTextCommand ( F_SET_NAME, MyName, temp, None);
		free (temp);

		SendNumCommand ( F_SET_MASK, NULL, &masks[0], NULL, None);
		//sprintf (mask_mesg, "SET_MASK %lu %lu\n", (unsigned long)message_mask, (unsigned long) lock_on_send_mask);
		//SendInfo ( mask_mesg, None);
	}
	/* don't really have to do this here, but anyway : */
	InitSession();
	return fd;
}
Example #18
0
int
main(int argc, char **argv, char **envp)
{
	struct Session session;
	time_t	t1, t2;

	int tmp = 0;

	if(RegisterHandlers() == -1)
	{
		fprintf(stderr, "[!] Cannot register signal handlers, aborting\n");
		goto cleanup;
	}
	
	InitSession(&session, envp, argv);

	if(ParseArguments(argc, argv, &session) == -1)
	{
		PrintHelp(argv[0]);
		goto cleanup;
	}

	if(OpenLogFile(&session) == -1)
	{
		fprintf(stderr, "[!] Cannot open %s for logging, aborting\n",
			session.logfilename);

		goto cleanup;
	}

	if(PrepareArgv(&session) == -1)
	{
		fprintf(stderr, "[!] Cannot parse arguments\n");
		goto cleanup;
	}
	
	if(InitFuzzingStrings(&session) == -1)
	{
		fprintf(stderr, "[!] Error initializing fuzzing variables\n");
		goto cleanup;
	}

	switch(session.mode)
	{
		/* Smart mode read the file structure from a file */ 
		case MODE_SMART:
		{
			fprintf(stdout, "[%%] Reading headers structure from %s\n",
			session.headers);

			session.headercount = Extract_DataFields(&session);
			break;
		}
		/* ASCII mode read a file and tries to get the right file structure =) */
		case MODE_ASCII:
		{
			fprintf(stdout, "[%%] Reading ASCII structure from %s\n",
				session.input);
			
			session.headercount = Extract_ASCII_Structure(&session);
			break;
		}
	}

	if((session.mode == MODE_ASCII) || (session.mode == MODE_SMART))
	{
		if(!session.headercount)
		{
			fprintf(stderr, "[!] Error loading Offsets from input file\n");
			goto cleanup;
		}

		session.range.low   = 0;
		session.range.high  = session.headercount;
		
		fprintf(stdout, "[%%] Loaded %d fields in headers\n",
			session.headercount);
	}

	tmp = CountFuzzingStrings(&session);
	
	fprintf(stdout, "[%%] Loaded %d fuzzing variables\n", tmp);
	fprintf(stdout, "[%%] Fuzzing from %d to %d\n",	session.range.low,
		session.range.high);
	
	if(session.mode == MODE_BRUTE)
	{
		session.byte = session.range.low;
		tmp         *= session.range.high - session.range.low + 1;
	}
	else
	{
		session.curfield = session.d;
		session.byte     = session.curfield->offset;
		tmp             *= session.headercount;
	}

	PrintLogHeader(&session);

	fprintf(stdout, "[%%] Number of files to be generated %d\n", tmp);
	fprintf(stdout, "[%%] Proceding with fuzzing\n");

	time(&t1);
	StartSession(&session);
	time(&t2);

	fprintf(stdout, "[%%] Time elapsed %f\n", difftime(t2, t1));
	fprintf(stdout, "[%%] Number of succesful executions %d\n", session.exec);
	fprintf(stdout, "[%%] Skipped executions due to fuzzing string size %d\n", session.skipped);
	fprintf(stdout, "[%%] Number of \"bugs\" found: %d\n", session.bugs);
	
	/* Cleanup Resources */
	cleanup:
	{
		FreeFuzzingList(session.f);
		FreeMaps(session.maps);
		CloseLogFile(&session);
	}
	
	return 0;
}
Example #19
0
/***********************************************************************
 *  Procedure:
 *	main - start of afterstep
 ************************************************************************/
int
main (int argc, char **argv, char **envp)
{
    register int i ;
	
	int start_viewport_x = 0 ;
	int start_viewport_y = 0 ;
	int start_desk = 0 ;

#ifdef LOCAL_DEBUG
#if 0
	LOCAL_DEBUG_OUT( "calibrating sleep_a_millisec : %s","" );
	for( i = 0 ; i < 500 ; ++i )
		sleep_a_millisec( 10 );
	LOCAL_DEBUG_OUT( "500 sliip_a_millisec(10) completed%s","" );
	for( i = 0 ; i < 50 ; ++i )
		sleep_a_millisec( 100 );
	LOCAL_DEBUG_OUT( "50 sliip_a_millisec(100) completed%s","" );
	for( i = 0 ; i < 10 ; ++i )
		sleep_a_millisec( 300 );
	LOCAL_DEBUG_OUT( "10 sliip_a_millisec(300) completed%s","" );
#endif
#endif

	_as_grab_screen_func = GrabEm;
	_as_ungrab_screen_func = UngrabEm;

	original_DISPLAY_string = getenv("DISPLAY");
	if (original_DISPLAY_string)
		original_DISPLAY_string = mystrdup(original_DISPLAY_string);

#ifdef DEBUG_TRACE_X
	trace_window_id2name_hook = &window_id2name;
#endif
	set_DeadPipe_handler(DeadPipe);

#if !HAVE_DECL_ENVIRON
	override_environ( envp );
#endif
    InitMyApp( CLASS_AFTERSTEP, argc, argv, NULL, AfterStep_usage, 0);

	LinkAfterStepConfig();

    AfterStepState = MyArgs.flags ;
    clear_flags( AfterStepState, ASS_NormalOperation );
	set_flags( AfterStepState, ASS_SuppressDeskBack );

#ifdef __CYGWIN__
    CloseOnExec = ASCloseOnExec ;
#endif

#if defined(LOG_FONT_CALLS)
	fprintf (stderr, "logging font calls now\n");
#endif

    /* These signals are mandatory : */
    signal (SIGUSR1, Restart);
    /* These signals we would like to handle only if those are not handled already (by debugger): */
    IgnoreSignal(SIGINT);
    IgnoreSignal(SIGHUP);
    IgnoreSignal(SIGQUIT);
    IgnoreSignal(SIGTERM);

    if( ConnectX( ASDefaultScr, AS_ROOT_EVENT_MASK ) < 0  )
	{
		show_error( "Hostile X server encountered - unable to proceed :-(");
		return 1;/* failed to accure window management selection - other wm is running */
	}


	ASDBus_fd = asdbus_init();

	XSetWindowBackground( dpy, Scr.Root, Scr.asv->black_pixel );
	Scr.Look.desktop_animation_tint = get_random_tint_color();

    cover_desktop();
	if( get_flags( AfterStepState, ASS_Restarting ))
	{	
		show_progress( "AfterStep v.%s is restarting ...", VERSION );
		display_progress( True, "AfterStep v.%s is restarting ...", VERSION );
	}else
	{	
    	show_progress( "AfterStep v.%s is starting up ...", VERSION );
		display_progress( True, "AfterStep v.%s is starting up ...", VERSION );
	}

	if (ASDBus_fd>=0)
	{
    	show_progress ("Successfuly accured System DBus connection.");	
		asdbus_RegisterSMClient(SMClientID_string);
	}
	
SHOW_CHECKPOINT;
	InitSession();
SHOW_CHECKPOINT;
	XSync (dpy, 0);
SHOW_CHECKPOINT;
    set_parent_hints_func( afterstep_parent_hints_func ); /* callback for collect_hints() */
SHOW_CHECKPOINT;
    SetupModules();
SHOW_CHECKPOINT;
	SetupScreen();
SHOW_CHECKPOINT;
	event_setup( True /*Bool local*/ );
SHOW_CHECKPOINT;
	/*
     *  Lets init each and every screen separately :
     */
	
    for (i = 0; i < Scr.NumberOfScreens; i++)
	{
        show_progress( "Initializing screen %d ...", i );
        display_progress( True, "Initializing screen %d ...", i );

        if (i != Scr.screen)
        {
            if( !get_flags(MyArgs.flags, ASS_SingleScreen) )
            {
                int pid = spawn_child( MyName, (i<MAX_USER_SINGLETONS_NUM)?i:-1, i, NULL, None, C_NO_CONTEXT, True, True, NULL );
                if( pid >= 0 )
                    show_progress( "\t instance of afterstep spawned with pid %d.", pid );
                else
                    show_error( "failed to launch instance of afterstep to handle screen #%d", i );
            }
        }else
        {
            make_screen_envvars(ASDefaultScr);
            putenv (Scr.rdisplay_string);
            putenv (Scr.display_string);
            if( is_output_level_under_threshold( OUTPUT_LEVEL_PROGRESS ) )
            {
                show_progress( "\t screen[%d].size = %ux%u", Scr.screen, Scr.MyDisplayWidth, Scr.MyDisplayHeight );
                display_progress( True, "    screen[%d].size = %ux%u", Scr.screen, Scr.MyDisplayWidth, Scr.MyDisplayHeight );
                show_progress( "\t screen[%d].root = %lX", Scr.screen, Scr.Root );
                show_progress( "\t screen[%d].color_depth = %d", Scr.screen, Scr.asv->true_depth );
                display_progress( True, "    screen[%d].color_depth = %d", Scr.screen, Scr.asv->true_depth );
                show_progress( "\t screen[%d].colormap    = 0x%lX", Scr.screen, Scr.asv->colormap );
                show_progress( "\t screen[%d].visual.id         = %X",  Scr.screen, Scr.asv->visual_info.visualid );
                display_progress( True, "    screen[%d].visual.id         = %X",  Scr.screen, Scr.asv->visual_info.visualid );
                show_progress( "\t screen[%d].visual.class      = %d",  Scr.screen, Scr.asv->visual_info.class );
                display_progress( True, "    screen[%d].visual.class      = %d",  Scr.screen, Scr.asv->visual_info.class );
                show_progress( "\t screen[%d].visual.red_mask   = 0x%8.8lX", Scr.screen, Scr.asv->visual_info.red_mask   );
                show_progress( "\t screen[%d].visual.green_mask = 0x%8.8lX", Scr.screen, Scr.asv->visual_info.green_mask );
                show_progress( "\t screen[%d].visual.blue_mask  = 0x%8.8lX", Scr.screen, Scr.asv->visual_info.blue_mask  );
                show_progress( "\t screen[%d].rdisplay_string = \"%s\"", Scr.screen, Scr.rdisplay_string );
                show_progress( "\t screen[%d].display_string = \"%s\"", Scr.screen, Scr.display_string );
                display_progress( True, "    screen[%d].display_string = \"%s\"", Scr.screen, Scr.display_string );
            }
        }
    }

   /* make sure we're on the right desk, and the _WIN_DESK property is set */
    Scr.CurrentDesk = INVALID_DESK ;
    if( get_flags( Scr.wmprops->set_props, WMC_ASDesks )  )
	{
		start_desk = Scr.wmprops->as_current_desk ;
    }else if( get_flags( Scr.wmprops->set_props, WMC_DesktopCurrent )  )
    {
        int curr = Scr.wmprops->desktop_current ;
        start_desk = curr;
        if( get_flags( Scr.wmprops->set_props, WMC_DesktopViewport ) &&
            curr < Scr.wmprops->desktop_viewports_num )
        {
            /* we have to do that prior to capturing any window so that they'll get in
             * correct position and will not end up outside of the screen */
            start_viewport_x = Scr.wmprops->desktop_viewport[curr<<1] ;
			start_viewport_y = Scr.wmprops->desktop_viewport[(curr<<1)+1] ;
        }
    }
    if( get_flags( Scr.wmprops->set_props, WMC_ASViewport )  )
	{
		start_viewport_x = Scr.wmprops->as_current_vx ;
		start_viewport_y = Scr.wmprops->as_current_vy ;
	}
	/* temporarily setting up desktop 0 */
	ChangeDesks(0);

    /* Load config ... */
    /* read config file, set up menus, colors, fonts */
    LoadASConfig (0, PARSE_EVERYTHING);

    /* Reparent all the windows and setup pan frames : */
    XSync (dpy, 0);
   /***********************************************************/
#ifndef DONT_GRAB_SERVER                    /* grabbed   !!!!!*/
	grab_server();                		/* grabbed   !!!!!*/
#endif										/* grabbed   !!!!!*/
    init_screen_panframes(ASDefaultScr);            /* grabbed   !!!!!*/
    display_progress( True, "Capturing all windows ..." );
    CaptureAllWindows (ASDefaultScr);               /* grabbed   !!!!!*/
    display_progress( False, "Done." );
    check_screen_panframes(ASDefaultScr);           /* grabbed   !!!!!*/
    ASSync( False );
#ifndef DONT_GRAB_SERVER                    /* grabbed   !!!!!*/
	ungrab_server();					/* UnGrabbed !!!!!*/
#endif										/* UnGrabbed !!!!!*/
	/**********************************************************/
    XDefineCursor (dpy, Scr.Root, Scr.Feel.cursors[ASCUR_Default]);

    display_progress( True, "Seting initial viewport to %+d%+d ...", Scr.wmprops->as_current_vx, Scr.wmprops->as_current_vy );

    SetupFunctionHandlers();
    display_progress( True, "Processing all pending events ..." );
    ConfigureNotifyLoop();
    display_progress( True, "All done." );
    remove_desktop_cover();

	if( !get_flags(AfterStepStartupFlags, ASSF_BypassAutoexec))
    	DoAutoexec(get_flags( AfterStepState, ASS_Restarting));
	
	/* once all the windows are swallowed and placed in its proper desks - we cas restore proper
	   desktop/viewport : */
	clear_flags( AfterStepState, ASS_SuppressDeskBack );
	ChangeDeskAndViewport ( start_desk, start_viewport_x, start_viewport_y, False);

    /* all system Go! we are completely Operational! */
    set_flags( AfterStepState, ASS_NormalOperation);

#if (defined(LOCAL_DEBUG)||defined(DEBUG)) && defined(DEBUG_ALLOCS)
    LOCAL_DEBUG_OUT( "printing memory%s","");
    spool_unfreed_mem( "afterstep.allocs.startup", NULL );
#endif
    LOCAL_DEBUG_OUT( "entering main loop%s","");

    HandleEvents ();
	return (0);
}