spbranch.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  1. // spbranch.cpp : 定义应用程序的入口点。
  2. //
  3. #include "stdafx.h"
  4. #include "spbranch.h"
  5. #define EXCEPTION_INSUFFICE_RESOURCE ((DWORD )0x00000001L)
  6. #define INSERT_CONTEXT
  7. CHAR g_szDevName[MAX_PATH] = {0};
  8. //HANDLE g_hHeap;
  9. BYTE* g_pbtRequest;
  10. BYTE* g_pbtReply;
  11. DWORD g_dwEceptionCode;
  12. CSpBranch gSpBranch;
  13. PTOP_LEVEL_EXCEPTION_FILTER pfnUnhandledExceptionFilterPrev;
  14. DWORD GetAnswerToRequest(LPBYTE, DWORD, LPBYTE);
  15. DWORD SetExceptionCodeToReply(LPBYTE);
  16. void CustomExitProcess(UINT uExitCode);
  17. void CleanupProcess();
  18. ErrorCodeEnum GetAdapterLastErr(LPCTSTR, ErrorCodeEnum);
  19. LONG WINAPI CustomUnhandleExceptionFilter(PEXCEPTION_POINTERS);
  20. void ShowProcessIntegrityLevel(int*);
  21. int GetCurrentRunPath(char *pPath);
  22. int GetCurrentRVCPath(char *pPath);
  23. // ErrorMessage support function.
  24. // Retrieves the system error message for the GetLastError() code.
  25. // Note: caller must use LocalFree() on the returned LPCTSTR buffer.
  26. LPCTSTR ErrorMessage(DWORD error)
  27. {
  28. LPVOID lpMsgBuf;
  29. FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
  30. | FORMAT_MESSAGE_FROM_SYSTEM
  31. | FORMAT_MESSAGE_IGNORE_INSERTS,
  32. NULL,
  33. error,
  34. MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
  35. (LPTSTR) &lpMsgBuf,
  36. 0,
  37. NULL);
  38. return((LPCTSTR)lpMsgBuf);
  39. }
  40. LPCTSTR CmdTypeToString(CMDType type)
  41. {
  42. switch(type)
  43. {
  44. case BRCMD_START: return "BRCMD_START";
  45. break;
  46. case BRCMD_GETSTATE: return "BRCMD_GETSTATE";
  47. break;
  48. case BRCMD_OPENDEV: return "BRCMD_OPENDEV";
  49. break;
  50. case BRCMD_CLOSEDEV: return "BRCMD_CLOSEDEV";
  51. break;
  52. case BRCMD_GETERROR: return "BRCMD_GETERROR";
  53. break;
  54. case BRCMD_SENDCMD: return "BRCMD_SENDCMD";
  55. break;
  56. case BRCMD_GETDEVINFO: return "BRCMD_GETDEVINFO";
  57. break;
  58. case BRCMD_END:
  59. default:
  60. return "BRCMD_END";
  61. break;
  62. }
  63. return "BRCMD_END";
  64. }
  65. LPCTSTR DevStateToString(DevThreadState state)
  66. {
  67. switch(state)
  68. {
  69. case State_NoInit: return "State_NoInit";
  70. break;
  71. case State_Invalid: return "State_Invalid";
  72. break;
  73. case State_LoadFailed: return "State_LoadFailed";
  74. break;
  75. case State_LoadSucc: return "State_LoadSucc";
  76. break;
  77. case State_OpenFailed: return "State_OpenFailed";
  78. break;
  79. case State_Opened: return "State_Opened";
  80. break;
  81. case State_Idle: return "State_Idle";
  82. break;
  83. case State_Busy: return "State_Busy";
  84. break;
  85. case State_Max:
  86. default:
  87. return "State_Max";
  88. break;
  89. }
  90. return "State_Max";
  91. }
  92. void FormatError(LPCTSTR fmt, ...)
  93. {
  94. va_list arg;
  95. va_start(arg, fmt);
  96. int n = _vscprintf(fmt, arg);
  97. if(n > 0)
  98. {
  99. CHAR tmpMsg[MAX_PRINTF_MSG_LEN] = {0};
  100. vsprintf_s(tmpMsg, MAX_PRINTF_MSG_LEN, fmt, arg);
  101. #ifdef INSERT_CONTEXT
  102. if(strlen(g_szDevName) <= 0)
  103. {
  104. CHAR szProcess[12] = {0};
  105. sprintf_s(szProcess, "%d", GetCurrentProcessId());
  106. WRITE_ERROR_PARAM("[%12s] %s", szProcess, tmpMsg);
  107. }
  108. else
  109. {
  110. WRITE_ERROR_PARAM("[%12s] %s", g_szDevName, tmpMsg);
  111. }
  112. #else
  113. WRITE_ERROR_PARAM("%s", tmpMsg);
  114. #endif // INSERT_CONTEXT
  115. }
  116. va_end(arg);
  117. }
  118. void FormatInfo(LPCTSTR fmt, ...)
  119. {
  120. va_list arg;
  121. va_start(arg, fmt);
  122. int n = _vscprintf(fmt, arg);
  123. if(n > 0)
  124. {
  125. CHAR tmpMsg[MAX_PRINTF_MSG_LEN] = {0};
  126. vsprintf_s(tmpMsg, MAX_PRINTF_MSG_LEN, fmt, arg);
  127. #ifdef INSERT_CONTEXT
  128. if(strlen(g_szDevName) <= 0)
  129. {
  130. CHAR szProcess[12] = {0};
  131. sprintf_s(szProcess, "%d", GetCurrentProcessId());
  132. WRITE_INFO_PARAM("[%12s] %s", szProcess, tmpMsg);
  133. }
  134. else
  135. {
  136. WRITE_INFO_PARAM("[%12s] %s", g_szDevName, tmpMsg);
  137. }
  138. #else
  139. WRITE_INFO_PARAM("%s", tmpMsg);
  140. #endif // INSERT_CONTEXT
  141. }
  142. va_end(arg);
  143. }
  144. void PrintError(LPCTSTR errDesc, BOOL bGetLastError)
  145. {
  146. if(bGetLastError)
  147. {
  148. DWORD dwErrCode = GetLastError();
  149. LPCTSTR errMsg = ErrorMessage(dwErrCode);
  150. #ifdef INSERT_CONTEXT
  151. if(strlen(g_szDevName) <= 0)
  152. {
  153. CHAR szProcess[12] = {0};
  154. sprintf_s(szProcess, "%d", GetCurrentProcessId());
  155. WRITE_ERROR_PARAM(TEXT("[%12s] %s: %s(%d)."), szProcess, errDesc, errMsg, dwErrCode);
  156. }
  157. else
  158. {
  159. WRITE_ERROR_PARAM(TEXT("[%12s] %s: %s(%d)."), g_szDevName, errDesc, errMsg, dwErrCode);
  160. }
  161. #else
  162. WRITE_ERROR_PARAM(TEXT("%s: %s(%d)."), errDesc, errMsg, dwErrCode);
  163. #endif // INSERT_CONTEXT
  164. LocalFree((LPVOID)errMsg);
  165. return;
  166. }
  167. #ifdef INSERT_CONTEXT
  168. if(strlen(g_szDevName) <= 0)
  169. {
  170. CHAR szProcess[12] = {0};
  171. sprintf_s(szProcess, "%d", GetCurrentProcessId());
  172. WRITE_ERROR_PARAM(TEXT("[%12s] %s"), szProcess, errDesc);
  173. }
  174. else
  175. {
  176. WRITE_ERROR_PARAM(TEXT("[%12s] %s"), g_szDevName, errDesc);
  177. }
  178. #else
  179. WRITE_ERROR_PARAM(TEXT("%s"), errDesc);
  180. #endif // INSERT_CONTEXT
  181. }
  182. void PrintInfo(LPCTSTR inforDesc)
  183. {
  184. #ifdef INSERT_CONTEXT
  185. if(strlen(g_szDevName) <= 0)
  186. {
  187. CHAR szProcess[12] = {0};
  188. sprintf_s(szProcess, "%d", GetCurrentProcessId());
  189. WRITE_INFO_PARAM(TEXT("[%12s] %s"), szProcess, inforDesc);
  190. }
  191. else
  192. {
  193. WRITE_INFO_PARAM(TEXT("[%12s] %s"), g_szDevName, inforDesc);
  194. }
  195. #else
  196. WRITE_INFO_PARAM(TEXT("%s"), inforDesc);
  197. #endif // INSERT_CONTEXT
  198. }
  199. LONG FilterException(PEXCEPTION_POINTERS pep)
  200. {
  201. // Assume we recognize this exception and then Gobal unwind
  202. LONG lDisposition = EXCEPTION_EXECUTE_HANDLER;
  203. DWORD dwCode = pep->ExceptionRecord->ExceptionCode;
  204. g_dwEceptionCode = dwCode;
  205. FormatError("ExceptionCode: 0x%08x(%d).", dwCode, dwCode);
  206. switch (dwCode)
  207. {
  208. case EXCEPTION_ACCESS_VIOLATION:
  209. PrintError("EXCEPTION_ACCESS_VIOLATION", FALSE);
  210. break;
  211. case EXCEPTION_STACK_OVERFLOW:
  212. PrintError("EXCEPTION_STACK_OVERFLOW", FALSE);
  213. break;
  214. case EXCEPTION_INVALID_HANDLE:
  215. PrintError("EXCEPTION_INVALID_HANDLE", FALSE);
  216. break;
  217. default:
  218. // We don't recognize this exception
  219. lDisposition = EXCEPTION_CONTINUE_SEARCH;
  220. break;
  221. }
  222. // temporary --Josephus at 18:01:15 201726
  223. //lDisposition = EXCEPTION_CONTINUE_SEARCH;
  224. return (lDisposition);
  225. }
  226. void InitLogger(LPCTSTR lpszDbgPath/* = NULL*/)
  227. {
  228. //log initialize.
  229. char szLogPath[MAX_PATH] = {0};
  230. if(lpszDbgPath == NULL)
  231. {
  232. // -Josephus@201773 17:16:07
  233. if(GetCurrentRVCPath(szLogPath) < 0)
  234. {
  235. GET_LOGGER()->SetWriteAbleLevel(LEVEL_NONE_WRITEABLE);
  236. //PWSTR pszPath = NULL;
  237. //if(SHGetKnownFolderPath(FOLDERID_LocalAppDataLow, 0, NULL, &pszPath) != S_OK)
  238. //{
  239. // GET_LOGGER()->SetWriteAbleLevel(LEVEL_NONE_WRITEABLE);
  240. //}
  241. //else
  242. //{
  243. // WideCharToMultiByte(CP_ACP, 0, pszPath, -1, szLogPath, MAX_PATH, NULL, NULL);
  244. // CoTaskMemFree((LPVOID)pszPath);
  245. // strcat_s(szLogPath, MAX_PATH, "\\SpBranch");
  246. //}
  247. }
  248. else
  249. {
  250. strcat_s(szLogPath, MAX_PATH, "dbg\\SpBranch");
  251. // Check for existence and have write permssion or not.
  252. if( (_access(szLogPath, 0 )) == -1 || (_access(szLogPath, 2 )) == -1)
  253. {
  254. GET_LOGGER()->SetWriteAbleLevel(LEVEL_NONE_WRITEABLE);
  255. }
  256. else
  257. {
  258. GET_LOGGER()->SetFileWriteMode(Day_Seperated_Mode, (LPCTSTR)szLogPath);
  259. }
  260. }
  261. }
  262. else
  263. {
  264. strcpy_s(szLogPath, lpszDbgPath);
  265. // Check for existence and have write permssion or not.
  266. if( (_access(szLogPath, 0 )) == -1 || (_access(szLogPath, 2 )) == -1)
  267. {
  268. GET_LOGGER()->SetWriteAbleLevel(LEVEL_NONE_WRITEABLE);
  269. }
  270. else
  271. {
  272. GET_LOGGER()->SetFileWriteMode(Day_Seperated_Mode, (LPCTSTR)szLogPath);
  273. }
  274. }
  275. //log initialize end.
  276. return;
  277. }
  278. int _tmain(int argc, _TCHAR* argv[])
  279. {
  280. if(argc < 2 || strlen(argv[1]) <= 0 || strlen(argv[2]) <= 0)
  281. {
  282. ExitProcess(1);
  283. }
  284. // Install our global unhandled exception filter when
  285. // creating the first instance of the class.
  286. pfnUnhandledExceptionFilterPrev =
  287. SetUnhandledExceptionFilter(CustomUnhandleExceptionFilter);
  288. BOOL bSuc = FALSE;
  289. HANDLE hStdin, hStdout;
  290. hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
  291. hStdin = GetStdHandle(STD_INPUT_HANDLE);
  292. memset(g_szDevName, 0, sizeof(CHAR)*MAX_PATH);
  293. strcpy_s(g_szDevName, MAX_PATH, argv[2]);
  294. if(argc == 4 && strlen(argv[3]) > 0)
  295. {
  296. InitLogger(argv[3]);
  297. }
  298. else
  299. {
  300. InitLogger();
  301. }
  302. FormatInfo(" ============ Branch device child process start!============ processId = %u",
  303. GetCurrentProcessId());
  304. int nLevel = 0;
  305. ShowProcessIntegrityLevel(&nLevel);
  306. if ((hStdout == INVALID_HANDLE_VALUE) || (hStdin == INVALID_HANDLE_VALUE))
  307. {
  308. FormatError("GetStdHandle failed, out(%d), in(%d).", hStdout, hStdin);
  309. ExitProcess(1);
  310. }
  311. char szAdapterDir[MAX_PATH] = {0};
  312. char szAdapterPath[MAX_PATH] = {0};
  313. if(GetCurrentRunPath(szAdapterDir) < 0)
  314. {
  315. FormatError("GetCurrentRunPath failed.");
  316. ExitProcess(1);
  317. }
  318. sprintf_s(szAdapterPath, MAX_PATH, "%sIMDep\\%s", szAdapterDir, argv[1]);
  319. __try
  320. {
  321. //LoadLibrary and Init Entity.
  322. PrintInfo("LoadLibrary and Init Entity.");
  323. gSpBranch.Init(szAdapterPath, argv[2]);
  324. }
  325. __finally
  326. {
  327. PrintInfo("LoadLibrary and Init Entity finished.");
  328. }
  329. //g_hHeap = GetProcessHeap();
  330. g_pbtRequest = (BYTE*)HeapAlloc(GetProcessHeap(), 0, BUFSIZE*sizeof(BYTE));
  331. g_pbtReply = (BYTE*)HeapAlloc(GetProcessHeap(), 0, BUFSIZE*sizeof(BYTE));
  332. DWORD cbBytesRead = 0, cbReplyBytes = 0, cbWritten = 0;
  333. if (g_pbtRequest == NULL || g_pbtReply == NULL)
  334. {
  335. PrintError("HeapAlloc failed for exchange buffer");
  336. CustomExitProcess(1);
  337. }
  338. ErrorCodeEnum erroCode = Error_Unexpect;
  339. PrintInfo("** This is a exchange circle start from the child process.");
  340. for (;;)
  341. {
  342. // Read from standard input and stop on error or no data.
  343. PrintInfo(">>=>>=>> Waiting for request information from server...");
  344. bSuc = ReadFile(
  345. hStdin, // handle to pipe
  346. g_pbtRequest, // buffer to receive data
  347. BUFSIZE*sizeof(BYTE), // size of buffer
  348. &cbBytesRead, // number of bytes read
  349. NULL); // not overlapped I/O
  350. if (! bSuc || cbBytesRead == 0)
  351. {
  352. if(GetLastError() == ERROR_BROKEN_PIPE)
  353. {
  354. PrintError("Client disconnected");
  355. }
  356. else
  357. {
  358. PrintError("ReadFile operation failed");
  359. }
  360. break;
  361. }
  362. __try
  363. {
  364. ZeroMemory(g_pbtReply, BUFSIZE*sizeof(BYTE));
  365. cbReplyBytes = GetAnswerToRequest(g_pbtRequest, cbBytesRead, g_pbtReply);
  366. ZeroMemory(g_pbtRequest, BUFSIZE*sizeof(BYTE));
  367. }
  368. __except(FilterException(GetExceptionInformation()))
  369. {
  370. PrintError("GetAnswerToRequest appears exception.", FALSE);
  371. cbReplyBytes = SetExceptionCodeToReply(g_pbtReply);
  372. }
  373. PrintInfo("Start to WriteFiles...");
  374. bSuc = WriteFile(
  375. hStdout, // handle to pipe
  376. g_pbtReply, // buffer to write from
  377. cbReplyBytes, // number of bytes to write
  378. &cbWritten, // number of bytes written
  379. NULL); // not overlapped I/O
  380. if (! bSuc || cbReplyBytes != cbWritten)
  381. {
  382. PrintError("WriteFile operation failed");
  383. break;
  384. }
  385. FormatInfo("WriteFile suc, had been written %d bytes.", cbWritten);
  386. }
  387. CleanupProcess();
  388. return 0;
  389. }
  390. int APIENTRY _tWinMain(HINSTANCE hInstance,
  391. HINSTANCE hPrevInstance,
  392. LPTSTR lpCmdLine,
  393. int nCmdShow)
  394. {
  395. UNREFERENCED_PARAMETER(hPrevInstance);
  396. UNREFERENCED_PARAMETER(hInstance);
  397. return _tmain(__argc, __argv);
  398. }
  399. DWORD GetAnswerToRequest( LPBYTE pbtRequest, DWORD dwRead, LPBYTE pbtReply)
  400. {
  401. CAutoBuffer rvcBuf;
  402. //For CAutoBuffer when its destoryed.
  403. BYTE* btTmp = new BYTE[BUFSIZE];
  404. if(btTmp == NULL)
  405. {
  406. SpBranch_Command_Ans ans;
  407. ans.Init();
  408. ans.dwErroCode = Error_Resource;
  409. ans.desc = "Allocate buffer for request command failed in spbranch.";
  410. FormatError("Allocate buffer for request command failed");
  411. CAutoBuffer ansBuf = SpObject2Buffer(ans);
  412. CopyMemory(pbtReply, ansBuf.GetWriteableArray(), ansBuf.GetCount());
  413. return (sizeof(BYTE)*(ansBuf.GetCount()));
  414. }
  415. ZeroMemory(btTmp, BUFSIZE);
  416. CopyMemory(btTmp, pbtRequest, dwRead);
  417. rvcBuf.Attach(btTmp, dwRead);
  418. SpBranch_Command_Req req;
  419. SpBuffer2Object(rvcBuf, req);
  420. FormatInfo("Request Information : Size#%u, CmdType: %s(%d)",
  421. dwRead, CmdTypeToString((CMDType)req.nCmdType), req.nCmdType);
  422. SpBranch_Command_Ans ans;
  423. ans.Init();
  424. ErrorCodeEnum erroCode = Error_Unexpect;
  425. DevThreadState eCurState = gSpBranch.GetDevThreadState();
  426. if(gSpBranch.GetDevThreadState() < State_LoadSucc && req.nCmdType != BRCMD_GETSTATE)
  427. {
  428. FormatError("Current dev's state is invalid: %s.", DevStateToString(eCurState));
  429. ans.nparam1 = eCurState;
  430. ans.nparam2 = gSpBranch.GetLastErrorCode();
  431. ans.dwErroCode = Error_DevLoadFileFailed;
  432. gSpBranch.GetLastErrorMsg(ans.desc);
  433. }
  434. else
  435. {
  436. switch (req.nCmdType)
  437. {
  438. case BRCMD_SENDCMD:
  439. {
  440. CSimpleStringA ssRetString;
  441. if(gSpBranch.ExecuteCmd(req.ssparam1, ssRetString))
  442. {
  443. ans.dwErroCode = Error_Succeed;
  444. ans.nparam1 = 0;
  445. ans.ssparam1 = ssRetString;
  446. char szPrintMsg[MAX_PRINTF_MSG_LEN] = {0};
  447. CovertCmdParam(szPrintMsg, (LPCTSTR)req.ssparam1);
  448. FormatInfo("[param:%s] ExecuteCmd suc.", szPrintMsg);
  449. }
  450. else
  451. {
  452. char szPrintMsg[MAX_PRINTF_MSG_LEN] = {0};
  453. CovertCmdParam(szPrintMsg, (LPCTSTR)req.ssparam1);
  454. FormatError("[param:%s] ExecuteCmd failed returned 0x%08x",
  455. szPrintMsg, gSpBranch.GetLastErrorCode());
  456. gSpBranch.GetLastOperatError(ans.dwErroCode, ans.desc);
  457. }
  458. }
  459. break;
  460. case BRCMD_GETSTATE:
  461. {
  462. ans.dwErroCode = Error_Succeed;
  463. ans.nparam1 = eCurState;
  464. FormatInfo("GetState: state#%d.", ans.nparam1);
  465. }
  466. break;
  467. case BRCMD_OPENDEV:
  468. {
  469. if(gSpBranch.OpenDevice(req.ssparam1, req.ssparam2))
  470. {
  471. ans.dwErroCode = Error_Succeed;
  472. }
  473. else
  474. {
  475. gSpBranch.GetLastOperatError(ans.dwErroCode, ans.desc);
  476. }
  477. }
  478. break;
  479. case BRCMD_CLOSEDEV:
  480. {
  481. if(gSpBranch.CloseDevice())
  482. {
  483. ans.dwErroCode = Error_Succeed;
  484. }
  485. else
  486. {
  487. gSpBranch.GetLastOperatError(ans.dwErroCode, ans.desc);
  488. }
  489. }
  490. break;
  491. case BRCMD_GETERROR:
  492. {
  493. ans.dwErroCode = Error_NoPrivilege;
  494. ans.desc = "Actually its Error_NotImpl";
  495. }
  496. break;
  497. case BRCMD_GETDEVINFO:
  498. {
  499. DevCategoryInfo info;
  500. if(gSpBranch.GetDevCategory(info))
  501. {
  502. PrintInfo("GetDevCategory suc, start to set context.");
  503. FormatInfo("szModel:%s", info.szModel);
  504. ans.ssparam2 = info.szModel;
  505. FormatInfo("szVendor:%s", info.szVendor);
  506. ans.ssparam3 = info.szVendor;
  507. ans.nparam1 = info.eState;
  508. FormatInfo("szType:%s", info.szType);
  509. ans.ssparam1 = info.szType;
  510. FormatInfo("version:%d.%d.%d.%d",
  511. info.version.wMajor, info.version.wMinor, info.version.wRevision, info.version.wBuild);
  512. ans.ssparam4 = CSimpleStringA::Format("%d.%d.%d.%d",
  513. info.version.wMajor, info.version.wMinor, info.version.wRevision, info.version.wBuild);
  514. FormatInfo("finish setting context.");
  515. ans.dwErroCode = Error_Succeed;
  516. }
  517. else
  518. {
  519. gSpBranch.GetLastOperatError(ans.dwErroCode, ans.desc);
  520. }
  521. }
  522. break;
  523. default:
  524. {
  525. ans.dwErroCode = Error_NotExist;
  526. PrintInfo("Unexpect Command Type.");
  527. ans.desc = "Unexpect Command Type";
  528. }
  529. break;
  530. }
  531. }
  532. CAutoBuffer ansBuf = SpObject2Buffer(ans);
  533. CopyMemory(pbtReply, ansBuf.GetWriteableArray(), ansBuf.GetCount());
  534. return (sizeof(BYTE)*(ansBuf.GetCount()));
  535. }
  536. void CustomExitProcess(UINT uExitCode)
  537. {
  538. CleanupProcess();
  539. FormatInfo("** The branch loaded process exitting by hand ! ProcessId = %u.",
  540. GetCurrentProcessId());
  541. ExitProcess(uExitCode);
  542. }
  543. LONG WINAPI CustomUnhandleExceptionFilter(PEXCEPTION_POINTERS pep)
  544. {
  545. // Default to trying another filter (safest thing to do)
  546. LONG lDisposition = EXCEPTION_CONTINUE_SEARCH;
  547. // If no node fixed the problem, try the previous exception filter
  548. if (lDisposition == EXCEPTION_CONTINUE_SEARCH)
  549. {
  550. CleanupProcess();
  551. lDisposition = pfnUnhandledExceptionFilterPrev(pep);
  552. }
  553. return(lDisposition);
  554. }
  555. void CleanupProcess()
  556. {
  557. if (g_pbtRequest != NULL)
  558. {
  559. HeapFree(GetProcessHeap(), 0, g_pbtRequest);
  560. g_pbtRequest = NULL;
  561. }
  562. if(g_pbtReply != NULL)
  563. {
  564. HeapFree(GetProcessHeap(), 0, g_pbtReply);
  565. g_pbtReply = NULL;
  566. }
  567. }
  568. DWORD SetExceptionCodeToReply(LPBYTE pbtReply)
  569. {
  570. SpBranch_Command_Ans ans;
  571. ans.Init();
  572. ans.nparam1 = (int)(g_dwEceptionCode & 0x0000FFFF);
  573. ans.nparam2 = (int)((g_dwEceptionCode & 0xFFFF0000) >> 16);
  574. ans.dwErroCode = Error_Exception;
  575. ans.desc = "Current operation occurs exception.";
  576. CAutoBuffer ansBuf = SpObject2Buffer(ans);
  577. CopyMemory(pbtReply, ansBuf.GetWriteableArray(), ansBuf.GetCount());
  578. return (sizeof(BYTE)*(ansBuf.GetCount()));
  579. }
  580. void ShowProcessIntegrityLevel(int* pIntegrityLevel)
  581. {
  582. HANDLE hToken;
  583. HANDLE hProcess;
  584. DWORD dwLengthNeeded;
  585. DWORD dwError = ERROR_SUCCESS;
  586. PTOKEN_MANDATORY_LABEL pTIL = NULL;
  587. LPWSTR pStringSid;
  588. DWORD dwIntegrityLevel;
  589. hProcess = GetCurrentProcess();
  590. if (OpenProcessToken(hProcess, TOKEN_QUERY |
  591. TOKEN_QUERY_SOURCE, &hToken))
  592. {
  593. // Get the Integrity level.
  594. if (!GetTokenInformation(hToken, TokenIntegrityLevel,
  595. NULL, 0, &dwLengthNeeded))
  596. {
  597. dwError = GetLastError();
  598. if (dwError == ERROR_INSUFFICIENT_BUFFER)
  599. {
  600. pTIL = (PTOKEN_MANDATORY_LABEL)LocalAlloc(0,
  601. dwLengthNeeded);
  602. if (pTIL != NULL)
  603. {
  604. if (GetTokenInformation(hToken, TokenIntegrityLevel,
  605. pTIL, dwLengthNeeded, &dwLengthNeeded))
  606. {
  607. dwIntegrityLevel = *GetSidSubAuthority(pTIL->Label.Sid,
  608. (DWORD)(UCHAR)(*GetSidSubAuthorityCount(pTIL->Label.Sid)-1));
  609. if (dwIntegrityLevel < SECURITY_MANDATORY_MEDIUM_RID)
  610. {
  611. // Low Integrity
  612. PrintInfo("Current process's Integrity: Low");
  613. *pIntegrityLevel = 3;
  614. }
  615. else if (dwIntegrityLevel >= SECURITY_MANDATORY_MEDIUM_RID &&
  616. dwIntegrityLevel < SECURITY_MANDATORY_HIGH_RID)
  617. {
  618. // Medium Integrity
  619. PrintInfo("Current process's Integrity: Medium");
  620. *pIntegrityLevel = 2;
  621. }
  622. else if (dwIntegrityLevel >= SECURITY_MANDATORY_HIGH_RID)
  623. {
  624. // High Integrity
  625. PrintInfo("Current process's Integrity: High");
  626. *pIntegrityLevel = 1;
  627. }
  628. }
  629. LocalFree(pTIL);
  630. }
  631. }
  632. }
  633. CloseHandle(hToken);
  634. }
  635. }
  636. int GetCurrentRunPath(char *pPath)
  637. {
  638. char *pBuf = new char[MAX_PATH];
  639. if (pBuf == NULL)
  640. return -1;
  641. ZeroMemory(pBuf,MAX_PATH);
  642. GetModuleFileName(NULL,pBuf,MAX_PATH);
  643. int len = strnlen_s(pBuf,MAX_PATH);
  644. if (len <= 0)
  645. {
  646. delete []pBuf;
  647. return -2;
  648. }
  649. char *pch;
  650. pch = strstr (pBuf,"bin");
  651. if (pch == NULL)
  652. return -3;
  653. int lenDel = strnlen_s(pch,MAX_PATH);
  654. if (len <= 0)
  655. {
  656. delete []pBuf;
  657. return -3;
  658. }
  659. strncpy_s(pPath,MAX_PATH,pBuf,len-lenDel);
  660. delete []pBuf;
  661. return strnlen_s(pPath,MAX_PATH);
  662. }
  663. int GetCurrentRVCPath(char *pPath)
  664. {
  665. char *pBuf = new char[MAX_PATH];
  666. if (pBuf == NULL)
  667. return -1;
  668. ZeroMemory(pBuf,MAX_PATH);
  669. GetModuleFileName(NULL,pBuf,MAX_PATH);
  670. int len = strnlen_s(pBuf,MAX_PATH);
  671. if (len <= 0)
  672. {
  673. delete []pBuf;
  674. return -2;
  675. }
  676. char *pch;
  677. pch = strstr (pBuf,"bin");
  678. if (pch == NULL)
  679. return -3;
  680. int lenDel = strnlen_s(pch,MAX_PATH);
  681. if (len <= 0)
  682. {
  683. delete []pBuf;
  684. return -3;
  685. }
  686. pBuf[1] = ':';
  687. pBuf[2] = '\\';
  688. pBuf[3] = '\0';
  689. strcat_s(pBuf, MAX_PATH, "rvc\\");
  690. strcpy_s(pPath, MAX_PATH, pBuf);
  691. delete []pBuf;
  692. return strnlen_s(pPath, MAX_PATH);
  693. pch[0] = '\0';
  694. len = strnlen_s(pBuf, MAX_PATH);
  695. for(int i=0; i<len; ++i) {
  696. if(pBuf[i] >= 'A' && pBuf[i] <= 'Z')
  697. pBuf[i] += 32;
  698. }
  699. //"Run\version\1.9.0.0\bin"
  700. pch = strstr(pBuf, "version");
  701. if(pch == NULL)
  702. {
  703. delete []pBuf;
  704. return -4;
  705. }
  706. pch[-1] = '\0';
  707. pch = strrchr(pBuf, '\\');
  708. if(pch == NULL)
  709. {
  710. delete []pBuf;
  711. return -5;
  712. }
  713. pch[1] = '\0';
  714. strcat_s(pBuf, MAX_PATH, "rvc\\");
  715. strcpy_s(pPath, MAX_PATH, pBuf);
  716. delete []pBuf;
  717. return strnlen_s(pPath, MAX_PATH);
  718. }