INT check_users(printInfoStruct& printInfo) { DOUBLE users = 0; WTS_SESSION_INFOW *pSessionInfo = NULL; DWORD count; DWORD index; if (debug) std::wcout << L"Trying to enumerate terminal sessions" << '\n'; if (!WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, &pSessionInfo, &count)) { std::wcout << L"Failed to enumerate terminal sessions" << '\n'; die(); if (pSessionInfo) WTSFreeMemory(pSessionInfo); return 3; } if (debug) std::wcout << L"Got all sessions (" << count << L"), traversing and counting active ones" << '\n'; for (index = 0; index < count; index++) { LPWSTR name; DWORD size; INT len; if (debug) std::wcout << L"Querrying session number " << index << '\n'; if (!WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, pSessionInfo[index].SessionId, WTSUserName, &name, &size)) continue; if (debug) std::wcout << L"Found \"" << name << L"\". Checking whether it's a real session" << '\n'; len = lstrlenW(name); WTSFreeMemory(name); if (!len) continue; if (pSessionInfo[index].State == WTSActive || pSessionInfo[index].State == WTSDisconnected) { users++; if (debug) std::wcout << L"\"" << name << L"\" is a real session, counting it. Now " << users << '\n'; } } if (debug) std::wcout << "Finished coutning user sessions (" << users << "). Freeing memory and returning" << '\n'; WTSFreeMemory(pSessionInfo); printInfo.users = users; return -1; }
// ------------------------------------------------------------------------ // ------------------------------------------------------------------------ void entering_info( DWORD SesId, DWORD SesTyp, HANDLE token, LPVOID param ){ //определение пользователя char *wuser = NULL; char *bufa = NULL; char *whost = NULL; DWORD usersize = 0; DWORD hostsize = 0; DWORD size = 0; // -- if((!WTSQuerySessionInformation( WTS_CURRENT_SERVER_HANDLE, SesId, WTSUserName, &wuser, &usersize )) ||(!WTSQuerySessionInformation( WTS_CURRENT_SERVER_HANDLE, SesId, WTSClientAddress, &bufa, &size ))){ prn_err( "WTSQuerySessionInformation failed.", GetLastError() ); return; }else if( bufa ){ WTS_CLIENT_ADDRESS *pAddr = (WTS_CLIENT_ADDRESS *) bufa; if(!WTSQuerySessionInformation( WTS_CURRENT_SERVER_HANDLE, SesId, WTSClientName, &whost, &hostsize )){ prn_err( "WTSQuerySessionInformation failed.", GetLastError() ); }else{ char bs[10]; ZeroMemory(&bs, 12 ); char ba[25]; ZeroMemory(&ba, 26 ); sprintf( ba, "%u.%u.%u.%u", pAddr->Address[2], pAddr->Address[3], pAddr->Address[4], pAddr->Address[5] ); // ipv6 sprintf( ba, "%u.%u.%u.%u.%u.%u", pAddr->Address[0], pAddr->Address[1], pAddr->Address[2], pAddr->Address[3], pAddr->Address[4], pAddr->Address[5] ); // -- if(( SesTyp == 1 )||( SesTyp == 2 )){ strcpy( bs, "Console" ); }else if(( SesTyp == 3 )||( SesTyp == 4 )){ strcpy( bs, "Remote" ); }else if(( SesTyp == 5 )||( SesTyp == 6 )){ strcpy( bs, "Logon" ); }else if(( SesTyp == 7 )||( SesTyp == 8 )){ strcpy( bs, "Lock" ); }else{ sprintf( bs, "Type-%u", SesTyp ); } // -- if( strlen( ba ) < 8 ) strcpy( ba, "localhost" ); char pc[128]; // char *pc = malloc( sizeof( char ) * 64 ); ZeroMemory(&pc, 128 ); if( hostsize > 1 ) strcpy( pc, whost ); else strcpy( pc, "localhost" ); // -- if( SesTyp % 2 ){ // если не кратна двум то начало sprintf( msg_err, "Begin Session Id-%i, Type-%i (%s), User:%s, Host:%s, IP:%s.", SesId, SesTyp, bs, wuser, pc, ba ); prn_log( msg_err ); if(( JOB > 100 )&&( SesTyp < 7 )) new_session( SesId, SesTyp, bs, wuser, token, pc, ba ); }else{ sprintf( msg_err, "End Session Id-%i, Type-%i (%s), User:%s.", SesId, SesTyp, bs, wuser ); prn_log( msg_err ); if(( JOB > 100 )&&( SesTyp < 7 )) end_session( SesId, SesTyp, bs, wuser ); } // -- WTSFreeMemory( whost ); } // -- WTSFreeMemory( bufa ); WTSFreeMemory( wuser ); } }
static void WINAPI ServiceMain( DWORD dwArgc, LPTSTR *lpszArgv ) { WTS_SESSION_INFO *pInfos; DWORD count; if (WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE,NULL,1,&pInfos,&count)) { for (DWORD i=0;i<count;i++) { LogText("Session %d (%d)\n",pInfos[i].SessionId,pInfos[i].State); if (pInfos[i].State==WTSActive) { StartStartMenu(pInfos[i].SessionId); } } WTSFreeMemory(pInfos); } g_hServiceStatus=RegisterServiceCtrlHandlerEx(g_ServiceName,ServiceHandlerEx,NULL); if (g_hServiceStatus) { g_ServiceStatus.dwServiceType=SERVICE_WIN32; g_ServiceStatus.dwControlsAccepted=SERVICE_ACCEPT_STOP|SERVICE_ACCEPT_SHUTDOWN|SERVICE_ACCEPT_PAUSE_CONTINUE|SERVICE_ACCEPT_SESSIONCHANGE; g_ServiceStatus.dwWin32ExitCode=0; g_ServiceStatus.dwServiceSpecificExitCode=0; g_ServiceStatus.dwCurrentState=SERVICE_RUNNING; g_ServiceStatus.dwCheckPoint=0; g_ServiceStatus.dwWaitHint=0; SetServiceStatus(g_hServiceStatus, &g_ServiceStatus); } }
int rdpei_server_init(RdpeiServerContext *context) { void *buffer = NULL; DWORD bytesReturned; RdpeiServerPrivate *priv = context->priv; priv->channelHandle = WTSVirtualChannelOpenEx(WTS_CURRENT_SESSION, RDPEI_DVC_CHANNEL_NAME, WTS_CHANNEL_OPTION_DYNAMIC); if (!priv->channelHandle) { fprintf(stderr, "%s: unable to open channel\n", __FUNCTION__); return -1; } if (!WTSVirtualChannelQuery(priv->channelHandle, WTSVirtualEventHandle, &buffer, &bytesReturned) || (bytesReturned != sizeof(HANDLE))) { fprintf(stderr, "%s: error during WTSVirtualChannelQuery(WTSVirtualEventHandle) or invalid returned size(%d)\n", __FUNCTION__, bytesReturned); if (buffer) WTSFreeMemory(buffer); goto out_close; } CopyMemory(&priv->eventHandle, buffer, sizeof(HANDLE)); WTSFreeMemory(buffer); return 0; out_close: WTSVirtualChannelClose(priv->channelHandle); return -1; }
/** * Function description * * @return 0 on success, otherwise a Win32 error code */ UINT rdpei_server_init(RdpeiServerContext *context) { void *buffer = NULL; DWORD bytesReturned; RdpeiServerPrivate *priv = context->priv; priv->channelHandle = WTSVirtualChannelOpenEx(WTS_CURRENT_SESSION, RDPEI_DVC_CHANNEL_NAME, WTS_CHANNEL_OPTION_DYNAMIC); if (!priv->channelHandle) { WLog_ERR(TAG, "WTSVirtualChannelOpenEx failed!"); return CHANNEL_RC_INITIALIZATION_ERROR; } if (!WTSVirtualChannelQuery(priv->channelHandle, WTSVirtualEventHandle, &buffer, &bytesReturned) || (bytesReturned != sizeof(HANDLE))) { WLog_ERR(TAG, "WTSVirtualChannelQuery failed or invalid invalid returned size(%d)!", bytesReturned); if (buffer) WTSFreeMemory(buffer); goto out_close; } CopyMemory(&priv->eventHandle, buffer, sizeof(HANDLE)); WTSFreeMemory(buffer); return CHANNEL_RC_OK; out_close: WTSVirtualChannelClose(priv->channelHandle); return CHANNEL_RC_INITIALIZATION_ERROR; }
static BOOL should_terminate(void) { PWTS_PROCESS_INFO pinfo; DWORD i, j, count; if (!WTSEnumerateProcesses(WTS_CURRENT_SERVER_HANDLE, 0, 1, &pinfo, &count)) return TRUE; for (i = 0; i < count; i++) { if (pinfo[i].SessionId != g_session_id) continue; for (j = 0; j < g_startup_num_procs; j++) { if (pinfo[i].ProcessId == g_startup_procs[j]) break; } if (j == g_startup_num_procs) { WTSFreeMemory(pinfo); return FALSE; } } WTSFreeMemory(pinfo); return TRUE; }
static BOOL should_terminate(void) { PWTS_PROCESS_INFO pinfo; DWORD i, j, count; if (!g_connected && g_persistent_mode) { if (g_session_disconnect_ts == 0) return FALSE; if ((time(NULL) - g_session_disconnect_ts) < SESSION_TIMEOUT) return FALSE; /* timeout reached while waiting for reconnection to persistent session, terminating session. */ return TRUE; } if (g_persistent_mode) return FALSE; if (g_mbox_cnt != 0) return FALSE; if (!WTSEnumerateProcesses(WTS_CURRENT_SERVER_HANDLE, 0, 1, &pinfo, &count)) return TRUE; for (i = 0; i < count; i++) { if (pinfo[i].SessionId != g_session_id) continue; for (j = 0; j < g_system_num_procs; j++) { if (0 == _stricmp(pinfo[i].pProcessName, g_system_procs[j])) goto skip_to_next_process; } for (j = 0; j < g_startup_num_procs; j++) { if (pinfo[i].ProcessId == g_startup_procs[j]) break; } if (j == g_startup_num_procs) { WTSFreeMemory(pinfo); return FALSE; } skip_to_next_process: continue; } WTSFreeMemory(pinfo); return TRUE; }
static int rdpsnd_server_start(RdpsndServerContext* context) { void *buffer = NULL; DWORD bytesReturned; RdpsndServerPrivate *priv = context->priv; priv->ChannelHandle = WTSVirtualChannelOpen(context->vcm, WTS_CURRENT_SESSION, "rdpsnd"); if (!priv->ChannelHandle) return -1; if (!WTSVirtualChannelQuery(priv->ChannelHandle, WTSVirtualEventHandle, &buffer, &bytesReturned) || (bytesReturned != sizeof(HANDLE))) { WLog_ERR(TAG, "%s: error during WTSVirtualChannelQuery(WTSVirtualEventHandle) or invalid returned size(%d)\n", __FUNCTION__, bytesReturned); if (buffer) WTSFreeMemory(buffer); goto out_close; } CopyMemory(&priv->channelEvent, buffer, sizeof(HANDLE)); WTSFreeMemory(buffer); priv->rdpsnd_pdu = Stream_New(NULL, 4096); if (!priv->rdpsnd_pdu) goto out_close; if (priv->ownThread) { context->priv->StopEvent = CreateEvent(NULL, TRUE, FALSE, NULL); if (!context->priv->StopEvent) goto out_pdu; context->priv->Thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) rdpsnd_server_thread, (void*) context, 0, NULL); if (!context->priv->Thread) goto out_stopEvent; } return 0; out_stopEvent: CloseHandle(context->priv->StopEvent); context->priv->StopEvent = NULL; out_pdu: Stream_Free(context->priv->rdpsnd_pdu, TRUE); context->priv->rdpsnd_pdu = NULL; out_close: WTSVirtualChannelClose(context->priv->ChannelHandle); context->priv->ChannelHandle = NULL; return -1; }
static BOOL build_startup_procs(void) { PWTS_PROCESS_INFO pinfo; DWORD i, j, count; if (!WTSEnumerateProcesses(WTS_CURRENT_SERVER_HANDLE, 0, 1, &pinfo, &count)) return FALSE; g_startup_num_procs = 0; for (i = 0; i < count; i++) { if (pinfo[i].SessionId != g_session_id) continue; g_startup_num_procs++; } g_startup_procs = malloc(sizeof(DWORD) * g_startup_num_procs); j = 0; for (i = 0; i < count; i++) { if (pinfo[i].SessionId != g_session_id) continue; g_startup_procs[j] = pinfo[i].ProcessId; j++; } WTSFreeMemory(pinfo); return TRUE; }
static BOOL audin_server_open(audin_server_context* context) { audin_server* audin = (audin_server*) context; if (!audin->thread) { PULONG pSessionId = NULL; DWORD BytesReturned = 0; audin->SessionId = WTS_CURRENT_SESSION; if (WTSQuerySessionInformationA(context->vcm, WTS_CURRENT_SESSION, WTSSessionId, (LPSTR*) &pSessionId, &BytesReturned)) { audin->SessionId = (DWORD) *pSessionId; WTSFreeMemory(pSessionId); } audin->audin_channel = WTSVirtualChannelOpenEx(audin->SessionId, "AUDIO_INPUT", WTS_CHANNEL_OPTION_DYNAMIC); if (!audin->audin_channel) return FALSE; audin->stopEvent = CreateEvent(NULL, TRUE, FALSE, NULL); audin->thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) audin_server_thread_func, (void*) audin, 0, NULL); return TRUE; } return FALSE; }
int TestWtsApiEnumerateSessions(int argc, char* argv[]) { DWORD index; DWORD count; BOOL bSuccess; HANDLE hServer; PWTS_SESSION_INFO pSessionInfo; hServer = WTS_CURRENT_SERVER_HANDLE; count = 0; pSessionInfo = NULL; bSuccess = WTSEnumerateSessions(hServer, 0, 1, &pSessionInfo, &count); if (!bSuccess) { printf("WTSEnumerateSessions failed: %d\n", (int) GetLastError()); return -1; } printf("WTSEnumerateSessions count: %d\n", count); for (index = 0; index < count; index++) { printf("[%d] SessionId: %d State: %d\n", (int) index, (int) pSessionInfo[index].SessionId, (int) pSessionInfo[index].State); } WTSFreeMemory(pSessionInfo); return 0; }
int wts_send_message(int mode, const char * title, const char * text, int * perrcnt /* = 0 */) { if (perrcnt) *perrcnt = 0; // Get session list WTS_SESSION_INFOA * sessions; DWORD count; if (!WTSEnumerateSessionsA(WTS_CURRENT_SERVER_HANDLE, 0, 1, &sessions, &count)) return -1; int msgcnt = 0; for (unsigned i = 0; i < count; i++) { if ( !strcmpi(sessions[i].pWinStationName, "Console") || (mode >= 1 && sessions[i].State == WTSActive) || (mode >= 2 && sessions[i].State == WTSConnected)) { // Send Message, don't wait for OK button DWORD result; if (WTSSendMessageA(WTS_CURRENT_SERVER_HANDLE, sessions[i].SessionId, const_cast<char *>(title), strlen(title), const_cast<char *>(text), strlen(text), MB_OK|MB_ICONEXCLAMATION, 0 /*Timeout*/, &result, FALSE /*Wait*/)) msgcnt++; else if (perrcnt) (*perrcnt)++; } } WTSFreeMemory(sessions); return msgcnt; }
/* * Open a dynamic channel with the name given in szChannelName * the output file handle can be used in ReadFile/WriteFile calls */ DWORD OpenDynamicChannel(LPCSTR szChannelName, HANDLE* phFile) { HANDLE hWTSHandle = NULL; HANDLE hWTSFileHandle; PVOID vcFileHandlePtr = NULL; DWORD len; DWORD rc = ERROR_SUCCESS; hWTSHandle = WTSVirtualChannelOpenEx(WTS_CURRENT_SESSION, (LPSTR)szChannelName, WTS_CHANNEL_OPTION_DYNAMIC); if (!hWTSHandle) { rc = GetLastError(); printf("WTSVirtualChannelOpenEx API Call Failed: GetLastError() = %d\n", GetLastError()); goto exitpt; } BOOL bSucc = WTSVirtualChannelQuery(hWTSHandle, WTSVirtualFileHandle, &vcFileHandlePtr, &len); if ( !bSucc ) { rc = GetLastError(); goto exitpt; } if ( len != sizeof( HANDLE )) { rc = ERROR_INVALID_PARAMETER; goto exitpt; } hWTSFileHandle = *(HANDLE *)vcFileHandlePtr; bSucc = DuplicateHandle( GetCurrentProcess(), hWTSFileHandle, GetCurrentProcess(), phFile, 0, FALSE, DUPLICATE_SAME_ACCESS ); if ( !bSucc ) { rc = GetLastError(); goto exitpt; } rc = ERROR_SUCCESS; exitpt: if ( vcFileHandlePtr ) { WTSFreeMemory( vcFileHandlePtr ); } if ( hWTSHandle ) { WTSVirtualChannelClose( hWTSHandle ); } return rc; }
static void* tf_debug_channel_thread_func(void* arg) { void* fd; STREAM* s; void* buffer; UINT32 bytes_returned = 0; testPeerContext* context = (testPeerContext*) arg; freerdp_thread* thread = context->debug_channel_thread; if (WTSVirtualChannelQuery(context->debug_channel, WTSVirtualFileHandle, &buffer, &bytes_returned) == TRUE) { fd = *((void**) buffer); WTSFreeMemory(buffer); thread->signals[thread->num_signals++] = CreateFileDescriptorEvent(NULL, TRUE, FALSE, ((int) (long) fd)); } s = stream_new(4096); WTSVirtualChannelWrite(context->debug_channel, (BYTE*) "test1", 5, NULL); while (1) { freerdp_thread_wait(thread); if (freerdp_thread_is_stopped(thread)) break; stream_set_pos(s, 0); if (WTSVirtualChannelRead(context->debug_channel, 0, stream_get_head(s), stream_get_size(s), &bytes_returned) == FALSE) { if (bytes_returned == 0) break; stream_check_size(s, bytes_returned); if (WTSVirtualChannelRead(context->debug_channel, 0, stream_get_head(s), stream_get_size(s), &bytes_returned) == FALSE) { /* should not happen */ break; } } stream_set_pos(s, bytes_returned); printf("got %d bytes\n", bytes_returned); } stream_free(s); freerdp_thread_quit(thread); return 0; }
int findSession(TCHAR *userToFind) { int sessionId = -1; WTS_SESSION_INFO *sessions; DWORD count; if (!WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, &sessions, &count)) { printError(L"WTSEnumerateSessions failed: %s\n"); return -1; } for (DWORD i = 0; i < count; i++) { WCHAR *sessionUser; DWORD bytes; if (!WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, sessions[i].SessionId, WTSUserName, &sessionUser, &bytes)) { printError(L"WTSQuerySessionInformation error: %s\n"); continue; } #if DEBUG wprintf(L" * Session %d: \n user: %s\n state: %d\n name: %s\n", sessions[i].SessionId, sessionUser, sessions[i].State, sessions[i].pWinStationName); #endif if (sessionUser != NULL && _wcsicmp(userToFind, sessionUser) == 0) sessionId = sessions[i].SessionId; WTSFreeMemory(sessionUser); if (sessionId != -1) break; } WTSFreeMemory(sessions); return sessionId; }
/*----------------------------------------------------------------------------- Kill any Dr. Watson windows that are open (we already killed the browser process) -----------------------------------------------------------------------------*/ void CurlBlastDlg::KillProcs(void) { #ifndef _DEBUG WTS_PROCESS_INFO * proc = NULL; DWORD count = 0; if( WTSEnumerateProcesses(WTS_CURRENT_SERVER_HANDLE, 0, 1, &proc, &count) ) { for( DWORD i = 0; i < count; i++ ) { bool terminate = false; // check for Dr. Watson if( !lstrcmpi(PathFindFileName(proc[i].pProcessName), _T("dwwin.exe")) ) { if( !bDrWatson ) { log.LogEvent(event_KilledDrWatson); bDrWatson = true; } terminate = true; } else if(lstrcmpi(PathFindFileName(proc[i].pProcessName), _T("iexplore.exe"))) { if (worker) { EnterCriticalSection( &(worker->cs) ); // make sure it's not the browser we launched if( proc[i].ProcessId != worker->browserPID && worker->userSID && proc[i].pUserSid && IsValidSid(worker->userSID) && IsValidSid(proc[i].pUserSid) ) { // see if the SID matches if( EqualSid(proc[i].pUserSid, worker->userSID ) ) terminate = true; } LeaveCriticalSection( &(worker->cs) ); } } if( terminate ) { HANDLE hProc = OpenProcess(PROCESS_TERMINATE, FALSE, proc[i].ProcessId); if( hProc ) { TerminateProcess(hProc, 0); CloseHandle(hProc); } } } WTSFreeMemory(proc); } #endif }
// @pymethod object|win32ts|WTSQueryUserConfig|Returns user configuration // @rdesc The type of the returned value is dependent on the config class requested static PyObject *PyWTSQueryUserConfig(PyObject *self, PyObject *args, PyObject *kwargs) { static char *keywords[]={"ServerName","UserName","WTSConfigClass",NULL}; WCHAR *ServerName=NULL, *UserName=NULL; PyObject *obServerName, *obUserName, *ret=NULL; WTS_CONFIG_CLASS WTSConfigClass; LPWSTR buf=NULL; DWORD bufsize=0; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OOk:WTSQueryUserConfig", keywords, &obServerName, // @pyparm <o PyUnicode>|ServerName||Name ot terminal server &obUserName, // @pyparm <o PyUnicode>|UserName||Name of user &WTSConfigClass)) // @pyparm int|ConfigClass||Type of information to be returned, win32ts.WTSUserConfig* return NULL; if (PyWinObject_AsWCHAR(obServerName, &ServerName, TRUE) &&PyWinObject_AsWCHAR(obUserName, &UserName, FALSE)) if (!WTSQueryUserConfig(ServerName, UserName, WTSConfigClass, &buf, &bufsize)) PyWin_SetAPIError("WTSQueryUserConfig"); else switch(WTSConfigClass){ // @flagh ConfigClass|Returned value case WTSUserConfigInitialProgram: // @flag WTSUserConfigInitialProgram|Unicode string, program to be run when user logs on case WTSUserConfigWorkingDirectory: // @flag WTSUserConfigWorkingDirectory|Unicode string, working dir for initial program case WTSUserConfigModemCallbackPhoneNumber: // @flag WTSUserConfigModemCallbackPhoneNumber|Unicode string case WTSUserConfigTerminalServerProfilePath: // @flag WTSUserConfigTerminalServerProfilePath|Unicode string case WTSUserConfigTerminalServerHomeDir: // @flag WTSUserConfigTerminalServerHomeDir|Unicode string case WTSUserConfigTerminalServerHomeDirDrive: // @flag WTSUserConfigTerminalServerHomeDirDrive|Unicode string ret=PyWinObject_FromWCHAR(buf); break; case WTSUserConfigfInheritInitialProgram: // @flag WTSUserConfigfInheritInitialProgram|Int case WTSUserConfigfAllowLogonTerminalServer: // @flag WTSUserConfigfAllowLogonTerminalServer|Int, 1 if user can log on thru Terminal Service case WTSUserConfigTimeoutSettingsConnections: // @flag WTSUserConfigTimeoutSettingsConnections |Int, max connection time (ms) case WTSUserConfigTimeoutSettingsDisconnections:// @flag WTSUserConfigTimeoutSettingsDisconnections|Int case WTSUserConfigTimeoutSettingsIdle: // @flag WTSUserConfigTimeoutSettingsIdle|Int, max idle time (ms) case WTSUserConfigfDeviceClientDrives: // @flag WTSUserConfigfDeviceClientDrives|Int case WTSUserConfigfDeviceClientPrinters: // @flag WTSUserConfigfDeviceClientPrinters|Int case WTSUserConfigfDeviceClientDefaultPrinter: // @flag WTSUserConfigfDeviceClientDefaultPrinter|Int case WTSUserConfigBrokenTimeoutSettings: // @flag WTSUserConfigBrokenTimeoutSettings|Int case WTSUserConfigReconnectSettings: // @flag WTSUserConfigReconnectSettings|Int case WTSUserConfigModemCallbackSettings: // @flag WTSUserConfigModemCallbackSettings|Int case WTSUserConfigShadowingSettings: // @flag WTSUserConfigShadowingSettings|Int, indicates if user's session my be monitored case WTSUserConfigfTerminalServerRemoteHomeDir: // @flag WTSUserConfigfTerminalServerRemoteHomeDir|Int, ret=PyLong_FromUnsignedLong(*(DWORD *)buf); break; default: PyErr_SetString(PyExc_NotImplementedError,"Config class not supported yet"); } PyWinObject_FreeWCHAR(ServerName); PyWinObject_FreeWCHAR(UserName); if (buf) WTSFreeMemory(buf); return ret; }
static void* tf_debug_channel_thread_func(void* arg) { void* fd; wStream* s; void* buffer; DWORD BytesReturned = 0; testPeerContext* context = (testPeerContext*) arg; if (WTSVirtualChannelQuery(context->debug_channel, WTSVirtualFileHandle, &buffer, &BytesReturned) == TRUE) { fd = *((void**) buffer); WTSFreeMemory(buffer); context->event = CreateWaitObjectEvent(NULL, TRUE, FALSE, fd); } s = Stream_New(NULL, 4096); WTSVirtualChannelWrite(context->debug_channel, (PCHAR) "test1", 5, NULL); while (1) { WaitForSingleObject(context->event, INFINITE); if (WaitForSingleObject(context->stopEvent, 0) == WAIT_OBJECT_0) break; Stream_SetPosition(s, 0); if (WTSVirtualChannelRead(context->debug_channel, 0, (PCHAR) Stream_Buffer(s), Stream_Capacity(s), &BytesReturned) == FALSE) { if (BytesReturned == 0) break; Stream_EnsureRemainingCapacity(s, BytesReturned); if (WTSVirtualChannelRead(context->debug_channel, 0, (PCHAR) Stream_Buffer(s), Stream_Capacity(s), &BytesReturned) == FALSE) { /* should not happen */ break; } } Stream_SetPosition(s, BytesReturned); printf("got %lu bytes\n", BytesReturned); } Stream_Free(s, TRUE); return 0; }
void CServerDlg::OnOK() { //int nIndex = m_serverList2.GetCurSel(); //if (nIndex != LB_ERR) // m_serverList2.GetLBText(nIndex, serverName); WTSFreeMemory(&pServerInfo); m_serverList2.GetWindowText( serverName); //AfxMessageBox(serverName); g_pDoc->SetServerName( (TCHAR *) LPCTSTR(serverName)); CDialog::OnOK(); }
// Get user and domain from session information void CMultiOneTimePasswordProvider::_GetUserAndDomainName() { PWSTR szUserName = NULL; PWSTR szDomainName = NULL; DWORD dwLen; #ifdef _DEBUG //*************************** DEBUG: OutputDebugStringA("szUserName: (BEFORE) \t"); if (_szUserName != NULL) OutputDebugStringW(_szUserName); else OutputDebugStringA("NULL"); OutputDebugStringA("\n"); OutputDebugStringA("szDomainName: (BEFORE) \t"); if (_szDomainName != NULL) OutputDebugStringW(_szDomainName); else OutputDebugStringA("NULL"); OutputDebugStringA("\n"); //*/ #endif if ( ! WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, WTSUserName, &szUserName, &dwLen)) szUserName = NULL; if ( ! WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, WTSDomainName, &szDomainName, &dwLen)) szDomainName = NULL; _szUserName = (szUserName != NULL && szUserName[0] != NULL) ? StrDupW(szUserName) : NULL; _szDomainName = (szDomainName != NULL && szDomainName[0] != NULL) ? StrDupW(szDomainName) : NULL; if (szUserName != NULL) WTSFreeMemory(szUserName); if (szDomainName != NULL) WTSFreeMemory(szDomainName); #ifdef _DEBUG //*************************** DEBUG: OutputDebugStringA("_szUserName: \t"); if (_szUserName != NULL) OutputDebugStringW(_szUserName); else OutputDebugStringA("NULL"); OutputDebugStringA("\n"); OutputDebugStringA("_szDomainName: \t"); if (_szDomainName != NULL) OutputDebugStringW(_szDomainName); else OutputDebugStringA("NULL"); OutputDebugStringA("\n"); //*/ #endif }
BOOL QuerySessionInformationT(DWORD SessionId,WTS_INFO_CLASS WTSInfoClass,T& t) { DWORD buflen = 0; LPTSTR pv = NULL; t = T(); if(!WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE,SessionId,WTSInfoClass,&pv,&buflen)) { return FALSE; } //if(sizeof(T) > buflen) return FALSE; t = *(T*)pv; if(pv)WTSFreeMemory(pv); return TRUE; }
char *GetLogUserXP() { TCHAR *szLogName = NULL; DWORD dwSize = 0; if (WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, WTSUserName, &szLogName, &dwSize)) { char *lpUser = new char[256]; lstrcpy(lpUser, szLogName); WTSFreeMemory(szLogName); return lpUser; } else return NULL; }
bool Environment::getCurrentUserName(StringStorage *out, LogWriter *log) { TCHAR *userName; DWORD byteCount; DWORD sessionId = WTS::getActiveConsoleSessionId(log); if (WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, sessionId, WTSUserName, &userName, &byteCount) == 0) { return false; } out->setString(userName); WTSFreeMemory(userName); return true; }
static void* tf_debug_channel_thread_func(void* arg) { void* fd; STREAM* s; void* buffer; uint32 bytes_returned = 0; testPeerContext* context = (testPeerContext*) arg; freerdp_thread* thread = context->debug_channel_thread; if (WTSVirtualChannelQuery(context->debug_channel, WTSVirtualFileHandle, &buffer, &bytes_returned) == true) { fd = *((void**)buffer); WTSFreeMemory(buffer); thread->signals[thread->num_signals++] = wait_obj_new_with_fd(fd); } s = stream_new(4096); WTSVirtualChannelWrite(context->debug_channel, (uint8*) "test1", 5, NULL); while (1) { freerdp_thread_wait(thread); if (freerdp_thread_is_stopped(thread)) break; stream_set_pos(s, 0); if (WTSVirtualChannelRead(context->debug_channel, 0, stream_get_head(s), stream_get_size(s), &bytes_returned) == false) { if (bytes_returned == 0) break; stream_check_size(s, bytes_returned); if (WTSVirtualChannelRead(context->debug_channel, 0, stream_get_head(s), stream_get_size(s), &bytes_returned) == false) { /* should not happen */ break; } } stream_set_pos(s, bytes_returned); printf("got %d bytes\n", bytes_returned); } stream_free(s); freerdp_thread_quit(thread); return 0; }
static BOOL should_terminate(void) { PWTS_PROCESS_INFO pinfo; DWORD i, j, count; if (!WTSEnumerateProcesses(WTS_CURRENT_SERVER_HANDLE, 0, 1, &pinfo, &count)) return TRUE; for (i = 0; i < count; i++) { if (pinfo[i].SessionId != g_session_id) continue; // ieuser.exe hangs around even after IE has exited if (0 == _stricmp(pinfo[i].pProcessName, "ieuser.exe")) { continue; } // ctfmon.exe also likes to stay around if (0 == _stricmp(pinfo[i].pProcessName, "ctfmon.exe")) { continue; } for (j = 0; j < g_startup_num_procs; j++) { if (pinfo[i].ProcessId == g_startup_procs[j]) break; } if (j == g_startup_num_procs) { WTSFreeMemory(pinfo); return FALSE; } } WTSFreeMemory(pinfo); return TRUE; }
BOOL IsTerminalDisconnected() { PVOID pBuffer = NULL; DWORD pBytesReturned = 0; BOOL result = FALSE; if (WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, WTSConnectState, (LPTSTR *)&pBuffer, &pBytesReturned)) { if (*(PDWORD)pBuffer == WTSDisconnected) result = TRUE; } if (pBuffer) WTSFreeMemory(pBuffer); return result; }
// return true if running under remote desktop // (in which case CUDA and Stream apps don't work) // bool is_remote_desktop() { LPTSTR pBuf = NULL; DWORD dwLength; USHORT usProtocol=0, usConnectionState=0; if (WTSQuerySessionInformation( WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, WTSClientProtocolType, &pBuf, &dwLength )) { usProtocol = *(USHORT*)pBuf; WTSFreeMemory(pBuf); } if (WTSQuerySessionInformation( WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, WTSConnectState, &pBuf, &dwLength )) { usConnectionState = *(USHORT*)pBuf; WTSFreeMemory(pBuf); } // RDP Session implies Remote Desktop if (usProtocol == 2) return true; // Fast User Switching keeps the protocol set to the console but changes // the connected state to disconnected. if ((usProtocol == 0) && (usConnectionState == 4)) return true; return false; }
bool mod_ts::getProcesses(vector<KIWI_WTS_PROCESS_INFO> * mesProcesses, wstring * server) { bool reussite = false; PWTS_PROCESS_INFO tabProcess; DWORD nbProcess = 0; HANDLE hServer = NULL; if(openServer(&hServer, server)) { if(reussite = WTSEnumerateProcesses(hServer, 0, 1, &tabProcess, &nbProcess) != 0) { for(DWORD i = 0; i < nbProcess; i++) { KIWI_WTS_PROCESS_INFO a = { tabProcess[i].SessionId, tabProcess[i].ProcessId, tabProcess[i].pProcessName }; wstring user; wstring domain; if(mod_secacl::sidToName(tabProcess[i].pUserSid, &user, &domain, server)) { a.userSid.assign(domain); a.userSid.push_back(L'\\'); a.userSid.append(user); } else if(!mod_secacl::sidToStrSid(tabProcess[i].pUserSid, &a.userSid)) { if(tabProcess[i].pUserSid) { a.userSid.assign(L"erreur SID ; "); a.userSid.append(mod_system::getWinError()); } else a.userSid.assign(L"n.a."); } mesProcesses->push_back(a); } WTSFreeMemory(tabProcess); } closeServer(hServer); } return reussite; }
// Returns if the computer is currently locked bool CheckIsComputerLocked() { #ifdef OVR_OS_MS LPWSTR pBuf = nullptr; DWORD bytesReturned = 0; if (::WTSQuerySessionInformationW(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, WTSSessionInfoEx, &pBuf, &bytesReturned)) { if (pBuf && bytesReturned >= sizeof(WTSINFOEX)) { WTSINFOEXW* info = (WTSINFOEXW*)pBuf; WTSINFOEX_LEVEL1_W* level1 = (WTSINFOEX_LEVEL1_W*)&info->Data; bool isLocked = false; if (level1->SessionFlags == WTS_SESSIONSTATE_LOCK) { isLocked = true; } else if (level1->SessionFlags != WTS_SESSIONSTATE_UNLOCK) // if not unlocked, we expect locked { LogError("Unknown Lock State = %d", (int)level1->SessionFlags); } // Note: On Windows 7, the locked and unlocked flags are reversed! // See: https://msdn.microsoft.com/en-us/library/windows/desktop/ee621019(v=vs.85).aspx if (IsAtMostWindowsVersion(WindowsVersion::Windows7_SP1)) { isLocked = !isLocked; } return isLocked; } else { LogError("Wrong return size from WTSQuerySessionInformation %u", bytesReturned ); } if ( pBuf ) { WTSFreeMemory(pBuf); } } #endif // OVR_OS_MS return false; }
/** * Function description * * @return 0 on success, otherwise a Win32 error code */ static UINT echo_server_open_channel(echo_server* echo) { DWORD Error; HANDLE hEvent; DWORD StartTick; DWORD BytesReturned = 0; PULONG pSessionId = NULL; if (WTSQuerySessionInformationA(echo->context.vcm, WTS_CURRENT_SESSION, WTSSessionId, (LPSTR*) &pSessionId, &BytesReturned) == FALSE) { WLog_ERR(TAG, "WTSQuerySessionInformationA failed!"); return ERROR_INTERNAL_ERROR; } echo->SessionId = (DWORD) * pSessionId; WTSFreeMemory(pSessionId); hEvent = WTSVirtualChannelManagerGetEventHandle(echo->context.vcm); StartTick = GetTickCount(); while (echo->echo_channel == NULL) { if (WaitForSingleObject(hEvent, 1000) == WAIT_FAILED) { Error = GetLastError(); WLog_ERR(TAG, "WaitForSingleObject failed with error %lu!", Error); return Error; } echo->echo_channel = WTSVirtualChannelOpenEx(echo->SessionId, "ECHO", WTS_CHANNEL_OPTION_DYNAMIC); if (echo->echo_channel) break; Error = GetLastError(); if (Error == ERROR_NOT_FOUND) break; if (GetTickCount() - StartTick > 5000) break; } return echo->echo_channel ? CHANNEL_RC_OK : ERROR_INTERNAL_ERROR; }