result Device::SetDeviceInfo() { result r = E_SUCCESS; String platformVersion; String apiVersion; String imei; int screen_height = 0; int screen_width = 0; /*screen*/ r = SystemInfo::GetValue("ScreenWidth", screen_width); TryCatch(r == E_SUCCESS, , "SystemInfo: To get a value is failed"); r = SystemInfo::GetValue("ScreenHeight", screen_height); TryCatch(r == E_SUCCESS, , "SystemInfo: To get a value is failed"); r = SystemInfo::GetValue("PlatformVersion", platformVersion); TryCatch(r == E_SUCCESS, , "SystemInfo: To get a value is failed"); r = SystemInfo::GetValue("APIVersion", apiVersion); TryCatch(r == E_SUCCESS, , "SystemInfo: To get a value is failed"); r = SystemInfo::GetValue("IMEI", imei); TryCatch(r == E_SUCCESS, , "SystemInfo: To get a value is failed"); if(r == E_SUCCESS) { String res; res.Format(1024, L"window.device={platform:'bada',version:'%S',name:'n/a',phonegap:'0.9.5',uuid:'%S'}", platformVersion.GetPointer(), imei.GetPointer()); //AppLogDebug("%S", res.GetPointer()); pWeb->EvaluateJavascriptN(res); } return r; CATCH: AppLog("Error = %s\n", GetErrorMessage(r)); return r; }
BOOL CDlgIADsSecurityDescriptor::OnInitDialog() { CDialog::OnInitDialog(); if ( m_pSecurityDesc == NULL ) { return TRUE; } ///////////////////////////////////////////// // Populate the DACL //////////////////////////////////////////// HRESULT hr; IDispatch *pDisp; IADsAccessControlList *pACL; hr = m_pSecurityDesc->get_DiscretionaryAcl( &pDisp ); if (!SUCCEEDED(hr) ) { AfxMessageBox(GetErrorMessage(hr)); return TRUE; } hr = pDisp->QueryInterface( IID_IADsAccessControlList, (void**) &pACL ); pDisp->Release(); if ( SUCCEEDED(hr) ) { PopulateACL( pACL ); } return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE }
//------------------------------------------------------------------------------ bool CvDatabaseUtility::PopulateArrayByValue(int*& pArray, const char* szTypeTableName, const char* szDataTableName, const char* szTypeColumn, const char* szFilterColumn, const char* szFilterValue, const char* szValueColumn, int iDefaultValue /* = 0 */, int iMinArraySize /* = 0 */) { int iSize = MaxRows(szTypeTableName); InitializeArray(pArray, (iSize<iMinArraySize)?iMinArraySize:iSize, iDefaultValue); std::string strKey = "_PABV_"; strKey.append(szTypeTableName); strKey.append(szDataTableName); strKey.append(szFilterColumn); strKey.append(szValueColumn); Database::Results* pResults = GetResults(strKey); if(pResults == NULL) { char szSQL[512]; sprintf_s(szSQL, "select %s.ID, %s from %s inner join %s on %s = %s.Type where %s = ?", szTypeTableName, szValueColumn, szDataTableName, szTypeTableName, szTypeColumn, szTypeTableName, szFilterColumn); pResults = PrepareResults(strKey, szSQL); if(pResults == NULL) return false; } if(!pResults->Bind(1, szFilterValue, false)) { CvAssertMsg(false, GetErrorMessage()); return false; } while(pResults->Step()) { const int idx = pResults->GetInt(0); const int value = pResults->GetInt(1); pArray[idx] = value; } pResults->Reset(); return true; }
static FORCEINLINE HRESULT __DifRemovePostProcess( IN HDEVINFO DeviceInfoSet, IN PSP_DEVINFO_DATA DeviceInfoData, IN PCOINSTALLER_CONTEXT_DATA Context ) { HRESULT Error; UNREFERENCED_PARAMETER(DeviceInfoSet); UNREFERENCED_PARAMETER(DeviceInfoData); Log("====>"); Error = Context->InstallResult; if (Error != NO_ERROR) { SetLastError(Error); goto fail1; } Log("<===="); return NO_ERROR; fail1: Error = GetLastError(); { PTCHAR Message; Message = GetErrorMessage(Error); Log("fail1 (%s)", Message); LocalFree(Message); } return Error; }
CString CEMSocket::GetFullErrorMessage(DWORD nErrorCode) { CString strError; // Proxy error if (!GetLastProxyError().IsEmpty()) { strError = GetLastProxyError(); // If we had a proxy error and the socket error is WSAECONNABORTED, we just 'aborted' // the TCP connection ourself - no need to show that self-created error too. if (nErrorCode == WSAECONNABORTED) return strError; } // Winsock error if (nErrorCode) { if (!strError.IsEmpty()) strError += _T(": "); strError += GetErrorMessage(nErrorCode, 1); } return strError; }
static void PIPE_New( DaoProcess *proc, DaoValue *p[], int N ) { DaoPipeStream *stream = NULL; DString *fname = p[0]->xString.value; char *mode; stream = DaoPipeStream_New(); DaoProcess_PutValue( proc, (DaoValue*)stream ); if( DString_Size( fname ) == 0 ){ DaoProcess_RaiseError( proc, "Param", "Empty command" ); return; } mode = DString_GetData( p[1]->xString.value ); stream->file = popen( DString_GetData( fname ), mode ); if( stream->file == NULL ){ char errbuf[512]; GetErrorMessage( errno, errbuf, sizeof(errbuf) ); DaoProcess_RaiseError( proc, "Stream", errbuf ); return; } if( strstr( mode, "r" ) ) stream->base.mode |= DAO_STREAM_READABLE; if( strstr( mode, "w" ) ) stream->base.mode |= DAO_STREAM_WRITABLE; DaoFileStream_InitCallbacks( stream ); }
//------------------------------------------------------------------------------ bool CvDatabaseUtility::PopulateArrayByExistence(bool*& pArray, const char* szTypeTableName, const char* szDataTableName, const char* szTypeColumn, const char* szFilterColumn, const char* szFilterValue) { InitializeArray(pArray, MaxRows(szTypeTableName), false); std::string strKey = "_PABE_"; strKey.append(szTypeTableName); strKey.append(szDataTableName); strKey.append(szFilterColumn); Database::Results* pResults = GetResults(strKey); if(pResults == NULL) { char szSQL[512]; sprintf_s(szSQL, "select %s.ID from %s inner join %s on %s = %s.Type where %s = ?", szTypeTableName, szDataTableName, szTypeTableName, szTypeColumn, szTypeTableName, szFilterColumn); pResults = PrepareResults(strKey, szSQL); if(pResults == NULL) return false; } if(!pResults->Bind(1, szFilterValue, false)) { CvAssertMsg(false, GetErrorMessage()); return false; } while(pResults->Step()) { const int idx = pResults->GetInt(0); pArray[idx] = true; } pResults->Reset(); return true; }
/** * Get the error message. * @return The formatted error message. */ const char* IO::what() const throw () { return GetErrorMessage().c_str(); }
int rges(void) { static unsigned short errorCnt = 0; short status = MI_OK; int nextauth = 0; char i; unsigned char ats = 0; unsigned char adr = 0; unsigned nblocks = 256; unsigned char tt[2]; unsigned char snr[4]; unsigned char data[16]; unsigned char keyCoded[12]; printf("\r\nPress Esc to Quit! RGES \r\n"); while ((status = Mf500PcdConfig()) != MI_OK) { if (status == previousStatus) { if ( ! (errorCnt++ % 100 ) ) printf("."); } else { previousStatus = status; printf("\ninitialization error %d %s ",status,GetErrorMessage(status)); } } while( 1 ) { if ( _kbhit( ) ) { if( getch( ) == 27 ) break; printf( "press any key to continue ..." ); getch ( ); } if (adr >= nblocks) { adr = 0; } if ((status = Mf500PiccRequest(PICC_REQALL,tt)) == MI_OK) { if ((status = Mf500PiccAnticoll(0,snr)) == MI_OK) { if ((status = Mf500PiccSelect(snr,&ats)) != MI_OK) { if (status != previousStatus) printf("\ncommunication error at select"); } } else { if (status != previousStatus) printf("\ncommunication error at anticollision"); } } else { if (status != previousStatus) printf("\ncommunication error at request"); } if (status == MI_OK) { if (ats & MIF_PLUS) //answer to select nblocks = 256; else if (ats & MIF_STANDARD) nblocks = 64; else if (ats & MIF_LIGHT) nblocks = 12; else nblocks = 256; nextauth %= 4; // try four different keys switch(nextauth) { case 0: Mf500HostCodeKey(keyA,keyCoded); status = Mf500PiccAuthKey(PICC_AUTHENT1A,snr,keyCoded,adr); if (status != 0) { nextauth++; continue; } break; case 1: Mf500HostCodeKey(keyF,keyCoded); status = Mf500PiccAuthKey(PICC_AUTHENT1A,snr,keyCoded,adr); if (status != 0) { nextauth++; continue; } break; case 2: Mf500HostCodeKey(keyB,keyCoded); status = Mf500PiccAuthKey(PICC_AUTHENT1B,snr,keyCoded,adr); if (status != 0) { nextauth++; continue; } break; case 3: Mf500HostCodeKey(keyF,keyCoded); status = Mf500PiccAuthKey(PICC_AUTHENT1B,snr,keyCoded,adr); if (status != 0) { nextauth++; continue; } break; default: status = MI_NOTAUTHERR; } if(status == MI_OK) { if (adr==0) { printf("\r\n\n"); printf("tagtype 0x%02x%02x snr 0x",tt[1],tt[0]); for (i = 3;i>=0;i--) printf("%02x",snr[i]); printf(" ats 0x%02x",ats); printf(nextauth%2 ? " keyset1 ":" keyset0 "); printf(nextauth>=2 ? "keyB ":"keyA "); printf("\r\n\n"); } if((status = Mf500PiccRead(adr, data)) == MI_OK) { if (status != previousStatus) { printf("\n"); previousStatus = status; } block_show(ats, adr, data); } else { nextauth++; if (status != previousStatus) printf("\ncommunication error at read"); } } else { if (status != previousStatus) printf("\ncommunication error at authentication"); } if (ats&MIF_LIGHT) //MFL reads the pages two by two adr += 2; else adr++; Mf500PiccHalt(); } if (status) { if (status == previousStatus) { if ( ! (errorCnt++ % 100 ) ) printf("."); } else { previousStatus = status; printf(" %d %s ",status,GetErrorMessage(status)); } } } printf( "finishing\n" ); return 0; }
//////////////////////////////////////////// // OnExecute // Demonstrate: // IDirectorySearch::ExecuteSearch // IDirectorySearch::GetNextRow // IDirectorySearch::GetColumn // IDirectorySearch::SetSearchPreference // ///////////////////////////////////////////// void CDlgIDirectorySearch::OnExecute() { ASSERT( m_pSearch ); CWaitCursor wait; UpdateData(TRUE); // Get data from the Dialog Box HRESULT hr; ADS_SEARCH_HANDLE hSearch; ADS_SEARCH_COLUMN col; CString s; int idx=0; int nCount; LPWSTR *pszAttr=NULL; POSITION pos; USES_CONVERSION; ///////////////////////////////// // Reset the Total Number ////////////////////////////////// SetDlgItemText( IDC_TOTAL, _T("")); ///////////////////////////////////////////// // Get the attribute list, and preparing.. /////////////////////////////////////////// CStringList sAttrList; m_cListView.DeleteAllItems(); // Reset the UI while( m_cListView.DeleteColumn(0)) { ; } ////////////////////////////////////////////////// // Preparing for attribute list // and columns to display CString sTemp; m_cAttrList.GetWindowText(s); // we need to add adspath, so that we can refer to this object later when user dblclk the item if ( !s.IsEmpty() ) { sTemp = s; sTemp.MakeLower(); if ( s.Find(_T("adspath"),0) == -1 ) { s += _T(",ADsPath"); } } // convert to string list for easy manipulation StringToStringList( s, sAttrList ); nCount = sAttrList.GetCount(); idx=0; if ( nCount ) { pszAttr = (LPWSTR*) AllocADsMem( nCount * sizeof(LPWSTR)); pos = sAttrList.GetHeadPosition(); while ( pos != NULL ) { s = sAttrList.GetAt(pos); pszAttr[idx] = T2OLE(s); sAttrList.GetNext(pos ); idx++; } } else { nCount = -1; } ///////////////////////////////////////// // BEGIN Set the preferences /////////////////////////////////////// DWORD dwCountPref = 0; ADS_SEARCHPREF_INFO prefInfo[ MAX_SEARCH_PREF ]; ADS_SORTKEY *pSortKey = NULL; if ( m_bEnableFilter == FALSE ) { // Reset the preference m_pSearch->SetSearchPreference( prefInfo, dwCountPref ); } else // Preferences are specified { //////////////////////// // Timeout Pref //////////////////////////// if ( m_nTimeOut != 0 ) { prefInfo[dwCountPref].dwSearchPref = ADS_SEARCHPREF_TIMEOUT; prefInfo[dwCountPref].vValue.dwType = ADSTYPE_INTEGER; prefInfo[dwCountPref].vValue.Integer = m_nTimeOut; dwCountPref++; } ////////////////////////////// // Search Scope ///////////////////////////// idx = m_CADsSearchScope.GetCurSel(); if ( idx != CB_ERR ) { prefInfo[dwCountPref].dwSearchPref = ADS_SEARCHPREF_SEARCH_SCOPE; prefInfo[dwCountPref].vValue.dwType = ADSTYPE_INTEGER; prefInfo[dwCountPref].vValue.Integer = idx; dwCountPref++; } /////////////////////////////////////////////////// // Cache Result. The default is to cache the result ///////////////////////////////////////////////// if ( !m_bCacheResult ) { prefInfo[dwCountPref].dwSearchPref = ADS_SEARCHPREF_SEARCH_SCOPE; prefInfo[dwCountPref].vValue.dwType = ADSTYPE_BOOLEAN; prefInfo[dwCountPref].vValue.Boolean = FALSE; dwCountPref++; } ////////////////////////////////////////////////// // Page Size /////////////////////////////////////////////////// if ( m_nPageSize > 0 ) { prefInfo[dwCountPref].dwSearchPref = ADS_SEARCHPREF_PAGESIZE; prefInfo[dwCountPref].vValue.dwType = ADSTYPE_INTEGER;; prefInfo[dwCountPref].vValue.Integer = m_nPageSize; dwCountPref++; } //////////////////////////////////////////////// // Chase Referrals /////////////////////////////////////////////// idx = m_cChaseReferrals.GetCurSel(); if ( idx != CB_ERR ) { prefInfo[dwCountPref].dwSearchPref = ADS_SEARCHPREF_CHASE_REFERRALS; prefInfo[dwCountPref].vValue.dwType = ADSTYPE_INTEGER; switch( idx ) { case 0: prefInfo[dwCountPref].vValue.Integer = ADS_CHASE_REFERRALS_NEVER; break; case 1: prefInfo[dwCountPref].vValue.Integer = ADS_CHASE_REFERRALS_SUBORDINATE; break; case 2: prefInfo[dwCountPref].vValue.Integer = ADS_CHASE_REFERRALS_EXTERNAL; break; default: prefInfo[dwCountPref].vValue.Integer = ADS_CHASE_REFERRALS_EXTERNAL; } dwCountPref++; } /////////////////////////////////////////////// // Sort On //////////////////////////////////////////////// if ( !m_sSortOn.IsEmpty() ) { CStringList sList; UINT nCount; prefInfo[dwCountPref].dwSearchPref = ADS_SEARCHPREF_SORT_ON; prefInfo[dwCountPref].vValue.dwType = ADSTYPE_PROV_SPECIFIC; StringToStringList( m_sSortOn, sList ); nCount = sList.GetCount(); if ( nCount > 0 ) { POSITION pos; pos= sList.GetHeadPosition(); pSortKey = (ADS_SORTKEY *) LocalAlloc( LMEM_FIXED | LMEM_ZEROINIT, sizeof(ADS_SORTKEY) * nCount ); idx = 0; while( pos != NULL ) { pSortKey[idx].pszAttrType = T2OLE(sList.GetAt(pos)); pSortKey[idx].pszReserved = NULL; pSortKey[idx].fReverseorder =0; // Next idx++; sList.GetNext( pos ); } prefInfo[dwCountPref].vValue.ProviderSpecific.dwLength = sizeof(ADS_SORTKEY) * nCount; prefInfo[dwCountPref].vValue.ProviderSpecific.lpValue = (LPBYTE) pSortKey; dwCountPref++; } } ////////////////////////////////////////////// // Size Limit ////////////////////////////////////////////// if ( m_nSizeLimit > 0 ) { prefInfo[dwCountPref].dwSearchPref = ADS_SEARCHPREF_SIZE_LIMIT; prefInfo[dwCountPref].vValue.dwType = ADSTYPE_INTEGER; prefInfo[dwCountPref].vValue.Integer = m_nSizeLimit; dwCountPref++; } ////////////////////////////////////////////////// // A Synchronous /////////////////////////////////////////////////// if ( m_bAsynch ) { prefInfo[dwCountPref].dwSearchPref = ADS_SEARCHPREF_ASYNCHRONOUS; prefInfo[dwCountPref].vValue.dwType = ADSTYPE_BOOLEAN; prefInfo[dwCountPref].vValue.Integer = TRUE; dwCountPref++; } ///////////////////////////////////////////////////// // Attribute Type Only ////////////////////////////////////////////////////// if ( m_bAttrib ) { prefInfo[dwCountPref].dwSearchPref = ADS_SEARCHPREF_ATTRIBTYPES_ONLY; prefInfo[dwCountPref].vValue.dwType = ADSTYPE_BOOLEAN; prefInfo[dwCountPref].vValue.Integer = TRUE; dwCountPref++; } ///////////////////////////////////////////////////// // Derefence Alias ////////////////////////////////////////////////////// if ( m_nDeref != CB_ERR ) { prefInfo[dwCountPref].dwSearchPref = ADS_SEARCHPREF_DEREF_ALIASES; prefInfo[dwCountPref].vValue.dwType = ADSTYPE_INTEGER; prefInfo[dwCountPref].vValue.Integer = m_nDeref; dwCountPref++; } /////////////////////////////////////////////// // Now Set the selected preferences ////////////////////////////////////////////// hr = m_pSearch->SetSearchPreference( prefInfo, dwCountPref ); } ///////////////////////////////////////// // END Set the preferences /////////////////////////////////////// //////////////////////////////////////// // Execute the Search ////////////////////////////////////// DWORD dwCount=0; hr = m_pSearch->ExecuteSearch(T2OLE(m_sFilter), pszAttr, nCount, &hSearch ); //////////////////////////////// //// cleanup //////////////////////////////// if ( pszAttr ) { FreeADsMem( pszAttr ); } if ( pSortKey ) { LocalFree( pSortKey ); } if ( !SUCCEEDED(hr) ) { AfxMessageBox(GetErrorMessage(hr)); return; } //////////////////////////////////////////////////////// // Enumerate the rows //////////////////////////////////////////////////////// sAttrList.RemoveAll(); ///////////////////////////////////////////////////////// // Retrieve the column names returned from the server /////////////////////////////////////////////////////////// LPWSTR pszColumn; hr = m_pSearch->GetFirstRow( hSearch ); if ( !SUCCEEDED(hr) ) { return; } idx=0; while( (hr=m_pSearch->GetNextColumnName( hSearch, &pszColumn )) != S_ADS_NOMORE_COLUMNS ) { s = OLE2T( pszColumn ); m_cListView.InsertColumn(idx, s, LVCFMT_LEFT, 150 ); // adding columns to the UI sAttrList.AddTail(s); FreeADsMem( pszColumn ); idx++; } ///////////////////////////////////////////// // Start iterating the result set //////////////////////////////////////////// int nCol; CStringList sValueList; do { nCol=0; pos = sAttrList.GetHeadPosition(); while( pos != NULL ) { s = sAttrList.GetAt(pos); //column name // Get the Name and display it in the list hr = m_pSearch->GetColumn( hSearch, T2OLE(s), &col ); if ( SUCCEEDED(hr) ) { s =_T(""); if ( col.dwADsType != ADSTYPE_INVALID ) // if we request for attrib only, no value will be returned { ADsToStringList(col.pADsValues, col.dwNumValues, sValueList ); StringListToString( sValueList, s ); } if ( nCol ) { m_cListView.SetItemText(0,nCol, s); } else { m_cListView.InsertItem(0, s); } m_pSearch->FreeColumn( &col ); } nCol++; sAttrList.GetNext(pos); } dwCount++; ///////////////////////////// //Display the total so far //////////////////////////////// s.Format("%ld object(s)", dwCount ); SetDlgItemText( IDC_TOTAL, s ); } while( (hr=m_pSearch->GetNextRow( hSearch)) != S_ADS_NOMORE_ROWS ); m_pSearch->CloseSearchHandle( hSearch ); }
int SVNPatch::Init( const CString& patchfile, const CString& targetpath, CProgressDlg *pPprogDlg ) { CTSVNPath target = CTSVNPath(targetpath); if (patchfile.IsEmpty() || targetpath.IsEmpty() || !svn_dirent_is_absolute(target.GetSVNApiPath(m_pool))) { m_errorStr.LoadString(IDS_ERR_PATCHPATHS); return 0; } svn_error_t * err = NULL; apr_pool_t * scratchpool = NULL; svn_client_ctx_t * ctx = NULL; m_errorStr.Empty(); m_patchfile = patchfile; m_targetpath = targetpath; m_testPath.Empty(); m_patchfile.Replace('\\', '/'); m_targetpath.Replace('\\', '/'); apr_pool_create_ex(&scratchpool, m_pool, abort_on_pool_failure, NULL); svn_error_clear(svn_client_create_context2(&ctx, SVNConfig::Instance().GetConfig(m_pool), scratchpool)); ctx->notify_func2 = notify; ctx->notify_baton2 = this; if (pPprogDlg) { pPprogDlg->SetTitle(IDS_APPNAME); pPprogDlg->FormatNonPathLine(1, IDS_PATCH_PROGTITLE); pPprogDlg->SetShowProgressBar(false); pPprogDlg->ShowModeless(AfxGetMainWnd()); m_pProgDlg = pPprogDlg; } m_filePaths.clear(); m_nRejected = 0; m_nStrip = 0; CTSVNPath tsvnpatchfile = CTSVNPath(m_patchfile); CTSVNPath tsvntargetpath = CTSVNPath(m_targetpath); err = svn_client_patch(tsvnpatchfile.GetSVNApiPath(scratchpool), // patch_abspath tsvntargetpath.GetSVNApiPath(scratchpool), // local_abspath true, // dry_run m_nStrip, // strip_count false, // reverse true, // ignore_whitespace false, // remove_tempfiles patch_func, // patch_func this, // patch_baton ctx, // client context scratchpool); m_pProgDlg = NULL; apr_pool_destroy(scratchpool); // since we're doing a dry-run, a 'path not found' can happen // since new files/dirs aren't added in the patch func. if ((err)&&(err->apr_err != SVN_ERR_WC_PATH_NOT_FOUND)) { m_errorStr = GetErrorMessage(err); m_filePaths.clear(); svn_error_clear(err); return 0; } if ((m_nRejected > ((int)m_filePaths.size() / 3)) && !m_testPath.IsEmpty()) { m_nStrip++; bool found = false; for (m_nStrip = 0; m_nStrip < STRIP_LIMIT; ++m_nStrip) { for (std::vector<PathRejects>::iterator it = m_filePaths.begin(); it != m_filePaths.end(); ++it) { if (Strip(it->path).IsEmpty()) { found = true; m_nStrip--; break; } } if (found) break; } } if (m_nStrip == STRIP_LIMIT) m_filePaths.clear(); else if (m_nStrip > 0) { apr_pool_create_ex(&scratchpool, m_pool, abort_on_pool_failure, NULL); svn_error_clear(svn_client_create_context2(&ctx, SVNConfig::Instance().GetConfig(m_pool), scratchpool)); ctx->notify_func2 = notify; ctx->notify_baton2 = this; m_filePaths.clear(); m_nRejected = 0; err = svn_client_patch(CUnicodeUtils::GetUTF8(m_patchfile), // patch_abspath CUnicodeUtils::GetUTF8(m_targetpath), // local_abspath true, // dry_run m_nStrip, // strip_count false, // reverse true, // ignore_whitespace false, // remove_tempfiles patch_func, // patch_func this, // patch_baton ctx, // client context scratchpool); apr_pool_destroy(scratchpool); if (err) { m_errorStr = GetErrorMessage(err); m_filePaths.clear(); svn_error_clear(err); } } return (int)m_filePaths.size(); }
BOOL CHttpDownloadDlg::OnInitDialog() { CString cap; cap = GetResString(IDS_CANCEL); GetDlgItem(IDCANCEL)->SetWindowText(cap); if (!m_strTitle.IsEmpty()) SetWindowText(m_strTitle); //Let the parent class do its thing CDialog::OnInitDialog(); InitWindowStyles(this); //Setup the animation control m_ctrlAnimate.Open(IDR_HTTPDOWNLOAD_ANI); //Validate the URL ASSERT(m_sURLToDownload.GetLength()); //Did you forget to specify the file to download if (!AfxParseURL(m_sURLToDownload, m_dwServiceType, m_sServer, m_sObject, m_nPort)) { //Try sticking "http://" before it m_sURLToDownload = _T("http://") + m_sURLToDownload; if (!AfxParseURL(m_sURLToDownload, m_dwServiceType, m_sServer, m_sObject, m_nPort)) { TRACE(_T("Failed to parse the URL: %s\n"), m_sURLToDownload); EndDialog(IDCANCEL); return TRUE; } } //Check to see if the file we are downloading to exists and if //it does, then ask the user if they were it overwritten // edited: we always want to overwrite old language dlls and server.mets /*CFileStatus fs; ASSERT(m_sFileToDownloadInto.GetLength()); if (CFile::GetStatus(m_sFileToDownloadInto, fs)) { CString sMsg; sMsg.Format(GetResString(IDS_HTTPDOWNLOAD_OK_TO_OVERWRITE), m_sFileToDownloadInto); if (AfxMessageBox(sMsg, MB_YESNO) != IDYES) { TRACE(_T("Failed to confirm file overwrite, download aborted\n")); EndDialog(IDCANCEL); return TRUE; } }*/ //Try and open the file we will download into if (!m_FileToWrite.Open(m_sFileToDownloadInto, CFile::modeCreate | CFile::modeWrite | CFile::shareDenyWrite)) { DWORD dwError = GetLastError(); CString sMsg; sMsg.Format(GetResString(IDS_HTTPDOWNLOAD_FAIL_FILE_OPEN), GetErrorMessage(dwError)); AfxMessageBox(sMsg); EndDialog(IDCANCEL); return TRUE; } //Pull out just the filename component int nSlash = m_sObject.ReverseFind(_T('/')); if (nSlash == -1) nSlash = m_sObject.ReverseFind(_T('\\')); if (nSlash != -1 && m_sObject.GetLength() > 1) m_sFilename = m_sObject.Right(m_sObject.GetLength() - nSlash - 1); else m_sFilename = m_sObject; //Set the file status text CString sFileStatus; ASSERT(m_sObject.GetLength()); ASSERT(m_sServer.GetLength()); sFileStatus.Format(GetResString(IDS_HTTPDOWNLOAD_FILESTATUS), m_sFilename, m_sServer); m_ctrlFileStatus.SetWindowText(sFileStatus); // set labels SetDlgItemText(IDC_TIMELEFTTEXT,GetResString(IDS_ESTTIMELEFT)); SetDlgItemText(IDC_TRANSFER_RATE_LABEL,GetResString(IDS_TRANSFER_RATE_LABEL)); //Spin off the background thread which will do the actual downloading m_pThread = AfxBeginThread(_DownloadThread, this, THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED); if (m_pThread == NULL) { TRACE(_T("Failed to create download thread, dialog is aborting\n")); EndDialog(IDCANCEL); return TRUE; } m_pThread->m_bAutoDelete = FALSE; m_pThread->ResumeThread(); return TRUE; }
static int Open( vlc_object_t *p_object ) { stream_t *p_stream = (stream_t *) p_object; int64_t i_stream_size = stream_Size( p_stream->s ); if ( i_stream_size > 0 && i_stream_size < ARIB_STD_B25_TS_PROBING_MIN_DATA ) return VLC_EGENERIC; stream_sys_t *p_sys = p_stream->p_sys = calloc( 1, sizeof(*p_sys) ); if (p_sys == NULL) return VLC_ENOMEM; p_sys->p_b25 = create_arib_std_b25(); if ( p_sys->p_b25 ) { if ( p_sys->p_b25->set_multi2_round( p_sys->p_b25, 4 ) < 0 ) msg_Warn( p_stream, "cannot set B25 round number" ); if ( p_sys->p_b25->set_strip( p_sys->p_b25, 0 ) < 0 ) msg_Warn( p_stream, "cannot set B25 strip option" ); if ( p_sys->p_b25->set_emm_proc( p_sys->p_b25, 0 ) < 0 ) msg_Warn( p_stream, "cannot set B25 emm_proc" ); /* ARIB STD-B25 scrambled TS's packet size is always 188 bytes */ if ( p_sys->p_b25->set_unit_size( p_sys->p_b25, 188 ) < 0) msg_Warn( p_stream, "cannot set B25 TS packet size" ); p_sys->p_bcas = create_b_cas_card(); if ( p_sys->p_bcas ) { int i_code = p_sys->p_bcas->init( p_sys->p_bcas ); if ( i_code < 0 ) { /* Card could be just missing */ msg_Warn( p_stream, "cannot initialize BCAS card (missing ?): %s", GetErrorMessage( i_code, bcas_errors ) ); goto error; } B_CAS_ID bcasid; if ( p_sys->p_bcas->get_id( p_sys->p_bcas, &bcasid ) == 0 ) { for ( int32_t i=0; i<bcasid.count; i++) { msg_Dbg( p_stream, "BCAS card id 0x%"PRId64" initialized", bcasid.data[i] ); } } B_CAS_INIT_STATUS bcas_status; if ( p_sys->p_bcas->get_init_status( p_sys->p_bcas, &bcas_status ) == 0 ) { msg_Dbg( p_stream, "BCAS card system id 0x%"PRIx32, bcas_status.ca_system_id ); } i_code = p_sys->p_b25->set_b_cas_card( p_sys->p_b25, p_sys->p_bcas ); if ( i_code < 0 ) { msg_Err( p_stream, "cannot attach BCAS card to decoder: %s", GetErrorMessage( i_code, bcas_errors ) ); goto error; } } else msg_Err( p_stream, "cannot create BCAS card" ); } else { msg_Err( p_stream, "cannot create B25 instance" ); goto error; } p_stream->pf_read = Read; p_stream->pf_seek = Seek; p_stream->pf_control = Control; return VLC_SUCCESS; error: Close( VLC_OBJECT(p_stream) ); return VLC_EGENERIC; }
ERMsg CBioSIMModelBase::OnExecuteAtemporal(){ return GetErrorMessage(ERROR_REF_NOT_SUPPORT); }
eResult CSecRunAsUser::RestartAsRestricted(){ if (m_bRunningRestricted || m_bRunningAsEmule) return RES_OK; if (!LoadAPI()) return RES_FAILED; HANDLE hProcessToken = NULL; HANDLE hRestrictedToken = NULL; PTOKEN_USER pstructUserToken = NULL; try{ // get our access token from the process if(!OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY | TOKEN_READ, &hProcessToken)){ throw(CString(_T("Failed to retrieve access token from process"))); } // there is no easy way to check if we have already restircted token when not using the restricted sid list // so just check if we set the SANDBOX_INERT flag and hope noone else did // (which isunlikely tho because afaik you would only set it when using CreateRestirctedToken) :) DWORD dwLen = 0; DWORD dwInertFlag; if (!GetTokenInformation(hProcessToken, TokenSandBoxInert, &dwInertFlag, sizeof(dwInertFlag), &dwLen)){ throw(CString(_T("Failed to Flag-Status from AccessToken"))); } if (dwInertFlag != 0){ m_bRunningRestricted = true; throw(CString(_T("Already using a restricted Token it seems (everything is fine!)"))); } // get the user account SID to disable it in our new token dwLen = 0; while (!GetTokenInformation(hProcessToken, TokenUser, pstructUserToken, dwLen, &dwLen)){ if (GetLastError() == ERROR_INSUFFICIENT_BUFFER && pstructUserToken == NULL){ pstructUserToken = (PTOKEN_USER)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwLen); continue; } throw(CString(_T("Failed to retrieve UserSID from AccessToken"))); } if (pstructUserToken == NULL) throw(CString(_T("Failed to retrieve UserSID from AccessToken"))); // disabling our primary token would make sense from an Security POV, but this would cause file acces conflicts // in the default settings (since we cannot access files we created ourself if they don't have the write flag for the group "users") // so it stays enabled for now and we only reduce privileges // create the new token if(!CreateRestrictedToken(hProcessToken, DISABLE_MAX_PRIVILEGE | SANDBOX_INERT, 0 /*disabled*/, &pstructUserToken->User, 0, NULL, 0, NULL, &hRestrictedToken ) ){ throw(CString(_T("Failed to create Restricted Token"))); } // do the starting job PROCESS_INFORMATION ProcessInfo = {0}; TCHAR szAppPath[MAX_PATH]; DWORD dwModPathLen = GetModuleFileName(NULL, szAppPath, _countof(szAppPath)); if (dwModPathLen == 0 || dwModPathLen == _countof(szAppPath)) throw CString(_T("Failed to get module file path")); CString strAppName; strAppName.Format(_T("\"%s\""),szAppPath); STARTUPINFO StartInf = {0}; StartInf.cb = sizeof(StartInf); StartInf.dwFlags = STARTF_USESHOWWINDOW; StartInf.wShowWindow = SW_NORMAL; // remove the current mutex, so that the restart emule can create its own without problems // in the rare case CreateProcessWithLogonW fails, this will allow mult. instances, but if that function fails we have other problems anyway ::CloseHandle(theApp.m_hMutexOneInstance); if(!CreateProcessAsUser(hRestrictedToken, NULL, strAppName.GetBuffer(), NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &StartInf, &ProcessInfo) ){ CString e; GetErrorMessage(GetLastError(), e, 0); throw(CString(_T("CreateProcessAsUser failed"))); } strAppName.ReleaseBuffer(); CloseHandle(ProcessInfo.hProcess); CloseHandle(ProcessInfo.hThread); // cleanup HeapFree(GetProcessHeap(), 0, (LPVOID)pstructUserToken); pstructUserToken = NULL; CloseHandle(hRestrictedToken); CloseHandle(hProcessToken); } catch(CString strError){ if (hProcessToken != NULL) CloseHandle(hProcessToken); if (hRestrictedToken != NULL) CloseHandle(hRestrictedToken); if (pstructUserToken != NULL) HeapFree(GetProcessHeap(), 0, (LPVOID)pstructUserToken); theApp.QueueDebugLogLine(false, _T("SecureShellExecute exception: %s!"), strError); if (m_bRunningRestricted) return RES_OK; else return RES_FAILED; } return RES_OK_NEED_RESTART; }
ERMsg CBioSIMModelBase::OnExecuteMonthly(){ return GetErrorMessage(ERROR_REF_NOT_SUPPORT); }
std::wstring GetErrorMessage() { return GetErrorMessage(GetLastError()); }
void CListenSocket::OnAccept(int nErrorCode) { if (!nErrorCode) { m_nPendingConnections++; if (m_nPendingConnections < 1){ ASSERT(0); m_nPendingConnections = 1; } if (TooManySockets(true) && !CGlobalVariable::serverconnect->IsConnecting()){ StopListening(); return; } else if (!bListening) ReStartListening(); //If the client is still at maxconnections, this will allow it to go above it.. But if you don't, you will get a lowID on all servers. uint32 nFataErrors = 0; while (m_nPendingConnections > 0) { m_nPendingConnections--; CClientReqSocket* newclient; SOCKADDR_IN SockAddr = {0}; int iSockAddrLen = sizeof SockAddr; if (thePrefs.GetConditionalTCPAccept() && !thePrefs.GetProxySettings().UseProxy) { _iAcceptConnectionCondRejected = 0; SOCKET sNew = WSAAccept(m_SocketData.hSocket, (SOCKADDR*)&SockAddr, &iSockAddrLen, AcceptConnectionCond, 0); if (sNew == INVALID_SOCKET){ DWORD nError = GetLastError(); if (nError == WSAEWOULDBLOCK){ DebugLogError(LOG_STATUSBAR, _T("%hs: Backlogcounter says %u connections waiting, Accept() says WSAEWOULDBLOCK - setting counter to zero!"), __FUNCTION__, m_nPendingConnections); m_nPendingConnections = 0; break; } else{ if (nError != WSAECONNREFUSED || _iAcceptConnectionCondRejected == 0){ DebugLogError(LOG_STATUSBAR, _T("%hs: Backlogcounter says %u connections waiting, Accept() says %s - setting counter to zero!"), __FUNCTION__, m_nPendingConnections, GetErrorMessage(nError, 1)); nFataErrors++; } else if (_iAcceptConnectionCondRejected == 1) theStats.filteredclients++; } if (nFataErrors > 10){ // the question is what todo on a error. We cant just ignore it because then the backlog will fill up // and lock everything. We can also just endlos try to repeat it because this will lock up eMule // this should basically never happen anyway // however if we are in such a position, try to reinitalize the socket. DebugLogError(LOG_STATUSBAR, _T("%hs: Accept() Error Loop, recreating socket"), __FUNCTION__); Close(); StartListening(); m_nPendingConnections = 0; break; } continue; } newclient = new CClientReqSocket; VERIFY( newclient->InitAsyncSocketExInstance() ); newclient->m_SocketData.hSocket = sNew; newclient->AttachHandle(sNew); AddConnection(); } else { newclient = new CClientReqSocket; if (!Accept(*newclient, (SOCKADDR*)&SockAddr, &iSockAddrLen)){ newclient->Safe_Delete(); DWORD nError = GetLastError(); if (nError == WSAEWOULDBLOCK){ DebugLogError(LOG_STATUSBAR, _T("%hs: Backlogcounter says %u connections waiting, Accept() says WSAEWOULDBLOCK - setting counter to zero!"), __FUNCTION__, m_nPendingConnections); m_nPendingConnections = 0; break; } else{ DebugLogError(LOG_STATUSBAR, _T("%hs: Backlogcounter says %u connections waiting, Accept() says %s - setting counter to zero!"), __FUNCTION__, m_nPendingConnections, GetErrorMessage(nError, 1)); nFataErrors++; } if (nFataErrors > 10){ // the question is what todo on a error. We cant just ignore it because then the backlog will fill up // and lock everything. We can also just endlos try to repeat it because this will lock up eMule // this should basically never happen anyway // however if we are in such a position, try to reinitalize the socket. DebugLogError(LOG_STATUSBAR, _T("%hs: Accept() Error Loop, recreating socket"), __FUNCTION__); Close(); StartListening(); m_nPendingConnections = 0; break; } continue; } AddConnection(); if (SockAddr.sin_addr.S_un.S_addr == 0) // for safety.. { iSockAddrLen = sizeof SockAddr; newclient->GetPeerName((SOCKADDR*)&SockAddr, &iSockAddrLen); DebugLogWarning(_T("SockAddr.sin_addr.S_un.S_addr == 0; GetPeerName returned %s"), ipstr(SockAddr.sin_addr.S_un.S_addr)); } ASSERT( SockAddr.sin_addr.S_un.S_addr != 0 && SockAddr.sin_addr.S_un.S_addr != INADDR_NONE ); if (CGlobalVariable::ipfilter->IsFiltered(SockAddr.sin_addr.S_un.S_addr)){ if (thePrefs.GetLogFilteredIPs()) AddDebugLogLine(false, _T("Rejecting connection attempt (IP=%s) - IP filter (%s)"), ipstr(SockAddr.sin_addr.S_un.S_addr), CGlobalVariable::ipfilter->GetLastHit()); newclient->Safe_Delete(); theStats.filteredclients++; continue; } if (CGlobalVariable::clientlist->IsBannedClient(SockAddr.sin_addr.S_un.S_addr)){ if (thePrefs.GetLogBannedClients()){ CUpDownClient* pClient = CGlobalVariable::clientlist->FindClientByIP(SockAddr.sin_addr.S_un.S_addr); AddDebugLogLine(false, _T("Rejecting connection attempt of banned client %s %s"), ipstr(SockAddr.sin_addr.S_un.S_addr), pClient->DbgGetClientInfo()); } newclient->Safe_Delete(); continue; } } newclient->AsyncSelect(FD_WRITE | FD_READ | FD_CLOSE); } ASSERT( m_nPendingConnections >= 0 ); } }
void Network::OnTransactionAborted (HttpSession &httpSession, HttpTransaction &httpTransaction, result r) { AppLogDebug("Transaction Aborted"); String res; res.Format(128, L"Cordova.callbacks['%S'].fail({code:%d,message:'%s'});", callbackId.GetPointer(), r, GetErrorMessage(r)); AppLogDebug("%S", res.GetPointer()); pWeb->EvaluateJavascriptN(res); }
Exception::Exception(const std::string &what, int returnCode) throw() : std::runtime_error(what + ": " + GetErrorMessage(returnCode)) { }
/*! Displays a text description of an XBase error code. \param ErrorCode error to be displayed */ void xbXBase::DisplayError( xbShort ErrorCode ) const { std::cout << GetErrorMessage( ErrorCode ) << std::endl; }
static ssize_t Read( stream_t *p_stream, void *p_buf, size_t i_toread ) { stream_sys_t *p_sys = p_stream->p_sys; uint8_t *p_dst = p_buf; int i_total_read = 0; int i_ret; if ( !i_toread ) return -1; /* Use data from previous reads */ size_t i_fromremain = RemainRead( p_stream, p_dst, i_toread ); i_total_read += i_fromremain; p_dst += i_fromremain; i_toread -= i_fromremain; while ( i_toread ) { /* make use of the existing buffer, overwritten by decoder data later */ int i_srcread = vlc_stream_Read( p_stream->s, p_dst, i_toread ); if ( i_srcread > 0 ) { ARIB_STD_B25_BUFFER putbuf = { p_dst, i_srcread }; i_ret = p_sys->p_b25->put( p_sys->p_b25, &putbuf ); if ( i_ret < 0 ) { msg_Err( p_stream, "decoder put failed: %s", GetErrorMessage( i_ret, b25_errors ) ); return 0; } } else { if ( i_srcread < 0 ) msg_Err( p_stream, "Can't read %lu bytes from source stream: %d", i_toread, i_srcread ); return 0; } ARIB_STD_B25_BUFFER getbuf; i_ret = p_sys->p_b25->get( p_sys->p_b25, &getbuf ); if ( i_ret < 0 ) { msg_Err( p_stream, "decoder get failed: %s", GetErrorMessage( i_ret, b25_errors ) ); return 0; } if ( (size_t)getbuf.size > i_toread ) { /* Hold remaining data for next call */ RemainAdd( p_stream, getbuf.data + i_toread, getbuf.size - i_toread ); } int consume = __MIN( (size_t)getbuf.size, i_toread ); memcpy( p_dst, getbuf.data, consume ); i_total_read += consume; p_dst += consume; i_toread -= consume; } return i_total_read; }
bool Scanner::HasError() { const char* message = GetErrorMessage(); return message != NULL && strcmp(message, "") != 0; }
static BOOLEAN AllowUpdate( IN PTCHAR DriverName, OUT PBOOLEAN Allow ) { TCHAR ServiceKeyName[MAX_PATH]; HKEY ServiceKey; HRESULT Result; HRESULT Error; DWORD ValueLength; DWORD Value; DWORD Type; Log("====> (%s)", DriverName); Result = StringCbPrintf(ServiceKeyName, MAX_PATH, SERVICES_KEY "\\%s", DriverName); assert(SUCCEEDED(Result)); Error = RegOpenKeyEx(HKEY_LOCAL_MACHINE, ServiceKeyName, 0, KEY_READ, &ServiceKey); if (Error != ERROR_SUCCESS) { if (Error == ERROR_FILE_NOT_FOUND) { Value = 1; goto done; } SetLastError(Error); goto fail1; } ValueLength = sizeof (Value); Error = RegQueryValueEx(ServiceKey, "AllowUpdate", NULL, &Type, (LPBYTE)&Value, &ValueLength); if (Error != ERROR_SUCCESS) { if (Error == ERROR_FILE_NOT_FOUND) { Type = REG_DWORD; Value = 1; } else { SetLastError(Error); goto fail2; } } if (Type != REG_DWORD) { SetLastError(ERROR_BAD_FORMAT); goto fail3; } RegCloseKey(ServiceKey); done: if (Value == 0) { Log("DISALLOWED"); *Allow = FALSE; } Log("<===="); return TRUE; fail3: Log("fail3"); fail2: Log("fail2"); RegCloseKey(ServiceKey); fail1: Error = GetLastError(); { PTCHAR Message; Message = GetErrorMessage(Error); Log("fail1 (%s)", Message); LocalFree(Message); } return FALSE; }
void LocalSlaveProcess::Open(const char *command, const char *envptr) { SVRLOG("LocalSlaveProcess::Open(" << command << ")"); Kill(); while(*command && (byte)*command <= ' ') command++; #ifdef PLATFORM_WIN32 HANDLE hOutputReadTmp, hInputRead; HANDLE hInputWriteTmp, hOutputWrite; HANDLE hErrorWrite; SECURITY_ATTRIBUTES sa; sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.lpSecurityDescriptor = NULL; sa.bInheritHandle = TRUE; HANDLE hp = GetCurrentProcess(); CreatePipe(&hOutputReadTmp, &hOutputWrite, &sa, 0); DuplicateHandle(hp, hOutputWrite, hp, &hErrorWrite, 0, TRUE, DUPLICATE_SAME_ACCESS); CreatePipe(&hInputRead, &hInputWriteTmp, &sa, 0); DuplicateHandle(hp, hOutputReadTmp, hp, &hOutputRead, 0, FALSE, DUPLICATE_SAME_ACCESS); DuplicateHandle(hp, hInputWriteTmp, hp, &hInputWrite, 0, FALSE, DUPLICATE_SAME_ACCESS); CloseHandle(hOutputReadTmp); CloseHandle(hInputWriteTmp); PROCESS_INFORMATION pi; STARTUPINFO si; ZeroMemory(&si, sizeof(STARTUPINFO)); si.cb = sizeof(STARTUPINFO); si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; si.hStdInput = hInputRead; si.hStdOutput = hOutputWrite; si.hStdError = hErrorWrite; int n = (int)strlen(command) + 1; Buffer<char> cmd(n); memcpy(cmd, command, n); bool h = CreateProcess(NULL, cmd, &sa, &sa, TRUE, NORMAL_PRIORITY_CLASS, (void *)envptr, NULL, &si, &pi); SVRLOG("CreateProcess " << (h ? "succeeded" : "failed")); CloseHandle(hErrorWrite); CloseHandle(hInputRead); CloseHandle(hOutputWrite); if(h) { hProcess = pi.hProcess; CloseHandle(pi.hThread); } else { Free(); throw Exc(NFormat("Error running process: %s\nCommand: %s", GetErrorMessage(GetLastError()), command)); } #endif #ifdef PLATFORM_POSIX // parse command line for execve cmd_buf.Alloc(strlen(command) + 1); char *cmd_out = cmd_buf; const char *p = command; const char *b = p; while(*p && (byte)*p > ' ') if(*p++ == '\"') while(*p && *p++ != '\"') ; const char *app = cmd_out; args.Add(cmd_out); memcpy(cmd_out, b, p - b); cmd_out += p - b; *cmd_out++ = '\0'; while(*p) if((byte)*p <= ' ') p++; else { args.Add(cmd_out); while(*p && (byte)*p > ' ') if(*p == '\\') { if(*++p) *cmd_out++ = *p++; } else if(*p == '\"') { p++; while(*p && *p != '\"') if(*p == '\\') { if(*++p) *cmd_out++ = *p++; } else *cmd_out++ = *p++; if(*p == '\"') p++; } else *cmd_out++ = *p++; *cmd_out++ = '\0'; } args.Add(NULL); String app_full = GetFileOnPath(app, getenv("PATH"), true); if(IsNull(app_full)) throw Exc(Format("Cannot find executable '%s'\n", app)); if(pipe(rpipe) || pipe(wpipe)) throw Exc(NFormat(t_("pipe() error; error code = %d"), errno)); SVRLOG("\nLocalSlaveProcess::Open"); SVRLOG("rpipe[" << rpipe[0] << ", " << rpipe[1] << "]"); SVRLOG("wpipe[" << wpipe[0] << ", " << wpipe[1] << "]"); pid = fork(); SVRLOG("\tfork, pid = " << (int)pid << ", getpid = " << (int)getpid()); if(pid < 0) throw Exc(NFormat(t_("fork() error; error code = %d"), errno)); if(pid) { // parent process; clear child pipe endpoints SVRLOG("parent process - continue"); // rpipe[0] = wpipe[1] = -1; return; } SVRLOG("child process - execute application"); // rpipe[1] = wpipe[0] = -1; if(dup2(rpipe[0], 0) < 0) { // stdin SVRLOG("dup2(stdin) error: " << errno << ", " << strerror(errno)); } if(dup2(wpipe[1], 1) < 0) { // stdout SVRLOG("dup2(stdout) error: " << errno << ", " << strerror(errno)); } if(dup2(wpipe[1], 2) < 0) { // stderr SVRLOG("dup2(stderr) error: " << errno << ", " << strerror(errno)); } #if DO_SVRLOG SVRLOG(args.GetCount() << "arguments:"); for(int a = 0; a < args.GetCount(); a++) SVRLOG("[" << a << "]: <" << (args[a] ? args[a] : "NULL") << ">"); #endif//DO_SVRLOG SVRLOG("running execve, app = " << app << ", #args = " << args.GetCount()); const char *from = envptr; Vector<const char *> env; while(*from) { env.Add(from); from += strlen(from) + 1; } env.Add(NULL); execve(app_full, args.Begin(), (char *const *)env.Begin()); SVRLOG("execve failed, errno = " << errno); printf("Error running '%s', error code %d\n", command, errno); exit(-errno); #endif }
static BOOLEAN GetDriverKeyName( IN HKEY DeviceKey, OUT PTCHAR *Name ) { HRESULT Error; DWORD SubKeys; DWORD MaxSubKeyLength; DWORD SubKeyLength; PTCHAR SubKeyName; DWORD Index; HKEY SubKey; PTCHAR DriverKeyName; Error = RegQueryInfoKey(DeviceKey, NULL, NULL, NULL, &SubKeys, &MaxSubKeyLength, NULL, NULL, NULL, NULL, NULL, NULL); if (Error != ERROR_SUCCESS) { SetLastError(Error); goto fail1; } SubKeyLength = MaxSubKeyLength + sizeof (TCHAR); SubKeyName = malloc(SubKeyLength); if (SubKeyName == NULL) goto fail2; SubKey = NULL; DriverKeyName = NULL; for (Index = 0; Index < SubKeys; Index++) { DWORD MaxValueLength; DWORD DriverKeyNameLength; DWORD Type; SubKeyLength = MaxSubKeyLength + sizeof (TCHAR); memset(SubKeyName, 0, SubKeyLength); Error = RegEnumKeyEx(DeviceKey, Index, (LPTSTR)SubKeyName, &SubKeyLength, NULL, NULL, NULL, NULL); if (Error != ERROR_SUCCESS) { SetLastError(Error); goto fail3; } Error = RegOpenKeyEx(DeviceKey, SubKeyName, 0, KEY_READ, &SubKey); if (Error != ERROR_SUCCESS) { SubKey = NULL; continue; } Error = RegQueryInfoKey(SubKey, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &MaxValueLength, NULL, NULL); if (Error != ERROR_SUCCESS) { SetLastError(Error); goto fail4; } DriverKeyNameLength = MaxValueLength + sizeof (TCHAR); DriverKeyName = calloc(1, DriverKeyNameLength); if (DriverKeyName == NULL) goto fail5; Error = RegQueryValueEx(SubKey, "Driver", NULL, &Type, (LPBYTE)DriverKeyName, &DriverKeyNameLength); if (Error == ERROR_SUCCESS && Type == REG_SZ) break; free(DriverKeyName); DriverKeyName = NULL; RegCloseKey(SubKey); SubKey = NULL; } Log("%s", (DriverKeyName != NULL) ? DriverKeyName : "none found"); if (SubKey != NULL) RegCloseKey(SubKey); free(SubKeyName); *Name = DriverKeyName; return TRUE; fail5: Log("fail5"); fail4: Log("fail4"); if (SubKey != NULL) RegCloseKey(SubKey); fail3: Log("fail3"); free(SubKeyName); fail2: Log("fail2"); fail1: Error = GetLastError(); { PTCHAR Message; Message = GetErrorMessage(Error); Log("fail1 (%s)", Message); LocalFree(Message); } return FALSE; }
int main( int argc, char *argv[] ) { DWORD dwError = 0; PSTR pszErrMsg = NULL; if (argc < 2 ) { PrintUsage(NULL); goto cleanup; } if (!strcmp(argv[1], "--eventlog")) { if (argc < 4) { PrintUsage("--eventlog requires two arguments."); } else { dwError = EventlogConfFileToRegFile(argv[2], argv[3]); } } else if (!strcmp(argv[1], "--lsass")) { if (argc < 4) { PrintUsage("--lsass requires two arguments."); } else { dwError = LsassConfFileToRegFile(argv[2], argv[3]); } } else if (!strcmp(argv[1], "--netlogon")) { if (argc < 4) { PrintUsage("--netlogon requires two arguments."); } else { dwError = NetlogonConfFileToRegFile(argv[2], argv[3]); } } #ifdef ENABLE_TDB else if (!strcmp(argv[1], "--lwiauth")) { if (argc < 5) { PrintUsage("--lwiauth requires three arguments and usually root privileges."); } else { dwError = LwiauthConfFileToRegFile(argv[2], argv[3], argv[4]); } } #endif else if (!strcmp(argv[1], "--pstore-sqlite")) { if (argc < 3) { PrintUsage("--pstore-sqlite requires one argument and usually root privileges."); } else { dwError = SqliteMachineAccountToPstore(argv[2]); } } else { PrintUsage(NULL); } cleanup: if (dwError) { if (!GetErrorMessage(dwError, &pszErrMsg) && pszErrMsg) { fputs(pszErrMsg, stderr); fputs("\n", stderr); LW_SAFE_FREE_STRING(pszErrMsg); } else { fprintf(stderr, "Error %lu\n", (unsigned long)dwError); } return 1; } return 0; }
static BOOLEAN GetMatchingDeviceID( IN HKEY DriverKey, OUT PTCHAR *MatchingDeviceID ) { HRESULT Error; DWORD MaxValueLength; DWORD MatchingDeviceIDLength; DWORD Type; DWORD Index; Error = RegQueryInfoKey(DriverKey, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &MaxValueLength, NULL, NULL); if (Error != ERROR_SUCCESS) { SetLastError(Error); goto fail1; } MatchingDeviceIDLength = MaxValueLength + sizeof (TCHAR); *MatchingDeviceID = calloc(1, MatchingDeviceIDLength); if (*MatchingDeviceID == NULL) goto fail2; Error = RegQueryValueEx(DriverKey, "MatchingDeviceId", NULL, &Type, (LPBYTE)*MatchingDeviceID, &MatchingDeviceIDLength); if (Error != ERROR_SUCCESS) { SetLastError(Error); goto fail3; } if (Type != REG_SZ) { SetLastError(ERROR_BAD_FORMAT); goto fail4; } for (Index = 0; Index < strlen(*MatchingDeviceID); Index++) (*MatchingDeviceID)[Index] = (CHAR)toupper((*MatchingDeviceID)[Index]); Log("%s", *MatchingDeviceID); return TRUE; fail4: Log("fail4"); fail3: Log("fail3"); free(*MatchingDeviceID); fail2: Log("fail2"); fail1: Error = GetLastError(); { PTCHAR Message; Message = GetErrorMessage(Error); Log("fail1 (%s)", Message); LocalFree(Message); } return FALSE; }
void ErrorMessage::printErrorMessage(NAError * errcb) { NAWchar* tmp = msgBuf_; // This is always a positive number (but make sure of it!) NAErrorCode erc_abs = errcb->getErrCode(); if (erc_abs < 0) erc_abs = -erc_abs; // A warning is positive, an error negative -- // GetErrorMessage generates the proper text for each. NAErrorCode erc_signed = (errcb->getErrType() == NAError::NAERROR_WARNING) ? erc_abs : -erc_abs; NABoolean msgNotFound = GetErrorMessage(erc_signed, tmp); NABoolean forceParamSubst = msgNotFound && errcb->getErrParamCount() > 0; /* // if tmp was assigned to a different (e.g. a static) string, we need to copy // its contents into this msgBuf_ so that insertParams overwrites our copy // and not the original. */ NAWstrcpy(msgBuf_, tmp); if (forceParamSubst) { // msgBuf_ will contain a suitable msg-not-found message, so now we just // append substitution parameters to at least make debugging easier. // // This mirrors what ComCondition::getMessageText does. NAWstrcat(msgBuf_, WIDE_(" $0 $1 $2 $3 $4 $5 $6 $7 $8 $9")); //dbg: NAWstrcat(msgBuf_, WIDE_(" $ $$ $ab $9 $~ $~~ $~0 $0~ $~a $a~ $0x $0x~int0 $int0~x # $0~int0 $int0~0 $0 $00 $0$0")); //dbg: NAWstrcat(msgBuf_, WIDE_(" $Int0~0$int0~1 $0~Int0$1~int0 #")); //dbg: NAWstrcat(msgBuf_, WIDE_(" $Int0~0$int0~0 $0~Int0$0~int0 #")); //dbg: NAWstrcat(msgBuf_, WIDE_(" $Int0~0$0~int0 $0~Int0$int0~0 #")); } ErrorMessageOverflowCheckW(msgBuf_, MSG_BUF_SIZE); insertParams(errcb); if (forceParamSubst) { // remove trailing blanks and unsubstituted substitution marks #pragma nowarn(1506) // warning elimination Int32 tmpLen = NAWstrlen(msgBuf_); #pragma warn(1506) // warning elimination while (--tmpLen >= 0 && (msgBuf_[tmpLen] == NAWchar(' ') || msgBuf_[tmpLen] == NAWchar('\t') || msgBuf_[tmpLen] == ERRORPARAM_BEGINMARK)) ; msgBuf_[++tmpLen] = NAWchar('\0'); } char msgBuf8bit[2*MSG_BUF_SIZE]; UnicodeStringToLocale(CharInfo::ISO88591, msgBuf_, MSG_BUF_SIZE, msgBuf8bit, 2*MSG_BUF_SIZE); printf("%s\n", msgBuf8bit); fflush(stdout); } // ErrorMessage::printErrorMessage()
static BOOLEAN SupportChildDrivers( VOID ) { BOOLEAN Success; HKEY XenbusKey; HRESULT Error; DWORD SubKeys; DWORD MaxSubKeyLength; DWORD SubKeyLength; PTCHAR SubKeyName; HKEY DeviceKey; PTCHAR DriverKeyName; HKEY DriverKey; PTCHAR MatchingDeviceID; DWORD Index; Log("====>"); Success = OpenBusKey("XENHID", &XenbusKey); if (!Success) { // If there is no key then this must be a fresh installation if (GetLastError() == ERROR_FILE_NOT_FOUND) goto done; goto fail1; } Error = RegQueryInfoKey(XenbusKey, NULL, NULL, NULL, &SubKeys, &MaxSubKeyLength, NULL, NULL, NULL, NULL, NULL, NULL); if (Error != ERROR_SUCCESS) { SetLastError(Error); goto fail2; } SubKeyLength = MaxSubKeyLength + sizeof (TCHAR); SubKeyName = malloc(SubKeyLength); if (SubKeyName == NULL) goto fail3; for (Index = 0; Index < SubKeys; Index++) { SubKeyLength = MaxSubKeyLength + sizeof (TCHAR); memset(SubKeyName, 0, SubKeyLength); Error = RegEnumKeyEx(XenbusKey, Index, (LPTSTR)SubKeyName, &SubKeyLength, NULL, NULL, NULL, NULL); if (Error != ERROR_SUCCESS) { SetLastError(Error); goto fail4; } Success = OpenDeviceKey("XENHID", SubKeyName, &DeviceKey); if (!Success) goto fail5; Success = GetDriverKeyName(DeviceKey, &DriverKeyName); if (!Success) goto fail6; if (DriverKeyName == NULL) goto loop; Success = OpenDriverKey(DriverKeyName, &DriverKey); if (!Success) goto loop; Success = GetMatchingDeviceID(DriverKey, &MatchingDeviceID); if (!Success) goto fail7; Success = SupportDeviceID(MatchingDeviceID); if (!Success) goto fail8; free(MatchingDeviceID); RegCloseKey(DriverKey); loop: if (DriverKeyName != NULL) free(DriverKeyName); RegCloseKey(DeviceKey); } free(SubKeyName); RegCloseKey(XenbusKey); done: Log("<===="); return TRUE; fail8: Log("fail8"); free(MatchingDeviceID); fail7: Log("fail7"); RegCloseKey(DriverKey); free(DriverKeyName); fail6: Log("fail6"); RegCloseKey(DeviceKey); fail5: Log("fail5"); fail4: Log("fail4"); free(SubKeyName); fail3: Log("fail3"); fail2: Log("fail2"); RegCloseKey(XenbusKey); fail1: Error = GetLastError(); { PTCHAR Message; Message = GetErrorMessage(Error); Log("fail1 (%s)", Message); LocalFree(Message); } return FALSE; }