/************************************** Add a new context to the list **************************************/ context_t * context_new(void) { context_t * ctx; context_lock_list(); if ( context_list_start == NULL ) { context_list_start = (context_t*)malloc(sizeof(context_t)); memset(context_list_start,0,sizeof(context_t)); context_init(context_list_start); context_unlock_list(); return context_list_start; } ctx = context_list_start; while( ctx->next != NULL ) { ctx = ctx->next; } ctx->next = (context*)malloc(sizeof(context_t)); memset(ctx->next,0,sizeof(context_t)); context_init(ctx->next); ctx->next->previous = ctx; context_unlock_list(); return ctx->next; }
static void context_load (int scope, qbyte bufsize, byte *buffer) { size_t block_size; qbyte portable_size; /* Block size in network order */ SYMTAB *table; SYMBOL *symbol; /* Symbol we create in table */ table = context_init (scope); /* Initialise new symbol table */ while (bufsize) /* and fill-up from buffer */ { symbol = sym_assume_symbol (table, (char *) buffer, NULL); bufsize -= (strlen ((char *) buffer) + 1); buffer += (strlen ((char *) buffer) + 1); ((byte *) &portable_size) [0] = *buffer++; ((byte *) &portable_size) [1] = *buffer++; ((byte *) &portable_size) [2] = *buffer++; ((byte *) &portable_size) [3] = *buffer++; block_size = ntohl (portable_size); symbol-> data = mem_descr (buffer, block_size); bufsize -= 4; bufsize -= block_size; buffer += block_size; } }
void Init_rfuse() { VALUE mRFuse=rb_define_module("RFuse"); file_info_init(mRFuse); context_init(mRFuse); rfiller_init(mRFuse); rfuse_init(mRFuse); }
static int do_exec(void) { char *source_file = saffire_getopt_string(0); setlocale(LC_ALL,""); context_init(); object_init(); module_init(); t_ast_element *ast = ast_generate_from_file(source_file); if (dot_file) { dot_generate(ast, dot_file); } int ret = interpreter(ast); // Release memory of ast root if (ast != NULL) { ast_free_node(ast); } module_fini(); object_fini(); context_fini(); return ret; }
int main(int argc, const char *argv[]) { if(setup_cli(argc, argv) == -1) { usage(argv[0]); return EXIT_FAILURE; } config.syslog = 0; config.loglevel = CRIT; config.bufsize = 16384; struct node_conf conf = {NULL, 0}; struct context ctx; context_init(&ctx); memcpy(&config.node, &conf, sizeof(config.node)); slot_init_updater(&ctx); RUN_CASE(test_slot); RUN_CASE(test_hash); RUN_CASE(test_parser); RUN_CASE(test_cmd); RUN_CASE(test_server); RUN_CASE(test_dict); RUN_CASE(test_socket); RUN_CASE(test_client); RUN_CASE(test_timer); RUN_CASE(test_config); usleep(10000); slot_create_job(SLOT_UPDATER_QUIT); pthread_join(ctx.thread, NULL); report(); return manager.failed == 0 ? EXIT_SUCCESS : EXIT_FAILURE; }
int switch_init(struct switch_cfg *cfg) { switch_cfg = cfg; switch_cfg->switch_running = 1; switch_netc = net_server(switch_cfg->listen_ip, switch_cfg->listen_port, NET_PROTO_UDT, NET_SECURE_ADH, NULL, on_connect, on_disconnect, on_input, on_secure); if (switch_netc == NULL) { jlog(L_ERROR, "net_server failed"); return -1; } context_init(); pthread_t thread_loop; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); pthread_create(&thread_loop, &attr, switch_loop, NULL); return 0; }
rc_t CC KMain ( int argc, char *argv [] ) { Args * my_args; rc_t rc; rc = ArgsMakeAndHandle (&my_args, argc, argv, 1, Options, sizeof (Options) / sizeof (OptDef)); if (rc == 0) { context *ctx; context_init( &ctx ); rc = capture_arguments_and_options( my_args, ctx ); if ( rc == 0 ) { if ( namelistcount( ctx->src_files ) > 0 ) { rc = DumpSchema( ctx ); } else { MiniUsage (my_args); } } context_destroy( ctx ); ArgsWhack( my_args ); } return rc; }
/* *----------------------------------------------------------------------- * * Run the JSON tests from the SDAM Monitoring spec. * *----------------------------------------------------------------------- */ static void test_sdam_monitoring_cb (bson_t *test) { mongoc_client_t *client; mongoc_topology_t *topology; bson_t phase; bson_t phases; bson_t outcome; bson_iter_t phase_iter; bson_iter_t phase_field_iter; bson_iter_t outcome_iter; bson_iter_t iter; bson_t events_expected; context_t context; /* parse out the uri and use it to create a client */ BSON_ASSERT (bson_iter_init_find (&iter, test, "uri")); client = mongoc_client_new (bson_iter_utf8 (&iter, NULL)); topology = client->topology; context_init (&context); client_set_topology_event_callbacks (client, &context); /* for each phase, parse and validate */ BSON_ASSERT (bson_iter_init_find (&iter, test, "phases")); bson_iter_bson (&iter, &phases); bson_iter_init (&phase_iter, &phases); while (bson_iter_next (&phase_iter)) { bson_iter_bson (&phase_iter, &phase); /* this test doesn't exercise this code path naturally, see below in * _test_topology_events for a non-hacky test of this event */ _mongoc_topology_description_monitor_opening (&topology->description); process_sdam_test_ismaster_responses (&phase, &client->topology->description); /* parse out "outcome" and validate */ BSON_ASSERT (bson_iter_init_find (&phase_field_iter, &phase, "outcome")); bson_iter_bson (&phase_field_iter, &outcome); bson_iter_init (&outcome_iter, &outcome); while (bson_iter_next (&outcome_iter)) { if (strcmp ("events", bson_iter_key (&outcome_iter)) == 0) { bson_iter_bson (&outcome_iter, &events_expected); check_json_apm_events (&context.events, &events_expected); } else { fprintf (stderr, "ERROR: unparsed test field %s\n", bson_iter_key (&outcome_iter)); BSON_ASSERT (false); } } } mongoc_client_destroy (client); context_destroy (&context); }
/* * thread_build() */ void thread_build(struct thread *t, void (*fn)(void *), void *arg, void *stack_memory, addr_t stack_addr, priority_t pri) { t->t_ticks_scheduled = 10; t->t_ticks_left = 10; t->t_next = thread_list; thread_list = t; context_init(&t->t_context, fn, arg, stack_memory, stack_addr, pri); }
struct update_context *updater_context_create() { if (s_ctx != NULL) { return NULL; } s_ctx = calloc(1, sizeof(*s_ctx)); context_init(s_ctx); return s_ctx; }
void DS_init(void) { DECAF_linux_vmi_init(); context_init(); /*DalvikMterpOpcodes_init(); DalvikDisableJit_init(); DalvikPrinter_init(); */ //atexit(DS_close); }
/**@brief Initializes context table. */ static void context_table_init(uint32_t table_id) { uint32_t index; for (index = 0; index < IOT_CONTEXT_MANAGER_MAX_CONTEXTS; index++) { context_init(&m_context_table[table_id].contexts[index]); m_context_table[table_id].context_count = 0; m_context_table[table_id].p_interface = NULL; } }
static ERL_NIF_TERM hd512_init(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { ERL_NIF_TERM result; ErlNifResourceType* ctx_type = (ErlNifResourceType*)enif_priv_data(env); Context* ctx = (Context*)enif_alloc_resource(ctx_type, sizeof(Context)); context_init(ctx, H512, sizeof H512, PADDED_SIZE_5XX); result = enif_make_resource(env, ctx); enif_release_resource(ctx); return result; }
int main(int argc, const char **argv) { int opt; #if 0 if (argc != 2) { fprintf(stderr, "Usage: motlle `smottle`\n"); exit(2); } sscanf(argv[1], "%p", &load_address); #endif for (;;) switch (getopt(argc, argv, "+d")) { case 'd': debug_lvl = 2; break; case '?': break; case -1: goto done; } done: signal(SIGALRM, silly_sig); garbage_init(); interpret_init(); stack_init(); runtime_init(); call_init(); parser_init(); compile_init(); mcompile_init(); context_init(); ports_init(); if (optind < argc) make_global_state(argc - optind, argv + optind); else make_global_state(0, NULL); mudio_init(); print_init(); if (optind < argc) mload(argv[optind]); else push_repl(); for (;;) motlle_run1(); }
int main(void) { t_env env; env.window = window_create("acazuc", 1280, 720); context_init(&env); mlx_opengl_window_set_context(env.window->mlx_window); env.world = world_create(); mlx_loop_hook(env.window->mlx, loop_hook, &env); mlx_loop(env.window->mlx); return (0); }
static void _test_topology_events (bool pooled) { mongoc_client_t *client; mongoc_client_pool_t *pool = NULL; context_t context; bool r; bson_error_t error; bson_iter_t events_iter; bson_iter_t event_iter; uint32_t i; context_init (&context); if (pooled) { pool = test_framework_client_pool_new (); pool_set_topology_event_callbacks (pool, &context); client = mongoc_client_pool_pop (pool); } else { client = test_framework_client_new (); client_set_topology_event_callbacks (client, &context); } r = mongoc_client_command_simple (client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); ASSERT_OR_PRINT (r, error); if (pooled) { mongoc_client_pool_push (pool, client); mongoc_client_pool_destroy (pool); } else { mongoc_client_destroy (client); } /* first event is topology opening */ bson_iter_init (&events_iter, &context.events); bson_iter_next (&events_iter); ASSERT (bson_iter_recurse (&events_iter, &event_iter)); ASSERT (bson_iter_find (&event_iter, "topology_opening_event")); /* last event is topology closed */ for (i = 1; i < context.n_events; i++) { ASSERT (bson_iter_next (&events_iter)); } ASSERT (bson_iter_recurse (&events_iter, &event_iter)); ASSERT (bson_iter_find (&event_iter, "topology_closed_event")); /* no more events */ ASSERT (!bson_iter_next (&events_iter)); context_destroy (&context); }
rc_t CC KMain( int argc, char * argv[] ) { Args * args; rc_t rc = ArgsMakeAndHandle ( &args, argc, argv, 1, MyOptions, sizeof MyOptions / sizeof ( OptDef ) ); if ( rc != 0 ) LogErr( klogInt, rc, "ArgsMakeAndHandle() failed\n" ); else { context *ctx; KLogHandlerSetStdErr(); rc = context_init( &ctx ); if ( rc != 0 ) LogErr( klogInt, rc, "context_init() failed\n" ); else { rc = context_capture_arguments_and_options( args, ctx ); if ( rc != 0 ) LogErr( klogInt, rc, "context_capture_arguments_and_options() failed\n" ); else { if ( ctx->usage_requested ) MiniUsage( args ); else { switch( ctx->output_mode[ 0 ] ) { case 'd' : case 't' : if ( context_schema_count( ctx ) == 0 ) { OUTMSG(( "cannot write, schema-file is missing:\n" )); Usage( args ); rc = RC( rcApp, rcNoTarg, rcConstructing, rcSelf, rcNull ); } } if ( rc == 0 ) { /* ************************* */ rc = gater_and_write( ctx ); /* ************************* */ } } } context_destroy ( ctx ); } ArgsWhack ( args ); } return rc; }
void thread_init(struct thread *t, int priority, void *(*run)(void *), void *arg) { assert(t); assert(run); assert(thread_stack_get(t)); assert(thread_stack_get_size(t)); t->id = id_counter++; /* setup thread ID */ dlist_head_init(&t->thread_link); /* default unlink value */ t->task = NULL; t->critical_count = __CRITICAL_COUNT(CRITICAL_SCHED_LOCK); t->siglock = 0; t->state = TS_INIT; if (thread_local_alloc(t, MODOPS_THREAD_KEY_QUANTITY)) { panic("can't initialize thread_local"); } t->joining = NULL; t->run = run; t->run_arg = arg; /* cpu context init */ /* setup stack pointer to the top of allocated memory * The structure of kernel thread stack follow: * +++++++++++++++ top * | * v * the thread structure * xxxxxxx * the end * +++++++++++++++ bottom (t->stack - allocated memory for the stack) */ context_init(&t->context, CONTEXT_PRIVELEGED | CONTEXT_IRQDISABLE, thread_trampoline, thread_stack_get(t) + thread_stack_get_size(t)); sigstate_init(&t->sigstate); schedee_init(&t->schedee, priority, thread_process); /* initialize everthing else */ thread_wait_init(&t->thread_wait); }
void mudlle_init(void) { garbage_init(); global_init(); strbuf_init(); print_init(); stack_init(); module_init(); runtime_init(); compile_init(); mcompile_init(); interpret_init(); error_init(); ports_init(); context_init(); }
void print_string(const char *string, int num_lines, int freq_min, int freq_max, int col_time_ms) { Context context; Pa_Initialize(); context_init(&context, num_lines, freq_min, freq_max, col_time_ms); start_playback(&context); int num_cols = 0; const char *message = prepare_message(string, &num_cols); for (int col = 0; col < num_cols; col++) { const char *col_start = message + col*ROWS_PER_LETTER; print_text_column(&context, col_start, ROWS_PER_LETTER); } free((void*)message); stop_playback(&context); Pa_Terminate(); context_dealloc(&context); }
static void test_topology_events_disabled (void) { mongoc_client_t *client; context_t context; bool r; bson_error_t error; bson_iter_t events_iter; bson_iter_t event_iter; uint32_t i; context_init (&context); client = test_framework_client_new (); client_set_topology_event_callbacks (client, &context); r = mongoc_client_command_simple ( client, "admin", tmp_bson ("{'ping': 1}"), NULL, NULL, &error); ASSERT_OR_PRINT (r, error); /* disable callbacks before destroying so we don't see a topology closed * event */ mongoc_client_set_apm_callbacks (client, NULL, NULL); mongoc_client_destroy (client); /* first event is topology opening */ bson_iter_init (&events_iter, &context.events); bson_iter_next (&events_iter); ASSERT (bson_iter_recurse (&events_iter, &event_iter)); ASSERT (bson_iter_find (&event_iter, "topology_opening_event")); /* move forward to the last event */ for (i = 1; i < context.n_events; i++) { ASSERT (bson_iter_next (&events_iter)); } /* verify we didn't receive a topology closed event */ ASSERT (bson_iter_recurse (&events_iter, &event_iter)); ASSERT (!bson_iter_find (&event_iter, "topology_closed_event")); /* no more events */ ASSERT (!bson_iter_next (&events_iter)); context_destroy (&context); }
void main_execute(void) { ssl_configure(); /* configure global SSL settings */ context_init(); /* initialize global SSL context */ /* check if started from inetd */ if(local_options.next) { /* there are service sections -> daemon mode */ daemon_loop(); } else { /* inetd mode */ #if !defined (USE_WIN32) && !defined (__vms) max_fds=FD_SETSIZE; /* just in case */ drop_privileges(); #endif num_clients=1; client(alloc_client_session(&local_options, 0, 1)); } /* close SSL */ context_free(); /* free global SSL context */ log_close(); }
int loop_hook(void *data) { t_env *env; env = (t_env*)data; context_init(env); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //world_add_chunk(env->world, chunk_create(env->world, 16, 0)); glColor3f(0,0,0); glBegin(GL_QUADS); glVertex3f(-1, 1, 10); glVertex3f(1, 1, 10); glVertex3f(1, -1, 10); glVertex3f(-1, -1, 10); glEnd(); GL_ERROR(); world_render(env->world); mlx_opengl_swap_buffers(env->window->mlx_window); return (0); }
/** * Main entry point for processing arguments and starting the split process */ int main(int argc, char **argv) { // Create our context object, null it out struct csv_context ctx; memset(&ctx, 0, sizeof(struct csv_context)); // Initialize buffers context_init(&ctx); // Attempt to parse our arguments parse_args(&ctx, argc, argv); // Allocate memory for thread storage ctx.io_threads = malloc(ctx.thread_count * sizeof *ctx.io_threads); // OOM sanity check if(!ctx.io_threads) { fprintf(stderr, "Error: Couldn't allocate thread storage.\n"); exit(EXIT_FAILURE); } // Initialize our IO threads spool_threads(&ctx); // Process our input process_csv(&ctx); // Signal that we're done inside our queue fq_fin(&ctx.io_queue); // Join our threads join_threads(&ctx); // One last trigger showing we're done exec_trigger(ctx.trigger_cmd, "", 0); // Free memory from our context context_free(&ctx); // Success return 0; }
/*************************************************************************** Main: * create the copy-context * parse the commandline for arguments and options * react to help/usage - requests ( no dump in this case ) these functions are in vdb-copy-context.c * call copy_main() to execute the copy-operation * destroy the copy-context ***************************************************************************/ rc_t CC KMain ( int argc, char *argv [] ) { Args * args; rc_t rc = ArgsMakeAndHandle ( &args, argc, argv, 1, MyOptions, sizeof MyOptions / sizeof ( OptDef ) ); if ( rc != 0 ) { LOGERR( klogErr, rc, "ArgsMakeAndHandle() failed" ); } else { context *ctx; KLogHandlerSetStdErr(); rc = context_init( &ctx ); if ( rc != 0 ) { LOGERR( klogInt, rc, "KMain:context_init() failed" ); } else { rc = context_capture_arguments_and_options( args, ctx ); if ( rc != 0 ) { MiniUsage( args ); if ( argc < 2 ) rc = 0; } else { if ( ctx->usage_requested ) MiniUsage( args ); else rc = ref_seq_load_main( ctx ); /* <====================== */ } context_destroy( ctx ); } ArgsWhack ( args ); } return rc; }
uint32_t iot_context_manager_remove(const iot_interface_t * p_interface, iot_context_t * p_context) { VERIFY_MODULE_IS_INITIALIZED(); NULL_PARAM_CHECK(p_interface); NULL_PARAM_CHECK(p_context); uint32_t err_code = NRF_SUCCESS; CM_ENTRY(); CM_MUTEX_LOCK(); const uint32_t table_id = context_table_find(p_interface); if (table_id != IOT_CONTEXT_MANAGER_MAX_TABLES) { if (p_context->context_id != IPV6_CONTEXT_IDENTIFIER_NONE) { m_context_table[table_id].context_count--; } // Reinit context entry. context_init(p_context); } else { // No free context table found. CM_ERR("No context table found."); err_code = (NRF_ERROR_NOT_FOUND | IOT_CONTEXT_MANAGER_ERR_BASE); } CM_MUTEX_UNLOCK(); CM_EXIT(); return err_code; }
int main( void ) { context ctx; window* w; if( !(w = window_create( 640, 480 )) ) return -1; context_init( &ctx ); ctx.target = &w->fb; context_set_viewport( &ctx, 0, 0, w->fb.width, w->fb.height ); while( window_handle_events( w ) ) { framebuffer_clear( &w->fb, 0, 0, 0, 0xFF ); ia_begin( &ctx ); ia_color( &ctx, 1.0f, 1.0f, 1.0f, 1.0f ); ia_vertex( &ctx, -0.5f, -0.5f, 0.0f, 1.0f ); ia_vertex( &ctx, 0.5f, -0.5f, 0.0f, 1.0f ); ia_vertex( &ctx, -0.3f, 0.5f, 0.0f, 1.0f ); ia_vertex( &ctx, 0.3f, 0.5f, 0.0f, 1.0f ); ia_vertex( &ctx, 0.5f, -0.5f, 0.0f, 1.0f ); ia_vertex( &ctx, -0.3f, 0.5f, 0.0f, 1.0f ); ia_end( &ctx ); window_display_framebuffer( w ); } window_destroy( w ); return 0; }
void print_image(const char *filename, int freq_min, int freq_max, int col_time_ms) { char buf[2048]; Context context; int width, height, max; const char *image = read_pgm(filename, &width, &height, &max); if (image == NULL) { printf("Error loading %s", filename); exit(1); } Pa_Initialize(); context_init(&context, height, freq_min, freq_max, col_time_ms); start_playback(&context); for (int col = 0; col < width; col++) { for (int row = 0; row < height; row++) { buf[height - 1 - row] = image[row*width + col]; } print_image_column(&context, buf, height, max); } stop_playback(&context); Pa_Terminate(); context_dealloc(&context); }
static void _test_heartbeat_events (bool pooled, bool succeeded) { context_t context; mock_server_t *server; mongoc_uri_t *uri; mongoc_client_t *client; mongoc_client_pool_t *pool = NULL; future_t *future; request_t *request; char *expected_json; bson_error_t error; context_init (&context); /* auto-respond to "foo" command */ server = mock_server_new (); mock_server_run (server); mock_server_autoresponds (server, responder, NULL, NULL); uri = mongoc_uri_copy (mock_server_get_uri (server)); mongoc_uri_set_option_as_int32 (uri, "serverSelectionTimeoutMS", 400); if (pooled) { pool = mongoc_client_pool_new (uri); pool_set_heartbeat_event_callbacks (pool, &context); client = mongoc_client_pool_pop (pool); } else { client = mongoc_client_new_from_uri (uri); client_set_heartbeat_event_callbacks (client, &context); } /* trigger "ismaster" handshake */ future = future_client_command_simple (client, "admin", tmp_bson ("{'foo': 1}"), NULL, NULL, &error); /* topology scanner calls ismaster once */ request = mock_server_receives_ismaster (server); if (succeeded) { mock_server_replies_ok_and_destroys (request); } else { mock_server_hangs_up (request); request_destroy (request); } /* pooled client opens new socket, handshakes it by calling ismaster again */ if (pooled && succeeded) { request = mock_server_receives_ismaster (server); mock_server_replies_ok_and_destroys (request); } if (succeeded) { /* "foo" command succeeds */ ASSERT_OR_PRINT (future_get_bool (future), error); } else { ASSERT (!future_get_bool (future)); } if (pooled) { mongoc_client_pool_push (pool, client); mongoc_client_pool_destroy (pool); } else { mongoc_client_destroy (client); } /* even if pooled, only topology scanner sends events, so we get one pair */ if (succeeded) { expected_json = bson_strdup_printf ( "{'0': {'heartbeat_started_event': {'host': '%s'}}," " '1': {'heartbeat_succeeded_event': {'host': '%s'}}}", mock_server_get_host_and_port (server), mock_server_get_host_and_port (server)); } else { expected_json = bson_strdup_printf ( "{'0': {'heartbeat_started_event': {'host': '%s'}}," " '1': {'heartbeat_failed_event': {'host': '%s'}}}", mock_server_get_host_and_port (server), mock_server_get_host_and_port (server)); } check_json_apm_events (&context.events, tmp_bson (expected_json)); future_destroy (future); bson_free (expected_json); mongoc_uri_destroy (uri); mock_server_destroy (server); context_destroy (&context); }
/* * Entry Point. */ DWORD Init( SOCKET s ) { DWORD dwResult = ERROR_SUCCESS; BOOL bTerminate = FALSE; HANDLE hMessageThread = NULL; DLL_BUFFER VncDllBuffer = {0}; char cCommandLine[MAX_PATH] = {0}; DWORD dwHostSessionId = 0; DWORD dwActiveSessionId = 0; DWORD dwAgentSessionId = 0xFFFFFFFF; BYTE bFlags = 0; __try { do { // We maintain state for the rfb stream so as not to desynchronize the remote // client after session switching and the injection of multiple agents server side. context_init(); sock = s; if( sock == INVALID_SOCKET ) BREAK_WITH_ERROR( "[LOADER] Init. INVALID_SOCKET", ERROR_INVALID_PARAMETER ); if( recv( sock, (char *)&bFlags, 1, 0 ) == SOCKET_ERROR ) BREAK_ON_WSAERROR( "[LOADER] Init. recv bFlags failed" ); if( bFlags & VNCFLAG_DISABLECOURTESYSHELL ) AgentContext.bDisableCourtesyShell = TRUE; if( bFlags & VNCFLAG_DISABLESESSIONTRACKING ) bDisableSessionTracking = TRUE; dprintf( "[LOADER] Init. Starting, hAppInstance=0x%08X, sock=%d, bFlags=%d", hAppInstance, sock, bFlags ); // get the vnc dll we will inject into the active session if( loader_vncdll( &VncDllBuffer ) != ERROR_SUCCESS ) BREAK_ON_ERROR( "[LOADER] Init. loader_vncdll failed" ); // create a socket event and have it signaled on FD_CLOSE hSocketCloseEvent = WSACreateEvent(); if( hSocketCloseEvent == WSA_INVALID_EVENT ) BREAK_ON_WSAERROR( "[LOADER] Init. WSACreateEvent failed" ); if( WSAEventSelect( sock, hSocketCloseEvent, FD_CLOSE ) == SOCKET_ERROR ) BREAK_ON_WSAERROR( "[LOADER] Init. WSAEventSelect failed" ); // get the session id that our host process belongs to dwHostSessionId = session_id( GetCurrentProcessId() ); hMessageThread = CreateThread( NULL, 0, context_message_thread, NULL, 0, NULL ); if( !hMessageThread ) BREAK_ON_ERROR( "[LOADER] Init. CreateThread context_message_thread failed" ); // loop untill the remote client closes the connection, creating a vnc // server agent inside the active session upon the active session changing while( !bTerminate ) { // in case we have been waiting for a session to attach to the physical // console and the remote client has quit, we detect this here... if( WaitForSingleObject( hSocketCloseEvent, 0 ) == WAIT_OBJECT_0 ) { dprintf( "[LOADER] Init. Remote socket closed, terminating1..." ); break; } // get the session id for the interactive session dwActiveSessionId = session_activeid(); // test if there is no session currently attached to the physical console... if( dwActiveSessionId == 0xFFFFFFFF ) { dprintf( "[LOADER] Init. no session currently attached to the physical console..." ); // just try to wait it out... Sleep( 250 ); continue; } else if( dwActiveSessionId == dwAgentSessionId ) { dprintf( "[LOADER] Init. dwActiveSessionId == dwAgentSessionId..." ); // just try to wait it out... Sleep( 250 ); continue; } // do the local process or session injection if( dwHostSessionId != dwActiveSessionId ) { dprintf( "[LOADER] Init. Injecting into active session %d...", dwActiveSessionId ); if( session_inject( dwActiveSessionId, &VncDllBuffer ) != ERROR_SUCCESS ) BREAK_WITH_ERROR( "[LOADER] Init. session_inject failed", ERROR_ACCESS_DENIED ); } else { dprintf( "[LOADER] Init. Allready in the active session %d.", dwActiveSessionId ); if( ps_inject( GetCurrentProcessId(), &VncDllBuffer ) != ERROR_SUCCESS ) BREAK_WITH_ERROR( "[LOADER] Init. ps_inject current process failed", ERROR_ACCESS_DENIED ); } dwAgentSessionId = dwActiveSessionId; // loop, waiting for either the agents process to die, the remote socket to die or // the active session to change... while( TRUE ) { HANDLE hEvents[2] = {0}; DWORD dwWaitResult = 0; // wait for these event to be signaled or a timeout to occur... hEvents[0] = hSocketCloseEvent; hEvents[1] = hAgentProcess; dwWaitResult = WaitForMultipleObjects( 2, (HANDLE *)&hEvents, FALSE, 250 ); // bail if we have somehow failed (e.g. invalid handle) if( dwWaitResult == WAIT_FAILED ) { dprintf( "[LOADER] Init. WaitForMultipleObjects failed." ); // if we cant synchronize we bail out... bTerminate = TRUE; break; } // if we have just timedout, test the current active session... else if( dwWaitResult == WAIT_TIMEOUT ) { // if the agent is still in the active session just continue... if( dwAgentSessionId == session_activeid() ) continue; // if we are not to perform session tracking try and stay in the current session (as it might become the active input session at a later stage) if( bDisableSessionTracking ) { dprintf( "[LOADER] Init. Active session has changed, trying to stay in current session as session tracking disabled..." ); Sleep( 500 ); continue; } // if the agent is no longer in the active session we signal the agent to terminate if( !ReleaseMutex( hAgentCloseEvent ) ) dprintf( "[LOADER] Init. ReleaseMutex 1 hAgentCloseEvent failed. error=%d", GetLastError() ); dprintf( "[LOADER] Init. Active session has changed. Moving agent into new session..." ); dwAgentSessionId = 0xFFFFFFFF; // and we go inject a new agent into the new active session (or terminate if session tracking disabled) loader_agent_close(); break; } // sanity check the result for an abandoned mutex else if( (dwWaitResult >= WAIT_ABANDONED_0) && (dwWaitResult <= (WAIT_ABANDONED_0 + 1)) ) { dprintf( "[LOADER] Init. WAIT_ABANDONED_0 for %d", dwWaitResult - WAIT_ABANDONED_0 ); bTerminate = TRUE; break; } else { // otherwise if we have an event signaled, handle it switch( dwWaitResult - WAIT_OBJECT_0 ) { case 0: dprintf( "[LOADER] Init. Remote socket closed, terminating2..." ); bTerminate = TRUE; if( !ReleaseMutex( hAgentCloseEvent ) ) dprintf( "[LOADER] Init. ReleaseMutex 2 hAgentCloseEvent failed. error=%d", GetLastError() ); ReleaseMutex( hAgentCloseEvent ); break; case 1: dprintf( "[LOADER] Init. Injected agent's process has terminated..." ); loader_agent_close(); dwAgentSessionId = 0xFFFFFFFF; break; default: dprintf( "[LOADER] Init. WaitForMultipleObjects returned dwWaitResult=0x%08X", dwWaitResult ); bTerminate = TRUE; if( !ReleaseMutex( hAgentCloseEvent ) ) dprintf( "[LOADER] Init. ReleaseMutex 3 hAgentCloseEvent failed. error=%d", GetLastError() ); break; } } // get out of this loop... break; } } } while( 0 ); CLOSE_HANDLE( hSocketCloseEvent ); loader_agent_close(); closesocket( sock ); if( hMessageThread ) TerminateThread( hMessageThread, 0 ); } __except( EXCEPTION_EXECUTE_HANDLER ) { dprintf( "[LOADER] Init. EXCEPTION_EXECUTE_HANDLER\n\n" ); } dprintf( "[LOADER] Init. Finished." ); return dwResult; }