home *** CD-ROM | disk | FTP | other *** search
/ Chip 2004 March / CMCD0304.ISO / Software / Freeware / Programare / nullsoft / nsis20.exe / Contrib / nsExec / nsexec.c next >
C/C++ Source or Header  |  2004-01-31  |  12KB  |  419 lines

  1. /*
  2. Copyright (c) 2002 Robert Rainwater <rrainwater@yahoo.com>
  3.  
  4. This software is provided 'as-is', without any express or implied
  5. warranty.  In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7.  
  8. Permission is granted to anyone to use this software for any purpose,
  9. including commercial applications, and to alter it and redistribute it
  10. freely, subject to the following restrictions:
  11.  
  12.   1. The origin of this software must not be misrepresented; you must not
  13.    claim that you wrote the original software. If you use this software
  14.    in a product, an acknowledgment in the product documentation would be
  15.    appreciated but is not required.
  16.   2. Altered source versions must be plainly marked as such, and must not be
  17.    misrepresented as being the original software.
  18.   3. This notice may not be removed or altered from any source distribution.
  19.  
  20. */
  21. #include <windows.h>
  22. #include <commctrl.h>
  23. #include <Winnt.h>
  24. #include "../exdll/exdll.h"
  25.  
  26. #ifndef true
  27. #define true TRUE
  28. #endif
  29. #ifndef false
  30. #define false FALSE
  31. #endif
  32. #define LOOPTIMEOUT  100
  33.  
  34. HWND          g_hwndParent;
  35. HWND          g_hwndList;
  36. char *        g_exec;
  37. unsigned int  g_to;
  38.  
  39. void ExecScript(BOOL log);
  40. void LogMessage(const char *pStr);
  41. char *my_strstr(char *a, char *b);
  42. unsigned int my_atoi(char *s);
  43.  
  44. void __declspec(dllexport) Exec(HWND hwndParent, int string_size, char *variables, stack_t **stacktop) {
  45.   g_hwndParent=hwndParent;
  46.   EXDLL_INIT();
  47.   {
  48.     ExecScript(0);
  49.   }
  50. }
  51.  
  52. void __declspec(dllexport) ExecToLog(HWND hwndParent, int string_size, char *variables, stack_t **stacktop) {
  53.   g_hwndParent=hwndParent;
  54.   EXDLL_INIT();
  55.   {
  56.     ExecScript(1);
  57.   }
  58. }
  59.  
  60. void __declspec(dllexport) ExecToStack(HWND hwndParent, int string_size, char *variables, stack_t **stacktop) {
  61.   g_hwndParent=hwndParent;
  62.   EXDLL_INIT();
  63.   {
  64.     ExecScript(2);
  65.   }
  66. }
  67.  
  68. HINSTANCE g_hInst;
  69. BOOL WINAPI DllMain(HANDLE hInst, ULONG ul_reason_for_call, LPVOID lpReserved) {
  70.   g_hInst = hInst;
  71.   return TRUE;
  72. }
  73.  
  74. #define TAB_REPLACE "        "
  75. #define TAB_REPLACE_SIZE (sizeof(TAB_REPLACE)-1)
  76.  
  77. // Turn a pair of chars into a word
  78. // Turn four chars into a dword
  79. #ifdef __BIG_ENDIAN__ // Not very likely, but, still...
  80. #define CHAR2_TO_WORD(a,b) (((WORD)(b))|((a)<<8))
  81. #define CHAR4_TO_DWORD(a,b,c,d)    (((DWORD)CHAR2_TO_WORD(c,d))|(CHAR2_TO_WORD(a,b)<<16))
  82. #else
  83. #define CHAR2_TO_WORD(a,b) (((WORD)(a))|((b)<<8))
  84. #define CHAR4_TO_DWORD(a,b,c,d)    (((DWORD)CHAR2_TO_WORD(a,b))|(CHAR2_TO_WORD(c,d)<<16))
  85. #endif
  86.  
  87. void ExecScript(int log) {
  88.   char szRet[128] = "";
  89.   char *pExec;
  90.   int nComSpecSize;
  91.   char meDLLPath[MAX_PATH];    
  92.   char *p;
  93.  
  94.   nComSpecSize = GetModuleFileName(g_hInst, meDLLPath, MAX_PATH);
  95.   p = meDLLPath + nComSpecSize - 1;
  96.   g_exec = (char *)GlobalAlloc(GPTR, sizeof(char)*g_stringsize+nComSpecSize+1);
  97.  
  98.   do
  99.   {
  100.     if (*p == '\\')
  101.       break;
  102.     p = CharPrev(meDLLPath, p);
  103.   }
  104.   while (p > meDLLPath);
  105.   if (p == meDLLPath)
  106.   {
  107.     // bad path
  108.     lstrcpy(szRet, "error");
  109.     goto done;
  110.   }
  111.  
  112.   *p = 0;
  113.   GetTempFileName(meDLLPath, "ns", 0, g_exec);
  114.   *p = '\\';
  115.   if (CopyFile(meDLLPath, g_exec, FALSE))
  116.   {
  117.     HANDLE hFile, hMapping;
  118.     LPBYTE pMapView;
  119.     PIMAGE_NT_HEADERS pNTHeaders;
  120.     hFile = CreateFile(g_exec, GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING,0, 0);
  121.     hMapping = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, 0, NULL);
  122.     pMapView = MapViewOfFile(hMapping, FILE_MAP_WRITE, 0, 0, 0);
  123.     if (pMapView)
  124.     {
  125.       pNTHeaders = (PIMAGE_NT_HEADERS)(pMapView + ((PIMAGE_DOS_HEADER)pMapView)->e_lfanew);
  126.       pNTHeaders->FileHeader.Characteristics = IMAGE_FILE_32BIT_MACHINE | IMAGE_FILE_LOCAL_SYMS_STRIPPED | 
  127.         IMAGE_FILE_LINE_NUMS_STRIPPED | IMAGE_FILE_EXECUTABLE_IMAGE;
  128.       pNTHeaders->OptionalHeader.Subsystem = IMAGE_SUBSYSTEM_WINDOWS_CUI;
  129.       pNTHeaders->OptionalHeader.AddressOfEntryPoint = (DWORD)WinMain - (DWORD)g_hInst;  
  130.       UnmapViewOfFile(pMapView);
  131.     }
  132.     CloseHandle(hMapping);
  133.     CloseHandle(hFile);
  134.   }
  135.  
  136.   g_to = 0; // default is no timeout
  137.   g_hwndList = FindWindowEx(FindWindowEx(g_hwndParent,NULL,"#32770",NULL),NULL,"SysListView32",NULL);
  138.   pExec = g_exec + nComSpecSize;
  139.   while ( !*(pExec-1) ) pExec--;
  140.   *pExec = ' '; 
  141.   pExec++;
  142.   popstring(pExec);
  143.   if (my_strstr(pExec, "/TIMEOUT=")) {
  144.     char *szTimeout = pExec + 9;
  145.     g_to = my_atoi(szTimeout);
  146.     popstring(pExec);
  147.   }
  148.   if (!g_exec[0]) 
  149.   {
  150.     lstrcpy(szRet, "error");
  151.     goto done;
  152.   }
  153.   
  154.   {
  155.     STARTUPINFO si={sizeof(si),};
  156.     SECURITY_ATTRIBUTES sa={sizeof(sa),};
  157.     SECURITY_DESCRIPTOR sd={0,};
  158.     PROCESS_INFORMATION pi={0,};
  159.     OSVERSIONINFO osv={sizeof(osv)};
  160.     HANDLE newstdout=0,read_stdout=0;
  161.     DWORD dwRead = 1;
  162.     DWORD dwExit = !STILL_ACTIVE;
  163.     DWORD dwLastOutput;
  164.     static char szBuf[1024];
  165.     HGLOBAL hUnusedBuf;
  166.     char *szUnusedBuf = 0;
  167.  
  168.     if (log) {
  169.       hUnusedBuf = GlobalAlloc(GHND, log & 2 ? g_stringsize : sizeof(szBuf)*4);
  170.       if (!hUnusedBuf) {
  171.         lstrcpy(szRet, "error");
  172.         goto done;
  173.       }
  174.       szUnusedBuf = (char *)GlobalLock(hUnusedBuf);
  175.     }
  176.  
  177.     GetVersionEx(&osv);
  178.     if (osv.dwPlatformId == VER_PLATFORM_WIN32_NT) {
  179.       InitializeSecurityDescriptor(&sd,SECURITY_DESCRIPTOR_REVISION);
  180.       SetSecurityDescriptorDacl(&sd,true,NULL,false);
  181.       sa.lpSecurityDescriptor = &sd;
  182.     }
  183.     else 
  184.       sa.lpSecurityDescriptor = NULL;
  185.     sa.bInheritHandle = true;
  186.     if (!CreatePipe(&read_stdout,&newstdout,&sa,0)) {
  187.       lstrcpy(szRet, "error");
  188.       goto done;
  189.     }
  190.  
  191.     GetStartupInfo(&si);
  192.     si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
  193.     si.wShowWindow = SW_HIDE;
  194.     si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
  195.     si.hStdOutput = newstdout;
  196.     si.hStdError = newstdout;
  197.     if (!CreateProcess(NULL,g_exec,NULL,NULL,TRUE,CREATE_NEW_CONSOLE,NULL,NULL,&si,&pi)) {
  198.       lstrcpy(szRet, "error");
  199.       goto done;
  200.     }
  201.  
  202.     dwLastOutput = GetTickCount();
  203.  
  204.     while (dwExit == STILL_ACTIVE || dwRead) {
  205.       PeekNamedPipe(read_stdout, 0, 0, 0, &dwRead, NULL);
  206.       if (dwRead) {
  207.         dwLastOutput = GetTickCount();
  208.         ReadFile(read_stdout, szBuf, sizeof(szBuf)-1, &dwRead, NULL);
  209.         szBuf[dwRead] = 0;
  210.         if (log) {
  211.           char *p, *p2;
  212.           SIZE_T iReqLen = lstrlen(szBuf) + lstrlen(szUnusedBuf);
  213.           if (GlobalSize(hUnusedBuf) < iReqLen && (iReqLen < g_stringsize || !(log & 2))) {
  214.             GlobalUnlock(hUnusedBuf);
  215.             hUnusedBuf = GlobalReAlloc(hUnusedBuf, iReqLen+sizeof(szBuf), GHND);
  216.             if (!hUnusedBuf) {
  217.               lstrcpy(szRet, "error");
  218.               break;
  219.             }
  220.             szUnusedBuf = (char *)GlobalLock(hUnusedBuf);
  221.           }
  222.           p = szUnusedBuf; // get the old left overs
  223.           if (iReqLen < g_stringsize || !(log & 2)) lstrcat(p, szBuf);
  224.           else {
  225.             lstrcpyn(p + lstrlen(p), szBuf, g_stringsize - lstrlen(p));
  226.           }
  227.  
  228.           if (!(log & 2)) {
  229.             while (p = my_strstr(p, "\t")) {
  230.               if ((int)(p - szUnusedBuf) > (int)(GlobalSize(hUnusedBuf) - TAB_REPLACE_SIZE - 1))
  231.               {
  232.                 *p++ = ' ';
  233.               }
  234.               else
  235.               {
  236.                 int len = lstrlen(p);
  237.                 char *c_out=(char*)p+TAB_REPLACE_SIZE+len;
  238.                 char *c_in=(char *)p+len;
  239.                 while (len-- > 0) {
  240.                   *c_out--=*c_in--;
  241.                 }
  242.  
  243.                 lstrcpy(p, TAB_REPLACE);
  244.                 p += TAB_REPLACE_SIZE;
  245.                 *p = ' ';
  246.               }
  247.             }
  248.             
  249.             p = szUnusedBuf; // get the old left overs
  250.             for (p2 = p; *p2;) {
  251.               if (*p2 == '\r') {
  252.                 *p2++ = 0;
  253.                 continue;
  254.               }
  255.               if (*p2 == '\n') {
  256.                 *p2 = 0;
  257.                 while (!*p && p != p2) p++;
  258.                 LogMessage(p);
  259.                 p = ++p2;
  260.                 continue;
  261.               }
  262.               p2 = CharNext(p2);
  263.             }
  264.             
  265.             // If data was taken out from the unused buffer, move p contents to the start of szUnusedBuf
  266.             if (p != szUnusedBuf) {
  267.               char *p2 = szUnusedBuf;
  268.               while (*p) *p2++ = *p++;
  269.               *p2 = 0;
  270.             }
  271.           }
  272.         }
  273.       }
  274.       else {
  275.         if (g_to && GetTickCount() > dwLastOutput+g_to) {
  276.           TerminateProcess(pi.hProcess, -1);
  277.           lstrcpy(szRet, "timeout");
  278.         }
  279.         else Sleep(LOOPTIMEOUT);
  280.       }
  281.       GetExitCodeProcess(pi.hProcess, &dwExit);
  282.       if (dwExit != STILL_ACTIVE) {
  283.         PeekNamedPipe(read_stdout, 0, 0, 0, &dwRead, NULL);
  284.       }
  285.     }
  286. done:
  287.     if (log & 2) pushstring(szUnusedBuf);
  288.     if (log & 1 && *szUnusedBuf) LogMessage(szUnusedBuf);
  289.     if ( dwExit == STATUS_ILLEGAL_INSTRUCTION )
  290.       lstrcpy(szRet, "error");
  291.     if (!szRet[0]) wsprintf(szRet,"%d",dwExit);
  292.     pushstring(szRet);
  293.     CloseHandle(pi.hThread);
  294.     CloseHandle(pi.hProcess);
  295.     CloseHandle(newstdout);
  296.     CloseHandle(read_stdout);
  297.     *(pExec-1) = '\0';
  298.     DeleteFile(g_exec);
  299.     GlobalFree(g_exec);
  300.     if (log) {
  301.       GlobalUnlock(hUnusedBuf);
  302.       GlobalFree(hUnusedBuf);
  303.     }
  304.   }
  305. }
  306.  
  307. // Tim Kosse's LogMessage
  308. void LogMessage(const char *pStr) {
  309.   LVITEM item={0};
  310.   int nItemCount;
  311.   if (!g_hwndList) return;
  312.   //if (!lstrlen(pStr)) return;
  313.   nItemCount=SendMessage(g_hwndList, LVM_GETITEMCOUNT, 0, 0);
  314.   item.mask=LVIF_TEXT;
  315.   item.pszText=(char *)pStr;
  316.   item.cchTextMax=0;
  317.   item.iItem=nItemCount;
  318.   ListView_InsertItem(g_hwndList, &item);
  319.   ListView_EnsureVisible(g_hwndList, item.iItem, 0);
  320. }
  321.  
  322. char *my_strstr(char *a, char *b)
  323. {
  324.   int l = lstrlen(b);
  325.   while (lstrlen(a) >= l)
  326.   {
  327.     char c = a[l];
  328.     a[l] = 0;
  329.     if (!lstrcmpi(a, b))
  330.     {
  331.       a[l] = c;
  332.       return a;
  333.     }
  334.     a[l] = c;
  335.     a = CharNext(a);
  336.   }
  337.   return NULL;
  338. }
  339.  
  340. unsigned int my_atoi(char *s) {
  341.   unsigned int v=0;
  342.   if (*s == '0' && (s[1] == 'x' || s[1] == 'X')) {
  343.     s+=2;
  344.     for (;;) {
  345.       int c=*s++;
  346.       if (c >= '0' && c <= '9') c-='0';
  347.       else if (c >= 'a' && c <= 'f') c-='a'-10;
  348.       else if (c >= 'A' && c <= 'F') c-='A'-10;
  349.       else break;
  350.       v<<=4;
  351.       v+=c;
  352.     }
  353.   }
  354.   else if (*s == '0' && s[1] <= '7' && s[1] >= '0') {
  355.     s++;
  356.     for (;;) {
  357.       int c=*s++;
  358.       if (c >= '0' && c <= '7') c-='0';
  359.       else break;
  360.       v<<=3;
  361.       v+=c;
  362.     }
  363.   }
  364.   else {
  365.     for (;;) {
  366.       int c=*s++ - '0';
  367.       if (c < 0 || c > 9) break;
  368.       v*=10;
  369.       v+=c;
  370.     }
  371.   }
  372.   return (int)v;
  373. }
  374.  
  375. int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
  376. {
  377.   DWORD               Ret;
  378.   STARTUPINFO         si   = {0};
  379.   PROCESS_INFORMATION pi   = {0};
  380.   char command_line[1024];
  381.   char seekchar=' ';
  382.   char *cmdline;
  383.   
  384.   si.cb = sizeof(si);
  385.   // Make child process use this app's standard files. Not needed !??
  386.   //si.dwFlags    = STARTF_USESTDHANDLES;
  387.   //si.hStdInput  = GetStdHandle (STD_INPUT_HANDLE);
  388.   //si.hStdOutput = GetStdHandle (STD_OUTPUT_HANDLE);
  389.   //si.hStdError  = GetStdHandle (STD_ERROR_HANDLE);
  390.   lstrcpyn(command_line, GetCommandLine(), 1024);
  391.   
  392.   cmdline = command_line;
  393.   if (*cmdline == '\"') seekchar = *cmdline++;
  394.  
  395.   while (*cmdline && *cmdline != seekchar) cmdline=CharNext(cmdline);
  396.   cmdline=CharNext(cmdline);
  397.  
  398.   Ret = CreateProcess (NULL, cmdline,
  399.     NULL, NULL,
  400.     TRUE, 0,
  401.     NULL, NULL,
  402.     &si, &pi
  403.     );
  404.   
  405.   if ( Ret )
  406.   {
  407.     do
  408.     {
  409.       GetExitCodeProcess(pi.hProcess, &Ret);
  410.       Sleep(LOOPTIMEOUT);
  411.     } while ( Ret == STILL_ACTIVE );
  412.     CloseHandle (pi.hProcess);
  413.     CloseHandle (pi.hThread);
  414.     return Ret;
  415.   }
  416.   else
  417.     return STATUS_ILLEGAL_INSTRUCTION;
  418. }
  419.