BOOL ClientAuthenticate(const char *name, const char *hostname) { int rc, rcISC; SEC_WINNT_AUTH_IDENTITY nameAndPwd = {0}; int bytesReceived = 0, bytesSent = 0; char myTokenSource[256]; TimeStamp useBefore; DWORD ctxReq, ctxAttr; int dwRead,dwWritten; // input and output buffers SecBufferDesc obd, ibd; SecBuffer ob, ib[2]; BOOL haveInbuffer = FALSE; BOOL haveContext = FALSE; SCHANNEL_CRED cred = {0}; PCCERT_CONTEXT cert = NULL; HANDLE hMy = CertOpenSystemStore(0,"MY"); if(!hMy) { rcISC = SEC_E_NO_CREDENTIALS; server_error(1,"[%08x] %s\n",rcISC,GetErrorString(rcISC)); return FALSE; } if(name) { cert = CertFindCertificateInStore(hMy, X509_ASN_ENCODING, 0, CERT_FIND_SUBJECT_STR, (const wchar_t *)cvs::wide(name), NULL); if(!cert) { rcISC = SEC_E_NO_CREDENTIALS; server_error(1,"No certificate for '%s': %s\n",name,GetErrorString(rcISC)); return FALSE; } } cred.dwVersion = SCHANNEL_CRED_VERSION; cred.dwFlags = SCH_CRED_USE_DEFAULT_CREDS; if(cert) { cred.cCreds = 1; cred.paCred = &cert; } rc = AcquireCredentialsHandle( NULL, "SChannel", SECPKG_CRED_OUTBOUND, NULL, &cred, NULL, NULL, &credHandle, &useBefore ); ctxReq = ISC_REQ_MANUAL_CRED_VALIDATION | ISC_REQ_INTEGRITY | ISC_REQ_CONFIDENTIALITY | ISC_REQ_REPLAY_DETECT | ISC_REQ_SEQUENCE_DETECT | ISC_REQ_STREAM | ISC_REQ_USE_SUPPLIED_CREDS; strncpy(myTokenSource,hostname,sizeof(myTokenSource)); CertCloseStore(hMy,0); ib[0].pvBuffer = NULL; while ( 1 ) { obd.ulVersion = SECBUFFER_VERSION; obd.cBuffers = 1; obd.pBuffers = &ob; // just one buffer ob.BufferType = SECBUFFER_TOKEN; // preping a token here ob.cbBuffer = secPackInfo->cbMaxToken; ob.pvBuffer = malloc(secPackInfo->cbMaxToken); rcISC = InitializeSecurityContext( &credHandle, haveContext? &contextHandle: NULL, myTokenSource, ctxReq, 0, SECURITY_NATIVE_DREP, haveInbuffer? &ibd: NULL, 0, &contextHandle, &obd, &ctxAttr, &useBefore ); if ( ib[0].pvBuffer != NULL ) { free(ib[0].pvBuffer); ib[0].pvBuffer = NULL; } if ( rcISC == SEC_I_COMPLETE_AND_CONTINUE || rcISC == SEC_I_COMPLETE_NEEDED ) { CompleteAuthToken( &contextHandle, &obd ); if ( rcISC == SEC_I_COMPLETE_NEEDED ) rcISC = SEC_E_OK; else if ( rcISC == SEC_I_COMPLETE_AND_CONTINUE ) rcISC = SEC_I_CONTINUE_NEEDED; } if(rcISC<0) { server_error(1,"[%08x] %s\n",rcISC,GetErrorString(rcISC)); } // send the output buffer off to the server if ( ob.cbBuffer != 0 ) { if((dwWritten=tcp_write( (const char *) ob.pvBuffer, ob.cbBuffer))<=0) break; bytesSent += dwWritten; } free(ob.pvBuffer); ob.pvBuffer = NULL; ob.cbBuffer = 0; if ( rcISC != SEC_I_CONTINUE_NEEDED ) break; // prepare to get the server's response ibd.ulVersion = SECBUFFER_VERSION; ibd.cBuffers = 2; ibd.pBuffers = ib; // just one buffer ib[0].BufferType = SECBUFFER_TOKEN; // preping a token here ib[0].cbBuffer = secPackInfo->cbMaxToken; ib[0].pvBuffer = malloc(secPackInfo->cbMaxToken); ib[1].cbBuffer = 0; ib[1].pvBuffer = NULL; ib[1].BufferType = SECBUFFER_EMPTY; // Spare stuff // receive the server's response if((dwRead=tcp_read(ib[0].pvBuffer,ib[0].cbBuffer))<=0) break; bytesReceived += dwRead; // by now we have an input buffer and a client context haveInbuffer = TRUE; haveContext = TRUE; } // we arrive here as soon as InitializeSecurityContext() // returns != SEC_I_CONTINUE_NEEDED. if ( rcISC != SEC_E_OK ) haveContext = FALSE; else haveContext = TRUE; /* Looopback kerberos needs this */ return haveContext; }
CScriptValRooted ScriptInterface::ReadJSONFile(const VfsPath& path) { if (!VfsFileExists(path)) { LOGERROR(L"File '%ls' does not exist", path.string().c_str()); return CScriptValRooted(); } CVFSFile file; PSRETURN ret = file.Load(g_VFS, path); if (ret != PSRETURN_OK) { LOGERROR(L"Failed to load file '%ls': %hs", path.string().c_str(), GetErrorString(ret)); return CScriptValRooted(); } std::string content(file.DecodeUTF8()); // assume it's UTF-8 return ParseJSON(content); }
void CTCPSocket :: DoSendPlain( fd_set *send_fd ) { if( m_Socket == INVALID_SOCKET || m_HasError || !m_Connected || m_SendBuffer.empty( ) ) return; if( FD_ISSET( m_Socket, send_fd ) ) { // socket is ready, send it int s = send( m_Socket, m_SendBuffer.c_str( ), (int)m_SendBuffer.size( ), MSG_NOSIGNAL ); if( s > 0 ) { // success! only some of the data may have been sent, remove it from the buffer if( !m_LogFile.empty( ) ) { ofstream Log; Log.open( m_LogFile.c_str( ), ios :: app ); if( !Log.fail( ) ) { Log << "SEND >>> " << m_SendBuffer.substr(0, s) << endl; Log.close( ); } } m_SendBuffer = m_SendBuffer.substr( s ); m_LastSend = GetTime( ); } else if( s == SOCKET_ERROR && GetLastError( ) != EWOULDBLOCK ) { // send error m_HasError = true; m_Error = GetLastError( ); CONSOLE_Print( "[TCPSOCKET] error (send) - " + GetErrorString( ) ); return; } } }
void CParser::ParseProcedureType(int nTabs,bool bParseProcedurePropertyType) { //int nTabs = 5; CString sToken = m_oToken.GetCurrentToken(); m_sProgress = m_sProgress + GetTabs(nTabs) + "ParseProcedureType " + sToken + "\r\n"; if(IsProcedureType(sToken) == false) { //m_sErrors = m_sErrors + "Error in file "+ m_sFile + // "\'s parsing procedure type\r\n"; m_sProgress = m_sProgress + GetTabs(nTabs+1) + GetErrorString(); // + "\r\n"; } else if(sToken == "Property" && bParseProcedurePropertyType == true) { sToken = m_oToken.GetNextToken(); ParseProcedurePropertyType(); } m_oToken.GetNextToken(); }
void CParser::ParseEqualSign(int nTabs) { CString sToken = m_oToken.GetCurrentToken(); m_sProgress = m_sProgress + GetTabs(nTabs) + "ParseEqualSign " + sToken + "\r\n"; if(sToken == "=") { m_oToken.GetNextToken(); return; } else { m_sProgress = m_sProgress + GetTabs(nTabs+1) + GetErrorString(); ETokenType tt = m_oToken.GetCurrentTokenType(); if(tt != ttFunction || tt != ttNames) //|| tt < nTotalReserveWords) m_oToken.GetNextToken(); } }
void OnSignal(Entity * param0, const float3 & param1, const float3 & param2, float param3, float param4) { duk_context* ctx = ctx_; duk_push_global_object(ctx); duk_get_prop_string(ctx, -1, "_OnSignal"); duk_remove(ctx, -2); duk_push_number(ctx, (size_t)key_); duk_push_array(ctx); PushWeakObject(ctx, param0); duk_put_prop_index(ctx, -2, 0); PushValueObjectCopy<float3>(ctx, param1, float3_ID, float3_Finalizer); duk_put_prop_index(ctx, -2, 1); PushValueObjectCopy<float3>(ctx, param2, float3_ID, float3_Finalizer); duk_put_prop_index(ctx, -2, 2); duk_push_number(ctx, param3); duk_put_prop_index(ctx, -2, 3); duk_push_number(ctx, param4); duk_put_prop_index(ctx, -2, 4); bool success = duk_pcall(ctx, 2) == 0; if (!success) LogError("[JavaScript] OnSignal: " + GetErrorString(ctx)); duk_pop(ctx); }
void ConnectToNetworkDrive(const string& NewDir) { string strRemoteName; DriveLocalToRemoteName(DRIVE_REMOTE_NOT_CONNECTED,NewDir[0],strRemoteName); string strUserName, strPassword; GetStoredUserName(NewDir[0], strUserName); NETRESOURCE netResource; netResource.dwType = RESOURCETYPE_DISK; netResource.lpLocalName = UNSAFE_CSTR(NewDir); netResource.lpRemoteName = UNSAFE_CSTR(strRemoteName); netResource.lpProvider = 0; DWORD res = WNetAddConnection2(&netResource, nullptr, EmptyToNull(strUserName.data()), 0); if (res == ERROR_SESSION_CREDENTIAL_CONFLICT) res = WNetAddConnection2(&netResource, nullptr, nullptr, 0); if (res) { for (;;) { if (!GetNameAndPassword(strRemoteName, strUserName, strPassword, nullptr, GNP_USELAST)) break; res = WNetAddConnection2(&netResource, strPassword.data(), EmptyToNull(strUserName.data()), 0); if (!res) break; Global->CatchError(); if (res != ERROR_ACCESS_DENIED && res != ERROR_INVALID_PASSWORD && res != ERROR_LOGON_FAILURE) { Message(MSG_WARNING, 1, MSG(MError), GetErrorString().data(), MSG(MOk)); break; } } } }
void DecodingFile(QString fPath, HCRYPTKEY hKey) { QFile myFile(fPath); QString fName = myFile.fileName(); QRegExp rx("[^eFile.dat]"); int typeLen = 0; rx.indexIn(fName, typeLen); QFile srcFile("1" + fName.mid(0, typeLen)); DWORD blockLen = 0, fDataSize; BYTE* fData; myFile.open(QIODevice::ReadOnly); if (!myFile.exists()) { QMessageBox::critical(0, "Ошибка", "Файл не выбран", QMessageBox::Ok); return; } srcFile.open(QIODevice::WriteOnly); CryptDecrypt(hKey, 0, true, 0, NULL, &blockLen); fData = new BYTE[blockLen]; memset(fData, 0, blockLen); while ((fDataSize = myFile.read((char*) fData, blockLen))) { if (!CryptDecrypt(hKey, 0, fDataSize < blockLen, 0, fData, &fDataSize)) { QMessageBox::critical(0, "Ошибка", "Шифрование данных. " + GetErrorString(GetLastError()), QMessageBox::Ok); return; } srcFile.write((char*)fData, fDataSize); memset(fData, 0, blockLen); } delete[] fData; myFile.close(); srcFile.close(); }
LPCUSBSIO_API const wchar_t *I2C_Error(LPC_HANDLE handle, int32_t status) { LPCUSBSIO_I2C_Ctrl_t *dev = (LPCUSBSIO_I2C_Ctrl_t *) handle; const wchar_t *retStr = NULL; if (validHandle(handle) != 0) { if ((status == LPCUSBSIO_OK) || (LPCUSBSIO_ERR_HID_LIB == status)) { retStr = hid_error(dev->hidDev); } else { retStr = GetErrorString(status); } } else { retStr = hid_error(NULL); } return retStr; }
//------------------------------------------------------------------------------ InitFunc FindInitFunc(HMODULE &h, const wchar_t *fileName, ErrorReporter errorReporter) { h = LoadLibrary(fileName); if (!h) { errorReporter((std::wstring(L"Failed to load DLL ") + fileName + L": " + GetErrorString()).c_str()); return NULL; } static const std::string initFuncName("init_unit_test"); InitFunc initFunc = reinterpret_cast<InitFunc>(GetProcAddress(h, initFuncName.c_str())); // Do not report error: it might be that DLL is just not Boost.Test-enabled. if (!initFunc) { FreeLibrary(h); h = NULL; } return initFunc; }
void ScriptInterface::ReadJSONFile(const VfsPath& path, JS::MutableHandleValue out) { if (!VfsFileExists(path)) { LOGERROR("File '%s' does not exist", path.string8()); return; } CVFSFile file; PSRETURN ret = file.Load(g_VFS, path); if (ret != PSRETURN_OK) { LOGERROR("Failed to load file '%s': %s", path.string8(), GetErrorString(ret)); return; } std::string content(file.DecodeUTF8()); // assume it's UTF-8 if (!ParseJSON(content, out)) LOGERROR("Failed to parse '%s'", path.string8()); }
void CUDPServer :: RecvFrom( fd_set *fd, struct sockaddr_in *sin, string *message ) { if( m_Socket == INVALID_SOCKET || m_HasError || !sin || !message ){ return; } int AddrLen = sizeof( *sin ); if( FD_ISSET( m_Socket, fd ) ) { // data is waiting, receive it CONSOLE_Print( "DEBUUUUUUUUUUUUUUUUUUUUUG" ); char buffer[1024]; #ifdef WIN32 int c = recvfrom( m_Socket, buffer, 1024, 0, (struct sockaddr *)sin, &AddrLen ); #else int c = recvfrom( m_Socket, buffer, 1024, 0, (struct sockaddr *)sin, (socklen_t *)&AddrLen ); #endif if( c == SOCKET_ERROR && GetLastError( ) != EWOULDBLOCK ) { // receive error m_HasError = true; m_Error = GetLastError( ); CONSOLE_Print( "[UDPSERVER] error (recvfrom) - " + GetErrorString( ) ); } else if( c > 0 ) { // success! *message = string( buffer, c ); } } }
void CTCPSocket :: DoRecv( fd_set *fd ) { if( m_Socket == INVALID_SOCKET || m_HasError || !m_Connected ) return; if( FD_ISSET( m_Socket, fd ) ) { // data is waiting, receive it char buffer[1024]; int c = recv( m_Socket, buffer, 1024, 0 ); if( c == SOCKET_ERROR && GetLastError( ) != EWOULDBLOCK ) { // receive error m_HasError = true; m_Error = GetLastError( ); CONSOLE_Print( "[TCPSOCKET] error (recv) - " + GetErrorString( ) ); return; } else if( c == 0 ) { // the other end closed the connection CONSOLE_Print( "[TCPSOCKET] closed by remote host" ); m_Connected = false; } else if( c > 0 ) { // success! add the received data to the buffer m_RecvBuffer += string( buffer, c ); m_LastRecv = GetTime( ); } } }
int main(int argc, char* argv[]) { SC_HANDLE hSCManager = NULL, hService = NULL; char szImagePath[MAX_PATH]; SERVICE_TABLE_ENTRY ServiceTable[] = { { SERVICE_NAME, ServiceMain }, { NULL, NULL } }; if(argc==1) { // Attempt to start service. If this fails we're probably // not running as a service if(!StartServiceCtrlDispatcher(ServiceTable)) return 0; } if(argc!=2 || (strcmp(argv[1],"-i") && strcmp(argv[1],"-u") && strcmp(argv[1],"-test") && strcmp(argv[1],"-v") && strcmp(argv[1],"-systray") )) { fprintf(stderr, "NT CVS Service Handler\n\n" "Arguments:\n" "\t%s -i\tInstall\n" "\t%s -u\tUninstall\n" "\t%s -test\tInteractive run" "\t%s -v\tReport version number", basename(argv[0]),basename(argv[0]), basename(argv[0]), basename(argv[0])); return -1; } if (!strcmp(argv[1],"-v")) { puts(NTSERVICE_VERSION_STRING); return 0; } if(!strcmp(argv[1],"-i")) { // connect to the service control manager if((hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE)) == NULL) { fprintf(stderr,"OpenSCManager Failed\n"); return -1; } if((hService=OpenService(hSCManager,SERVICE_NAME,DELETE))!=NULL) { DeleteService(hService); CloseServiceHandle(hService); } GetModuleFileName(NULL,szImagePath,MAX_PATH); if ((hService = CreateService(hSCManager,SERVICE_NAME,DISPLAY_NAME, STANDARD_RIGHTS_REQUIRED|SERVICE_CHANGE_CONFIG, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, szImagePath, NULL, NULL, NULL, NULL, NULL)) == NULL) { fprintf(stderr,"CreateService Failed: %s\n",GetErrorString()); return -1; } { BOOL (WINAPI *pChangeServiceConfig2)(SC_HANDLE,DWORD,LPVOID); pChangeServiceConfig2=(BOOL (WINAPI *)(SC_HANDLE,DWORD,LPVOID))GetProcAddress(GetModuleHandle("advapi32"),"ChangeServiceConfig2A"); if(pChangeServiceConfig2) { SERVICE_DESCRIPTION sd = { NTSERVICE_VERSION_STRING }; pChangeServiceConfig2(hService,SERVICE_CONFIG_DESCRIPTION,&sd); } } CloseServiceHandle(hService); CloseServiceHandle(hSCManager); ReportError(FALSE,DISPLAY_NAME " installed successfully"); printf(DISPLAY_NAME " installed successfully\n"); } if(!strcmp(argv[1],"-u")) { // connect to the service control manager if((hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE)) == NULL) { fprintf(stderr,"OpenSCManager Failed\n"); return -1; } if((hService=OpenService(hSCManager,SERVICE_NAME,DELETE))==NULL) { fprintf(stderr,"OpenService Failed: %s\n",GetErrorString()); return -1; } if(!DeleteService(hService)) { fprintf(stderr,"DeleteService Failed: %s\n",GetErrorString()); return -1; } CloseServiceHandle(hService); CloseServiceHandle(hSCManager); ReportError(FALSE,DISPLAY_NAME " uninstalled successfully"); printf(DISPLAY_NAME " uninstalled successfully\n"); } else if(!strcmp(argv[1],"-test")) { ServiceMain(999,NULL); } return 0; }
Socket *Network::ConnectSocket(const char *address, unsigned short port, SocketTransportLayer transport) { addrinfo *result = NULL; addrinfo *ptr = NULL; addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = (transport == SocketOverTCP) ? SOCK_STREAM : SOCK_DGRAM; hints.ai_protocol = (transport == SocketOverTCP) ? IPPROTO_TCP : IPPROTO_UDP; char strPort[256]; sprintf(strPort, "%d", (unsigned int)port); int ret = getaddrinfo(address, strPort, &hints, &result); if (ret != 0) { LOG(LogError, "Network::Connect: getaddrinfo failed: %s", GetErrorString(ret).c_str()); return 0; } #ifdef WIN32 SOCKET connectSocket = WSASocket(result->ai_family, result->ai_socktype, result->ai_protocol, NULL, 0, WSA_FLAG_OVERLAPPED); #else SOCKET connectSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol); LOG(LogInfo, "A call to socket() returned a new socket 0x%8X.", (unsigned int)connectSocket); #endif if (connectSocket == INVALID_SOCKET) { LOG(LogError, "Network::Connect: Error at socket(): %s", GetLastErrorString().c_str()); freeaddrinfo(result); return 0; } // Connect to server. #ifdef WIN32 ret = WSAConnect(connectSocket, result->ai_addr, (int)result->ai_addrlen, 0, 0, 0, 0); #else ret = connect(connectSocket, result->ai_addr, (int)result->ai_addrlen); #endif if (ret == KNET_SOCKET_ERROR) { closesocket(connectSocket); connectSocket = INVALID_SOCKET; } freeaddrinfo(result); if (connectSocket == INVALID_SOCKET) { LOG(LogError, "Unable to connect to server!"); return 0; } EndPoint localEndPoint; sockaddr_in sockname; socklen_t socknamelen = sizeof(sockname); ret = getsockname(connectSocket, (sockaddr*)&sockname, &socknamelen); if (ret == 0) localEndPoint = EndPoint::FromSockAddrIn(sockname); else LOG(LogError, "Network::ConnectSocket: getsockname failed: %s!", Network::GetLastErrorString().c_str()); EndPoint remoteEndPoint; sockaddr_in peername; socklen_t peernamelen = sizeof(peername); ret = getpeername(connectSocket, (sockaddr*)&peername, &peernamelen); if (ret == 0) remoteEndPoint = EndPoint::FromSockAddrIn(peername); else LOG(LogError, "Network::ConnectSocket: getpeername failed: %s!", Network::GetLastErrorString().c_str()); std::string remoteHostName = remoteEndPoint.IPToString(); const size_t maxSendSize = (transport == SocketOverTCP) ? cMaxTCPSendSize : cMaxUDPSendSize; Socket socket(connectSocket, localEndPoint, localHostName.c_str(), remoteEndPoint, remoteHostName.c_str(), transport, ClientSocket, maxSendSize); socket.SetBlocking(false); sockets.push_back(socket); Socket *sock = &sockets.back(); return sock; }
/* * Connect to a network * * This function starts the connection process to a given network; * when the device changes status, the status change callback will * tell NetworkManager if the network is finally connected or not. * * One of the reasons it is done like that is to allow external tools * to control the device and the plugin just passing the status so * NetworkManager displays the right info. */ int iwmx_sdk_connect(struct wmxsdk *wmxsdk, const char *nsp_name) { int result = 0; WIMAX_API_RET r; char errstr[512]; UINT32 errstr_size = sizeof(errstr); WIMAX_API_DEVICE_STATUS dev_status; char sdk_name[MAX_SIZE_OF_NSP_NAME]; g_mutex_lock(&wmxsdk->connect_mutex); /* Guess what the current radio state is; if it is ON * already, don't redo it. */ dev_status = iwmxsdk_status_get(wmxsdk); if ((int) dev_status < 0) { result = dev_status; goto error_get_status; } switch (dev_status) { case WIMAX_API_DEVICE_STATUS_UnInitialized: nm_log_err(LOGD_WIMAX, "wmxsdk: SW BUG? HW is uninitialized"); result = -EINVAL; goto error_cant_do; case WIMAX_API_DEVICE_STATUS_RF_OFF_HW_SW: case WIMAX_API_DEVICE_STATUS_RF_OFF_HW: case WIMAX_API_DEVICE_STATUS_RF_OFF_SW: nm_log_err(LOGD_WIMAX, "wmxsdk: Cannot connect: radio is off"); result = -EPERM; goto error_cant_do; case WIMAX_API_DEVICE_STATUS_Ready: case WIMAX_API_DEVICE_STATUS_Scanning: break; case WIMAX_API_DEVICE_STATUS_Connecting: nm_log_dbg(LOGD_WIMAX, "Connect already pending, waiting for it"); result = -EINPROGRESS; goto error_cant_do; case WIMAX_API_DEVICE_STATUS_Data_Connected: nm_log_err(LOGD_WIMAX, "wmxsdk: BUG? need to disconnect?"); result = -EINVAL; goto error_cant_do; default: g_assert(1); } /* The SDK treats the network name as wchar_t* while the contents are * actually just UTF-8... WTF? Hand it a full buffer to work around * boundary cases where the NSP name contains an odd # of characters. */ memset(sdk_name, 0, sizeof (sdk_name)); memcpy(sdk_name, nsp_name, strlen (nsp_name)); /* Ok, do the connection, wait for a callback */ r = CmdConnectToNetwork(&wmxsdk->device_id, &sdk_name[0], 0, 0); if (r != WIMAX_API_RET_SUCCESS) { GetErrorString(&wmxsdk->device_id, r, errstr, &errstr_size); nm_log_err(LOGD_WIMAX, "wmxsdk: Cannot connect to network %s: %d (%s) - device is in state '%s'", nsp_name, r, errstr, iwmx_sdk_get_device_status_str(wmxsdk)); result = -EIO; } error_cant_do: error_get_status: g_mutex_unlock(&wmxsdk->connect_mutex); return result; }
void XmlParser::OnParseError () { ex::fprintf( stderr, "%s Parse error at line %d: %s\n", m_ParsingFileName, GetCurrentLineNumber(), GetErrorString() ); ex_error( "%s Parse error at line %d: %s\n", m_ParsingFileName, GetCurrentLineNumber(), GetErrorString() ); }
static char *GetLastErrorString( void ) { return GetErrorString( GetLastError() ); }
std::string Network::GetLastErrorString() { return GetErrorString(GetLastError()); }
void Widget::on_decryptFile_clicked() { HCRYPTPROV cryptProv; HCRYPTKEY hKey; BYTE* key; QFile keyV("key.dat"); DWORD keyBlobLen = 0; if (!keyV.exists()) { QMessageBox::critical(0, "Ошибка", "Отсутствует ключ", QMessageBox::Ok); return; } keyV.open(QIODevice::ReadOnly); if (!CryptAcquireContext(&cryptProv, NULL, MS_DEF_RSA_SCHANNEL_PROV, PROV_RSA_SCHANNEL, CRYPT_VERIFYCONTEXT)) { QMessageBox::critical(0, "Ошибка", "Получение контекста криптопровайдера. " + GetErrorString(GetLastError()), QMessageBox::Ok); return; } keyV.read((char *)&keyBlobLen, sizeof(keyBlobLen)); key = new BYTE[keyBlobLen]; memset(key, 0, keyBlobLen); keyV.read((char *)key, keyBlobLen); keyV.close(); CryptImportKey(cryptProv, key, keyBlobLen, 0, 0, &hKey); delete[] key; DecodingFile(fName, hKey); QMessageBox::information(0, "Процесс завершён", "Файл успешно расшифрован", QMessageBox::Ok); }
void Widget::on_encryptFile_clicked() { HCRYPTPROV cryptProv; HCRYPTKEY hKey; QByteArray key; QFile keyV("key.dat"); DWORD keyBlobLen = 0; QDataStream writeToFileFrom(&keyV); if (keyV.exists()) keyV.remove(); keyV.open(QIODevice::WriteOnly); if (!CryptAcquireContext(&cryptProv, NULL, MS_DEF_RSA_SCHANNEL_PROV, PROV_RSA_SCHANNEL, CRYPT_VERIFYCONTEXT)) { QMessageBox::critical(0, "Ошибка", "Получение контекста криптопровайдера. " + GetErrorString(GetLastError()), QMessageBox::Ok); return; } hKey = GenKey(cryptProv, ui->keyVal->text(), &key, keyBlobLen, ui->randKeyVal->isChecked()); writeToFileFrom << (quint32)keyBlobLen; keyV.write(key); keyV.close(); key.clear(); EncodingFile(fName, hKey); QMessageBox::information(0, "Процесс завершён", "Файл успешно зашифрован", QMessageBox::Ok); }
std::vector<std::string> CSimulation2::GetCivData() { VfsPath path(L"civs/"); VfsPaths pathnames; std::vector<std::string> data; // Load all JSON files in civs directory Status ret = vfs::GetPathnames(g_VFS, path, L"*.json", pathnames); if (ret == INFO::OK) { for (VfsPaths::iterator it = pathnames.begin(); it != pathnames.end(); ++it) { // Load JSON file CVFSFile file; PSRETURN ret = file.Load(g_VFS, *it); if (ret != PSRETURN_OK) { LOGERROR(L"CSimulation2::GetCivData: Failed to load file '%ls': %hs", path.string().c_str(), GetErrorString(ret)); } else { data.push_back(file.DecodeUTF8()); // assume it's UTF-8 } } } else { // Some error reading directory wchar_t error[200]; LOGERROR(L"CSimulation2::GetCivData: Error reading directory '%ls': %ls", path.string().c_str(), StatusDescription(ret, error, ARRAY_SIZE(error))); } return data; }
void CTCPClient :: Connect( string localaddress, string address, uint16_t port ) { if( m_Socket == INVALID_SOCKET || m_HasError || m_Connecting || m_Connected ) return; if( !localaddress.empty( ) ) { struct sockaddr_in LocalSIN; memset( &LocalSIN, 0, sizeof( LocalSIN ) ); LocalSIN.sin_family = AF_INET; if( ( LocalSIN.sin_addr.s_addr = inet_addr( localaddress.c_str( ) ) ) == INADDR_NONE ) LocalSIN.sin_addr.s_addr = INADDR_ANY; LocalSIN.sin_port = htons( 0 ); if( bind( m_Socket, (struct sockaddr *)&LocalSIN, sizeof( LocalSIN ) ) == SOCKET_ERROR ) { m_HasError = true; m_Error = GetLastError( ); CONSOLE_Print( "[TCPCLIENT] error (bind) - " + GetErrorString( ) ); return; } } // get IP address struct hostent *HostInfo; uint32_t HostAddress; HostInfo = gethostbyname( address.c_str( ) ); if( !HostInfo ) { m_HasError = true; // m_Error = h_error; CONSOLE_Print( "[TCPCLIENT] error (gethostbyname)" ); return; } memcpy( &HostAddress, HostInfo->h_addr, HostInfo->h_length ); // connect m_SIN.sin_family = AF_INET; m_SIN.sin_addr.s_addr = HostAddress; m_SIN.sin_port = htons( port ); if( connect( m_Socket, (struct sockaddr *)&m_SIN, sizeof( m_SIN ) ) == SOCKET_ERROR ) { if( GetLastError( ) != EINPROGRESS && GetLastError( ) != EWOULDBLOCK ) { // connect error m_HasError = true; m_Error = GetLastError( ); CONSOLE_Print( "[TCPCLIENT] error (connect) - " + GetErrorString( ) ); return; } } m_Connecting = true; }
BOOL CChildFrame::OpenCompositeDocument(LPCTSTR lpszFileName) { USES_CONVERSION; CWaitCursor wait; HRESULT hResult = E_FAIL; IStorage * ptrRootStg = NULL; // root storage HWND hWnd = (HWND)m_hWnd; hResult = ::StgIsStorageFile( T2COLE(m_szFileName) ); if( S_OK != hResult ) { TCHAR szFmt[MAX_PATH] = { 0 }; AtlLoadString(IDS_OPEN_ARCHIVE_ERROR, szFmt, _countof(szFmt)); TCHAR szOut[MAX_PATH*2] = { 0 }; wnsprintf(szOut, _countof(szOut), szFmt, lpszFileName); AtlMessageBox(m_hWnd, szOut, IDS_ERROR, MB_OK|MB_ICONSTOP); return FALSE; } // open the Compound document hResult = ::StgOpenStorage( T2COLE(m_szFileName), NULL, STGM_READWRITE | STGM_SHARE_EXCLUSIVE, 0, 0, &ptrRootStg ); if( FAILED(hResult) ) { TCHAR szFmt[MAX_PATH] = { 0 }; AtlLoadString(IDS_OPEN_FILE_ERROR, szFmt, _countof(szFmt)); TCHAR szError[MAX_PATH] = { 0 }; TCHAR szOut[MAX_PATH*2] = { 0 }; wnsprintf(szOut, _countof(szOut), szFmt, lpszFileName, GetErrorString(S_OK, szError, _countof(szError))); AtlMessageBox(m_hWnd, szOut, IDS_ERROR, MB_OK|MB_ICONSTOP); return FALSE; } TREE_ITEM_DATA * pRootData = new TREE_ITEM_DATA(ptrRootStg, STGTY_STORAGE); HTREEITEM hRoot = m_wndCatalog.InsertItem ( TVIF_IMAGE|TVIF_TEXT|TVIF_PARAM|TVIF_SELECTEDIMAGE, PathFindFileName(m_szFileName), 0, 1, TVIS_EXPANDED, 0, reinterpret_cast<LPARAM>(pRootData), NULL, NULL); std::stack < StgInfo > FolderStack; HTREEITEM htiParent = hRoot; IEnumSTATSTG * ptrEnum = NULL; hResult = ptrRootStg->EnumElements( 0, NULL, 0, &ptrEnum ); if( FAILED(hResult) ) { ptrRootStg->Release(); return 0; } TCHAR szSwap[MAX_PATH] = { 0 }; LARGE_INTEGER nStorageLength; nStorageLength.QuadPart = 0; STATSTG StatStg = { 0 }; while( S_OK == hResult ) { hResult = ptrEnum->Next( 1, &StatStg, NULL ); if( S_FALSE == hResult ) { ptrRootStg->Release(); ptrEnum->Release(); // m_wndCatalog.Expand(strFolder); if( !FolderStack.empty() ) { TCHAR szCurText[MAX_PATH] = {0}; m_wndCatalog.GetItemText(htiParent, szCurText, _countof(szCurText)); CString strTotal; strTotal.Format(TEXT("%s(%ld)"), szCurText, nStorageLength); m_wndCatalog.SetItemText(htiParent, strTotal); ptrRootStg = FolderStack.top().pStg; ptrEnum = FolderStack.top().pEnum; htiParent = FolderStack.top().hParent; FolderStack.pop(); hResult = S_OK; } continue; } switch(StatStg.type) { case STGTY_STORAGE: // 是存储对象, "文件夹" { //先清零 nStorageLength.QuadPart = 0; IStorage * ptrChildStg = NULL; HRESULT hr = ptrRootStg->OpenStorage( StatStg.pwcsName, NULL, STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, 0, &ptrChildStg ); if( SUCCEEDED(hr) ) { TREE_ITEM_DATA * pData = new TREE_ITEM_DATA(ptrChildStg, StatStg.type); HTREEITEM hFolder = m_wndCatalog.InsertItem ( TVIF_IMAGE|TVIF_TEXT|TVIF_PARAM|TVIF_SELECTEDIMAGE, WCHAR2TCHAR(StatStg.pwcsName, szSwap, _countof(szSwap)), 0, 1, TVIS_EXPANDED, 0, reinterpret_cast<LPARAM>(pData), htiParent, NULL); // 父存储入栈 FolderStack.push( StgInfo(ptrRootStg, ptrEnum, htiParent) ); // 子存储替代父存储 ptrRootStg = ptrChildStg; htiParent = hFolder; hr = ptrChildStg->EnumElements( 0, NULL, 0, &ptrEnum ); } } break; case STGTY_STREAM: // 是流, "文件" { CComPtr<IStream> spStream; HRESULT hr = ptrRootStg->OpenStream(StatStg.pwcsName, NULL, STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &spStream); ATLASSERT(SUCCEEDED(hr)); LARGE_INTEGER nSeekPos; nSeekPos.QuadPart = 0LL; ULARGE_INTEGER nLength = {0}; hr = spStream->Seek(nSeekPos, STREAM_SEEK_END, &nLength); CString strStreamName; WCHAR2TCHAR(StatStg.pwcsName, szSwap, _countof(szSwap)); if (SUCCEEDED(hr)) { nStorageLength.QuadPart += nLength.QuadPart; strStreamName.Format(TEXT("%s(%ld)"), szSwap, nLength); } else { strStreamName.Format(TEXT("%s(0)"), szSwap); } TREE_ITEM_DATA * pData = new TREE_ITEM_DATA(spStream, StatStg.type); m_wndCatalog.InsertItem ( TVIF_IMAGE|TVIF_TEXT|TVIF_PARAM|TVIF_SELECTEDIMAGE, strStreamName, 2, 2, TVIS_EXPANDED, 0, reinterpret_cast<LPARAM>(pData), htiParent, NULL); } break; case STGTY_LOCKBYTES: ATLTRACE(_T("===== STGTY_LOCKBYTES %d ====="), StatStg.type); break; case STGTY_PROPERTY: ATLTRACE(_T("===== STGTY_PROPERTY %d ====="), StatStg.type); break; default: ATLASSERT(!_T("Unknown storage type!!!")); break; } ::CoTaskMemFree( StatStg.pwcsName ); // 释放名称所使用的内存 } return 0; }
BOOL ServerAuthenticate(const char *hostname) { int rc, rcISC, rcl; BOOL haveToken; int bytesReceived = 0, bytesSent = 0; TimeStamp useBefore; // input and output buffers SecBufferDesc obd, ibd; SecBuffer ob, ib[2]; BOOL haveContext = FALSE; DWORD ctxReq,ctxAttr; int n; short len; SCHANNEL_CRED cred = {0}; char host[256]; struct addrinfo *ai=NULL, hints = {0}; PCCERT_CONTEXT cert; HANDLE hMy = CertOpenSystemStore(0,"MY"); if(!hMy) { rcISC = SEC_E_NO_CREDENTIALS; server_error(1,"[%08x] %s\n",rcISC,GetErrorString(rcISC)); return FALSE; } if(!hostname) { gethostname (host, sizeof host); hints.ai_flags=AI_CANONNAME; if(getaddrinfo(cvs::idn(host),NULL,&hints,&ai)) server_error (1, "can't get canonical hostname"); hostname = ai->ai_canonname; cert = CertFindCertificateInStore(hMy, X509_ASN_ENCODING, 0, CERT_FIND_SUBJECT_STR, (const wchar_t*)cvs::wide(cvs::decode_idn(hostname)), NULL); } else cert = CertFindCertificateInStore(hMy, X509_ASN_ENCODING, 0, CERT_FIND_SUBJECT_STR, (const wchar_t*)cvs::wide(hostname), NULL); if(!cert) { rcISC = SEC_E_NO_CREDENTIALS; server_error(1,"No certificate for '%s': %s\n",hostname,GetErrorString(rcISC)); return FALSE; } cred.cCreds = 1; cred.paCred = &cert; if(ai) freeaddrinfo(ai); cred.dwVersion = SCHANNEL_CRED_VERSION; cred.dwFlags = SCH_CRED_USE_DEFAULT_CREDS; rc = AcquireCredentialsHandle( NULL, "SChannel", SECPKG_CRED_INBOUND, NULL, &cred, NULL, NULL, &credHandle, &useBefore ); if ( rc == SEC_E_OK ) haveToken = TRUE; else haveToken = FALSE; CertCloseStore(hMy,0); while ( 1 ) { // prepare to get the server's response ibd.ulVersion = SECBUFFER_VERSION; ibd.cBuffers = 2; ibd.pBuffers = ib; // just one buffer ib[0].BufferType = SECBUFFER_TOKEN; // preping a token here ib[0].cbBuffer = secPackInfo->cbMaxToken; ib[0].pvBuffer = malloc(ib[0].cbBuffer); ib[1].cbBuffer = 0; ib[1].pvBuffer = NULL; ib[1].BufferType = SECBUFFER_EMPTY; // Spare stuff // receive the client's POD rcl = read( current_server()->in_fd, ib[0].pvBuffer, ib[0].cbBuffer); if(rcl<=0) { rc = SEC_E_INTERNAL_ERROR; break; } // by now we have an input buffer obd.ulVersion = SECBUFFER_VERSION; obd.cBuffers = 1; obd.pBuffers = &ob; // just one buffer ob.BufferType = SECBUFFER_TOKEN; // preping a token here ob.cbBuffer = secPackInfo->cbMaxToken; ob.pvBuffer = malloc(secPackInfo->cbMaxToken); if(rc<0) { len=0; if((n=write(current_server()->out_fd,&len,sizeof(len)))<=0) break; break; } ctxReq = ASC_REQ_INTEGRITY | ASC_REQ_CONFIDENTIALITY | ASC_REQ_REPLAY_DETECT | ASC_REQ_SEQUENCE_DETECT | ASC_REQ_STREAM; rc = AcceptSecurityContext( &credHandle, haveContext? &contextHandle: NULL, &ibd, ctxReq, SECURITY_NATIVE_DREP, &contextHandle, &obd, &ctxAttr, &useBefore ); if ( ib[0].pvBuffer != NULL ) { free( ib[0].pvBuffer ); ib[0].pvBuffer = NULL; } if ( rc == SEC_I_COMPLETE_AND_CONTINUE || rc == SEC_I_COMPLETE_NEEDED ) { CompleteAuthToken( &contextHandle, &obd ); if ( rc == SEC_I_COMPLETE_NEEDED ) rc = SEC_E_OK; else if ( rc == SEC_I_COMPLETE_AND_CONTINUE ) rc = SEC_I_CONTINUE_NEEDED; } // send the output buffer off to the server // warning -- this is machine-dependent! FIX IT! if ( rc == SEC_E_OK || rc == SEC_I_CONTINUE_NEEDED ) { if ( ob.cbBuffer != 0 ) { if((n=write(current_server()->out_fd,ob.pvBuffer, ob.cbBuffer))<=0) break; bytesSent += n; } free(ob.pvBuffer); ob.pvBuffer = NULL; ob.cbBuffer = 0; } else { break; } if ( rc != SEC_I_CONTINUE_NEEDED ) break; haveContext = TRUE; } // we arrive here as soon as InitializeSecurityContext() // returns != SEC_I_CONTINUE_NEEDED. if ( rc != SEC_E_OK ) { haveToken = FALSE; } if(rc<0) server_error(0,"[%08x] %s\n",rc, GetErrorString(rc)); return haveToken?TRUE:FALSE; }
/* * Initialize the WiMAX API, register with it, setup callbacks * */ static int iwmx_sdk_setup(struct wmxsdk *wmxsdk) { int result, status; WIMAX_API_RET r; char errstr[512]; UINT32 errstr_size = sizeof(errstr); result = -ENFILE; /* device_id initialized by iwmx_sdk_dev_add */ r = WiMaxDeviceOpen(&wmxsdk->device_id); if (r != WIMAX_API_RET_SUCCESS) { GetErrorString(&wmxsdk->device_id, r, errstr, &errstr_size); nm_log_err(LOGD_WIMAX, "wmxsdk: Cannot open device: %d (%s)", r, errstr); goto error_wimaxdeviceopen; } /* * We scan in auto mode (in the background) * * Otherwise is messy -- if we have NetworkManager triggering a scan * when we call iwmx_nm_scan() -> iwmx_sdk_scan(), most of the * times that causes a race condition when the UI asks for a * scan right before displaying the network menu. As there is * no way to cancel an ongoing scan before connecting, we are * stuck. So we do auto bg and have iwmx_sdk_scan() just return * the current network list. */ r = SetConnectionMode(&wmxsdk->device_id, WIMAX_API_CONNECTION_AUTO_SCAN_MANUAL_CONNECT); if (r != WIMAX_API_RET_SUCCESS) { GetErrorString(&wmxsdk->device_id, r, errstr, &errstr_size); nm_log_err(LOGD_WIMAX, "wmxsdk: Cannot set connectin mode to manual: %d (%s)", r, errstr); goto error_connection_mode; } r = SubscribeControlPowerManagement(&wmxsdk->device_id, __iwmx_sdk_rf_state_cb); if (r != WIMAX_API_RET_SUCCESS) { GetErrorString(&wmxsdk->device_id, r, errstr, &errstr_size); nm_log_err(LOGD_WIMAX, "wmxsdk: Cannot subscribe to radio change events: %u (%s)", r, errstr); result = -EIO; goto error_subscribe_rf_state; } r = SubscribeDeviceStatusChange(&wmxsdk->device_id, __iwmx_sdk_state_change_cb); if (r != WIMAX_API_RET_SUCCESS) { GetErrorString(&wmxsdk->device_id, r, errstr, &errstr_size); nm_log_err(LOGD_WIMAX, "wmxsdk: Cannot subscribe to state chaneg events: %d (%s)", r, errstr); goto error_subscribe_state_change; } r = SubscribeNetworkSearchWideScanEx(&wmxsdk->device_id, __iwmx_sdk_wide_scan_cb); if (r != WIMAX_API_RET_SUCCESS) { GetErrorString(&wmxsdk->device_id, r, errstr, &errstr_size); nm_log_err(LOGD_WIMAX, "wmxsdk: Cannot subscribe to wide scan events: %d (%s)", r, errstr); goto error_subscribe_wide_scan; } r = SubscribeNetworkSearchEx(&wmxsdk->device_id, __iwmx_sdk_scan_cb); if (r != WIMAX_API_RET_SUCCESS) { GetErrorString(&wmxsdk->device_id, r, errstr, &errstr_size); nm_log_err(LOGD_WIMAX, "wmxsdk: Cannot subscribe to scan events: %d (%s)", r, errstr); goto error_subscribe_scan; } r = SubscribeConnectToNetwork(&wmxsdk->device_id, __iwmx_sdk_connect_cb); if (r != WIMAX_API_RET_SUCCESS) { GetErrorString(&wmxsdk->device_id, r, errstr, &errstr_size); nm_log_err(LOGD_WIMAX, "wmxsdk: Cannot subscribe to connect events: %d (%s)", r, errstr); goto error_subscribe_connect; } r = SubscribeDisconnectToNetwork(&wmxsdk->device_id, __iwmx_sdk_disconnect_cb); if (r != WIMAX_API_RET_SUCCESS) { GetErrorString(&wmxsdk->device_id, r, errstr, &errstr_size); nm_log_err(LOGD_WIMAX, "wmxsdk: Cannot subscribe to disconnect events: %d (%s)", r, errstr); goto error_subscribe_disconnect; } r = SubscribeMediaStatusUpdate(&wmxsdk->device_id, __iwmx_sdk_media_status_update_cb); if (r != WIMAX_API_RET_SUCCESS) { GetErrorString(&wmxsdk->device_id, r, errstr, &errstr_size); nm_log_err(LOGD_WIMAX, "wmxsdk: Cannot subscribe to media status events: %d (%s)", r, errstr); goto error_subscribe_media_status; } status = iwmx_sdk_get_device_status(wmxsdk); if ((int) status < 0) status = WIMAX_API_DEVICE_STATUS_UnInitialized; g_mutex_lock(&wmxsdk->status_mutex); wmxsdk->status = status; g_mutex_unlock(&wmxsdk->status_mutex); _schedule_state_change(wmxsdk, status, WIMAX_API_DEVICE_STATUS_UnInitialized, WIMAX_API_STATUS_REASON_Normal, WIMAX_API_DEVICE_CONNECTION_PROGRESS_Ranging); return 0; UnsubscribeMediaStatusUpdate(&wmxsdk->device_id); error_subscribe_media_status: UnsubscribeDisconnectToNetwork(&wmxsdk->device_id); error_subscribe_disconnect: UnsubscribeConnectToNetwork(&wmxsdk->device_id); error_subscribe_connect: UnsubscribeNetworkSearchEx(&wmxsdk->device_id); error_subscribe_scan: UnsubscribeNetworkSearchWideScanEx(&wmxsdk->device_id); error_subscribe_wide_scan: UnsubscribeDeviceStatusChange(&wmxsdk->device_id); error_subscribe_state_change: UnsubscribeControlPowerManagement(&wmxsdk->device_id); error_subscribe_rf_state: error_connection_mode: WiMaxDeviceClose(&wmxsdk->device_id); error_wimaxdeviceopen: return result; }
inline std::string GetErrorString() { return GetErrorString( ::GetLastError() ); }
/* * Turn the radio on or off * * First it checks that we are in the right state before doing * anything; there might be no need to do anything. * * Issue a command to the WiMAX API, wait for a callback confirming it * is done. Sometimes the callback is missed -- in that case, do force * a state change evaluation. * * Frustration note: * * Geezoos efing Xist, they make difficult even the most simple * of the operations * * This thing is definitely a pain. If the radio is ON already * and you switch it on again...well, there is no way to tell * because you don't get a callback saying it basically * suceeded. But on the other hand, if the thing was in a * different state and action needs to be taken, you have to wait * for a callback to confirm it's done. However, there is also an * state change callback, which is almost the same, so now you * have to handle things in two "unrelated" threads of execution. * * How the shpx are you expected to tell the difference? Check * status first? On timeout? Nice gap (eighteen wheeler size) for * race conditions. */ int iwmx_sdk_rf_state_set(struct wmxsdk *wmxsdk, WIMAX_API_RF_STATE rf_state) { int result; WIMAX_API_RET r; char errstr[512]; UINT32 errstr_size = sizeof(errstr); WIMAX_API_DEVICE_STATUS dev_status; g_assert(rf_state == WIMAX_API_RF_ON || rf_state == WIMAX_API_RF_OFF); /* Guess what the current radio state is; if it is ON * already, don't redo it. */ dev_status = iwmx_sdk_get_device_status(wmxsdk); if ((int) dev_status < 0) { result = dev_status; goto error_get_status; } switch (dev_status) { case WIMAX_API_DEVICE_STATUS_UnInitialized: result = -EINVAL; goto error_cant_do; case WIMAX_API_DEVICE_STATUS_RF_OFF_HW_SW: case WIMAX_API_DEVICE_STATUS_RF_OFF_HW: nm_log_err(LOGD_WIMAX, "wmxsdk: cannot turn on radio: hw switch is off"); result = -EPERM; goto error_cant_do; break; case WIMAX_API_DEVICE_STATUS_RF_OFF_SW: if (rf_state == WIMAX_API_RF_OFF) { result = 0; nm_log_dbg(LOGD_WIMAX, "radio is already off"); goto out_done; } break; case WIMAX_API_DEVICE_STATUS_Ready: case WIMAX_API_DEVICE_STATUS_Scanning: case WIMAX_API_DEVICE_STATUS_Connecting: case WIMAX_API_DEVICE_STATUS_Data_Connected: if (rf_state == WIMAX_API_RF_ON) { result = 0; nm_log_dbg(LOGD_WIMAX, "radio is already on"); goto out_done; } break; default: g_assert(1); } /* Ok, flip the radio */ r = CmdControlPowerManagement(&wmxsdk->device_id, rf_state); if (r != WIMAX_API_RET_SUCCESS) { GetErrorString(&wmxsdk->device_id, r, errstr, &errstr_size); nm_log_err(LOGD_WIMAX, "wmxsdk: Cannot flip radio to %d: %d (%s) [device is in state %s]", rf_state, r, errstr, iwmx_sdk_get_device_status_str(wmxsdk)); result = -EIO; } else result = -EINPROGRESS; out_done: error_cant_do: error_get_status: return result; }
inline std::string GetErrorString() { return GetErrorString( errno ); }
int main(int argc, char* argv[]) { SC_HANDLE hSCManager = NULL, hService = NULL; TCHAR szImagePath[MAX_PATH]; HKEY hk; DWORD dwType; SERVICE_TABLE_ENTRY ServiceTable[] = { { SERVICE_NAME, ServiceMain }, { NULL, NULL } }; LPSTR szRoot; if(argc==1) { // Attempt to start service. If this fails we're probably // not running as a service if(!StartServiceCtrlDispatcher(ServiceTable)) return 0; } if(argc<2 || (strcmp(argv[1],"-i") && strcmp(argv[1],"-reglsa") && strcmp(argv[1],"-u") && strcmp(argv[1],"-unreglsa") && strcmp(argv[1],"-test") && strcmp(argv[1],"-v") )) { fprintf(stderr, "CVSNT Service Handler\n\n" "Arguments:\n" "\t%s -i [cvsroot]\tInstall\n" "\t%s -reglsa\tRegister LSA helper\n" "\t%s -u\tUninstall\n" "\t%s -unreglsa\tUnregister LSA helper\n" "\t%s -test\tInteractive run\n" "\t%s -v\tReport version number\n", basename(argv[0]),basename(argv[0]), basename(argv[0]), basename(argv[0]), basename(argv[0]), basename(argv[0]) ); return -1; } if(!strcmp(argv[1],"-reglsa")) { TCHAR lsaBuf[10240]; DWORD dwLsaBuf; if(RegOpenKeyEx(HKEY_LOCAL_MACHINE,_T("SYSTEM\\CurrentControlSet\\Control\\Lsa"),0,KEY_ALL_ACCESS,&hk)) { fprintf(stderr,"Couldn't open LSA registry key, error %d\n",GetLastError()); return -1; } dwLsaBuf=sizeof(lsaBuf); if(RegQueryValueEx(hk,_T("Authentication Packages"),NULL,&dwType,(BYTE*)lsaBuf,&dwLsaBuf)) { fprintf(stderr,"Couldn't read LSA registry key, error %d\n",GetLastError()); return -1; } if(dwType!=REG_MULTI_SZ) { fprintf(stderr,"LSA key isn't REG_MULTI_SZ!!!\n"); return -1; } lsaBuf[dwLsaBuf]='\0'; TCHAR *p = lsaBuf; while(*p) { if(!_tcscmp(p,"setuid")) break; p+=strlen(p)+1; } if(!*p) { strcpy(p,"setuid"); dwLsaBuf+=strlen(p)+1; lsaBuf[dwLsaBuf]='\0'; if(RegSetValueEx(hk,_T("Authentication Packages"),NULL,dwType,(BYTE*)lsaBuf,dwLsaBuf)) { fprintf(stderr,"Couldn't write LSA registry key, error %d\n",GetLastError()); return -1; } } return 0; } if(!strcmp(argv[1],"-unreglsa")) { TCHAR lsaBuf[10240]; DWORD dwLsaBuf; if(RegOpenKeyEx(HKEY_LOCAL_MACHINE,_T("SYSTEM\\CurrentControlSet\\Control\\Lsa"),0,KEY_ALL_ACCESS,&hk)) { fprintf(stderr,"Couldn't open LSA registry key, error %d\n",GetLastError()); return -1; } dwLsaBuf=sizeof(lsaBuf); if(RegQueryValueEx(hk,_T("Authentication Packages"),NULL,&dwType,(BYTE*)lsaBuf,&dwLsaBuf)) { fprintf(stderr,"Couldn't read LSA registry key, error %d\n",GetLastError()); return -1; } if(dwType!=REG_MULTI_SZ) { fprintf(stderr,"LSA key isn't REG_MULTI_SZ!!!\n"); return -1; } lsaBuf[dwLsaBuf]='\0'; TCHAR *p = lsaBuf; while(*p) { if(!_tcscmp(p,"setuid")) break; p+=strlen(p)+1; } if(*p) { size_t l = strlen(p)+1; memcpy(p,p+l,(dwLsaBuf-((p+l)-lsaBuf))+1); dwLsaBuf-=l; if(RegSetValueEx(hk,_T("Authentication Packages"),NULL,dwType,(BYTE*)lsaBuf,dwLsaBuf)) { fprintf(stderr,"Couldn't write LSA registry key, error %d\n",GetLastError()); return -1; } } return 0; } if(RegCreateKeyEx(HKEY_LOCAL_MACHINE,_T("Software\\CVS\\Pserver"),NULL,_T(""),REG_OPTION_NON_VOLATILE,KEY_ALL_ACCESS,NULL,&hk,NULL)) { fprintf(stderr,"Couldn't create HKLM\\Software\\CVS\\Pserver key, error %d\n",GetLastError()); return -1; } if (!strcmp(argv[1],"-v")) { puts(NTSERVICE_VERSION_STRING); return 0; } if(!strcmp(argv[1],"-i")) { if(argc==3) { szRoot = argv[2]; if(GetFileAttributesA(szRoot)==(DWORD)-1) { fprintf(stderr,"Repository directory '%s' not found\n",szRoot); return -1; } dwType=REG_SZ; RegSetValueExA(hk,"Repository0",NULL,dwType,(BYTE*)szRoot,strlen(szRoot)+1); } // connect to the service control manager if((hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE)) == NULL) { fprintf(stderr,"OpenSCManager Failed\n"); return -1; } if((hService=OpenService(hSCManager,SERVICE_NAME,DELETE))!=NULL) { DeleteService(hService); CloseServiceHandle(hService); } GetModuleFileName(NULL,szImagePath,MAX_PATH); if ((hService = CreateService(hSCManager,SERVICE_NAME,DISPLAY_NAME, STANDARD_RIGHTS_REQUIRED|SERVICE_CHANGE_CONFIG, SERVICE_WIN32_OWN_PROCESS|SERVICE_INTERACTIVE_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, szImagePath, NULL, NULL, NULL, NULL, NULL)) == NULL) { fprintf(stderr,"CreateService Failed: %s\n",GetErrorString()); return -1; } { BOOL (WINAPI *pChangeServiceConfig2)(SC_HANDLE,DWORD,LPVOID); pChangeServiceConfig2=(BOOL (WINAPI *)(SC_HANDLE,DWORD,LPVOID))GetProcAddress(GetModuleHandle("advapi32"),"ChangeServiceConfig2A"); if(pChangeServiceConfig2) { SERVICE_DESCRIPTION sd = { NTSERVICE_VERSION_STRING }; if(!pChangeServiceConfig2(hService,SERVICE_CONFIG_DESCRIPTION,&sd)) { 0; } } } CloseServiceHandle(hService); CloseServiceHandle(hSCManager); ReportError(FALSE,DISPLAY_NAMEA " installed successfully"); printf(DISPLAY_NAMEA " installed successfully\n"); } RegCloseKey(hk); if(!strcmp(argv[1],"-u")) { // connect to the service control manager if((hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE)) == NULL) { fprintf(stderr,"OpenSCManager Failed\n"); return -1; } if((hService=OpenService(hSCManager,SERVICE_NAME,DELETE))==NULL) { fprintf(stderr,"OpenService Failed: %s\n",GetErrorString()); return -1; } if(!DeleteService(hService)) { fprintf(stderr,"DeleteService Failed: %s\n",GetErrorString()); return -1; } CloseServiceHandle(hService); CloseServiceHandle(hSCManager); ReportError(FALSE,DISPLAY_NAMEA " uninstalled successfully"); printf(DISPLAY_NAMEA " uninstalled successfully\n"); } else if(!strcmp(argv[1],"-test")) { ServiceMain(999,NULL); } return 0; }