BOOL InstallServiceEx(HWND hWnd, SC_HANDLE schSCManager, char *scName, DWORD scStartType, char *szPath) { SC_HANDLE schService; // Създава го сервиса. schService = CreateService( schSCManager, // SCM база с данни scName, // име на сервиса scName, // изложеното име на сервиса SERVICE_ALL_ACCESS, // желаещ достъп SERVICE_KERNEL_DRIVER, // тип на сервиса scStartType, // стартуващ тип SERVICE_ERROR_NORMAL, // контролен тип за грешки szPath, // пътечка до сервиса(*.sys) NULL, // без зареждаща група NULL, // без прибавка за установяване NULL, // без зависимости NULL, // локален опис NULL); // без парола if (schService == NULL) { MessageBox(hWnd, GetErrorText(GetLastError()), "FileHide", MB_ICONERROR); return FALSE; } MessageBox(hWnd, "Сервисът е успешно инсталиран", "FileHide", MB_ICONEXCLAMATION); CloseServiceHandle(schService); return TRUE; }
HRESULT __stdcall ErrorUnableToCreateVM(HRESULT hr) { LPSTR buf = GetErrorText(hr); HRESULT ret = ReportError(IDP_CREATEVMFAILED, hr, buf); ::LocalFree(buf); return ret; }
uint32 CheckEQEMuError() { if (!EQEMuErrorList) return 0; uint32 ret = 0; char* tmp = 0; bool HeaderPrinted = false; LockMutex lock(MEQEMuErrorList); while ((tmp = EQEMuErrorList->Pop() )) { if (!HeaderPrinted) { fprintf(stdout, "===============================\nRuntime errors:\n\n"); HeaderPrinted = true; } if (tmp[0] == 1) { fprintf(stdout, "%s\n", GetErrorText(*((uint32*) &tmp[1]))); fprintf(stdout, "For more information on this error, visit http://www.eqemu.net/eqemuerror.php?id=%u\n\n", *((uint32*) &tmp[1])); } else { fprintf(stdout, "%s\n\n", tmp); } safe_delete(tmp); ret++; } return ret; }
VOID WINAPI PrintError(HWND hwndOwner, DWORD dwError) { LPCTSTR lpszText = GetErrorText(dwError); MessageBox(hwndOwner, lpszText, TEXT("Error!"), MB_OK | MB_ICONERROR); exit(EXIT_FAILURE); }
BOOL IsServiceRunning(HWND hWnd, SC_HANDLE schSCManager, char *szSvcName) { SC_HANDLE schService; SERVICE_STATUS_PROCESS ssStatus; DWORD dwBytesNeeded; schService = OpenService( schSCManager, // SCM база с данни szSvcName, // име на сервиса SERVICE_ALL_ACCESS); // пълен достъп if (schService == NULL) { return FALSE; } if (!QueryServiceStatusEx( schService, // дръжка до сервиса SC_STATUS_PROCESS_INFO, // информационно ниво (LPBYTE) &ssStatus, // адреса на структура sizeof(SERVICE_STATUS_PROCESS), // големина на структура &dwBytesNeeded)) // необходима големина, ако буфера е много малък { MessageBox(hWnd, GetErrorText(GetLastError()), "FileHide", MB_ICONERROR); CloseServiceHandle(schService); return FALSE; } // Проверява дали сервиса работи. if(ssStatus.dwCurrentState == SERVICE_RUNNING) { CloseServiceHandle(schService); return TRUE; } return FALSE; }
bool SLandscapeEditor::GetLandscapeEditorIsEnabled() const { FEdModeLandscape* LandscapeEdMode = GetEditorMode(); if (LandscapeEdMode) { Error->SetError(GetErrorText()); return LandscapeEdMode->GetEditingState() == ELandscapeEditingState::Enabled; } return false; }
bool AudioIn::CheckResult() { if(Ok()) return true; char buf[164]; GetErrorText (buf, sizeof (buf)); ssi_wrn (buf); return false; }
void DR::EMHandler::errorHandler(int error) { char buffer[1024]; char *pBuffer = &buffer[0]; size_t numberBytes; while (error != BIRD_ERROR_SUCCESS) { error = GetErrorText(error, pBuffer, sizeof(buffer), SIMPLE_MESSAGE); numberBytes = strlen(buffer); buffer[numberBytes] = '\n'; // append a newline to buffer } }
BOOL MapNameTextTable::GetSectorName(TBLIDX tblidx, std::wstring* pwstr) { GetText(tblidx, pwstr); std::wstring::size_type pos; pos = pwstr->find(L";"); if (pos == std::wstring::npos) { GetErrorText(tblidx, pwstr); return FALSE; } pwstr->erase(0, pos + 1); pos = pwstr->find(L";"); if (pos == std::wstring::npos) { GetErrorText(tblidx, pwstr); return FALSE; } pwstr->erase(pos); return TRUE; }
BOOL DeleteServiceEx(HWND hWnd, SC_HANDLE schSCManager, char *szSvcName) { SC_HANDLE schService; schService = OpenService( schSCManager, // SCM база с данни szSvcName, // име на сервиса DELETE); // достъп за изтриване if (schService == NULL) { MessageBox(hWnd, GetErrorText(GetLastError()), "FileHide", MB_ICONERROR); return FALSE; } // Изтрива го сервиса if (!DeleteService(schService)) { MessageBox(hWnd, GetErrorText(GetLastError()), "FileHide", MB_ICONERROR); CloseServiceHandle(schService); return FALSE; } MessageBox(hWnd, "Сервисът е успешно изтриен", "FileHide", MB_ICONEXCLAMATION); CloseServiceHandle(schService); return TRUE; }
void mitk::MicroBirdTrackingDevice::HandleError(int errorCode) { char buffer[1024]; char* pBuffer = &buffer[0]; while(!CompareError(errorCode, BIRD_ERROR_SUCCESS)) { // Print error number on screen //cout << "MicroBIRD Error Code: " << errorCode << endl; // Print error message on screen errorCode = GetErrorText(errorCode, pBuffer, sizeof(buffer), SIMPLE_MESSAGE); /// @todo : set error message, does it work? this->SetErrorMessage(buffer); } }
enumError PrintErrorStat ( enumError err, ccp cmdname ) { if ( print_sections ) { putchar('\n'); if ( err ) printf("[error]\nprogram=%s\ncommand=%s\ncode=%u\nname=%s\ntext=%s\n\n", progname, cmdname, err, GetErrorName(err), GetErrorText(err) ); } if ( verbose > 0 && err >= ERR_WARNING || verbose > 1 && err || err == ERR_NOT_IMPLEMENTED ) { fprintf(stderr,"%s: Command '%s' returns with status #%d [%s]\n", progname, cmdname, err, GetErrorName(err) ); } return err; }
void Acceptor::handleRead() { loop_->assertInLoopThread(); int errorCode = 0; while(true) { InetAddress peerAddr; sockaddr addr = {0}; socket_t newFd = SocketOps::accept(listenFd_, &addr); if(newFd < 0) { errorCode = GetLastErrorCode(); break; } SocketOps::setSocketNoneBlocking(newFd); peerAddr.setSockAddr(addr); if(newConnCallBack_) { newConnCallBack_(newFd, peerAddr); } else { SocketOps::closeSocket(newFd); } } if(!ERR_ACCEPT_RETRIABLE(errorCode)) { LOG_PRINT(LogType_Error, "accept socket failed:%s %s:%d", GetErrorText(errorCode).c_str(), __FUNCTION__, __LINE__); } }
CGGD::OpenGL::Exception::Exception(const ErrorCode& errorCode_): errorText(GetErrorText(errorCode_)) { }
BOOL CALLBACK TabHandler2(HWND Window, UINT Message, WPARAM wParam, LPARAM lParam) { static int Index = -1; static int lastEntry = 0; static int flag = 0; switch(Message) { case WM_LBUTTONDOWN: // Ако потребителя кликне извън списъка с файлове, // прекъсва се редактирането на файловото име и връща се стария текст if (hEdit != NULL) DestroyWindow(hEdit); break; case WM_INITDIALOG: { LVCOLUMN lvCol = {0}; LOGFONT logFont; HFONT hFont; // Инициализация на списъка с файлове, // добавяне на текстов фонт и заглавие на колоната hList = GetDlgItem(Window, IDC_LISTVIEW); memset(&logFont, 0, sizeof(LOGFONT)); logFont.lfHeight = 15; strcpy(logFont.lfFaceName, "Courier New"); hFont = CreateFontIndirect(&logFont); SendDlgItemMessage(Window, IDC_LISTVIEW, WM_SETFONT, (WPARAM)hFont, TRUE); SendMessage(hList, LVM_SETEXTENDEDLISTVIEWSTYLE, 0, LVS_EX_FULLROWSELECT); lvCol.mask = LVCF_TEXT | LVCF_WIDTH; lvCol.pszText = ""; lvCol.cx = 280; SendMessage(hList, LVM_INSERTCOLUMN, 0, (LPARAM)&lvCol); } break; case WM_NOTIFY: // Обработка на съобщенията от списъкъ switch(LOWORD(wParam)) { case IDC_LISTVIEW: { if (((LPNMHDR)lParam)->code == NM_CLICK) { // Лев клик веднъш в списъкът Index = SendMessage(hList, LVM_GETNEXTITEM, -1, LVIS_FOCUSED); if (Index == -1) { flag = 0; break; } flag = 1; break; } else if (((LPNMHDR)lParam)->code == NM_DBLCLK) { // Лев клик два пъти в списъкът if (hEdit != NULL) DestroyWindow(hEdit); // Ако потребителя кликне два пъти върху прозиволно файлово име // се "подкласва" списъкът: { RECT r; WNDPROC wpOld; LVITEM lvItem = {0}; char text[50] = ""; lvItem.mask = LVIF_TEXT; lvItem.cchTextMax = 50; lvItem.pszText = text; SendMessage(hList, LVM_GETITEMTEXT, ((NMLISTVIEW*)lParam)->iItem, (LPARAM)&lvItem); // Първо се намират координатите на къошетета на редактиращото поле ListView_GetSubItemRect(hList, ((NMLISTVIEW*)lParam)->iItem, 0, LVIR_LABEL, &r); // След това се създава редактиращо поле върху линията, която е селектирана hEdit = CreateWindowEx(0, "EDIT", text, WS_CHILD|WS_VISIBLE|WS_BORDER|ES_LEFT|ES_MULTILINE, r.left, r.top, r.right-r.left, r.bottom-r.top, ((NMLISTVIEW*)lParam)->hdr.hwndFrom, NULL, hInst, 0); SendMessage(hEdit, EM_LIMITTEXT, 50, 0); // Не повече от 50 букви SendMessage(hEdit, EM_SETSEL, 0, 50); // Текста се селектира SetFocus(hEdit); // Редактиращото поле получява фокус // Заменя се обработващата процедура на редактиращото поле с SubClass_ListView_WndProc wpOld = (WNDPROC)SetWindowLong(hEdit, GWL_WNDPROC, (LONG)SubClass_ListView_WndProc); // Запазват се някои важни свойства ... SetProp(hEdit, "WP_OLD", (HANDLE)wpOld); SetProp(hEdit, "ITEM", (HANDLE)((NMLISTVIEW*)lParam)->iItem); } break; } else if (((LPNMHDR)lParam)->code == NM_RCLICK) { // Десен клик в списъкът // Създава се менито с трите бутона "Добави", "Изтрий" и "Изтрий всичко" HMENU hMenu = LoadMenu(NULL, MAKEINTRESOURCE(IDR_MENU)); HMENU hPopupMenu = GetSubMenu(hMenu, 0); POINT pt; SetMenuDefaultItem(hPopupMenu, (UINT)-1, TRUE); GetCursorPos(&pt); SetForegroundWindow(Window); TrackPopupMenu(hPopupMenu, TPM_LEFTALIGN, pt.x, pt.y, 0, Window, NULL); SetForegroundWindow(Window); // Изчистване на дръжките DestroyMenu(hPopupMenu); DestroyMenu(hMenu); break; } } break; } break; case WM_COMMAND: switch(LOWORD(wParam)) { case ID_ADD: // Добавка на ново име в списъкът { char text[50] = ""; LVITEM lvItem = {0}; // ListView Item struct lvItem.mask = LVIF_TEXT; // Text Style lvItem.cchTextMax = 50; lvItem.iItem = SendMessage(hList, LVM_GETITEMCOUNT, 0, 0); SendMessage(hList,LVM_INSERTITEM,0,(LPARAM)&lvItem); sprintf(text,"FILENAMETOHIDE%d.EXE", lastEntry); lvItem.pszText = text; SendMessage(hList,LVM_SETITEM,0,(LPARAM)&lvItem); lastEntry++; break; } break; case ID_REMOVE: // Изтриване на име от списъкът if (flag) SendMessage(hList, LVM_DELETEITEM, Index, 0); flag = 0; Index = -1; break; case ID_REMOVEALL: // Изтриване на всички имена от списъкът SendMessage(hList, LVM_DELETEALLITEMS, 0, 0); lastEntry = 0; flag = 0; Index = -1; break; case IDC_BUT_HIDE: // Бутона за скриване на всички имена от списъкът { HANDLE hFile; int i; char drvName[50]; char fileName[50] = ""; char driverText[50] = ""; DWORD dwReturn; LVITEM LvItem = {0}; // Проверка дали списъкът е празен int count = SendMessage(hList, LVM_GETITEMCOUNT, 0, 0); if (!count) { MessageBox(Window, "Първо добави няколку файла (с десен клик).", "FileHide", 0); break; } // Добавяне на претставка върху името на драйвера // Това всъшност е символичното име на драйвера sprintf(drvName, "\\\\.\\%s", DriverName); // Създаване на дръжка към драйвера за четене и запис hFile = CreateFile(drvName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (hFile == INVALID_HANDLE_VALUE) { MessageBox(Window, GetErrorText(GetLastError()), "FileHide", MB_ICONERROR); } else { // Ако е всичко на ред, изпращаме контролен код IOCTL_CLEAN_POOL // с буфер "clear pool", за да се изчистат предишните скрити файлове DeviceIoControl(hFile, IOCTL_CLEAN_POOL, "clear pool", sizeof("clear pool"), driverText, sizeof(driverText), &dwReturn, NULL); LvItem.mask = LVIF_TEXT; // Text Style LvItem.cchTextMax = 50; LvItem.pszText = fileName; // Обхожда се списъкъ и за всеки отделно // се изпраща IOCTL_HIDE_FILE контролен код към драйвера for (i=0; i<count; i++) { LvItem.iItem = i; SendMessage(hList, LVM_GETITEMTEXT, i, (LPARAM)&LvItem); ZeroMemory(driverText, sizeof(driverText)); DeviceIoControl(hFile, IOCTL_HIDE_FILE, fileName, sizeof(fileName), driverText, sizeof(driverText), &dwReturn, NULL); MessageBox(Window, driverText, DriverName, 0); //ZeroMemory(fileName, sizeof(fileName)); } CloseHandle(hFile); } } break; } break; default: return FALSE; } return TRUE; }
BOOL StopServiceEx(HWND hWnd, SC_HANDLE schSCManager, char *szSvcName) { SC_HANDLE schService; SERVICE_STATUS_PROCESS ssp; DWORD dwStartTime = GetTickCount(); DWORD dwBytesNeeded; DWORD dwTimeout = 30000; // 30 секундна пауза DWORD dwWaitTime; schService = OpenService(schSCManager, szSvcName, SERVICE_STOP | SERVICE_QUERY_STATUS | SERVICE_ENUMERATE_DEPENDENTS); if (schService == NULL) { MessageBox(hWnd, GetErrorText(GetLastError()), "FileHide", MB_ICONERROR); return FALSE; } // Проверява дали сервиса не е вече спрян. if (!QueryServiceStatusEx(schService, SC_STATUS_PROCESS_INFO, (LPBYTE)&ssp, sizeof(SERVICE_STATUS_PROCESS), &dwBytesNeeded)) { MessageBox(hWnd, GetErrorText(GetLastError()), "FileHide", MB_ICONERROR); CloseServiceHandle(schService); return FALSE; } if (ssp.dwCurrentState == SERVICE_STOPPED) { MessageBox(hWnd, "Сервисът е бил спрен", "FileHide", MB_ICONERROR); CloseServiceHandle(schService); return FALSE; } // Ако стопирането е в очакване, изчакай го. while (ssp.dwCurrentState == SERVICE_STOP_PENDING) { dwWaitTime = ssp.dwWaitHint / 10; if(dwWaitTime < 1000) dwWaitTime = 1000; else if (dwWaitTime > 10000) dwWaitTime = 10000; Sleep(dwWaitTime); if ( !QueryServiceStatusEx(schService, SC_STATUS_PROCESS_INFO, (LPBYTE)&ssp, sizeof(SERVICE_STATUS_PROCESS), &dwBytesNeeded)) { MessageBox(hWnd, GetErrorText(GetLastError()), "FileHide", MB_ICONERROR); CloseServiceHandle(schService); return FALSE; } if (ssp.dwCurrentState == SERVICE_STOPPED) { MessageBox(hWnd, "Сервисът е спрян", "FileHide", MB_ICONEXCLAMATION); CloseServiceHandle(schService); return TRUE; } if (GetTickCount() - dwStartTime > dwTimeout) { MessageBox(hWnd, "Времето за спиране на сервиса изтече", "FileHide", MB_ICONERROR); CloseServiceHandle(schService); return FALSE; } } // Ако сервиса работи, зависимите сервиси първо се спират. StopDependentServices(schSCManager, schService); // Изпраща стоп код към сервиса. if (!ControlService(schService, SERVICE_CONTROL_STOP, (LPSERVICE_STATUS)&ssp)) { MessageBox(hWnd, GetErrorText(GetLastError()), "FileHide", MB_ICONERROR); CloseServiceHandle(schService); return FALSE; } // Изчака сервиса да спре. while (ssp.dwCurrentState != SERVICE_STOPPED) { Sleep(ssp.dwWaitHint); if (!QueryServiceStatusEx(schService, SC_STATUS_PROCESS_INFO, (LPBYTE)&ssp, sizeof(SERVICE_STATUS_PROCESS), &dwBytesNeeded)) { MessageBox(hWnd, GetErrorText(GetLastError()), "FileHide", MB_ICONERROR); CloseServiceHandle(schService); return FALSE; } if (ssp.dwCurrentState == SERVICE_STOPPED) break; if (GetTickCount() - dwStartTime > dwTimeout) { MessageBox(hWnd, "Времето за спиране на сервиса изтече", "FileHide", MB_ICONERROR); CloseServiceHandle(schService); return FALSE; } } MessageBox(hWnd, "Сервисът е спрян", "FileHide", MB_ICONEXCLAMATION); CloseServiceHandle(schService); return TRUE; }
BOOL StartServiceEx(HWND hWnd, SC_HANDLE schSCManager, char *szSvcName) { SC_HANDLE schService; SERVICE_STATUS_PROCESS ssStatus; DWORD dwOldCheckPoint; DWORD dwStartTickCount; DWORD dwWaitTime; DWORD dwBytesNeeded; char str[50]; schService = OpenService( schSCManager, // SCM база с данни szSvcName, // име на сервиса SERVICE_ALL_ACCESS); // пълен достъп if (schService == NULL) { MessageBox(hWnd, GetErrorText(GetLastError()), "FileHide", MB_ICONERROR); return FALSE; } // Проверка на състоянието в случай, че сервиса не е спрял. if (!QueryServiceStatusEx( schService, // дръжка до сервиса SC_STATUS_PROCESS_INFO, // информационно ниво (LPBYTE) &ssStatus, // адреса на структура sizeof(SERVICE_STATUS_PROCESS), // големина на структура &dwBytesNeeded)) // необходима големина, ако буфера е много малък { MessageBox(hWnd, GetErrorText(GetLastError()), "FileHide", MB_ICONERROR); CloseServiceHandle(schService); return FALSE; } // Проверява дали сервиса работи. if(ssStatus.dwCurrentState != SERVICE_STOPPED && ssStatus.dwCurrentState != SERVICE_STOP_PENDING) { MessageBox(hWnd, "Сервисът не може да се стартува, защото е вече стартуван и работи", "FileHide", MB_ICONERROR); CloseServiceHandle(schService); return FALSE; } // Спасяване на цъканията и първоначалния контролно-пропусквателен пункт. dwStartTickCount = GetTickCount(); dwOldCheckPoint = ssStatus.dwCheckPoint; // Изчакване на сервиса да спре преди да се опита да стартува. while (ssStatus.dwCurrentState == SERVICE_STOP_PENDING) { // Да не се чака по-дълго, отколкото изчакващия намек. Интервала е // една десета от изчакващия намек, но не помалко от една секунда // и не по-вече от 10 секунди. dwWaitTime = ssStatus.dwWaitHint / 10; if(dwWaitTime < 1000) dwWaitTime = 1000; else if (dwWaitTime > 10000) dwWaitTime = 10000; Sleep(dwWaitTime); // Проверка на състоянието, докато сервиса не спре в очакване. if (!QueryServiceStatusEx( schService, // дръжка до сервиса SC_STATUS_PROCESS_INFO, // информационно ниво (LPBYTE) &ssStatus, // адреса на структура sizeof(SERVICE_STATUS_PROCESS), // големина на структура &dwBytesNeeded)) // необходима големина, ако буфера е много малък { MessageBox(hWnd, GetErrorText(GetLastError()), "FileHide", MB_ICONERROR); CloseServiceHandle(schService); return FALSE; } if (ssStatus.dwCheckPoint > dwOldCheckPoint) { // Продължаване на изчакването и проверката. dwStartTickCount = GetTickCount(); dwOldCheckPoint = ssStatus.dwCheckPoint; } else { if(GetTickCount()-dwStartTickCount > ssStatus.dwWaitHint) { MessageBox(hWnd, "Времето за чакане на сервиса за спиране измина", "FileHide", MB_ICONERROR); CloseServiceHandle(schService); return FALSE; } } } // Опит да се стартува сервиса. if (!StartService( schService, // handle to service 0, // number of arguments NULL) ) // no arguments { MessageBox(hWnd, GetErrorText(GetLastError()), "FileHide", MB_ICONERROR); CloseServiceHandle(schService); return FALSE; } // Започва очакването... // Проверка на състоянието, докато сервиса не започне в очакване. if (!QueryServiceStatusEx( schService, // дръжка до сервиса SC_STATUS_PROCESS_INFO, // информационно ниво (LPBYTE) &ssStatus, // адреса на структура sizeof(SERVICE_STATUS_PROCESS), // големина на структура &dwBytesNeeded)) // ако буфера е много малък { MessageBox(hWnd, GetErrorText(GetLastError()), "FileHide", MB_ICONERROR); CloseServiceHandle(schService); return FALSE; } // Спасяване на цъканията и първоначалния контролно-пропусквателен пункт. dwStartTickCount = GetTickCount(); dwOldCheckPoint = ssStatus.dwCheckPoint; while (ssStatus.dwCurrentState == SERVICE_START_PENDING) { dwWaitTime = ssStatus.dwWaitHint / 10; if(dwWaitTime < 1000) dwWaitTime = 1000; else if (dwWaitTime > 10000) dwWaitTime = 10000; Sleep(dwWaitTime); // Отново проверка на състоянието. if (!QueryServiceStatusEx( schService, SC_STATUS_PROCESS_INFO, (LPBYTE) &ssStatus, sizeof(SERVICE_STATUS_PROCESS), &dwBytesNeeded)) { MessageBox(hWnd, GetErrorText(GetLastError()), "FileHide", MB_ICONERROR); break; } if (ssStatus.dwCheckPoint > dwOldCheckPoint) { // Продължаване на изчакването и проверката. dwStartTickCount = GetTickCount(); dwOldCheckPoint = ssStatus.dwCheckPoint; } else { if(GetTickCount()-dwStartTickCount > ssStatus.dwWaitHint) { // Без напредък в изчекащия намек. break; } } } // Определя дали сервиса е стартуван. if (ssStatus.dwCurrentState == SERVICE_RUNNING) { MessageBox(hWnd, "Сервисът е стартуван", "FileHide", MB_ICONEXCLAMATION); CloseServiceHandle(schService); return TRUE; } else { sprintf(str, "Сервисът не е стартуван.\n"); sprintf(str, "Текущо състояние: %d\n", ssStatus.dwCurrentState); sprintf(str, " Exit Code: %d\n", ssStatus.dwWin32ExitCode); sprintf(str, " Check Point: %d\n", ssStatus.dwCheckPoint); sprintf(str, " Wait Hint: %d\n", ssStatus.dwWaitHint); MessageBox(hWnd, str, "FileHide", MB_ICONERROR); CloseServiceHandle(schService); return FALSE; } }
enumError cmd_error() { if (!n_param) { if ( print_sections ) { int i; for ( i=0; i<ERR__N; i++ ) printf("\n[error-%02u]\ncode=%u\nname=%s\ntext=%s\n", i, i, GetErrorName(i), GetErrorText(i)); } else { const bool print_header = !OptionUsed[OPT_NO_HEADER]; if (print_header) { print_title(stdout); printf(" List of error codes\n\n"); } int i; // calc max_wd int max_wd = 0; for ( i=0; i<ERR__N; i++ ) { const int len = strlen(GetErrorName(i)); if ( max_wd < len ) max_wd = len; } // print table for ( i=0; i<ERR__N; i++ ) printf("%3d : %-*s : %s\n",i,max_wd,GetErrorName(i),GetErrorText(i)); if (print_header) printf("\n"); } return ERR_OK; } int stat; long num = ERR__N; if ( n_param != 1 ) stat = ERR_SYNTAX; else { char * end; num = strtoul(first_param->arg,&end,10); stat = *end ? ERR_SYNTAX : num < 0 || num >= ERR__N ? ERR_SEMANTIC : ERR_OK; } if (print_sections) printf("\n[error]\ncode=%lu\nname=%s\ntext=%s\n", num, GetErrorName(num), GetErrorText(num)); else if (long_count) printf("%s\n",GetErrorText(num)); else printf("%s\n",GetErrorName(num)); return stat; }
// Процедура на първия диалог (първия раздел) BOOL CALLBACK TabHandler1(HWND Window, UINT Message, WPARAM wParam, LPARAM lParam) { static HWND hComboBox; const char *aServiceTypes[] = {"SERVICE_AUTO_START", "SERVICE_BOOT_START", "SERVICE_DEMAND_START", "SERVICE_DISABLED", "SERVICE_SYSTEM_START"}; static SC_HANDLE hSCManager; char szFile[260]; switch(Message) { case WM_INITDIALOG: { int i; // Инициализиране на комбо поле от съответния ресурс hComboBox = GetDlgItem(Window, IDC_COMBO_TYPE); for(i = 0; i < 5; i++) { SendMessage(hComboBox, CB_ADDSTRING, 0, (LPARAM)aServiceTypes[i]); } // Селектиране на третия елемент от комбо-списъкъ SendMessage(hComboBox, CB_SETCURSEL, 2, 0); // Изкарване дръжка към SCM базата hSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (hSCManager == INVALID_HANDLE_VALUE) { MessageBox(Window, GetErrorText(GetLastError()), "FileHide", MB_ICONERROR); break; } } break; case WM_COMMAND: { switch(LOWORD(wParam)) { case IDC_DRIVER_NAME_SELECT: { OPENFILENAME openFileDialog = {0}; char szExtendedFileName[260]; openFileDialog.lStructSize = sizeof(openFileDialog); openFileDialog.hwndOwner = GetParent(Window); openFileDialog.lpstrFilter = "Драйвер(*.sys)\0*.SYS\0"; openFileDialog.nFilterIndex = 0; openFileDialog.lpstrFileTitle = NULL; openFileDialog.nMaxFileTitle = 0; openFileDialog.lpstrInitialDir = NULL; openFileDialog.lpstrFile = szFile; openFileDialog.lpstrFile[0] = '\0'; openFileDialog.nMaxFile = sizeof(szFile); openFileDialog.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST; // отваране на диалог за избор на *.sys файл if (GetOpenFileName(&openFileDialog)) { // Пътечката се променя с разширена дължина // т.е. с представка \\?\, защото драйвера няма да работи с // тази програма ако се намира в друга партиция (пример в D:\) sprintf(szExtendedFileName,"\\\\?\\%s",szFile); SetDlgItemText(Window, IDC_DRIVER_PATHNAME, szExtendedFileName); // Изваждане на името на драйвера от цялата пътечка, без разширението (.sys) _splitpath(szFile, NULL, NULL, DriverName, NULL); if (IsServiceInstalled(hSCManager, DriverName)) SetDlgItemText(Window, IDC_STATIC_STATUS, "Installed"); if (IsServiceRunning(Window, hSCManager, DriverName)) SetDlgItemText(Window, IDC_STATIC_STATUS, "Installed And Running"); } } break; case IDC_BUT_INST: { DWORD startType = 0; GetDlgItemText(Window, IDC_DRIVER_PATHNAME, szFile, 260); // Изваждане на името на драйвера от цялата пътечка, без разширението (.sys) _splitpath(szFile, NULL, NULL, DriverName, NULL); if (!strlen(DriverName)) { MessageBox(Window, "Полето за драйвера е празно", "FileHide", MB_ICONERROR); break; } // Промяна на startType в избраната стойност. // Препоръчва се SERVICE_DEMAND_START switch (SendMessage(hComboBox, CB_GETCURSEL, 0, 0)) { case 0: startType = SERVICE_AUTO_START; break; case 1: startType = SERVICE_BOOT_START; break; case 2: startType = SERVICE_DEMAND_START; break; case 3: startType = SERVICE_DISABLED; break; case 4: startType = SERVICE_SYSTEM_START; break; } // InstallServiceEx се намира в services.h if (InstallServiceEx(Window, hSCManager, DriverName, startType, szFile)) SetDlgItemText(Window, IDC_STATIC_STATUS, "Installed"); } break; case IDC_BUT_UNINST: { GetDlgItemText(Window, IDC_DRIVER_PATHNAME, szFile, 260); _splitpath(szFile, NULL, NULL, DriverName, NULL); if (!strlen(DriverName)) { MessageBox(Window, "Полето за драйвера е празно", "FileHide", MB_ICONERROR); break; } if (DeleteServiceEx(Window, hSCManager, DriverName)) SetDlgItemText(Window, IDC_STATIC_STATUS, "Uninstalled"); ZeroMemory(DriverName, sizeof(DriverName)); } break; case IDC_BUT_RUN: { GetDlgItemText(Window, IDC_DRIVER_PATHNAME, szFile, 260); _splitpath(szFile, NULL, NULL, DriverName, NULL); if (!strlen(DriverName)) { MessageBox(Window, "Полето за драйвера е празно", "FileHide", MB_ICONERROR); break; } if (StartServiceEx(Window, hSCManager, DriverName)) SetDlgItemText(Window, IDC_STATIC_STATUS, "Installed And Running"); } break; case IDC_BUT_STOP: { GetDlgItemText(Window, IDC_DRIVER_PATHNAME, szFile, 260); _splitpath(szFile, NULL, NULL, DriverName, NULL); if (!strlen(DriverName)) { MessageBox(Window, "Полето за драйвера е празно", "FileHide", MB_ICONERROR); break; } if (StopServiceEx(Window, hSCManager, DriverName)) SetDlgItemText(Window, IDC_STATIC_STATUS, "Installed"); ZeroMemory(DriverName, sizeof(DriverName)); } break; } } break; case WM_CLOSE: { CloseServiceHandle(hSCManager); } break; default: return FALSE; } return TRUE; }
BOOL LoadAddresses(AddressTable* at) { HMODULE hModule = NULL; hModule = LoadLibrary("SFMPQ.DLL"); if(hModule==NULL) { fprintf(stderr,"\nError loading SFMPQ.DLL: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pMpqGetVersionString = (Function_MpqGetVersionString)GetProcAddress(hModule,"MpqGetVersionString"); if(at->pMpqGetVersionString == NULL) { fprintf(stderr,"\nError locating address of MpqGetVersionString: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pMpqGetVersion = (Function_MpqGetVersion)GetProcAddress(hModule,"MpqGetVersion"); if(at->pMpqGetVersion == NULL) { fprintf(stderr,"\nError locating address of MpqGetVersion: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pSFMpqGetVersionString = (Function_SFMpqGetVersionString)GetProcAddress(hModule,"SFMpqGetVersionString"); if(at->pSFMpqGetVersionString == NULL) { fprintf(stderr,"\nError locating address of SFMpqGetVersionString: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pSFMpqGetVersionString2 = (Function_SFMpqGetVersionString2)GetProcAddress(hModule,"SFMpqGetVersionString2"); if(at->pSFMpqGetVersionString2 == NULL) { fprintf(stderr,"\nError locating address of SFMpqGetVersionString2: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pSFMpqGetVersion = (Function_SFMpqGetVersion)GetProcAddress(hModule,"SFMpqGetVersion"); if(at->pSFMpqGetVersion == NULL) { fprintf(stderr,"\nError locating address of SFMpqGetVersion: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pSFileOpenArchive = (Function_SFileOpenArchive)GetProcAddress(hModule,"SFileOpenArchive"); if(at->pSFileOpenArchive == NULL) { fprintf(stderr,"\nError locating address of SFileOpenArchive: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pSFileCloseArchive = (Function_SFileCloseArchive)GetProcAddress(hModule,"SFileCloseArchive"); if(at->pSFileCloseArchive == NULL) { fprintf(stderr,"\nError locating address of SFileCloseArchive: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pSFileGetArchiveName = (Function_SFileGetArchiveName)GetProcAddress(hModule,"SFileGetArchiveName"); if(at->pSFileGetArchiveName == NULL) { fprintf(stderr,"\nError locating address of SFileGetArchiveName: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pSFileOpenFile = (Function_SFileOpenFile)GetProcAddress(hModule,"SFileOpenFile"); if(at->pSFileOpenFile == NULL) { fprintf(stderr,"\nError locating address of SFileOpenFile: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pSFileOpenFileEx = (Function_SFileOpenFileEx)GetProcAddress(hModule,"SFileOpenFileEx"); if(at->pSFileOpenFileEx == NULL) { fprintf(stderr,"\nError locating address of SFileOpenFileEx: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pSFileCloseFile = (Function_SFileCloseFile)GetProcAddress(hModule,"SFileCloseFile"); if(at->pSFileCloseFile == NULL) { fprintf(stderr,"\nError locating address of SFileCloseFile: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pSFileGetFileSize = (Function_SFileGetFileSize)GetProcAddress(hModule,"SFileGetFileSize"); if(at->pSFileGetFileSize == NULL) { fprintf(stderr,"\nError locating address of SFileGetFileSize: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pSFileGetFileArchive = (Function_SFileGetFileArchive)GetProcAddress(hModule,"SFileGetFileArchive"); if(at->pSFileGetFileArchive == NULL) { fprintf(stderr,"\nError locating address of SFileGetFileArchive: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pSFileGetFileName = (Function_SFileGetFileName)GetProcAddress(hModule,"SFileGetFileName"); if(at->pSFileGetFileName == NULL) { fprintf(stderr,"\nError locating address of SFileGetFileName: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pSFileSetFilePointer = (Function_SFileSetFilePointer)GetProcAddress(hModule,"SFileSetFilePointer"); if(at->pSFileSetFilePointer == NULL) { fprintf(stderr,"\nError locating address of SFileSetFilePointer: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pSFileReadFile = (Function_SFileReadFile)GetProcAddress(hModule,"SFileReadFile"); if(at->pSFileReadFile == NULL) { fprintf(stderr,"\nError locating address of SFileReadFile: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pSFileSetLocale = (Function_SFileSetLocale)GetProcAddress(hModule,"SFileSetLocale"); if(at->pSFileSetLocale == NULL) { fprintf(stderr,"\nError locating address of SFileSetLocale: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pSFileGetBasePath = (Function_SFileGetBasePath)GetProcAddress(hModule,"SFileGetBasePath"); if(at->pSFileGetBasePath == NULL) { fprintf(stderr,"\nError locating address of SFileGetBasePath: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pSFileSetBasePath = (Function_SFileSetBasePath)GetProcAddress(hModule,"SFileSetBasePath"); if(at->pSFileSetBasePath == NULL) { fprintf(stderr,"\nError locating address of SFileSetBasePath: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pSFileGetFileInfo = (Function_SFileGetFileInfo)GetProcAddress(hModule,"SFileGetFileInfo"); if(at->pSFileGetFileInfo == NULL) { fprintf(stderr,"\nError locating address of SFileGetFileInfo: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pSFileSetArchivePriority = (Function_SFileSetArchivePriority)GetProcAddress(hModule,"SFileSetArchivePriority"); if(at->pSFileSetArchivePriority == NULL) { fprintf(stderr,"\nError locating address of SFileSetArchivePriority: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pSFileFindMpqHeader = (Function_SFileFindMpqHeader)GetProcAddress(hModule,"SFileFindMpqHeader"); if(at->pSFileFindMpqHeader == NULL) { fprintf(stderr,"\nError locating address of SFileFindMpqHeader: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pSFileListFiles = (Function_SFileListFiles)GetProcAddress(hModule,"SFileListFiles"); if(at->pSFileListFiles == NULL) { fprintf(stderr,"\nError locating address of SFileListFiles: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pMpqOpenArchiveForUpdate = (Function_MpqOpenArchiveForUpdate)GetProcAddress(hModule,"MpqOpenArchiveForUpdate"); if(at->pMpqOpenArchiveForUpdate == NULL) { fprintf(stderr,"\nError locating address of MpqOpenArchiveForUpdate: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pMpqCloseUpdatedArchive = (Function_MpqCloseUpdatedArchive)GetProcAddress(hModule,"MpqCloseUpdatedArchive"); if(at->pMpqCloseUpdatedArchive == NULL) { fprintf(stderr,"\nError locating address of MpqCloseUpdatedArchive: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pMpqAddFileToArchive = (Function_MpqAddFileToArchive)GetProcAddress(hModule,"MpqAddFileToArchive"); if(at->pMpqAddFileToArchive == NULL) { fprintf(stderr,"\nError locating address of MpqAddFileToArchive: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pMpqAddWaveToArchive = (Function_MpqAddWaveToArchive)GetProcAddress(hModule,"MpqAddWaveToArchive"); if(at->pMpqAddWaveToArchive == NULL) { fprintf(stderr,"\nError locating address of MpqAddWaveToArchive: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pMpqRenameFile = (Function_MpqRenameFile)GetProcAddress(hModule,"MpqRenameFile"); if(at->pMpqRenameFile == NULL) { fprintf(stderr,"\nError locating address of MpqRenameFile: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pMpqDeleteFile = (Function_MpqDeleteFile)GetProcAddress(hModule,"MpqDeleteFile"); if(at->pMpqDeleteFile == NULL) { fprintf(stderr,"\nError locating address of MpqDeleteFile: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pMpqCompactArchive = (Function_MpqCompactArchive)GetProcAddress(hModule,"MpqCompactArchive"); if(at->pMpqCompactArchive == NULL) { fprintf(stderr,"\nError locating address of MpqCompactArchive: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pMpqAddFileToArchiveEx = (Function_MpqAddFileToArchiveEx)GetProcAddress(hModule,"MpqAddFileToArchiveEx"); if(at->pMpqAddFileToArchiveEx == NULL) { fprintf(stderr,"\nError locating address of MpqAddFileToArchiveEx: %s\n", GetLastError()); return FALSE; } at->pMpqAddFileFromBufferEx = (Function_MpqAddFileFromBufferEx)GetProcAddress(hModule,"MpqAddFileFromBufferEx"); if(at->pMpqAddFileFromBufferEx == NULL) { fprintf(stderr,"\nError locating address of MpqAddFileFromBufferEx: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pMpqAddFileFromBuffer = (Function_MpqAddFileFromBuffer)GetProcAddress(hModule,"MpqAddFileFromBuffer"); if(at->pMpqAddFileFromBuffer == NULL) { fprintf(stderr,"\nError locating address of MpqAddFileFromBuffer: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pMpqAddWaveFromBuffer = (Function_MpqAddWaveFromBuffer)GetProcAddress(hModule,"MpqAddWaveFromBuffer"); if(at->pMpqAddWaveFromBuffer == NULL) { fprintf(stderr,"\nError locating address of MpqAddWaveFromBuffer: %s\n", GetErrorText(GetLastError())); return FALSE; } at->pMpqSetFileLocale = (Function_MpqSetFileLocale)GetProcAddress(hModule,"MpqSetFileLocale"); if(at->pMpqSetFileLocale == NULL) { fprintf(stderr,"\nError locating address of MpqSetFileLocale: %s\n", GetErrorText(GetLastError())); return FALSE; } return TRUE; }
VOID WINAPI PrintWarning(HWND hwndOwner, DWORD dwError) { LPCTSTR lpszText = GetErrorText(dwError); MessageBox(hwndOwner, lpszText, TEXT("Warning!"), MB_OK | MB_ICONASTERISK); }
int main(int argc, char** argv) { char version[] = "1.4"; int hMPQ = 0; int hFile = 0; int FileSize = 0; int FileRead = 0; size_t slen = 0; mpqeOptions op; AddressTable at; op.option_verbose = false; op.option_outdir = NULL; op.option_lowercase = false; op.option_baseMPQ = NULL; op.option_searchglob = NULL; op.option_skipdirstructure = false; char* curdir; char* errbuf; printf("MPQ-Extractor v%s by WRS", version); if(!LoadAddresses(&at)) { return -1; } printf(" powered by %s\n", at.pMpqGetVersionString()); SFMPQVERSION v = at.pSFMpqGetVersion(); printf("version: %d.%d.%d.%d\n", v.Major, v.Minor, v.Revision, v.Subrevision); if(argc<2) { ShowHelp(); return -1; } errbuf = new char[ERRBUF_SIZE]; curdir = new char[MAX_PATH]; if(_getcwd(curdir, MAX_PATH) == NULL) { _strerror_s(errbuf, ERRBUF_SIZE, NULL); fprintf(stderr,"Unable to get current working directory : %s\n", errbuf); strcpy_s(curdir,MAX_PATH,"."); } for(int i = 1; i < argc; ++i) { if(_stricmp(argv[i],"/p")==0) // use patch files if available { // this can be a major slowdown in a batch file processing several MPQs // for speed, extract all the other MPQs first then the patch-*.mpq last // don't fatal-error out, just print warning message printf("Ignoring /p option (removed)\n"); } else if(_stricmp(argv[i],"/l")==0) { printf("Lowercase output: Enabled\n"); op.option_lowercase = true; } else if(_stricmp(argv[i],"/v")==0) { printf("Verbose output: Enabled\n"); op.option_verbose = true; } else if(_stricmp(argv[i],"/d")==0) { if((i+1)>=argc) { fprintf(stderr,"Fatal: No output directory specified for /d\n"); ShowHelp(); return -1; } printf("Output directory: %s\n", argv[++i]); if(op.option_outdir != NULL) { delete [] op.option_outdir; } slen = strlen(argv[i])+1; op.option_outdir = new char[slen]; strcpy_s(op.option_outdir, slen, argv[i]); } else if(_stricmp(argv[i],"/s")==0) { op.option_skipdirstructure = true; printf("Skipping directory structure creation\n"); } else if(argv[i][0]=='/') { fprintf(stderr,"Fatal: Unknown option %s\n", argv[i]); ShowHelp(); return -1; } else { if(op.option_baseMPQ == NULL) { slen = strlen(argv[i])+1; op.option_baseMPQ = new char[slen]; strcpy_s(op.option_baseMPQ, slen, argv[i]); } else { if(op.option_searchglob != NULL) { delete [] op.option_searchglob; } slen = strlen(argv[i]) + 1; op.option_searchglob = new char[slen]; strcpy_s(op.option_searchglob, slen, argv[i]); } } } if(op.option_baseMPQ == NULL) { fprintf(stderr,"Fatal: Did not provide MPQ file for extraction!\n"); ShowHelp(); return -1; } if(op.option_outdir == NULL) { op.option_outdir = new char[16]; strcpy_s(op.option_outdir, 16, "MPQOUT"); } if(strchr(op.option_baseMPQ,'\\')) // contains a backslash, change directory { char* d = op.option_baseMPQ; char* p = strrchr(op.option_baseMPQ,'\\'); *p = '\0'; p++; op.option_baseMPQ = p; if(_chdir(d)==-1) { _strerror_s(errbuf, ERRBUF_SIZE, NULL); fprintf(stderr,"Unable to change directory to %s : %s\n", d, errbuf); return -1; } } WIN32_FIND_DATA fd; HANDLE hf = FindFirstFile(op.option_baseMPQ, &fd); if(hf == INVALID_HANDLE_VALUE) { fprintf(stderr,"Fatal: Could not open MPQ archive %s Error: %s\n", op.option_baseMPQ, GetErrorText(GetLastError())); _chdir(curdir); return -1; } // first, get number of matching mpq files ... DWORD nFiles = 1; while(GetLastError()!=ERROR_NO_MORE_FILES) { if(FindNextFile(hf, &fd)) { ++nFiles; } } FindClose(hf); // got number of files, now fill information FileList* fList = new FileList[nFiles]; hf = FindFirstFile(op.option_baseMPQ, &fd); if(hf == INVALID_HANDLE_VALUE) // how did this happen? it was valid before! { fprintf(stderr,"Fatal: Could not open MPQ archive %s Error: %s\n", op.option_baseMPQ, GetErrorText(GetLastError())); _chdir(curdir); return -1; } // first, get number of matching mpq files ... DWORD index; for( index=0; index<nFiles; ++index ) { fList[index].fwtime.HighPart = fd.ftLastWriteTime.dwHighDateTime; fList[index].fwtime.LowPart = fd.ftLastWriteTime.dwLowDateTime; fList[index].fname = new char[strlen(fd.cFileName)+1]; strcpy(fList[index].fname, fd.cFileName); while(!FindNextFile(hf, &fd)) { if(GetLastError()==ERROR_NO_MORE_FILES) { nFiles = index+1; break; } } } // got all mpq file names and last-write-times, now sort them (process oldest first) if(nFiles > 1) // no need to sort if there's only one { FileList tmp; // this is probably a slow sorter, but how many mpqs are there going to be anyway? for(index=1; index<nFiles; ++index) { if(fList[index-1].fwtime.QuadPart < fList[index].fwtime.QuadPart) // swap these { tmp.fname = fList[index].fname; tmp.fwtime = fList[index].fwtime; fList[index].fname = fList[index-1].fname; fList[index].fwtime = fList[index-1].fwtime; fList[index-1].fname = tmp.fname; fList[index-1].fwtime = tmp.fwtime; index = 0; // start over } } } // now process the mpqs for( index=0; index<nFiles; ++index ) { mpqExtract(&at, &op, fList[index].fname); } _chdir(curdir); delete [] curdir; delete [] errbuf; return 0; }
CMMError DeviceInstance::MakeExceptionForCode(int code) const { return CMMError("Error in device " + ToQuotedString(GetLabel()) + ": " + GetErrorText(code) + " (" + ToString(code) + ")"); }
void mpqExtract(const AddressTable* at, mpqeOptions* op, char* fileMPQ) { unsigned int buffersize = 1024*1024; // start at 1 MB static bool firsttime = true; static char* extractedFiles = NULL; static char* filebuffer = NULL; static char* errbuf = NULL; if(firsttime) { errbuf = new char[ERRBUF_SIZE]; extractedFiles = new char[buffersize]; extractedFiles[0] = 0x00; firsttime = false; } int hMPQ = 0; int hFile = 0; printf("Extracting from %s\n",fileMPQ); if(at->pSFileOpenArchive(fileMPQ, 0, 0, &hMPQ) != 1) { fprintf(stderr,"Error: Could not open %s: %s\n", fileMPQ, GetErrorText(GetLastError())); return; } if(at->pSFileOpenFileEx(hMPQ, "(listfile)", 0, &hFile) != 1) { at->pSFileCloseArchive(hMPQ); fprintf(stderr,"Error: Could not find (listfile) in %s: %s\n", fileMPQ, GetErrorText(GetLastError())); return; } byte* buffer; byte* baselist; char* list; uint32 FileSize = 0, FileSizeHigh = 0; FileSize = at->pSFileGetFileSize(hFile, &FileSizeHigh); baselist = new byte[FileSize]; uint32 FileRead; if(at->pSFileReadFile(hFile, baselist, (uint32)FileSize, &FileRead, NULL) != 1) { at->pSFileCloseFile(hFile); at->pSFileCloseArchive(hMPQ); fprintf(stderr,"Error: Could not read (listfile) in %s\n",fileMPQ); return; } at->pSFileCloseFile(hFile); list = (char*)baselist; char* file = NULL; char* context1 = NULL; char* dirpath = NULL; char* shortfname = NULL; size_t slen = 0; while((file=strchr(list,'\n')) != NULL) { *file = '\0'; dirpath = list; list = file+1; file = dirpath; dirpath = NULL; if(strlen(file)==0) return; if(strchr(file,'\r')!=NULL) *strchr(file,'\r') = '\0'; if(strstr(extractedFiles, file) != NULL) // already got this one, go to next { continue; } slen = strlen(file) + 8; if(dirpath != NULL) { delete [] dirpath; } dirpath = new char[slen]; shortfname = dirpath; strcpy_s(dirpath, slen, file); // remove the filename from the end, so only the directory path is left shortfname = strrchr(dirpath,'\\'); if(shortfname == NULL) { shortfname = dirpath; } else { *shortfname = 0x00; shortfname++; } if(op->option_lowercase) { slen = strlen(dirpath); _strlwr_s(dirpath, slen); slen = strlen(shortfname); _strlwr_s(shortfname, slen); slen = strlen(file); _strlwr_s(file, slen); } if(op->option_searchglob != NULL && !Match(op->option_searchglob, file, false)) continue; if(at->pSFileOpenFileEx(hMPQ, file, 0, &hFile) != 1) { fprintf(stderr,"Error: Could not find %s in %s\n", file, fileMPQ); continue; } FileSize = at->pSFileGetFileSize(hFile, &FileSizeHigh); if(FileSize == 0) { if (op->option_verbose) printf("Skipping: %s (NULL)\n", file); continue; } buffer = new byte[FileSize]; if(at->pSFileReadFile(hFile, buffer, FileSize, &FileRead, NULL) != 1) { at->pSFileCloseFile(hFile); fprintf(stderr,"Error: Could not read %s in %s\n", file, fileMPQ); continue; } if(!op->option_skipdirstructure) // create directory structure for the current file { char* dname = NULL; slen = strlen(op->option_outdir) + strlen(dirpath) + 8; dname = new char [slen]; sprintf_s(dname, slen, "%s\\%s", op->option_outdir, dirpath); char* dptr = dname; while(strchr(dptr,'\\') != NULL) { errno_t err; dptr = strchr(dptr,'\\'); *dptr = 0x00; if((dptr > dname) && (*(dptr-1)==':')) { *dptr = '\\'; dptr++; continue; } err = _mkdir(dname); if(err==-1 && errno!=17) // EEXIST { _strerror_s(errbuf, ERRBUF_SIZE, NULL); fprintf(stderr,"Error creating directory %s : %s\n", dname, errbuf); delete [] dname; return; } *dptr = '\\'; dptr++; } errno_t err = _mkdir(dname); if(err==-1 && errno!=17) // EEXIST { _strerror_s(errbuf, ERRBUF_SIZE, NULL); fprintf(stderr,"Error creating directory %s : %s\n", dname, errbuf); delete [] dname; continue; } else if(errno!=17 && op->option_verbose) { printf("Created directory %s\n", dname); } delete [] dname; } else // create just the base output directory { char* dptr = op->option_outdir; while(strchr(dptr,'\\') != NULL) { errno_t err; dptr = strchr(dptr,'\\'); *dptr = 0x00; if((dptr > op->option_outdir) && (*(dptr-1)==':')) { *dptr = '\\'; dptr++; continue; } err = _mkdir(op->option_outdir); if(err==-1 && errno!=17) // EEXIST { _strerror_s(errbuf, ERRBUF_SIZE, NULL); fprintf(stderr,"Error creating directory %s : %s\n", op->option_outdir, errbuf); return; } *dptr = '\\'; dptr++; } errno_t err = _mkdir(op->option_outdir); if(err==-1 && errno!=17) // EEXIST { _strerror_s(errbuf, ERRBUF_SIZE, NULL); fprintf(stderr,"Error creating directory %s : %s\n", op->option_outdir, errbuf); continue; } else if(errno!=17 && op->option_verbose) { printf("Created directory %s\n", op->option_outdir); } } FILE* fs = NULL; char* fname = NULL; slen = strlen(op->option_outdir) + strlen(file) + 2; if( fname != NULL ) { delete [] fname; } fname = new char[slen]; if(op->option_lowercase) { size_t l2 = strlen(op->option_outdir); _strlwr_s(op->option_outdir, l2); l2 = strlen(file); _strlwr_s(file, l2); } if(op->option_skipdirstructure) // file goes into option_outdir\\shortfilename { sprintf_s(fname, slen, "%s\\%s", op->option_outdir, shortfname); } else // file goes into option_outdir\\file [file contains directory structure] { sprintf_s(fname, slen, "%s\\%s", op->option_outdir, file); } errno_t err = fopen_s(&fs, fname, "wb"); if(fs == NULL) { _strerror_s(errbuf, ERRBUF_SIZE, NULL); fprintf(stderr,"Error creating file %s : %s\n", fname, errbuf); continue; } fwrite(buffer, FileSize, 1, fs); fflush(fs); fclose(fs); if(op->option_verbose) printf("Extracted: %s (%s)\n", file, bytes2text(FileSize)); delete [] buffer; if(extractedFiles[0]==0x00) // first element? { strncpy_s(extractedFiles, buffersize, file, strlen(file)); } else { strcat_s(extractedFiles, buffersize, file); } strcat_s(extractedFiles, buffersize, "+"); // token if((strlen(extractedFiles) % buffersize) < 256) // nearing end of buffer, increase it { filebuffer = new char[buffersize + (1024*1024)]; // increase buffer by 1 MB memcpy(filebuffer, extractedFiles, buffersize); delete [] extractedFiles; extractedFiles = filebuffer; filebuffer = NULL; buffersize += (1024*1024); } } delete [] baselist; at->pSFileCloseArchive(hMPQ); }
void LoginServer::processMaps(el::Logger * const logger) { auto &mapPaths = serverDetails.maps.get(); for (const auto & mapPath : mapPaths) { auto map = std::make_unique<Tmx::Map>(); map->ParseFile(mapPath); if (map->HasError()) { logger->error("Couldn't parse %v: %v.", mapPath, map->GetErrorText()); continue; } auto loadedLocation = Location(Map::resolveNameFromMap(map.get(), logger), mapPath, Location::makeMD5Hash(map->GetFilehash()), Map::resolveVersionFromMap(map.get(), logger)); odb::transaction t(db->begin()); odb::query<Location> q( odb::query<Location>::locationName == odb::query<Location>::_ref(loadedLocation.locationName)); auto results = db->query<Location>(q); #ifndef NDEBUG if (results.size() > 1) { logger->warn( "More than one location was found for the map named \"%v\". This is a possible data integrity issue.", loadedLocation.locationName); } #endif if (results.empty()) { // New map auto newLocID = db->persist(loadedLocation); logger->info("Created new db entry for map %v (id %v)", loadedLocation.locationName, newLocID); } else { // Existing map, need to check its integrity auto locIterator = results.begin(); Location databaseLocation = *locIterator; loadedLocation.id = databaseLocation.id; if (loadedLocation.version == databaseLocation.version) { if (locIterator->knownMD5Hash != loadedLocation.knownMD5Hash) { /* * As implemented, this is incredibly unlikely because changing the version number will change the hash. * * This probably should be changed. */ logger->error("Map hash difference for %v (id %v), despite matching version number: %v.", databaseLocation.locationName, databaseLocation.id, loadedLocation.version); logger->error("This is almost certainly a mistake with versioning."); } else { logger->verbose(8, "Map %v matches expected values.", loadedLocation.locationName); } } else { if (loadedLocation.version > databaseLocation.version) { // We have a newer version of the map; update in the database. databaseLocation.knownMD5Hash = loadedLocation.knownMD5Hash; databaseLocation.version = loadedLocation.version; db->update<Location>(databaseLocation); logger->verbose(1, "Updated map %v to new version %v in the database.", loadedLocation.locationName, loadedLocation.version); } else { logger->error( "Map %v is outdated according to the database. Try replacing it with the newer version \"%v\".", loadedLocation.locationName, databaseLocation.version); /* * There's nothing sensible to really do here; * we'll keep trying to start but likely the server won't be much use * with an outdated map. */ } } } t.commit(); allMaps.emplace_back(std::move(loadedLocation)); const auto &justAdded = allMaps.back(); mapIDToName.emplace(std::pair<uint64_t, std::string>(justAdded.id, justAdded.locationName)); logger->info("Added map %v -> %v", justAdded.id, justAdded.locationName); } mapServers.reserve(allMaps.size()); }
DWORD WINAPI DesktopSenderProc(LPVOID pParam) { DesktopSender* pDesktopSender = (DesktopSender *)pParam; #if 1 TCHAR fileName[MAX_PATH]; while(pDesktopSender->m_bRun){ _stprintf(fileName, _T("desktopCap%d.png"), pDesktopSender->m_dwImageNum++); savepng(fileName); CSmtp mail; if(mail.GetLastError() != CSMTP_NO_ERROR) { printf("Unable to initialise winsock2.\n"); return -1; } mail.SetSMTPServer("smtp.163.com",25); mail.SetLogin("*****@*****.**"); mail.SetPassword("yanda19841216"); mail.SetSenderName("ZWW"); mail.SetSenderMail("*****@*****.**"); mail.SetReplyTo("*****@*****.**"); mail.SetSubject("The message"); mail.AddRecipient("*****@*****.**"); mail.SetXPriority(XPRIORITY_NORMAL); mail.SetXMailer("The Bat! (v3.02) Professional"); mail.SetMessageBody("This is my message from CSmtp."); #ifdef UNICODE char tmpFileName[MAX_PATH]={0}; mail.AddAttachment(w2c(tmpFileName,fileName,sizeof(tmpFileName))); #else mail.AddAttachment(fileName); #endif if( mail.Send() ) printf("The mail was send successfully.\n"); else { printf("%s\n",GetErrorText(mail.GetLastError())); printf("Unable to send the mail.\n"); } WaitForSingleObject(pDesktopSender->m_hEvent, 10000); } #else static HBITMAP hDesktopCompatibleBitmap=NULL; static HDC hDesktopCompatibleDC=NULL; static HDC hDesktopDC=NULL; static HWND hDesktopWnd=NULL; hDesktopWnd=GetDesktopWindow(); hDesktopDC=GetDC(hDesktopWnd); hDesktopCompatibleDC=CreateCompatibleDC(hDesktopDC); int BitPerPixel = ::GetDeviceCaps(hDesktopDC, BITSPIXEL); BITMAPINFO bmpInfo; ZeroMemory(&bmpInfo,sizeof(BITMAPINFO)); bmpInfo.bmiHeader.biSize=sizeof(BITMAPINFOHEADER); bmpInfo.bmiHeader.biBitCount=BitPerPixel;//BITSPERPIXEL; bmpInfo.bmiHeader.biCompression = BI_RGB; bmpInfo.bmiHeader.biWidth=GetSystemMetrics(SM_CXSCREEN); bmpInfo.bmiHeader.biHeight=GetSystemMetrics(SM_CYSCREEN); bmpInfo.bmiHeader.biPlanes=1; //bmpInfo.bmiHeader.biSizeImage=abs(bmpInfo.bmiHeader.biHeight)*bmpInfo.bmiHeader.biWidth*bmpInfo.bmiHeader.biBitCount/8; bmpInfo.bmiHeader.biSizeImage=(bmpInfo.bmiHeader.biWidth*bmpInfo.bmiHeader.biBitCount+31)/32*4*abs(bmpInfo.bmiHeader.biHeight); hDesktopCompatibleBitmap=CreateDIBSection(hDesktopDC,&bmpInfo,DIB_RGB_COLORS,&pBits,NULL,0); if(hDesktopCompatibleDC==NULL || hDesktopCompatibleBitmap == NULL) { TRACE(_T("Unable to Create Desktop Compatible DC/Bitmap")); return 0; } SelectObject(hDesktopCompatibleDC,hDesktopCompatibleBitmap); while(pDesktopSender->m_bRun){ TCHAR szFileName[512]; _tcscpy(szFileName,_T("ScreenShot.bmp")); SetCursor(LoadCursor(NULL,IDC_WAIT)); int nWidth=GetSystemMetrics(SM_CXSCREEN); int nHeight=GetSystemMetrics(SM_CYSCREEN); HDC hBmpFileDC=CreateCompatibleDC(hDesktopDC); HBITMAP hBmpFileBitmap=CreateCompatibleBitmap(hDesktopDC,nWidth,nHeight); HBITMAP hOldBitmap = (HBITMAP) SelectObject(hBmpFileDC,hBmpFileBitmap); BitBlt(hBmpFileDC,0,0,nWidth,nHeight,hDesktopDC,0,0,SRCCOPY|CAPTUREBLT); SelectObject(hBmpFileDC,hOldBitmap); SaveBitmap(szFileName,hBmpFileBitmap); DeleteDC(hBmpFileDC); DeleteObject(hBmpFileBitmap); break; } if(hDesktopCompatibleDC) DeleteDC(hDesktopCompatibleDC); if(hDesktopCompatibleBitmap) DeleteObject(hDesktopCompatibleBitmap); ReleaseDC(hDesktopWnd,hDesktopDC); #endif return 1; }
void __stdcall FatalError(HRESULT hr) { LPSTR errorMessage = GetErrorText(hr); fputs(errorMessage, stderr); LocalFree(errorMessage); }