Subversion Repositories filter_foundry

Rev

Rev 454 | Rev 482 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

  1. /*
  2.     This file is part of "Filter Foundry", a filter plugin for Adobe Photoshop
  3.     Copyright (C) 2003-2009 Toby Thain, toby@telegraphics.com.au
  4.     Copyright (C) 2018-2021 Daniel Marschall, ViaThinkSoft
  5.  
  6.     This program is free software; you can redistribute it and/or modify
  7.     it under the terms of the GNU General Public License as published by
  8.     the Free Software Foundation; either version 2 of the License, or
  9.     (at your option) any later version.
  10.  
  11.     This program is distributed in the hope that it will be useful,
  12.     but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.     GNU General Public License for more details.
  15.  
  16.     You should have received a copy of the GNU General Public License
  17.     along with this program; if not, write to the Free Software
  18.     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  19. */
  20.  
  21. #include "ff.h"
  22.  
  23. #include <time.h>
  24.  
  25. #include "file_compat.h"
  26. #include "compat_string.h"
  27. #include "compat_win.h"
  28. #include "versioninfo_modify_win.h"
  29. #include "version.h"
  30.  
  31. extern HINSTANCE hDllInstance;
  32.  
  33. typedef struct _PE32 {
  34.         uint32_t magic; // 0x50450000
  35.         IMAGE_FILE_HEADER fileHeader; // COFF Header without Signature
  36.         IMAGE_OPTIONAL_HEADER32 optHeader; // Standard COFF fields, Windows Specific Fields, Data Directories
  37. } PE32;
  38.  
  39. Boolean doresources(FSSpec* dst, int bits);
  40.  
  41. void dbglasterror(TCHAR *func){
  42.         TCHAR s[0x300] = {0};
  43.  
  44.         xstrcpy(&s[0],func);
  45.         xstrcat(&s[0],TEXT(" failed: "));
  46.         FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), 0, s + xstrlen(s), 0x300 - (DWORD)xstrlen(s), NULL);
  47.         dbg(&s[0]);
  48. }
  49.  
  50. /*
  51. BOOL CALLBACK enumfunc(HMODULE hModule,LPCTSTR lpszType,LPCTSTR lpszName,WORD wIDLanguage,LONG lParam){
  52.         char s[0x100];
  53.         sprintf(s,"EnumResourceLanguages callback: module=%#x type=%s name=%s lang=%d",
  54.                 hModule,lpszType,lpszName,wIDLanguage);
  55.         dbg(s);
  56.         return TRUE;
  57. }
  58. */
  59.  
  60. int domanifest(char *newmanifest, char *manifestp, PARM_T* pparm, int bits) {
  61.         char name[1024] = { 0 };
  62.         char description[1024] = { 0 };
  63.         size_t i;
  64.         size_t iname = 0;
  65.         int idescription = 0;
  66.  
  67.         // Description
  68.         for (i = 0; i < strlen(pparm->szCategory); i++) {
  69.                 char c = pparm->szCategory[i];
  70.                 if ((c != '<') && (c != '>')) {
  71.                         description[idescription++] = c;
  72.                 }
  73.         }
  74.         description[idescription++] = ' ';
  75.         description[idescription++] = '-';
  76.         description[idescription++] = ' ';
  77.         for (i = 0; i < strlen(pparm->szTitle); i++) {
  78.                 char c = pparm->szTitle[i];
  79.                 if ((c != '<') && (c != '>')) {
  80.                         description[idescription++] = c;
  81.                 }
  82.         }
  83.         description[idescription++] = '\0';
  84.  
  85.         // Name
  86.         strcpy(name, "Telegraphics.FilterFoundry.");
  87.         iname = strlen("Telegraphics.FilterFoundry.");
  88.         for (i = 0; i < strlen(pparm->szCategory); i++) {
  89.                 char c = pparm->szCategory[i];
  90.                 if (((c >= 'A') && (c <= 'Z')) || ((c >= 'a') && (c <= 'z')) || ((c >= '0') && (c <= '9'))) {
  91.                         name[iname++] = c;
  92.                 }
  93.         }
  94.         name[iname++] = '.';
  95.         for (i = 0; i < strlen(pparm->szTitle); i++) {
  96.                 char c = pparm->szTitle[i];
  97.                 if (((c >= 'A') && (c <= 'Z')) || ((c >= 'a') && (c <= 'z')) || ((c >= '0') && (c <= '9'))) {
  98.                         name[iname++] = c;
  99.                 }
  100.         }
  101.         name[iname++] = '\0';
  102.  
  103.         if (bits == 64) {
  104.                 return sprintf(newmanifest, manifestp, (char*)name, "amd64", VERSION_STR, (char*)description);
  105.         }
  106.         else {
  107.                 return sprintf(newmanifest, manifestp, (char*)name, "x86", VERSION_STR, (char*)description);
  108.         }
  109. }
  110.  
  111. ULONG changeVersionInfo(FSSpec* dst, HANDLE hUpdate, PARM_T* pparm, int bits) {
  112.         LPTSTR soleFilename;
  113.         LPWSTR changeRequestStrW, tmp;
  114.         ULONG dwError = NOERROR;
  115.         HRSRC hResInfo;
  116.         HGLOBAL hg;
  117.         ULONG size;
  118.         PVOID pv;
  119.         //BOOL fDiscard = TRUE;
  120.  
  121.         if (soleFilename = xstrrchr(&dst->szName[0], '\\')) {
  122.                 ++soleFilename;
  123.         }
  124.         else {
  125.                 soleFilename = &dst->szName[0];
  126.         }
  127.  
  128.         // Format of argument "PCWSTR changes" is "<name>\0<value>\0<name>\0<value>\0....."
  129.         // You can CHANGE values for any given name
  130.         // You can DELETE entries by setting the value to "\b" (0x08 backspace character)
  131.         // You cannot (yet) ADD entries.
  132.         changeRequestStrW = (LPWSTR)malloc((6 * 2 * 100 + 1) * sizeof(WCHAR));
  133.         if (changeRequestStrW == 0) return E_OUTOFMEMORY;
  134.         memset((char*)changeRequestStrW, 0, sizeof(changeRequestStrW));
  135.  
  136.         tmp = changeRequestStrW;
  137.  
  138.         tmp += mbstowcs(tmp, "Comments", 100);
  139.         tmp++;
  140.         tmp += mbstowcs(tmp, "Built using Filter Foundry " VERSION_STR, 100);
  141.         tmp++;
  142.  
  143.         tmp += mbstowcs(tmp, "CompanyName", 100);
  144.         tmp++;
  145.         if (strlen(pparm->szAuthor) > 0) {
  146.                 tmp += mbstowcs(tmp, pparm->szAuthor, 100);
  147.         }
  148.         else {
  149.                 tmp += mbstowcs(tmp, "\b", 100); // \b = remove
  150.         }
  151.         tmp++;
  152.  
  153.         tmp += mbstowcs(tmp, "LegalCopyright", 100);
  154.         tmp++;
  155.         if (strlen(pparm->szCopyright) > 0) {
  156.                 tmp += mbstowcs(tmp, pparm->szCopyright, 100);
  157.         }
  158.         else {
  159.                 tmp += mbstowcs(tmp, "\b", 100); // \b = remove
  160.         }
  161.         tmp++;
  162.  
  163.         tmp += mbstowcs(tmp, "FileDescription", 100);
  164.         tmp++;
  165.         if (strlen(pparm->szTitle) > 0) {
  166.                 tmp += mbstowcs(tmp, pparm->szTitle, 100);
  167.         }
  168.         else {
  169.                 tmp += mbstowcs(tmp, "Untitled filter", 100);
  170.         }
  171.         tmp++;
  172.  
  173.         tmp += mbstowcs(tmp, "OriginalFilename", 100);
  174.         tmp++;
  175.         #ifdef UNICODE
  176.         xstrcpy(tmp, soleFilename);
  177.         tmp += xstrlen(soleFilename);
  178.         #else
  179.         tmp += mbstowcs(tmp, soleFilename, 100);
  180.         #endif
  181.         tmp++;
  182.  
  183.         tmp += mbstowcs(tmp, "License", 100);
  184.         tmp++;
  185.         tmp += mbstowcs(tmp, "\b", 100); // \b = remove, since filter is standalone and might have its own license
  186.         tmp++;
  187.  
  188.         tmp += mbstowcs(tmp, "", 1);
  189.  
  190.         if (hResInfo = FindResourceEx(hDllInstance, TEXT("TPLT"), MAKEINTRESOURCE(3000 + bits), MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US)))
  191.         {
  192.                 if (hg = LoadResource(hDllInstance, hResInfo))
  193.                 {
  194.                         if (size = SizeofResource(hDllInstance, hResInfo))
  195.                         {
  196.                                 if (pv = LockResource(hg))
  197.                                 {
  198.                                         if (UpdateVersionRaw(pv, size, &pv, &size, changeRequestStrW))
  199.                                         {
  200.                                                 if (_UpdateResource(hUpdate, RT_VERSION, MAKEINTRESOURCE(1), MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), pv, size))
  201.                                                 {
  202.                                                         //fDiscard = FALSE;
  203.                                                 }
  204.                                                 else {
  205.                                                         //dwError = GetLastError();
  206.                                                 }
  207.                                         }
  208.                                         LocalFree(pv);
  209.                                 }
  210.                         }
  211.                 }
  212.         }
  213.  
  214.         free(changeRequestStrW);
  215.  
  216.         return dwError;
  217. }
  218.  
  219. typedef long                          __time32_t;
  220.  
  221. Boolean update_pe_timestamp(const FSSpec* dst, __time32_t timestamp) {
  222.         size_t peoffset;
  223.         FILEREF fptr;
  224.         Boolean res;
  225.         FILECOUNT cnt;
  226.  
  227.         if (FSpOpenDF(dst, fsRdWrPerm, &fptr) != noErr) return false;
  228.  
  229.         res =
  230.                 SetFPos(fptr, fsFromStart, 0x3C) ||
  231.                 (cnt = sizeof(peoffset), noErr) ||
  232.                 FSRead(fptr, &cnt, &peoffset) ||
  233.                 SetFPos(fptr, fsFromStart, (long)peoffset + /*0x0008*/offsetof(PE32, fileHeader.TimeDateStamp)) ||
  234.                 (cnt = sizeof(__time32_t), noErr) ||
  235.                 FSWrite(fptr, &cnt, &timestamp);
  236.  
  237.         FSClose(fptr);
  238.  
  239.         return res == noErr; // res=0 means everything was noErr, res=1 means something was !=noErr
  240. }
  241.  
  242. int binary_replace_file(FSSpec* dst, uint64_t search, uint64_t replace, Boolean align, int maxamount) {
  243.         uint64_t srecord = 0;
  244.         int found = 0;
  245.         FILEREF fptr;
  246.         FILECOUNT cnt;
  247.  
  248.         if (FSpOpenDF(dst, fsRdWrPerm, &fptr) != noErr) return -1;
  249.  
  250.         cnt = sizeof(srecord);
  251.         while (FSRead(fptr, &cnt, &srecord) == noErr)
  252.         {
  253.                 if (srecord == search) {
  254.                         srecord = replace;
  255.                         SetFPos(fptr, fsFromMark, -1 * (long)sizeof(srecord));
  256.                         cnt = (int)sizeof(srecord);
  257.                         FSWrite(fptr, &cnt, &srecord);
  258.                         SetFPos(fptr, fsFromStart, 0); // important for fseek
  259.                         found++;
  260.                         if (found == maxamount) break;
  261.                 }
  262.                 else {
  263.                         if (!align) {
  264.                                 SetFPos(fptr, fsFromMark, -1 * (long)(sizeof(srecord) - 1));
  265.                         }
  266.                 }
  267.         }
  268.         FSClose(fptr);
  269.  
  270.         return found;
  271. }
  272.  
  273. uint32_t calculate_checksum(FSSpec* dst) {
  274.         //Calculate checksum of image
  275.         // Taken from "PE Bliss" Cross-Platform Portable Executable C++ Library
  276.         // https://github.com/mrexodia/portable-executable-library/blob/master/pe_lib/pe_checksum.cpp
  277.         // Converted from C++ to C by Daniel Marschall
  278.  
  279.         FILEREF fptr;
  280.         unsigned long long checksum = 0;
  281.         IMAGE_DOS_HEADER header;
  282.         FILEPOS filesize, i;
  283.         unsigned long long top;
  284.         unsigned long pe_checksum_pos;
  285.         static const unsigned long checksum_pos_in_optional_headers = 64;
  286.         FILECOUNT cnt;
  287.  
  288.         if (FSpOpenDF(dst, fsRdWrPerm, &fptr) != noErr) return 0x00000000;
  289.  
  290.         //Read DOS header
  291.         SetFPos(fptr, fsFromStart, 0);
  292.         cnt = sizeof(IMAGE_DOS_HEADER);
  293.         FSRead(fptr, &cnt, &header);
  294.  
  295.         //Calculate PE checksum
  296.         SetFPos(fptr, fsFromStart, 0);
  297.         top = 0xFFFFFFFF;
  298.         top++;
  299.  
  300.         //"CheckSum" field position in optional PE headers - it's always 64 for PE and PE+
  301.         //Calculate real PE headers "CheckSum" field position
  302.         //Sum is safe here
  303.         pe_checksum_pos = header.e_lfanew + sizeof(IMAGE_FILE_HEADER) + sizeof(uint32_t) + checksum_pos_in_optional_headers;
  304.  
  305.         //Calculate checksum for each byte of file
  306.         filesize = 0;
  307.         GetEOF(fptr, &filesize);
  308.         SetFPos(fptr, fsFromStart, 0);
  309.         for (i = 0; i < filesize; i += 4)
  310.         {
  311.                 unsigned long dw = 0;
  312.  
  313.                 //Read DWORD from file
  314.                 cnt = sizeof(dw);
  315.                 FSRead(fptr, &cnt, &dw);
  316.                 //Skip "CheckSum" DWORD
  317.                 if (i == pe_checksum_pos)
  318.                         continue;
  319.  
  320.                 //Calculate checksum
  321.                 checksum = (checksum & 0xffffffff) + dw + (checksum >> 32);
  322.                 if (checksum > top)
  323.                         checksum = (checksum & 0xffffffff) + (checksum >> 32);
  324.         }
  325.  
  326.         //Finish checksum
  327.         checksum = (checksum & 0xffff) + (checksum >> 16);
  328.         checksum = (checksum)+(checksum >> 16);
  329.         checksum = checksum & 0xffff;
  330.  
  331.         checksum += (unsigned long)(filesize);
  332.  
  333.         FSClose(fptr);
  334.  
  335.         //Return checksum
  336.         return (uint32_t)checksum;
  337. }
  338.  
  339. Boolean repair_pe_checksum(FSSpec* dst) {
  340.         size_t peoffset;
  341.         FILEREF fptr;
  342.         FILECOUNT cnt;
  343.         Boolean res;
  344.  
  345.         uint32_t checksum = calculate_checksum(dst);
  346.         //if (checksum == 0x00000000) return false;
  347.  
  348.         if (FSpOpenDF(dst, fsRdWrPerm, &fptr) != noErr) return false;
  349.  
  350.         res =
  351.                 SetFPos(fptr, fsFromStart, 0x3C) ||
  352.                 (cnt = sizeof(peoffset), noErr) ||
  353.                 FSRead(fptr, &cnt, &peoffset) ||
  354.                 SetFPos(fptr, fsFromStart, (long)peoffset + /*0x0058*/offsetof(PE32, optHeader.CheckSum)) ||
  355.                 (cnt = sizeof(uint32_t), noErr) ||
  356.                 FSWrite(fptr, &cnt, &checksum);
  357.  
  358.         FSClose(fptr);
  359.  
  360.         return res == noErr; // res=0 means everything was noErr, res=1 means something was !=noErr
  361. }
  362.  
  363. typedef struct {
  364.         char funcname[8];
  365.         uint16_t codelen;
  366. } operdef_t;
  367.  
  368. typedef struct {
  369.         char funcname[8];
  370.         uint16_t numparams;
  371. } funcdef_t;
  372.  
  373. typedef struct {
  374.         char funcname[8];
  375.         char referencename[8];
  376. } symndef_t;
  377.  
  378. Boolean doresources(FSSpec* dst, int bits){
  379.         HRSRC datarsrc,aetersrc,manifestsrc;
  380.         HGLOBAL datah,aeteh,hupdate,manifesth;
  381.  
  382.         operdef_t dummy_oper;
  383.         funcdef_t dummy_func;
  384.         symndef_t dummy_symn;
  385.  
  386.         Ptr newpipl = NULL, newaete = NULL;
  387.         LPVOID datap, aetep, manifestp;
  388.         char* manifestp_copy;
  389.         PARM_T *pparm = NULL;
  390.         size_t piplsize,aetesize,origsize;
  391.         char title[256];
  392.         LPCTSTR parm_type;
  393.         LPCTSTR parm_id;
  394.         Boolean discard = true;
  395.         uint64_t obfuscseed = 0;
  396.         long event_id;
  397.  
  398.         memset(&dummy_oper, 0, sizeof(operdef_t));
  399.         memset(&dummy_func, 0, sizeof(funcdef_t));
  400.         memset(&dummy_symn, 0, sizeof(symndef_t));
  401.  
  402.         if( (hupdate = _BeginUpdateResource(&dst->szName[0],false)) ){
  403.                 DBG("BeginUpdateResource OK");
  404.                 if( (datarsrc = FindResource(hDllInstance,MAKEINTRESOURCE(16000 + bits), TEXT("TPLT")))
  405.                         && (datah = LoadResource(hDllInstance,datarsrc))
  406.                         && (datap = (Ptr)LockResource(datah))
  407.                         && (aetersrc = FindResource(hDllInstance, MAKEINTRESOURCE(16000), TEXT("AETE")))
  408.                         && (aeteh = LoadResource(hDllInstance, aetersrc))
  409.                         && (aetep = (Ptr)LockResource(aeteh))
  410.                         && (manifestsrc = FindResource(hDllInstance, MAKEINTRESOURCE(1), TEXT("TPLT")))
  411.                         && (manifesth = LoadResource(hDllInstance, manifestsrc))
  412.                         && (manifestp = (Ptr)LockResource(manifesth)) )
  413.                 {
  414.                         char* newmanifest;
  415.                         int manifestsize = SizeofResource(hDllInstance, manifestsrc);
  416.  
  417.                         newmanifest = (char*)malloc((size_t)manifestsize + 4096/*+4KiB for name,description,etc.*/);
  418.  
  419.                         DBG("loaded DATA, PiPL");
  420.  
  421.                         strcpy(title,gdata->parm.szTitle);
  422.                         if(gdata->parm.popDialog)
  423.                                 strcat(title,"...");
  424.  
  425.                         origsize = SizeofResource(hDllInstance,datarsrc);
  426.  
  427.                         if( (newpipl = (Ptr)malloc(origsize+0x300))
  428.                          && (newaete = (Ptr)malloc(4096))
  429.                          && (pparm = (PARM_T*)malloc(sizeof(PARM_T))) )
  430.                         {
  431.                                 // ====== Generate AETE and PIPL
  432.  
  433.                                 /* add user-specified title and category to new PiPL */
  434.                                 memcpy(newpipl,datap,origsize);
  435.                                 /* note that Windows PiPLs have 2 byte version datum in front
  436.                                    that isn't reflected in struct definition or Mac resource template: */
  437.                                 piplsize = fixpipl((PIPropertyList*)(newpipl+2),origsize-2,&title[0], &event_id) + 2;
  438.  
  439.                                 /* set up the PARM resource with saved parameters */
  440.                                 memcpy(pparm,&gdata->parm,sizeof(PARM_T));
  441.  
  442.                                 /* Generate 'aete' resource (contains names of the parameters for the "Actions" tab in Photoshop) */
  443.                                 aetesize = aete_generate(newaete, pparm, event_id);
  444.  
  445.                                 // ====== Create fitting manifest for the activation context
  446.  
  447.                                 manifestp_copy = (char*)malloc((size_t)manifestsize + 1/*sz*/);
  448.                                 if (manifestp_copy != 0) {
  449.                                         memcpy(manifestp_copy, manifestp, manifestsize); // copy manifestp to manifestp_copy, because manifestp is readonly
  450.                                         manifestp_copy[manifestsize] = '\0'; // and add the null-terminating char, because domanifest() uses sprintf() on it
  451.                                         manifestsize = domanifest(newmanifest, manifestp_copy, pparm, bits);
  452.                                         free(manifestp_copy);
  453.                                 }
  454.  
  455.                                 // ====== Change version attributes
  456.  
  457.                                 if (changeVersionInfo(dst, hupdate, pparm, bits) != NOERROR) {
  458.                                         simplewarning((TCHAR*)TEXT("changeVersionInfo failed"));
  459.                                 }
  460.  
  461.                                 // ====== Obfuscate pparm!
  462.  
  463.                                 if (gdata->obfusc) {
  464.                                         parm_type = OBFUSCDATA_TYPE_NEW;
  465.                                         parm_id = OBFUSCDATA_ID_NEW;
  466.  
  467.                                         // Note: After we have finished updating the resources, we will write <obfuscseed> into the binary code of the 8BF file
  468.                                         obfuscseed = obfusc(pparm);
  469.                                 }else{
  470.                                         parm_type = PARM_TYPE;
  471.                                         parm_id = PARM_ID_NEW;
  472.                                 }
  473.  
  474.                                 // ====== Save AETE, PIPL, Manifest and PARM/RCDATA
  475.  
  476.                                 /* Attention: The resource we have found using FindResource() might have a different
  477.                                    language than the resource we are saving (Neutral), so we might end up having
  478.                                    multiple languages for the same resource. Therefore, the language "Neutral" was
  479.                                    set in the Scripting.rc file for the resource AETE and PIPL.rc for the resources PIPL. */
  480.  
  481.                                 if(
  482.                                            _UpdateResource(hupdate, RT_DIALOG, MAKEINTRESOURCE(ID_BUILDDLG), MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), NULL, 0) // clean up things we don't need in the standalone plugin
  483.                                         && _UpdateResource(hupdate, RT_DIALOG, MAKEINTRESOURCE(ID_MAINDLG), MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), NULL, 0) // clean up things we don't need in the standalone plugin
  484.                                         && _UpdateResource(hupdate, RT_GROUP_ICON, TEXT("CAUTION_ICO"), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), NULL, 0) // clean up things we don't need in the standalone plugin
  485. //                                      && _UpdateResource(hupdate, RT_ICON, MAKEINTRESOURCE(1)/*Caution*/, MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), NULL, 0) // clean up things we don't need in the standalone plugin
  486.                                         && _UpdateResource(hupdate, RT_GROUP_CURSOR, TEXT("HAND_QUESTION"), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), NULL, 0) // clean up things we don't need in the standalone plugin
  487.                                         // TODO: Removing the single resources don't work correctly. Sometimes the cursors are numbered 4,5,6 and sometimes 1,2,3 . Probably conflicts with icons
  488. //                                      && _UpdateResource(hupdate, RT_CURSOR, MAKEINTRESOURCE(3)/*QuestionHand*/, MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), NULL, 0) // clean up things we don't need in the standalone plugin
  489.                                         && _UpdateResource(hupdate, TEXT("PIPL") /* note: caps!! */, MAKEINTRESOURCE(16000), MAKELANGID(LANG_NEUTRAL,SUBLANG_NEUTRAL),newpipl,(DWORD)piplsize)
  490.                                         && _UpdateResource(hupdate, TEXT("AETE") /* note: caps!! */, MAKEINTRESOURCE(16000), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), newaete, (DWORD)aetesize)
  491.                                         // OPER and FUNC are written so that "Plugin Manager 2.1" thinks that this plugin is a Filter Factory plugin! SYNM is not important, though.
  492.                                         && (gdata->obfusc || _UpdateResource(hupdate, TEXT("OPER"), MAKEINTRESOURCE(16000), MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), &dummy_oper, sizeof(dummy_oper)))
  493.                                         && (gdata->obfusc || _UpdateResource(hupdate, TEXT("FUNC"), MAKEINTRESOURCE(16000), MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), &dummy_func, sizeof(dummy_func)))
  494.                                         && (gdata->obfusc || _UpdateResource(hupdate, TEXT("SYNM"), MAKEINTRESOURCE(16000), MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), &dummy_symn, sizeof(dummy_symn)))
  495.                                         && _UpdateResource(hupdate, RT_MANIFEST, MAKEINTRESOURCE(1), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), newmanifest, (DWORD)manifestsize)
  496.                                         && _UpdateResource(hupdate, parm_type,parm_id, MAKELANGID(LANG_NEUTRAL,SUBLANG_NEUTRAL),pparm,sizeof(PARM_T)) )
  497.                                 {
  498.                                         discard = false;
  499.                                 } else {
  500.                                         dbglasterror((TCHAR*)TEXT("UpdateResource"));
  501.                                 }
  502.                         }
  503.  
  504.                         free(newmanifest);
  505.  
  506.                         // Here, the file will be saved
  507.                         if (_EndUpdateResource(hupdate, discard)) {
  508.                                 if (gdata->obfusc) {
  509.                                         // We modify the binary code to replace the deobfuscate-seed from <cObfuscSeed> to <obfuscseed>
  510.  
  511.                                         // First try with alignment "4" (this should be the usual case),
  512.                                         // and if that failed, try without alignment ("1").
  513.                                         // We only need to set maxamount to "1", because "const volatile" makes sure that
  514.                                         // the compiler won't place (inline) it at several locations in the code.
  515.                                         if ((binary_replace_file(dst, cObfuscSeed, obfuscseed, /*align to 4*/1, /*maxamount=*/1) == 0) &&
  516.                                                 (binary_replace_file(dst, cObfuscSeed, obfuscseed, /*align to 1*/0, /*maxamount=*/1) == 0))
  517.                                         {
  518.                                                 dbg((TCHAR*)TEXT("binary_replace_file failed"));
  519.                                                 discard = true;
  520.                                         }
  521.                                 }
  522.  
  523.                                 if (!update_pe_timestamp(dst, (__time32_t)time(0))) {
  524.                                         simplewarning((TCHAR*)TEXT("update_pe_timestamp failed"));
  525.                                 }
  526.  
  527.                                 if (!repair_pe_checksum(dst)) {
  528.                                         simplewarning((TCHAR*)TEXT("repair_pe_checksum failed"));
  529.                                 }
  530.                         }else dbglasterror((TCHAR*)TEXT("EndUpdateResource"));
  531.  
  532.                 }else dbglasterror((TCHAR*)TEXT("Find-, Load- or LockResource"));
  533.  
  534.                 if(pparm) free(pparm);
  535.                 if(newpipl) free(newpipl);
  536.                 if(newaete) free(newaete);
  537.         }else
  538.                 dbglasterror((TCHAR*)TEXT("BeginUpdateResource"));
  539.         return !discard;
  540. }
  541.  
  542. Boolean remove_64_filename_prefix(LPTSTR dstname) {
  543.         // foobar.8bf => foobar.8bf
  544.         // foobar64.8bf => foobar.8bf
  545.         size_t i;
  546.         for (i = xstrlen(dstname); i > 2; i--) {
  547.                 if (dstname[i] == '.') {
  548.                         if ((dstname[i - 2] == '6') && (dstname[i - 1] == '4')) {
  549.                                 size_t tmp = xstrlen(dstname);
  550.                                 memcpy(&dstname[i - 2], &dstname[i], (xstrlen(dstname) - i + 1) * sizeof(TCHAR));
  551.                                 dstname[tmp - 2] = 0;
  552.                                 return true;
  553.                         }
  554.                 }
  555.         }
  556.         return false;
  557. }
  558.  
  559. Boolean add_64_filename_prefix(LPTSTR dstname) {
  560.         // foobar.8bf => foobar64.8bf
  561.         size_t i;
  562.         for (i = xstrlen(dstname); i > 2; i--) {
  563.                 if (dstname[i] == '.') {
  564.                         size_t tmp = xstrlen(dstname);
  565.                         memcpy(&dstname[i + 2], &dstname[i], (xstrlen(dstname) - i + 1) * sizeof(TCHAR));
  566.                         dstname[i] = '6';
  567.                         dstname[i + 1] = '4';
  568.                         dstname[tmp + 2] = 0;
  569.                         return true;
  570.                 }
  571.         }
  572.         return false;
  573. }
  574.  
  575. BOOL FileExists(LPCTSTR szPath) {
  576.         DWORD dwAttrib = GetFileAttributes(szPath);
  577.         return (dwAttrib != INVALID_FILE_ATTRIBUTES &&
  578.                 !(dwAttrib & FILE_ATTRIBUTE_DIRECTORY));
  579. }
  580.  
  581. Boolean extract_file(LPCTSTR lpType, LPCTSTR lpName, FSSpec* dst) {
  582.         HGLOBAL datah;
  583.         LPVOID datap;
  584.         HRSRC datarsrc;
  585.         FILECOUNT datalen;
  586.         FILEREF fptr;
  587.         OSErr res;
  588.  
  589.         if ((datarsrc = FindResource((HMODULE)hDllInstance, lpName, lpType))
  590.                 && (datah = LoadResource((HMODULE)hDllInstance, datarsrc))
  591.                 && (datalen = (FILECOUNT)SizeofResource((HMODULE)hDllInstance, datarsrc))
  592.                 && (datap = (Ptr)LockResource(datah))) {
  593.  
  594.                 FSpDelete(dst);
  595.                 if (FSpCreate(dst, kPhotoshopSignature, PS_FILTER_FILETYPE, 0/*sfr->sfScript*/) != noErr) return false;
  596.  
  597.                 if (FSpOpenDF(dst, fsRdWrPerm, &fptr) != noErr) return false;
  598.  
  599.                 res = FSWrite(fptr, &datalen, datap);
  600.  
  601.                 FSClose(fptr);
  602.  
  603.                 return res == noErr;
  604.         }
  605.         else {
  606.                 return false;
  607.         }
  608. }
  609.  
  610. BOOL StripAuthenticode(FSSpec* dst) {
  611.         HANDLE hFile = CreateFile(&dst->szName[0], GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, 0, NULL);
  612.         if (hFile == INVALID_HANDLE_VALUE) {
  613.                 CloseHandle(hFile);
  614.                 return FALSE;
  615.         }
  616.         if (!_ImageRemoveCertificate(hFile, 0)) {
  617.                 CloseHandle(hFile);
  618.                 return FALSE;
  619.         }
  620.         CloseHandle(hFile);
  621.         return TRUE;
  622. }
  623.  
  624. OSErr do_make_standalone(FSSpec* dst, int bits) {
  625.         char errA[MAX_PATH + 200];
  626.         #ifdef UNICODE
  627.         TCHAR errW[MAX_PATH + 200];
  628.         #endif
  629.         Boolean res;
  630.  
  631.         //DeleteFile(dstname);
  632.         if (extract_file(TEXT("TPLT"), MAKEINTRESOURCE(1000 + bits), dst)) {
  633.                 // In case we did digitally sign the FilterFoundry plugin (which is currently not the case though),
  634.                 // we must now remove the signature, because the embedding of parameter data has invalidated it.
  635.                 // Do it before we manipulate anything, in order to avoid that there is an invalid binary (which might annoy AntiVirus software)
  636.                 StripAuthenticode(dst);
  637.  
  638.                 // Now do the resources
  639.                 res = doresources(dst, bits);
  640.                 if (!res) {
  641.                         DeleteFile(&dst->szName[0]);
  642.  
  643.                         sprintf(errA, "Could not create %d bit standalone plugin (doresources failed).", bits);
  644.                         #ifdef UNICODE
  645.                         mbstowcs(errW, errA, MAX_PATH + 200);
  646.                         simplealert(&errW[0]);
  647.                         #else
  648.                         simplealert(&errA[0]);
  649.                         #endif
  650.                 }
  651.         }
  652.         else {
  653.                 // If you see this error, please make sure that you have called foundry_3264_mixer to include the 32/64 plugins as resource!
  654.                 res = false;
  655.                 //DeleteFile(dstname);
  656.  
  657.                 sprintf(errA, "Could not create %d bit standalone plugin (File extraction failed).", bits);
  658.                 #ifdef UNICODE
  659.                 mbstowcs(errW, errA, MAX_PATH + 200);
  660.                 simplealert(&errW[0]);
  661.                 #else
  662.                 simplealert(&errA[0]);
  663.                 #endif
  664.         }
  665.  
  666.         return res ? noErr : ioErr;
  667. }
  668.  
  669. OSErr make_standalone(StandardFileReply *sfr){
  670.         OSErr tmpErr, outErr;
  671.         FSSpec dst = { 0 };
  672.  
  673.         outErr = noErr;
  674.  
  675.         // Make 32 bit:
  676.         // Destfile = no64_or_32(chosenname)
  677.         xstrcpy(dst.szName, sfr->sfFile.szName);
  678.         remove_64_filename_prefix(&dst.szName[0]);
  679.         tmpErr = do_make_standalone(&dst, 32);
  680.         if (tmpErr != noErr)
  681.                 outErr = tmpErr;
  682.         else
  683.                 showmessage((TCHAR*)TEXT("32 bit standalone filter was successfully created"));
  684.  
  685.         // Make 64 bit:
  686.         // Destfile = no64_or_32(chosenname) + 64
  687.         xstrcpy(dst.szName, sfr->sfFile.szName);
  688.         remove_64_filename_prefix(&dst.szName[0]);
  689.         add_64_filename_prefix(&dst.szName[0]);
  690.         tmpErr = do_make_standalone(&dst, 64);
  691.         if (tmpErr != noErr)
  692.                 outErr = tmpErr;
  693.         else
  694.                 showmessage((TCHAR*)TEXT("64 bit standalone filter was successfully created"));
  695.  
  696.         return outErr;
  697. }
  698.  
  699.