mirror of
https://github.com/Ylianst/MeshAgent
synced 2025-12-10 21:33:38 +00:00
Major agent update.
This commit is contained in:
330
.gitignore
vendored
Normal file
330
.gitignore
vendored
Normal file
@@ -0,0 +1,330 @@
|
||||
## Ignore Visual Studio temporary files, build results, and
|
||||
## files generated by popular Visual Studio add-ons.
|
||||
##
|
||||
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
|
||||
|
||||
# User-specific files
|
||||
*.suo
|
||||
*.user
|
||||
*.userosscache
|
||||
*.sln.docstates
|
||||
|
||||
# User-specific files (MonoDevelop/Xamarin Studio)
|
||||
*.userprefs
|
||||
|
||||
# Build results
|
||||
[Dd]ebug/
|
||||
[Dd]ebugPublic/
|
||||
[Rr]elease/
|
||||
[Rr]eleases/
|
||||
#x64/
|
||||
#x86/
|
||||
bld/
|
||||
[Bb]in/
|
||||
[Oo]bj/
|
||||
[Ll]og/
|
||||
Debug_NoOpenSSL/
|
||||
Release_NoOpenSSL/
|
||||
Library_Debug_NoOpenSSL/
|
||||
Library_Release_NoOpenSSL/
|
||||
|
||||
# Visual Studio 2015/2017 cache/options directory
|
||||
.vs/
|
||||
# Uncomment if you have tasks that create the project's static files in wwwroot
|
||||
#wwwroot/
|
||||
|
||||
# Visual Studio 2017 auto generated files
|
||||
Generated\ Files/
|
||||
|
||||
# MSTest test Results
|
||||
[Tt]est[Rr]esult*/
|
||||
[Bb]uild[Ll]og.*
|
||||
|
||||
# NUNIT
|
||||
*.VisualState.xml
|
||||
TestResult.xml
|
||||
|
||||
# Build Results of an ATL Project
|
||||
[Dd]ebugPS/
|
||||
[Rr]eleasePS/
|
||||
dlldata.c
|
||||
|
||||
# Benchmark Results
|
||||
BenchmarkDotNet.Artifacts/
|
||||
|
||||
# .NET Core
|
||||
project.lock.json
|
||||
project.fragment.lock.json
|
||||
artifacts/
|
||||
**/Properties/launchSettings.json
|
||||
|
||||
# StyleCop
|
||||
StyleCopReport.xml
|
||||
|
||||
# Files built by Visual Studio
|
||||
*_i.c
|
||||
*_p.c
|
||||
*_i.h
|
||||
*.ilk
|
||||
*.meta
|
||||
*.obj
|
||||
*.pch
|
||||
*.pdb
|
||||
*.pgc
|
||||
*.pgd
|
||||
*.rsp
|
||||
*.sbr
|
||||
*.tlb
|
||||
*.tli
|
||||
*.tlh
|
||||
*.tmp
|
||||
*.tmp_proj
|
||||
*.log
|
||||
*.vspscc
|
||||
*.vssscc
|
||||
.builds
|
||||
*.pidb
|
||||
*.svclog
|
||||
*.scc
|
||||
|
||||
# Chutzpah Test files
|
||||
_Chutzpah*
|
||||
|
||||
# Visual C++ cache files
|
||||
ipch/
|
||||
*.aps
|
||||
*.ncb
|
||||
*.opendb
|
||||
*.opensdf
|
||||
*.sdf
|
||||
*.cachefile
|
||||
*.VC.db
|
||||
*.VC.VC.opendb
|
||||
|
||||
# Visual Studio profiler
|
||||
*.psess
|
||||
*.vsp
|
||||
*.vspx
|
||||
*.sap
|
||||
|
||||
# Visual Studio Trace Files
|
||||
*.e2e
|
||||
|
||||
# TFS 2012 Local Workspace
|
||||
$tf/
|
||||
|
||||
# Guidance Automation Toolkit
|
||||
*.gpState
|
||||
|
||||
# ReSharper is a .NET coding add-in
|
||||
_ReSharper*/
|
||||
*.[Rr]e[Ss]harper
|
||||
*.DotSettings.user
|
||||
|
||||
# JustCode is a .NET coding add-in
|
||||
.JustCode
|
||||
|
||||
# TeamCity is a build add-in
|
||||
_TeamCity*
|
||||
|
||||
# DotCover is a Code Coverage Tool
|
||||
*.dotCover
|
||||
|
||||
# AxoCover is a Code Coverage Tool
|
||||
.axoCover/*
|
||||
!.axoCover/settings.json
|
||||
|
||||
# Visual Studio code coverage results
|
||||
*.coverage
|
||||
*.coveragexml
|
||||
|
||||
# NCrunch
|
||||
_NCrunch_*
|
||||
.*crunch*.local.xml
|
||||
nCrunchTemp_*
|
||||
|
||||
# MightyMoose
|
||||
*.mm.*
|
||||
AutoTest.Net/
|
||||
|
||||
# Web workbench (sass)
|
||||
.sass-cache/
|
||||
|
||||
# Installshield output folder
|
||||
[Ee]xpress/
|
||||
|
||||
# DocProject is a documentation generator add-in
|
||||
DocProject/buildhelp/
|
||||
DocProject/Help/*.HxT
|
||||
DocProject/Help/*.HxC
|
||||
DocProject/Help/*.hhc
|
||||
DocProject/Help/*.hhk
|
||||
DocProject/Help/*.hhp
|
||||
DocProject/Help/Html2
|
||||
DocProject/Help/html
|
||||
|
||||
# Click-Once directory
|
||||
publish/
|
||||
|
||||
# Publish Web Output
|
||||
*.[Pp]ublish.xml
|
||||
*.azurePubxml
|
||||
# Note: Comment the next line if you want to checkin your web deploy settings,
|
||||
# but database connection strings (with potential passwords) will be unencrypted
|
||||
*.pubxml
|
||||
*.publishproj
|
||||
|
||||
# Microsoft Azure Web App publish settings. Comment the next line if you want to
|
||||
# checkin your Azure Web App publish settings, but sensitive information contained
|
||||
# in these scripts will be unencrypted
|
||||
PublishScripts/
|
||||
|
||||
# NuGet Packages
|
||||
*.nupkg
|
||||
# The packages folder can be ignored because of Package Restore
|
||||
**/[Pp]ackages/*
|
||||
# except build/, which is used as an MSBuild target.
|
||||
!**/[Pp]ackages/build/
|
||||
# Uncomment if necessary however generally it will be regenerated when needed
|
||||
#!**/[Pp]ackages/repositories.config
|
||||
# NuGet v3's project.json files produces more ignorable files
|
||||
*.nuget.props
|
||||
*.nuget.targets
|
||||
|
||||
# Microsoft Azure Build Output
|
||||
csx/
|
||||
*.build.csdef
|
||||
|
||||
# Microsoft Azure Emulator
|
||||
ecf/
|
||||
rcf/
|
||||
|
||||
# Windows Store app package directories and files
|
||||
AppPackages/
|
||||
BundleArtifacts/
|
||||
Package.StoreAssociation.xml
|
||||
_pkginfo.txt
|
||||
*.appx
|
||||
|
||||
# Visual Studio cache files
|
||||
# files ending in .cache can be ignored
|
||||
*.[Cc]ache
|
||||
# but keep track of directories ending in .cache
|
||||
!*.[Cc]ache/
|
||||
|
||||
# Others
|
||||
ClientBin/
|
||||
~$*
|
||||
*~
|
||||
*.dbmdl
|
||||
*.dbproj.schemaview
|
||||
*.jfm
|
||||
*.pfx
|
||||
*.publishsettings
|
||||
orleans.codegen.cs
|
||||
|
||||
# Including strong name files can present a security risk
|
||||
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
|
||||
#*.snk
|
||||
|
||||
# Since there are multiple workflows, uncomment next line to ignore bower_components
|
||||
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
|
||||
#bower_components/
|
||||
|
||||
# RIA/Silverlight projects
|
||||
Generated_Code/
|
||||
|
||||
# Backup & report files from converting an old project file
|
||||
# to a newer Visual Studio version. Backup files are not needed,
|
||||
# because we have git ;-)
|
||||
_UpgradeReport_Files/
|
||||
Backup*/
|
||||
UpgradeLog*.XML
|
||||
UpgradeLog*.htm
|
||||
ServiceFabricBackup/
|
||||
|
||||
# SQL Server files
|
||||
*.mdf
|
||||
*.ldf
|
||||
*.ndf
|
||||
|
||||
# Business Intelligence projects
|
||||
*.rdl.data
|
||||
*.bim.layout
|
||||
*.bim_*.settings
|
||||
|
||||
# Microsoft Fakes
|
||||
FakesAssemblies/
|
||||
|
||||
# GhostDoc plugin setting file
|
||||
*.GhostDoc.xml
|
||||
|
||||
# Node.js Tools for Visual Studio
|
||||
.ntvs_analysis.dat
|
||||
node_modules/
|
||||
|
||||
# TypeScript v1 declaration files
|
||||
typings/
|
||||
|
||||
# Visual Studio 6 build log
|
||||
*.plg
|
||||
|
||||
# Visual Studio 6 workspace options file
|
||||
*.opt
|
||||
|
||||
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
|
||||
*.vbw
|
||||
|
||||
# Visual Studio LightSwitch build output
|
||||
**/*.HTMLClient/GeneratedArtifacts
|
||||
**/*.DesktopClient/GeneratedArtifacts
|
||||
**/*.DesktopClient/ModelManifest.xml
|
||||
**/*.Server/GeneratedArtifacts
|
||||
**/*.Server/ModelManifest.xml
|
||||
_Pvt_Extensions
|
||||
|
||||
# Paket dependency manager
|
||||
.paket/paket.exe
|
||||
paket-files/
|
||||
|
||||
# FAKE - F# Make
|
||||
.fake/
|
||||
|
||||
# JetBrains Rider
|
||||
.idea/
|
||||
*.sln.iml
|
||||
|
||||
# CodeRush
|
||||
.cr/
|
||||
|
||||
# Python Tools for Visual Studio (PTVS)
|
||||
__pycache__/
|
||||
*.pyc
|
||||
|
||||
# Cake - Uncomment if you are using it
|
||||
# tools/**
|
||||
# !tools/packages.config
|
||||
|
||||
# Tabs Studio
|
||||
*.tss
|
||||
|
||||
# Telerik's JustMock configuration file
|
||||
*.jmconfig
|
||||
|
||||
# BizTalk build output
|
||||
*.btp.cs
|
||||
*.btm.cs
|
||||
*.odx.cs
|
||||
*.xsd.cs
|
||||
|
||||
# OpenCover UI analysis results
|
||||
OpenCover/
|
||||
|
||||
# Azure Stream Analytics local run output
|
||||
ASALocalRun/
|
||||
|
||||
# MSBuild Binary and Structured Log
|
||||
*.binlog
|
||||
|
||||
# Klocwork
|
||||
.klocwork/
|
||||
499
DevOps/ProtexAutomation/GenerateCOSReport/COS.html
Normal file
499
DevOps/ProtexAutomation/GenerateCOSReport/COS.html
Normal file
File diff suppressed because one or more lines are too long
BIN
DevOps/ProtexAutomation/GenerateCOSReport/COS.xls
Normal file
BIN
DevOps/ProtexAutomation/GenerateCOSReport/COS.xls
Normal file
Binary file not shown.
BIN
DevOps/ProtexAutomation/GenerateCOSReport/GetCOSReport.jar
Normal file
BIN
DevOps/ProtexAutomation/GenerateCOSReport/GetCOSReport.jar
Normal file
Binary file not shown.
226
DevOps/ProtexAutomation/GenerateCOSReport/GetCOSReport.java
Normal file
226
DevOps/ProtexAutomation/GenerateCOSReport/GetCOSReport.java
Normal file
@@ -0,0 +1,226 @@
|
||||
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
|
||||
import javax.xml.ws.soap.SOAPFaultException;
|
||||
|
||||
import com.blackducksoftware.sdk.fault.SdkFault;
|
||||
import com.blackducksoftware.sdk.protex.client.util.BDProtexSample;
|
||||
import com.blackducksoftware.sdk.protex.client.util.ProtexServerProxy;
|
||||
import com.blackducksoftware.sdk.protex.project.Project;
|
||||
import com.blackducksoftware.sdk.protex.project.ProjectApi;
|
||||
import com.blackducksoftware.sdk.protex.report.Report;
|
||||
import com.blackducksoftware.sdk.protex.report.ReportApi;
|
||||
import com.blackducksoftware.sdk.protex.report.ReportFormat;
|
||||
import com.blackducksoftware.sdk.protex.report.ReportSection;
|
||||
import com.blackducksoftware.sdk.protex.report.ReportSectionType;
|
||||
import com.blackducksoftware.sdk.protex.report.ReportTemplateRequest;
|
||||
|
||||
|
||||
/**
|
||||
* This sample generates COS report and writes it to a file in HTML and xls
|
||||
*
|
||||
* It demonstrates:
|
||||
* - How to generate a report from a client side supplied template
|
||||
* - How to receive this report and write it to a file (using MTOM - Attachments)
|
||||
*/
|
||||
public class GetCOSReport extends BDProtexSample {
|
||||
|
||||
|
||||
private static void usage() {
|
||||
System.out.println("Input Parameters:" );
|
||||
System.out.println("arg[0] - Protex server URL");
|
||||
System.out.println("arg[1] - Protex user ID");
|
||||
System.out.println("arg[2] - Password");
|
||||
System.out.println("arg[3] - Project ID");
|
||||
System.out.println("arg[4] - Output path\\Filename (without extension)");
|
||||
System.out.println("arg[5] - SCS Report Header text");
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
// check and save parameters
|
||||
if (args.length < 5) {
|
||||
System.err.println("Not enough parameters!");
|
||||
usage();
|
||||
System.exit(-1);
|
||||
}
|
||||
|
||||
String serverUri = args[0];
|
||||
String username = args[1];
|
||||
String password = args[2];
|
||||
String projectId = args[3];
|
||||
String reportFileName = args[4];
|
||||
//String headerText = args[5];
|
||||
String tableOfContents = "true";
|
||||
|
||||
ReportApi reportApi = null;
|
||||
ProjectApi projectApi = null;
|
||||
try {
|
||||
Long connectionTimeout = 120 * 1000L;
|
||||
ProtexServerProxy myProtexServer = new ProtexServerProxy(serverUri, username, password,
|
||||
connectionTimeout);
|
||||
|
||||
reportApi = myProtexServer.getReportApi(15 * connectionTimeout);
|
||||
projectApi = myProtexServer.getProjectApi(15 * connectionTimeout);
|
||||
|
||||
} catch (RuntimeException e) {
|
||||
System.err.println("Connection to server '" + serverUri + "' failed: " + e.getMessage());
|
||||
System.exit(-1);
|
||||
}
|
||||
Boolean showTOC = Boolean.valueOf("true".equals(tableOfContents));
|
||||
|
||||
//now get the rest of the report data
|
||||
ReportTemplateRequest templateRequest = new ReportTemplateRequest();
|
||||
templateRequest.setName(projectId);
|
||||
Project project = projectApi.getProjectById(projectId);
|
||||
String projectName = project.getName();
|
||||
templateRequest.setTitle("Protex COS Report for " + projectName);
|
||||
//templateRequest.setHeader(headerText);
|
||||
templateRequest.setForced(Boolean.TRUE);
|
||||
//templateRequest.setTableofcontents("TOC");
|
||||
|
||||
|
||||
|
||||
ReportSection section = new ReportSection();
|
||||
section.setLabel("Summary");
|
||||
section.setSectionType(ReportSectionType.SUMMARY);
|
||||
templateRequest.getSections().add(section);
|
||||
|
||||
section = new ReportSection();
|
||||
section.setLabel("Analysis Summary");
|
||||
section.setSectionType(ReportSectionType.ANALYSIS_SUMMARY);
|
||||
templateRequest.getSections().add(section);
|
||||
|
||||
section = new ReportSection();
|
||||
section.setLabel("BOM");
|
||||
section.setSectionType(ReportSectionType.BILL_OF_MATERIALS);
|
||||
templateRequest.getSections().add(section);
|
||||
|
||||
section = new ReportSection();
|
||||
section.setLabel("Licenses in Effect");
|
||||
section.setSectionType(ReportSectionType.LICENSES_IN_EFFECT);
|
||||
templateRequest.getSections().add(section);
|
||||
|
||||
section = new ReportSection();
|
||||
section.setLabel("License Conflicts");
|
||||
section.setSectionType(ReportSectionType.LICENSE_CONFLICTS);
|
||||
templateRequest.getSections().add(section);
|
||||
|
||||
section = new ReportSection();
|
||||
section.setLabel("File Inventory");
|
||||
section.setSectionType(ReportSectionType.FILE_INVENTORY);
|
||||
templateRequest.getSections().add(section);
|
||||
|
||||
section = new ReportSection();
|
||||
section.setLabel("IP Architecture");
|
||||
section.setSectionType(ReportSectionType.IP_ARCHITECTURE);
|
||||
templateRequest.getSections().add(section);
|
||||
|
||||
section = new ReportSection();
|
||||
section.setLabel("Obligations");
|
||||
section.setSectionType(ReportSectionType.OBLIGATIONS);
|
||||
templateRequest.getSections().add(section);
|
||||
|
||||
section = new ReportSection();
|
||||
section.setLabel("Identified Files");
|
||||
section.setSectionType(ReportSectionType.IDENTIFIED_FILES);
|
||||
templateRequest.getSections().add(section);
|
||||
|
||||
section = new ReportSection();
|
||||
section.setLabel("Excluded Components");
|
||||
section.setSectionType(ReportSectionType.EXCLUDED_COMPONENTS);
|
||||
templateRequest.getSections().add(section);
|
||||
|
||||
section = new ReportSection();
|
||||
section.setLabel("Work History - Bill of Material");
|
||||
section.setSectionType(ReportSectionType.WORK_HISTORY_BILL_OF_MATERIALS);
|
||||
templateRequest.getSections().add(section);
|
||||
|
||||
section = new ReportSection();
|
||||
section.setLabel("Work History - File Inventory");
|
||||
section.setSectionType(ReportSectionType.WORK_HISTORY_FILE_INVENTORY);
|
||||
templateRequest.getSections().add(section);
|
||||
|
||||
section = new ReportSection();
|
||||
section.setLabel("Potential Bill Of Materials");
|
||||
section.setSectionType(ReportSectionType.POTENTIAL_BILL_OF_MATERIALS);
|
||||
templateRequest.getSections().add(section);
|
||||
|
||||
section = new ReportSection();
|
||||
section.setLabel("Searches");
|
||||
section.setSectionType(ReportSectionType.STRING_SEARCHES);
|
||||
templateRequest.getSections().add(section);
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// Call the Api
|
||||
Report reportHTML = null;
|
||||
Report reportXLS = null;
|
||||
try {
|
||||
try {
|
||||
reportHTML = reportApi.generateAdHocProjectReport(projectId, templateRequest, ReportFormat.HTML, showTOC);
|
||||
reportXLS = reportApi.generateAdHocProjectReport(projectId, templateRequest, ReportFormat.XLS, showTOC);
|
||||
} catch (SdkFault e) {
|
||||
System.err.println("generateProjectReport failed: " + e.getMessage());
|
||||
System.exit(-1);
|
||||
}
|
||||
|
||||
// Check for valid return
|
||||
if (reportHTML == null || reportXLS == null) {
|
||||
System.err.println("unexpected return object");
|
||||
System.exit(-1);
|
||||
}
|
||||
|
||||
if (reportHTML.getFileName() == null || reportXLS.getFileName() == null) {
|
||||
System.err.println("unexpected return object: File name can't be null or empty");
|
||||
System.exit(-1);
|
||||
}
|
||||
|
||||
if (reportHTML.getFileContent() == null || reportXLS.getFileContent() == null) {
|
||||
System.err.println("unexpected return object: File content can't be null or empty");
|
||||
System.exit(-1);
|
||||
}
|
||||
|
||||
File transferredFileHTML = new File(reportFileName + ".html");
|
||||
File transferredFileXLS = new File(reportFileName + ".xls");
|
||||
FileOutputStream outStream = null;
|
||||
try {
|
||||
|
||||
outStream = new FileOutputStream(transferredFileHTML);
|
||||
reportHTML.getFileContent().writeTo(outStream);
|
||||
} catch (IOException e) {
|
||||
System.err.println("report.getFileContent().writeTo() failed: " + e.getMessage());
|
||||
System.exit(-1);
|
||||
} finally {
|
||||
if (outStream != null) {
|
||||
outStream.close();
|
||||
}
|
||||
}
|
||||
System.out.println("\nHTML Report written to: " + transferredFileHTML.getAbsolutePath());
|
||||
|
||||
try {
|
||||
|
||||
outStream = new FileOutputStream(transferredFileXLS);
|
||||
reportXLS.getFileContent().writeTo(outStream);
|
||||
} catch (IOException e) {
|
||||
System.err.println("report.getFileContent().writeTo() failed: " + e.getMessage());
|
||||
System.exit(-1);
|
||||
} finally {
|
||||
if (outStream != null) {
|
||||
outStream.close();
|
||||
}
|
||||
}
|
||||
System.out.println("\nXLS Report written to: " + transferredFileXLS.getAbsolutePath());
|
||||
} catch (SOAPFaultException e) {
|
||||
System.err.println("SampleGenerateReportFromTemplate failed: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
System.exit(-1);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
18
DevOps/ProtexAutomation/GenerateCOSReport/ReadMe.txt
Normal file
18
DevOps/ProtexAutomation/GenerateCOSReport/ReadMe.txt
Normal file
@@ -0,0 +1,18 @@
|
||||
GetCOSReport.java will generate Code Origination Scan (COS) report from the Protex project specified and writes to
|
||||
a output file in HTML and xls format
|
||||
|
||||
How to Execute:
|
||||
java -jar GetCOSReport.jar <Protex server URL> <User ID> <User Password> <Project ID> <Output Path\Filename without extension>
|
||||
|
||||
Input Parameters:
|
||||
IN arg[0] - Protex server URL
|
||||
IN arg[1] - User ID
|
||||
IN arg[2] - Password
|
||||
IN arg[3] - Protex project ID
|
||||
OUT arg[4] - Output Path\filename (without file extension)
|
||||
Example:
|
||||
java -jar GetCOSReport.jar http://jfipscn01.intel.com abc@intel.com abc MyTest_5271 c:\ScanResults\MyTest_COS
|
||||
|
||||
Output:
|
||||
c:\ScanResults\MyTest_COS.html
|
||||
c:\ScanResults\MyTest_COS.xls
|
||||
Binary file not shown.
@@ -0,0 +1,126 @@
|
||||
import java.io.*;
|
||||
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.Node;
|
||||
import org.w3c.dom.NodeList;
|
||||
|
||||
public class GenerateCodeCenterDashboard {
|
||||
|
||||
private static void usage() {
|
||||
System.out.println("Input Parameters:" );
|
||||
System.out.println("Folder path\\name - Location and folder name where all Code Center xml files are stored\n" +
|
||||
"File path\\name - location and filename to store the dashboard summary html report ");
|
||||
System.out.println("");
|
||||
|
||||
}
|
||||
|
||||
/**********************************************************************************
|
||||
*
|
||||
* @param xml file generated by GetAssociateAndValidateResult script
|
||||
* @return HTML String
|
||||
*********************************************************************************/
|
||||
public String getCodeCenterResult(File file) {
|
||||
try {
|
||||
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
|
||||
DocumentBuilder db = dbf.newDocumentBuilder();
|
||||
//System.out.println("Exists: " + file.getName() + " " + file.exists());
|
||||
if (file.exists()) {
|
||||
Document doc = db.parse(file);
|
||||
|
||||
|
||||
|
||||
NodeList appList = doc.getElementsByTagName("Application");
|
||||
Node appName = appList.item(0);
|
||||
Element appElement = (Element) appName;
|
||||
|
||||
NodeList validList = doc.getElementsByTagName("ValidationStatus");
|
||||
Node validNode = validList.item(0);
|
||||
Element validElement = (Element) validNode;
|
||||
|
||||
NodeList approveList = doc.getElementsByTagName("ApprovedStatus");
|
||||
Node approveNode = approveList.item(0);
|
||||
Element approveElement = (Element) approveNode;
|
||||
|
||||
|
||||
String prj_str = "<tr><td style='text-align: center;'>" + appElement.getTextContent() + "</td>";
|
||||
if (validElement.getTextContent().equals("PASSED"))
|
||||
prj_str = prj_str + "<td style='text-align: center;'>" + validElement.getTextContent() + "</td>";
|
||||
else
|
||||
prj_str = prj_str + "<td style='text-align: center;': bgcolor=gold> <b> <font color=red>" + validElement.getTextContent() + "</td>";
|
||||
|
||||
if (approveElement.getTextContent().equals("APPROVED"))
|
||||
prj_str = prj_str + "<td style='text-align: center;'>" + approveElement.getTextContent() + "</td></tr>";
|
||||
else
|
||||
prj_str = prj_str + "<td style='text-align: center;': bgcolor=gold> <b> <font color=red>" + approveElement.getTextContent() + "</td></tr>";
|
||||
|
||||
|
||||
return prj_str;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println(e);
|
||||
}
|
||||
return "Error!! Parsing XML reports";
|
||||
}
|
||||
|
||||
/***********************************************************************************
|
||||
* main()
|
||||
* @param args
|
||||
***********************************************************************************/
|
||||
public static void main(String[] args)
|
||||
{
|
||||
|
||||
if (args.length < 2) {
|
||||
System.err.println("Not enough parameters!");
|
||||
usage();
|
||||
System.exit(-1);
|
||||
}
|
||||
|
||||
GenerateCodeCenterDashboard parser = new GenerateCodeCenterDashboard();
|
||||
String filename;
|
||||
File folder = new File( args[0] );
|
||||
File[] listOfFiles = folder.listFiles();
|
||||
String html_content = "";
|
||||
String OSName = null;
|
||||
String delimiter = null;
|
||||
OSName = System.getProperty("os.name");
|
||||
if (OSName.contains("Windows")) delimiter = "\\";
|
||||
else delimiter = "/";
|
||||
|
||||
for (int i = 0; i < listOfFiles.length; i++)
|
||||
{
|
||||
if (listOfFiles[i].isFile())
|
||||
{
|
||||
filename = folder.getPath() + delimiter + listOfFiles[i].getName();
|
||||
//System.out.println("File: " + filename);
|
||||
if (filename.endsWith(".xml") || filename.endsWith(".XML"))
|
||||
{
|
||||
File filehandle = new File(filename);
|
||||
String prj_str = parser.getCodeCenterResult( filehandle );
|
||||
html_content = html_content + prj_str;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
File f = new File(args[1]);
|
||||
try {
|
||||
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
|
||||
bw.write( "<html><body>"
|
||||
+ "<h1> <span style='text-align:center;font-weight:bold'> Code Center Summary </span></h1>"
|
||||
+ "<table border='2px'>"
|
||||
+ "<tr style='background-color: rgb(240, 240, 240);'>"
|
||||
+ "<th style='border-left: 1px solid;'> Code Center Application </th>"
|
||||
+ "<th style='border-left: 1px solid;'> Validation Status </th>"
|
||||
+ "<th style='border-left: 1px solid;'> Approval Status </th>"
|
||||
+ "</tr>"
|
||||
+ html_content + "</table></body></html>" ) ;
|
||||
|
||||
bw.close();
|
||||
} catch (Exception e) {
|
||||
System.out.println(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
GenerateCodeCenterDashboard.java parses the Code Center Application results xml files generated by GetAssociateAndValidateResult.java;
|
||||
read the data and writes the data in a summary (Dashboard) into the output html file.
|
||||
NOTE: All the Code Center Application xml files are required to be stored in a single folder
|
||||
|
||||
How to Execute:
|
||||
java -jar GenerateProtexScanDashboard.jar <stored scan files Path\foldername> <output file path\filename>
|
||||
|
||||
Input Parameters:
|
||||
IN arg[0] - Location (PATH) of Code Center result files
|
||||
OUT arg[1] - Dashboard Output Path\filename.html
|
||||
|
||||
|
||||
Example:
|
||||
Windows> java -jar GenerateCodeCenterDashboard.jar c:\Results\CCXML c:\Results\CodeCenter_Dashboard.html
|
||||
Linux> java -jar GenerateCodeCenterDashboard.jar /Results/CCXML /Results/CodeCenter_Dashboard.html
|
||||
|
||||
Output:
|
||||
Windows: c:\Results\CodeCenter_Dashboard.html (Will contain scan result summary of all Code Center xml files)
|
||||
Linux: /Results/CodeCenter_Dashboard.html (Will contain scan result summary of all Code Center xml files)
|
||||
Binary file not shown.
@@ -0,0 +1,740 @@
|
||||
|
||||
|
||||
import java.util.List;
|
||||
import java.util.ListIterator;
|
||||
import java.util.regex.Pattern;
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.File;
|
||||
import java.io.FileWriter;
|
||||
|
||||
import com.blackducksoftware.sdk.codecenter.application.ApplicationApi;
|
||||
import com.blackducksoftware.sdk.codecenter.application.data.Application;
|
||||
import com.blackducksoftware.sdk.codecenter.application.data.ApplicationNameVersionOrIdToken;
|
||||
import com.blackducksoftware.sdk.codecenter.application.data.ApplicationNameVersionToken;
|
||||
import com.blackducksoftware.sdk.codecenter.cola.*;
|
||||
import com.blackducksoftware.sdk.codecenter.cola.data.Component;
|
||||
import com.blackducksoftware.sdk.codecenter.cola.data.LicenseNameOrIdToken;
|
||||
import com.blackducksoftware.sdk.codecenter.cola.data.LicenseSummary;
|
||||
import com.blackducksoftware.sdk.codecenter.attribute.AttributeApi;
|
||||
import com.blackducksoftware.sdk.codecenter.attribute.data.AbstractAttribute;
|
||||
import com.blackducksoftware.sdk.codecenter.attribute.data.AttributeNameOrIdToken;
|
||||
import com.blackducksoftware.sdk.codecenter.client.util.BDSCodeCenterSample;
|
||||
import com.blackducksoftware.sdk.codecenter.client.util.CodeCenterServerProxyV7_0;
|
||||
import com.blackducksoftware.sdk.codecenter.common.data.ApprovalStatusEnum;
|
||||
import com.blackducksoftware.sdk.codecenter.common.data.AttributeValue;
|
||||
import com.blackducksoftware.sdk.codecenter.fault.SdkFault;
|
||||
import com.blackducksoftware.sdk.codecenter.request.RequestApi;
|
||||
import com.blackducksoftware.sdk.codecenter.request.data.*;
|
||||
|
||||
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// This sample file extract application details, application metadata, BOMs, request for metadata and
|
||||
// each components metadata in BOM. It stores all the data in an HTML format into the file passed as argument
|
||||
// The output file if the IP Plan of the application
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
public class GenerateIPPlanReport extends BDSCodeCenterSample {
|
||||
|
||||
|
||||
private static void usage() {
|
||||
|
||||
System.out.println("Input Parameters:" );
|
||||
System.out.println("arg[0] - Code Center server URL");
|
||||
System.out.println("arg[1] - Code Center user ID");
|
||||
System.out.println("arg[2] - Password");
|
||||
System.out.println("arg[3] - Application name");
|
||||
System.out.println("arg[4] - Output Path");
|
||||
}
|
||||
|
||||
|
||||
/************************************************************************************
|
||||
* GetComponentData: Get component and component request details for each component in BOM of the application
|
||||
* @param thisapp
|
||||
* @param applicationApi
|
||||
* @param apptoken
|
||||
* @param requestApi
|
||||
* @param colaApi
|
||||
* @param attributeApi
|
||||
* @return String with data in html format
|
||||
************************************************************************************/
|
||||
public String GetComponentData(Application thisapp, ApplicationApi applicationApi, ApplicationNameVersionToken apptoken,
|
||||
RequestApi requestApi, ColaApi colaApi, AttributeApi attributeApi ) {
|
||||
|
||||
|
||||
String ptr_str = "";
|
||||
RequestPageFilter pageFilter = new RequestPageFilter();
|
||||
pageFilter.setFirstRowIndex(0);
|
||||
pageFilter.setLastRowIndex(2000);
|
||||
pageFilter.setSortAscending(false);
|
||||
pageFilter.setSortedColumn(RequestColumn.REQUEST_APPROVAL_STATUS);
|
||||
pageFilter.getApprovalStatuses().add(ApprovalStatusEnum.APPROVED);
|
||||
//get total number of Components in BOM
|
||||
List<RequestSummary> requestsList = null;
|
||||
try {
|
||||
//requestsList = applicationApi.getApplicationRequests(apptoken);
|
||||
requestsList = applicationApi.searchApplicationRequests((ApplicationNameVersionOrIdToken)apptoken, "", pageFilter);
|
||||
|
||||
} catch (Exception e) {
|
||||
System.err.println("getApplicationRequests() failed while fetching the details of the request to be updated: "
|
||||
+ e.getMessage());
|
||||
System.exit(-1);
|
||||
}
|
||||
|
||||
if (requestsList == null) {
|
||||
System.err.println("getApplicationRequests() failed: returned null as result");
|
||||
System.exit(-1);
|
||||
}
|
||||
|
||||
System.out.println("# Requests: " + requestsList.size());
|
||||
|
||||
|
||||
for (RequestSummary request : requestsList) {
|
||||
Component thiscomp = null;
|
||||
Request thisreq = null;
|
||||
String Name = " ";
|
||||
String Version = " ";
|
||||
String License = " ";
|
||||
String ReqLicense = " ";
|
||||
String ReqLicenseUsage = " ";
|
||||
String Description = " ";
|
||||
String Homepage = " ";
|
||||
String Supplier = " ";
|
||||
String SupplierCategory = " ";
|
||||
String SoftwareStackClassification = " ";
|
||||
String SoftwareTechnologyClassification = " ";
|
||||
String SpecificTechnologyClassification = " ";
|
||||
String OperatingSystem = " ";
|
||||
String OperatingSystemOther = " ";
|
||||
String ProgrammingLanguage = " ";
|
||||
String ProgrammingLanguageOther = " ";
|
||||
String DeliveryFormat = " ";
|
||||
String CopyrightOwnership = " ";
|
||||
String LicenseSource = " ";
|
||||
String LicenseLocation = " ";
|
||||
String AdditionalInformationAndComments = " ";
|
||||
String Comments = " ";
|
||||
String SourceLocation = " ";
|
||||
String SourceLocationSub = " ";
|
||||
String VersionRest = " ";
|
||||
String ApprovalStatus = " ";
|
||||
String LocationCntrl = " ";
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// Get the individual component request details like control string,
|
||||
// license source, etc....
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
try {
|
||||
thisreq = requestApi.getRequest(request.getId());
|
||||
} catch (Exception e) {
|
||||
System.err.println("getRequest failed: "
|
||||
+ e.getMessage());
|
||||
System.exit(-1);
|
||||
}//try....catch
|
||||
|
||||
List<AttributeValue> reqAttList = null;
|
||||
try {
|
||||
ReqLicense = thisreq.getLicenseInfo().getNameToken().getName().trim().replaceAll(Pattern.quote("\r\n"), "\n").replaceAll(Pattern.quote("\r"), "\n");
|
||||
} catch (Exception e) {
|
||||
//System.err.println("WARNING: empty Component Request License field");
|
||||
}
|
||||
try {
|
||||
ReqLicenseUsage = thisreq.getUsage().toString();
|
||||
} catch (Exception e) {
|
||||
//System.err.println("WARNING: empty Component Request Usage field");
|
||||
}
|
||||
try {
|
||||
ApprovalStatus = thisreq.getApprovalStatus().toString();
|
||||
} catch (Exception e) {
|
||||
//System.err.println("WARNING: empty Component Request Approval Status field");
|
||||
}
|
||||
try {
|
||||
reqAttList = thisreq.getAttributeValues();
|
||||
} catch (Exception e) {
|
||||
//System.err.println("WARNING: empty Component Request Metadata Values field");
|
||||
}
|
||||
try {
|
||||
if ( null != reqAttList ) {
|
||||
if ( 0 < reqAttList.size() ) {
|
||||
//System.out.println("RequestAttList size is " + reqAttList.size());
|
||||
for (AttributeValue attValue : reqAttList) {
|
||||
AttributeNameOrIdToken attNameToken = attValue.getAttributeId();
|
||||
AbstractAttribute attribute = attributeApi.getAttribute(attNameToken);
|
||||
String attName = attribute.getName().trim();
|
||||
List<String> attStringList = attValue.getValues();
|
||||
|
||||
if (null != attStringList) {
|
||||
if ( 0 < attStringList.size() ) {
|
||||
ListIterator<String> LI = attStringList.listIterator();
|
||||
String attstring = LI.next().trim();
|
||||
while ( LI.hasNext() ) {
|
||||
attstring = attstring + "\n" + LI.next().trim();
|
||||
}
|
||||
attstring = attstring.replaceAll(Pattern.quote("\r\n"), "\n").replaceAll(Pattern.quote("\r"), "\n");
|
||||
if ( attName.equals("CPR - Additional Information and Comments") ) {
|
||||
AdditionalInformationAndComments = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("CPR - License Location") ) {
|
||||
LicenseLocation = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("CPR - License Source") ) {
|
||||
LicenseSource = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("CPR - Location") ) {
|
||||
SourceLocation = attstring.trim();
|
||||
if ( SourceLocation.length() > 0 ) {
|
||||
if ( SourceLocation.startsWith("/") ) {
|
||||
SourceLocation = SourceLocation.substring(1);
|
||||
}
|
||||
if ( SourceLocation.endsWith("/") ) {
|
||||
SourceLocation = SourceLocation.substring(0, (SourceLocation.length() - 1) );
|
||||
}
|
||||
}
|
||||
}
|
||||
if ( attName.equals("CPR - Location - Cntrl") ) {
|
||||
LocationCntrl = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("CPR - Location - Sub") ) {
|
||||
SourceLocationSub = attstring.trim();
|
||||
if ( SourceLocationSub.length() > 0 ) {
|
||||
if ( SourceLocationSub.startsWith("/") ) {
|
||||
SourceLocationSub = SourceLocationSub.substring(1);
|
||||
}
|
||||
if ( SourceLocationSub.endsWith("/") ) {
|
||||
SourceLocationSub = SourceLocationSub.substring(0, (SourceLocationSub.length() - 1) );
|
||||
}
|
||||
}
|
||||
}
|
||||
if ( attName.equals("CPR - Versions") ) {
|
||||
VersionRest = attstring.trim();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.err.println("Failed to create component request data, caught exception: " + e.getMessage());
|
||||
}
|
||||
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// Get the individual component details
|
||||
/////////////////////////////////////////////////////////////////////
|
||||
try {
|
||||
thiscomp = colaApi.getCatalogComponent(request.getComponentId());
|
||||
} catch (Exception e) {
|
||||
System.err.println("getCatalogComponent() failed: "
|
||||
+ e.getMessage());
|
||||
System.exit(-1);
|
||||
}//try....catch
|
||||
|
||||
try {
|
||||
Name = thiscomp.getNameVersion().getName().trim();
|
||||
} catch (Exception e) {
|
||||
System.err.println("WARNING: empty Component Name field");
|
||||
}
|
||||
try {
|
||||
Version = thiscomp.getNameVersion().getVersion().trim();
|
||||
} catch (Exception e) {
|
||||
System.err.println("WARNING: empty Component Version field");
|
||||
}
|
||||
try {
|
||||
Description = thiscomp.getDescription().trim();
|
||||
} catch (Exception e) {
|
||||
System.err.println("WARNING: empty Component Description field");
|
||||
}
|
||||
try {
|
||||
Homepage = thiscomp.getHomepage().trim();
|
||||
} catch (Exception e) {
|
||||
System.err.println("WARNING: empty Component Homepage field");
|
||||
}
|
||||
|
||||
try {
|
||||
//License = thiscomp.getLicenseInfo().getNameToken().getName().trim().replaceAll(Pattern.quote("\r\n"), "\n").replaceAll(Pattern.quote("\r"), "\n");
|
||||
License = thiscomp.getDeclaredLicenses().get(0).getNameToken().getName().trim().replaceAll(Pattern.quote("\r\n"), "\n").replaceAll(Pattern.quote("\r"), "\n");
|
||||
} catch (Exception e) {
|
||||
System.err.println("WARNING: empty Component Declared License field");
|
||||
}
|
||||
List<AttributeValue> compAttList = null;
|
||||
try {
|
||||
compAttList = thiscomp.getAttributeValues();
|
||||
} catch (Exception e) {
|
||||
System.err.println("WARNING: empty Component Attribute Values field");
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// Read the attributes of the component
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
if ( null != compAttList ) {
|
||||
if ( 0 < compAttList.size() ) {
|
||||
for (AttributeValue attValue : compAttList) {
|
||||
|
||||
AttributeNameOrIdToken attNameToken = attValue.getAttributeId();
|
||||
AbstractAttribute attribute = null;
|
||||
try {
|
||||
attribute = attributeApi.getAttribute(attNameToken);
|
||||
} catch (SdkFault e) {
|
||||
System.err.println("WARNING: empty Component Attributes field");
|
||||
}
|
||||
String attName = attribute.getName().trim();
|
||||
|
||||
List<String> attStringList = attValue.getValues();
|
||||
if (null != attStringList) {
|
||||
if ( 0 < attStringList.size() ) {
|
||||
ListIterator<String> LI = attStringList.listIterator();
|
||||
String attstring = LI.next().trim();
|
||||
while ( LI.hasNext() ) {
|
||||
attstring = attstring + "\n\n\n" + LI.next().trim();
|
||||
}
|
||||
attstring = attstring.replaceAll(Pattern.quote("\r\n"), "\n").replaceAll(Pattern.quote("\r"), "\n");
|
||||
if ( attName.equals("APP/CPC - SW Stack Classification") ) {
|
||||
SoftwareStackClassification = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("APP/CPC - SW Technology Classification") ) {
|
||||
SoftwareTechnologyClassification = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("APP/CPC - SW Technology Classification - Other") ) {
|
||||
SpecificTechnologyClassification = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("CPC - Copyright Ownership") ) {
|
||||
CopyrightOwnership = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("CPC - Distribution Type") ) {
|
||||
DeliveryFormat = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("CPC - Operating System") ) {
|
||||
OperatingSystem = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("CPC - Operating System - Other") ) {
|
||||
OperatingSystemOther = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("CPC - Programming Language") ) {
|
||||
ProgrammingLanguage = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("CPC - Programming Language - Other") ) {
|
||||
ProgrammingLanguageOther = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("CPC - Software Supplier Category") ) {
|
||||
SupplierCategory = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("CPC - Supplier Name") ) {
|
||||
Supplier = attstring.trim();
|
||||
}
|
||||
|
||||
}//if attstringlist
|
||||
|
||||
} //if attstringlist
|
||||
} //For each compattlist
|
||||
} //if compAttsize
|
||||
ptr_str = ptr_str + "<tr><td style='text-align: center;'>" + Name + "</td>"
|
||||
+ "<td style='text-align: center;'>" + Version + "</td>"
|
||||
+ "<td style='text-align: center;'>" + License + "</td>"
|
||||
+ "<td style='text-align: center;'>" + Description + "</td>"
|
||||
+ "<td style='text-align: center;'>" + Homepage + "</td>"
|
||||
+ "<td style='text-align: center;'>" + Supplier + "</td>"
|
||||
+ "<td style='text-align: center;'>" + SupplierCategory + "</td>"
|
||||
+ "<td style='text-align: center;'>" + SoftwareStackClassification + "</td>"
|
||||
+ "<td style='text-align: center;'>" + SoftwareTechnologyClassification + "</td>"
|
||||
+ "<td style='text-align: center;'>" + SpecificTechnologyClassification + "</td>"
|
||||
+ "<td style='text-align: center;'>" + OperatingSystem + "</td>"
|
||||
+ "<td style='text-align: center;'>" + ProgrammingLanguage + "</td>"
|
||||
+ "<td style='text-align: center;'>" + DeliveryFormat + "</td>"
|
||||
+ "<td style='text-align: center;'>" + CopyrightOwnership + "</td>"
|
||||
+ "<td style='text-align: center;'>" + ReqLicense + "</td>"
|
||||
+ "<td style='text-align: center;'>" + ReqLicenseUsage + "</td>"
|
||||
+ "<td style='text-align: center;'>" + SourceLocation + "</td>"
|
||||
+ "<td style='text-align: center;'>" + SourceLocationSub + "</td>"
|
||||
+ "<td style='text-align: center;'>" + LocationCntrl + "</td>"
|
||||
+ "<td style='text-align: center;'>" + LicenseLocation + "</td>"
|
||||
+ "<td style='text-align: center;'>" + LicenseSource + "</td>"
|
||||
+ "<td style='text-align: center;'>" + AdditionalInformationAndComments + "</td>"
|
||||
+ "<td style='text-align: center;'>" + VersionRest + "</td>"
|
||||
|
||||
+ "</tr>";
|
||||
} // compattlist = null
|
||||
} //for RequestSummary request
|
||||
|
||||
return ptr_str;
|
||||
|
||||
};
|
||||
|
||||
|
||||
/*********************************************************************************************
|
||||
* GetApplicationData() Get Application's details and Metadata
|
||||
* @param thisapp
|
||||
* @param attributeApi
|
||||
* @param colaApi
|
||||
* @return String with data in html format
|
||||
*********************************************************************************************/
|
||||
public String GetApplicationData(Application thisapp, AttributeApi attributeApi, ColaApi colaApi) {
|
||||
|
||||
String Name = null;
|
||||
String Version = null;
|
||||
String ProgramPlatform = null;
|
||||
String ProductName = null;
|
||||
String Description = null;
|
||||
String IdentificationsProductName = null;
|
||||
String SubGroupName = null;
|
||||
String GroupName = null;
|
||||
String OutboundLicense = null;
|
||||
String OBLInstructions = null;
|
||||
String License = null;
|
||||
String LicenseAcceptance = null;
|
||||
String InformationClassification = null;
|
||||
String ExportECCN = null;
|
||||
String Standards = null;
|
||||
String StandardsMember = null;
|
||||
String StandardsList = null;
|
||||
String Indemnification = null;
|
||||
String IndemnificationGMApprover = null;
|
||||
String Warranty = null;
|
||||
String WarrantyDataSheet = null;
|
||||
String SoftwareStackClassification = null;
|
||||
String SoftwareTechnologyClassification = null;
|
||||
String SoftwareTechnologyClassificationOther = null;
|
||||
//String ThirdPartyPatents = null;
|
||||
String IntelPatents = null;
|
||||
String IntelPatentStatus = null;
|
||||
String OpenSource = null;
|
||||
String ptr_str = "";
|
||||
|
||||
|
||||
List<AttributeValue> appAttList = null;
|
||||
try {
|
||||
try {
|
||||
Name = thisapp.getName();
|
||||
} catch (Exception e) {
|
||||
System.err.println("Missing application data: Name, caught exception: " + e.getMessage());
|
||||
}
|
||||
try {
|
||||
Version = thisapp.getVersion();
|
||||
} catch (Exception e) {
|
||||
System.err.println("Missing application data: Version, caught exception: " + e.getMessage());
|
||||
}
|
||||
LicenseNameOrIdToken LicenseToken = null;
|
||||
try {
|
||||
LicenseToken = thisapp.getLicenseId();
|
||||
} catch (Exception e) {
|
||||
System.err.println("Missing application data: LicenseToken, caught exception: " + e.getMessage());
|
||||
}
|
||||
if ( LicenseToken != null ) {
|
||||
try {
|
||||
License = colaApi.getLicense(LicenseToken).getNameToken().getName();
|
||||
} catch (Exception e) {
|
||||
System.err.println("Missing application data: LicenseToken, caught exception: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
Description = thisapp.getDescription().trim().replaceAll(Pattern.quote("\r\n"), "\u0001").replaceAll(Pattern.quote("\r"), "\u0001").replaceAll(Pattern.quote("\n"), "\u0001");
|
||||
} catch (Exception e) {
|
||||
System.err.println("Missing application data: Description, caught exception: " + e.getMessage());
|
||||
}
|
||||
try {
|
||||
appAttList = thisapp.getAttributeValues();
|
||||
} catch (Exception e) {
|
||||
System.err.println("Missing application data: attributeValues, caught exception: " + e.getMessage());
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// get application metadata
|
||||
//////////////////////////////////////////////////////////////////////////////
|
||||
if ( null != appAttList ) {
|
||||
if ( 0 < appAttList.size() ) {
|
||||
for (AttributeValue attValue : appAttList) {
|
||||
AttributeNameOrIdToken attNameToken = attValue.getAttributeId();
|
||||
AbstractAttribute attribute = attributeApi.getAttribute(attNameToken);
|
||||
String attName = attribute.getName().trim();
|
||||
List<String> attStringList = attValue.getValues();
|
||||
if (null != attStringList) {
|
||||
if ( 0 < attStringList.size() ) {
|
||||
ListIterator<String> LI = attStringList.listIterator();
|
||||
String attstring = LI.next().trim();
|
||||
while ( LI.hasNext() ) {
|
||||
attstring = attstring + "\n\n\n" + LI.next().trim();
|
||||
}
|
||||
|
||||
attstring = attstring.replaceAll(Pattern.quote("\r\n"), "\n").replaceAll(Pattern.quote("\r"), "\n");
|
||||
if ( attName.equals("APP - Identifications - Program and Platforms")) {
|
||||
ProgramPlatform = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("APP - Identifications - Product Name")) {
|
||||
ProductName = attstring.trim();
|
||||
}
|
||||
//if ( attName.equals("APP - 3rd Party Patents")) {
|
||||
//ThirdPartyPatents = attstring.trim();
|
||||
//}
|
||||
if ( attName.equals("APP - Export - ECCN")) {
|
||||
ExportECCN = attstring.trim();
|
||||
}
|
||||
if ( attName.startsWith("APP - Super Group")) {
|
||||
GroupName = attstring.trim();
|
||||
}
|
||||
if ( attName.startsWith("APP - Group - IAG")) {
|
||||
SubGroupName = attstring.trim();
|
||||
}
|
||||
if ( attName.startsWith("APP - Group - SMG")) {
|
||||
SubGroupName = attstring.trim();
|
||||
}
|
||||
if ( attName.startsWith("APP - Group - SSG")) {
|
||||
SubGroupName = attstring.trim();
|
||||
}
|
||||
if ( attName.startsWith("APP - Group - TMG")) {
|
||||
SubGroupName = attstring.trim();
|
||||
}
|
||||
if ( attName.startsWith("APP - Group - Intel Labs")) {
|
||||
SubGroupName = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("APP - Identifications - Product Name")) {
|
||||
IdentificationsProductName = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("APP - Indemnification")) {
|
||||
Indemnification = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("APP - Indemnification - GM Approval")) {
|
||||
IndemnificationGMApprover = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("APP - Information Classification")) {
|
||||
InformationClassification = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("APP - Intel Patents")) {
|
||||
IntelPatents = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("APP - Intel Patents - Status")) {
|
||||
IntelPatentStatus = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("APP - OBL")) {
|
||||
OutboundLicense = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("APP - OBL - Instructions")) {
|
||||
OBLInstructions = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("APP - OBL - Acceptance")) {
|
||||
LicenseAcceptance = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("APP - Open Source")) {
|
||||
OpenSource = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("APP - Standards")) {
|
||||
Standards = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("APP - Standards - List")) {
|
||||
StandardsList = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("APP - Standards - Member")) {
|
||||
StandardsMember = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("APP - Super Group")) {
|
||||
GroupName = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("APP/CPC - SW Stack Classification")) {
|
||||
SoftwareStackClassification = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("APP/CPC - SW Technology Classification")) {
|
||||
SoftwareTechnologyClassification = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("APP/CPC - SW Technology Classification - Other")) {
|
||||
SoftwareTechnologyClassificationOther = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("APP - Warranty")) {
|
||||
Warranty = attstring.trim();
|
||||
}
|
||||
if ( attName.equals("APP - Warranty - Data Sheet")) {
|
||||
WarrantyDataSheet = attstring.trim();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ptr_str = "<tr><td style='text-align: center;'>" + Name + "</td>"
|
||||
+ "<td style='text-align: center;'>" + Version + "</td>"
|
||||
+ "<td style='text-align: center;'>" + ProgramPlatform + "</td>"
|
||||
+ "<td style='text-align: center;'>" + ProductName + "</td>"
|
||||
+ "<td style='text-align: center;'>" + GroupName + "/" + SubGroupName + "</td>"
|
||||
+ "<td style='text-align: center;'>" + OutboundLicense + "</td>"
|
||||
+ "<td style='text-align: center;'>" + OBLInstructions + "</td>"
|
||||
+ "<td style='text-align: center;'>" + LicenseAcceptance + "</td>"
|
||||
+ "<td style='text-align: center;'>" + InformationClassification + "</td>"
|
||||
+ "<td style='text-align: center;'>" + OpenSource + "</td>"
|
||||
+ "<td style='text-align: center;'>" + ExportECCN + "</td>"
|
||||
+ "<td style='text-align: center;'>" + Standards + "</td>"
|
||||
+ "<td style='text-align: center;'>" + StandardsMember + "</td>"
|
||||
+ "<td style='text-align: center;'>" + StandardsList + "</td>"
|
||||
+ "<td style='text-align: center;'>" + Indemnification + "</td>"
|
||||
+ "<td style='text-align: center;'>" + IndemnificationGMApprover + "</td>"
|
||||
+ "<td style='text-align: center;'>" + Warranty + "</td>"
|
||||
+ "<td style='text-align: center;'>" + WarrantyDataSheet + "</td>"
|
||||
+ "<td style='text-align: center;'>" + SoftwareStackClassification + "</td>"
|
||||
+ "<td style='text-align: center;'>" + SoftwareTechnologyClassification + "</td>"
|
||||
+ "<td style='text-align: center;'>" + SoftwareTechnologyClassificationOther + "</td>"
|
||||
//+ "<td style='text-align: center;'>" + ThirdPartyPatents + "</td>"
|
||||
+ "<td style='text-align: center;'>" + IntelPatents + "</td>"
|
||||
+ "<td style='text-align: center;'>" + IntelPatentStatus + "</td>"
|
||||
|
||||
|
||||
+ "</tr>";
|
||||
} catch (Exception e) {
|
||||
System.err.println("Failed to create application data, caught exception: " + e.getMessage());
|
||||
}
|
||||
return ptr_str;
|
||||
};
|
||||
|
||||
/**********************************************************************************
|
||||
* main()
|
||||
* @param args
|
||||
* @throws Exception
|
||||
**********************************************************************************/
|
||||
public static void main(String[] args) throws Exception {
|
||||
// check and save parameters
|
||||
if (args.length < 5) {
|
||||
System.err.println("\n\nNot enough parameters!");
|
||||
usage();
|
||||
System.exit(-1);
|
||||
}
|
||||
|
||||
String serverUri = args[0];
|
||||
String username = args[1];
|
||||
String password = args[2];
|
||||
String applicationName = args[3];
|
||||
String Path = args[4];
|
||||
String outFile = "";
|
||||
|
||||
ApplicationApi applicationApi = null;
|
||||
RequestApi requestApi = null;
|
||||
AttributeApi attributeApi = null;
|
||||
ColaApi colaApi = null;
|
||||
|
||||
try {
|
||||
Long connectionTimeout = 600 * 1000L;
|
||||
CodeCenterServerProxyV7_0 myCodeCenterServer = new CodeCenterServerProxyV7_0(serverUri, username, password,
|
||||
connectionTimeout);
|
||||
applicationApi = myCodeCenterServer.getApplicationApi();
|
||||
attributeApi = myCodeCenterServer.getAttributeApi();
|
||||
colaApi = myCodeCenterServer.getColaApi();
|
||||
requestApi = myCodeCenterServer.getRequestApi();
|
||||
} catch (RuntimeException e) {
|
||||
System.err.println("\nConnection to server '" + serverUri + "' failed: " + e.getMessage());
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// get the application object
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
Application thisapp = null;
|
||||
ApplicationNameVersionToken apptoken = new ApplicationNameVersionToken();
|
||||
String OSName = null;
|
||||
String delimiter = null;
|
||||
OSName = System.getProperty("os.name");
|
||||
if (OSName.contains("Windows")) delimiter = "\\";
|
||||
else delimiter = "/";
|
||||
outFile = Path + delimiter + applicationName + " IP Plan.html";
|
||||
try {
|
||||
apptoken.setName(applicationName);
|
||||
apptoken.setVersion("Unspecified");
|
||||
thisapp = applicationApi.getApplication(apptoken);
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
apptoken.setVersion("unspecified");
|
||||
thisapp = applicationApi.getApplication(apptoken);
|
||||
} catch (Exception e1) {
|
||||
System.err.println("get APP " + applicationName + " caught exception : " + e1.getMessage());
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
if ( null == thisapp ) {
|
||||
System.err.println("FAILED: to get app for " + applicationName );
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
String html_content = "";
|
||||
|
||||
GenerateIPPlanReport ipplan = new GenerateIPPlanReport();
|
||||
html_content = ipplan.GetApplicationData(thisapp, attributeApi, colaApi);
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Write the application and components in an HTML file with HTML tags
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
File f = new File(outFile);
|
||||
try {
|
||||
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
|
||||
// Write application details and metadata
|
||||
bw.write( "<html><body>"
|
||||
+ "<header><h1> <span style='text-align:center;font-weight:bold'>" + applicationName + " IP Plan"
|
||||
+ "</span></h1></header>"
|
||||
+ "<table border='2px'>"
|
||||
+ "<tr style='background-color: rgb(240, 240, 240);'>"
|
||||
+ "<th> Application Name </th>"
|
||||
+ "<th> Application version </th>"
|
||||
+ "<th> Program/Platform </th>"
|
||||
+ "<th> Product Name </th>"
|
||||
+ "<th> Group Name </th>"
|
||||
+ "<th> OBL </th>"
|
||||
+ "<th> OBL Instruction </th>"
|
||||
+ "<th> License Acceptance </th>"
|
||||
+ "<th> Information Classification </th>"
|
||||
+ "<th> Open Source Distribution </th>"
|
||||
+ "<th> Export Community Control Number </th>"
|
||||
+ "<th> Standards </th>"
|
||||
+ "<th> Standard Member </th>"
|
||||
+ "<th> Standard List </th>"
|
||||
+ "<th> Indemnification </th>"
|
||||
+ "<th> Indemnification GM Approver </th>"
|
||||
+ "<th> Warranty </th>"
|
||||
+ "<th> Warranty - Product/Software Data Sheet </th>"
|
||||
+ "<th> Software Stack Classification </th>"
|
||||
+ "<th> Software Technology Classification </th>"
|
||||
+ "<th> Specific Technology Classification </th>"
|
||||
//+ "<th> 3rd Party Patents </th>"
|
||||
+ "<th> Intel Patents </th>"
|
||||
+ "<th> Intel Patent Status </th>"
|
||||
+ "</tr>"
|
||||
+ html_content
|
||||
+ "</table>" ) ;
|
||||
bw.write(" ");
|
||||
|
||||
html_content = ipplan.GetComponentData(thisapp, applicationApi, apptoken, requestApi, colaApi, attributeApi);
|
||||
|
||||
// Write each component and its request component details and its metadata
|
||||
bw.write( "<header><h1> <span style='text-align:center;font-weight:bold'>" + " Bill Of Materials"
|
||||
+ "</span></h1></header>"
|
||||
+"<table border='2px'>"
|
||||
+ "<tr style='background-color: rgb(240, 240, 240);'>"
|
||||
+ "<th> Component Name </th>"
|
||||
+ "<th> Component version </th>"
|
||||
+ "<th> License </th>"
|
||||
+ "<th> Description </th>"
|
||||
+ "<th> Homepage </th>"
|
||||
+ "<th> Supplier </th>"
|
||||
+ "<th> Supplier Category </th>"
|
||||
+ "<th> Software Stack Classification </th>"
|
||||
+ "<th> Software Technology Classification </th>"
|
||||
+ "<th> Software Technology Classification Other </th>"
|
||||
+ "<th> Operating System </th>"
|
||||
+ "<th> Programming Language </th>"
|
||||
+ "<th> Distribution Type </th>"
|
||||
+ "<th> Copyright Ownership </th>"
|
||||
+ "<th> Requested License </th>"
|
||||
+ "<th> Requested Usage </th>"
|
||||
+ "<th> Software Location </th>"
|
||||
+ "<th> Software Sub Location </th>"
|
||||
+ "<th> Control Strings </th>"
|
||||
+ "<th> License Location </th>"
|
||||
+ "<th> License Source </th>"
|
||||
+ "<th> Version Restrictions </th>"
|
||||
+ "<th> Information and Comments </th>"
|
||||
+ "</tr>"
|
||||
+ html_content
|
||||
+ "</table></body></html>" ) ;
|
||||
System.out.println("Done");
|
||||
|
||||
bw.close();
|
||||
} catch (Exception e) {
|
||||
System.out.println(e);
|
||||
}
|
||||
|
||||
} //main()
|
||||
|
||||
} //class GenerateIPPlan
|
||||
File diff suppressed because one or more lines are too long
20
DevOps/ProtexAutomation/GenerateIPPlanReport/ReadMe.txt
Normal file
20
DevOps/ProtexAutomation/GenerateIPPlanReport/ReadMe.txt
Normal file
@@ -0,0 +1,20 @@
|
||||
GenerateIPPlanReport.java extracts application metadata and BOM details from the Code Center application specified in input parameter
|
||||
and writes to a output file in HTML format. The output file created is with filename as "<Application Name> IP Plan.html"
|
||||
|
||||
How to Execute:
|
||||
java -jar GenerateIPPlanReport.jar <Code Center Server URL> <User ID> <User Password> <Application Name> <Output Path>
|
||||
|
||||
Input Parameters:
|
||||
IN arg[0] - Code Center server URL
|
||||
IN arg[1] - Code Center user ID
|
||||
IN arg[2] - Password
|
||||
IN arg[3] - Application name
|
||||
OUT arg[4] - Output Path (without filename)
|
||||
Example:
|
||||
Windows> java -jar GenerateIPPlanReport.jar http://sccodecenter.intel.com abc@intel.com abc "Android R4 AOSP Abi" "c:\IP Plans"
|
||||
Linux> java -jar GenerateIPPlanReport.jar http://sccodecenter.intel.com abc@intel.com abc "Android R4 AOSP Abi" "/IP Plans"
|
||||
|
||||
Output:
|
||||
Windows: c:\IP Plans\Android R4 AOSP Abi IP Plan.html
|
||||
Linux: /IP Plans/Android R4 AOSP Abi IP Plan.html
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,174 @@
|
||||
import java.io.*;
|
||||
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.Node;
|
||||
import org.w3c.dom.NodeList;
|
||||
|
||||
public class GenerateProtexScanDashboard {
|
||||
|
||||
private static void usage() {
|
||||
System.out.println("Input Parameters:" );
|
||||
System.out.println("Folder path\\name - Location and folder name where all scan results xml files are stored\n" +
|
||||
"File path\\name - location and filename to store the dashboard summary html report ");
|
||||
System.out.println("");
|
||||
|
||||
}
|
||||
|
||||
public String getAllScanResult(File file) {
|
||||
try {
|
||||
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
|
||||
DocumentBuilder db = dbf.newDocumentBuilder();
|
||||
int number;
|
||||
//File file = new File(fileName);
|
||||
|
||||
//System.out.println("Exists: " + file.getName() + " " + file.exists());
|
||||
if (file.exists()) {
|
||||
Document doc = db.parse(file);
|
||||
|
||||
|
||||
//System.out.println("File: " + fileName);
|
||||
//System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
|
||||
//System.out.println("Root element attrib :" + doc.getDocumentElement().getAttribute("name"));
|
||||
|
||||
NodeList serverList = doc.getElementsByTagName("ServerUrl");
|
||||
Node serverUrlNode = serverList.item(0);
|
||||
Element serverUrlElement = (Element) serverUrlNode;
|
||||
//System.out.println("Server url: " + serverUrlElement.getTextContent());
|
||||
|
||||
NodeList analyzedTimeList = doc.getElementsByTagName("LastAnalyzed");
|
||||
Node anaTimeNode = analyzedTimeList.item(0);
|
||||
Element anaTimeElement = (Element) anaTimeNode;
|
||||
//System.out.println("ANAly Time: " + anaTimeElement.getTextContent());
|
||||
|
||||
NodeList analyzedList = doc.getElementsByTagName("Analyzed");
|
||||
Node anaNode = analyzedList.item(0);
|
||||
Element anaElement = (Element) anaNode;
|
||||
//System.out.println("ANAly : " + anaElement.getTextContent());
|
||||
|
||||
NodeList pendingList = doc.getElementsByTagName("PendingID");
|
||||
Node penNode = pendingList.item(0);
|
||||
Element penElement = (Element) penNode;
|
||||
//System.out.println("Pending : " + penElement.getTextContent());
|
||||
|
||||
NodeList totCompList = doc.getElementsByTagName("TotalComponents");
|
||||
Node tCompNode = totCompList.item(0);
|
||||
Element tCompElement = (Element) tCompNode;
|
||||
//System.out.println("total Comp : " + tCompElement.getTextContent());
|
||||
|
||||
NodeList totLicList = doc.getElementsByTagName("TotalLicenses");
|
||||
Node tLicNode = totLicList.item(0);
|
||||
Element tLicElement = (Element) tLicNode;
|
||||
//System.out.println("Tot Lic : " + tLicElement.getTextContent());
|
||||
|
||||
NodeList pendingRevList = doc.getElementsByTagName("PendingReview");
|
||||
Node penRevNode = pendingRevList.item(0);
|
||||
Element penRevElement = (Element) penRevNode;
|
||||
//System.out.println("Pending Rev: " + penRevElement.getTextContent());
|
||||
|
||||
NodeList licVioList = doc.getElementsByTagName("LicenseViolations");
|
||||
Node licVioNode = licVioList.item(0);
|
||||
Element licVioElement = (Element) licVioNode;
|
||||
//System.out.println("Lice Violati : " + licVioElement.getTextContent());
|
||||
|
||||
String prj_str = "<tr><td><a href='" + serverUrlElement.getTextContent() + "' target='_blank'>"
|
||||
+ doc.getDocumentElement().getAttribute("name") + "</a></td>"
|
||||
+ "<td style='text-align: center;'>" + anaTimeElement.getTextContent() + "</td>"
|
||||
+ "<td style='text-align: center;'>" + anaElement.getTextContent() + "</td>";
|
||||
|
||||
number = Integer.parseInt(penElement.getTextContent());
|
||||
if (number > 0)
|
||||
prj_str = prj_str + "<td style='text-align: center;': bgcolor=gold> <b> <font color=red>" + penElement.getTextContent() + "</font></b></td>";
|
||||
else
|
||||
prj_str = prj_str + "<td style='text-align: center;'>" + penElement.getTextContent() + "</td>";
|
||||
|
||||
prj_str = prj_str + "<td style='text-align: center;'>" + tCompElement.getTextContent() + "</td>"
|
||||
+ "<td style='text-align: center;'>" + tLicElement.getTextContent() + "</td>";
|
||||
|
||||
number = Integer.parseInt(penRevElement.getTextContent());
|
||||
if (number > 0)
|
||||
prj_str = prj_str + "<td style='text-align: center;': bgcolor=gold> <b> <font color=red>" + penRevElement.getTextContent() + "</font></b></td>";
|
||||
else
|
||||
prj_str = prj_str + "<td style='text-align: center;'>" + penRevElement.getTextContent() + "</td>";
|
||||
|
||||
number = Integer.parseInt(licVioElement.getTextContent());
|
||||
if (number > 0)
|
||||
prj_str = prj_str + "<td style='text-align: center;': bgcolor=gold> <b> <font color=red>" + licVioElement.getTextContent() + "</font></b></td>";
|
||||
else
|
||||
prj_str = prj_str + "<td style='text-align: center;'>" + licVioElement.getTextContent() + "</td>";
|
||||
|
||||
// prj_str = prj_str + "<td style='text-align: center;'><a href='COS_report.html' target='_blank'>COS Report</a></td></tr>";
|
||||
|
||||
return prj_str;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println(e);
|
||||
}
|
||||
return "Error!! Parsing XML reports";
|
||||
}
|
||||
|
||||
public static void main(String[] args)
|
||||
{
|
||||
|
||||
if (args.length < 2) {
|
||||
System.err.println("Not enough parameters!");
|
||||
usage();
|
||||
System.exit(-1);
|
||||
}
|
||||
|
||||
GenerateProtexScanDashboard parser = new GenerateProtexScanDashboard();
|
||||
String filename;
|
||||
File folder = new File( args[0] );
|
||||
File[] listOfFiles = folder.listFiles();
|
||||
String html_content = "";
|
||||
String OSName = null;
|
||||
String delimiter = null;
|
||||
OSName = System.getProperty("os.name");
|
||||
if (OSName.contains("Windows")) delimiter = "\\";
|
||||
else delimiter = "/";
|
||||
|
||||
for (int i = 0; i < listOfFiles.length; i++)
|
||||
{
|
||||
if (listOfFiles[i].isFile())
|
||||
{
|
||||
filename = folder.getPath() + delimiter + listOfFiles[i].getName();
|
||||
//System.out.println("File: " + filename);
|
||||
if (filename.endsWith(".xml") || filename.endsWith(".XML"))
|
||||
{
|
||||
File filehandle = new File(filename);
|
||||
String prj_str = parser.getAllScanResult( filehandle );
|
||||
html_content = html_content + prj_str;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
File f = new File(args[1]);
|
||||
try {
|
||||
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
|
||||
bw.write( "<html><body>"
|
||||
+ "<h1> <span style='text-align:center;font-weight:bold'> Protex Scan Summary </span></h1>"
|
||||
+ "<table border='2px'>"
|
||||
+ "<tr style='background-color: rgb(240, 240, 240);'>"
|
||||
+ "<th rowspan='2'> Protex Project </th>"
|
||||
+ "<th rowspan='2'> Last Scan Timestamp </th>"
|
||||
+ "<th colspan='2' style='border-bottom: 1px solid;'> Files </th>"
|
||||
+ "<th colspan='4' style='border-bottom: 1px solid;'> BOM </th>"
|
||||
// + "<th rowspan='2'> Detailed Summary </th>"
|
||||
+ "</tr><tr style='background-color: rgb(240, 240, 240);'>"
|
||||
+ "<th style='border-left: 1px solid;'> Analyzed </th>"
|
||||
+ "<th style='border-left: 1px solid;'> Pending </th>"
|
||||
+ "<th style='border-left: 1px solid;'> Components </th>"
|
||||
+ "<th style='border-left: 1px solid;'> NumLicense </th>"
|
||||
+ "<th style='border-left: 1px solid;'> PendingReview </th>"
|
||||
+ "<th style='border-left: 1px solid;'> LicenseViolations </th></tr>"
|
||||
+ html_content + "</table></body></html>" ) ;
|
||||
|
||||
bw.close();
|
||||
} catch (Exception e) {
|
||||
System.out.println(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
GenerateProtexScanDashboard.java parses the scan results xml files generated by GetScanResults.java; read the data and
|
||||
writes the data in a summary (Dashboard) into the output html file.
|
||||
NOTE: All the scan analysis result xml files (generated from GetScanResult script are required to be stored in a single folder)
|
||||
|
||||
How to Execute:
|
||||
java -jar GenerateProtexScanDashboard.jar <stored scan files Path\foldername> <output file path\filename>
|
||||
|
||||
Input Parameters:
|
||||
IN arg[0] - Location of scan analysis files
|
||||
OUT arg[1] - Dashboard Output Path\filename.html
|
||||
|
||||
Example:
|
||||
Windows> java -jar GenerateProtexScanDashboard.jar c:\ScanResults c:\scanResults\Protex_Project_Summary.html
|
||||
Linux> java -jar GenerateProtexScanDashboard.jar /ScanResults /scanResults/Protex_Project_Summary.html
|
||||
|
||||
Output:
|
||||
Windows: c:\scanResults\Protex_Project_Summary.html (Will contain scan result summary of all xml files)
|
||||
Linux: /scanResults/Protex_Project_Summary.html
|
||||
Binary file not shown.
@@ -0,0 +1,219 @@
|
||||
|
||||
import java.util.List;
|
||||
import java.io.PrintWriter;
|
||||
|
||||
import javax.xml.ws.soap.SOAPFaultException;
|
||||
|
||||
import com.blackducksoftware.sdk.codecenter.application.ApplicationApi;
|
||||
import com.blackducksoftware.sdk.codecenter.application.data.Application;
|
||||
import com.blackducksoftware.sdk.codecenter.application.data.ApplicationNameVersionOrIdToken;
|
||||
import com.blackducksoftware.sdk.codecenter.application.data.ApplicationNameVersionToken;
|
||||
import com.blackducksoftware.sdk.codecenter.client.util.BDSCodeCenterSample;
|
||||
import com.blackducksoftware.sdk.codecenter.client.util.CodeCenterServerProxyV7_0;
|
||||
import com.blackducksoftware.sdk.codecenter.cola.ColaApi;
|
||||
import com.blackducksoftware.sdk.codecenter.cola.data.Component;
|
||||
import com.blackducksoftware.sdk.codecenter.common.data.ApprovalStatusEnum;
|
||||
import com.blackducksoftware.sdk.codecenter.request.RequestApi;
|
||||
import com.blackducksoftware.sdk.codecenter.request.data.Request;
|
||||
import com.blackducksoftware.sdk.codecenter.request.data.RequestColumn;
|
||||
import com.blackducksoftware.sdk.codecenter.request.data.RequestPageFilter;
|
||||
import com.blackducksoftware.sdk.codecenter.request.data.RequestSummary;
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//This sample file dis-associates any previous association with Protex project
|
||||
//and associates with the Project passed in as argument and validates with project
|
||||
//RETURNS 0 FOR SUCCESS AND 1 FOR FAILURE
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
public class GetAssociateAndValidateResult extends BDSCodeCenterSample {
|
||||
|
||||
private static ApplicationApi appApi = null;
|
||||
|
||||
private static void usage() {
|
||||
System.out.println("Input Parameters:" );
|
||||
System.out.println("arg[0] - Code Center server URL");
|
||||
System.out.println("arg[1] - Code Center user ID");
|
||||
System.out.println("arg[2] - Password");
|
||||
System.out.println("arg[3] - Application Name");
|
||||
System.out.println("arg[4] - Output Path without filename");
|
||||
}
|
||||
|
||||
|
||||
/***************************************************************************************************
|
||||
* main()
|
||||
* @param args
|
||||
* @throws Exception
|
||||
**************************************************************************************************/
|
||||
public static void main(String[] args) throws Exception {
|
||||
// check and save parameters
|
||||
if (args.length < 5) {
|
||||
System.err.println("\n\nNot enough parameters!");
|
||||
usage();
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
String serverUri = args[0];
|
||||
String username = args[1];
|
||||
String password = args[2];
|
||||
// Set the attachment Id
|
||||
String applicationName = args[3];
|
||||
String Path = args[4];
|
||||
String outFilePath = "";
|
||||
String ValidationStatus = "ERROR";
|
||||
String ApprovalStatus = "UNAPPROVED";
|
||||
RequestApi requestApi = null;
|
||||
ColaApi colaApi = null;
|
||||
try {
|
||||
Long connectionTimeout = 120 * 1000L;
|
||||
CodeCenterServerProxyV7_0 myCodeCenterServer = new CodeCenterServerProxyV7_0(serverUri, username, password,
|
||||
connectionTimeout);
|
||||
// Try some longer timeouts.
|
||||
// yes this is a blanket hack
|
||||
// revisit this later to see if timeouts can be reduced to normal.
|
||||
appApi = myCodeCenterServer.getApplicationApi();
|
||||
appApi = myCodeCenterServer.getApplicationApi( 0L ); //workaround from bd. call this twice and use infinite timeout
|
||||
requestApi = myCodeCenterServer.getRequestApi();
|
||||
colaApi = myCodeCenterServer.getColaApi();
|
||||
} catch (RuntimeException e) {
|
||||
System.err.println("\nConnection to server '" + serverUri + "' failed: " + e.getMessage());
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// get the application object
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
Application thisapp = null;
|
||||
ApplicationNameVersionToken apptoken = new ApplicationNameVersionToken();
|
||||
try {
|
||||
apptoken.setName(applicationName);
|
||||
apptoken.setVersion("Unspecified");
|
||||
thisapp = appApi.getApplication(apptoken);
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
apptoken.setVersion("unspecified");
|
||||
thisapp = appApi.getApplication(apptoken);
|
||||
} catch (Exception e1) {
|
||||
System.err.println("get APP " + applicationName + " caught exception : " + e1.getMessage());
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
if ( null == thisapp ) {
|
||||
System.err.println("FAILED: to get app for " + applicationName );
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//Read validation status
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
ValidationStatus = thisapp.getValidationStatus().toString();
|
||||
/*if ( validateException || (! ValidationStatus.equals("PASSED")) ) {
|
||||
System.err.println("Validation status is " + ValidationStatus + " for app " + applicationName );
|
||||
ValidationStatus = "Unavailable";
|
||||
}*/
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//Read Application Approval Status
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
List<RequestSummary> requestsList = null;
|
||||
String ptr_str = "";
|
||||
RequestPageFilter pageFilter = new RequestPageFilter();
|
||||
pageFilter.setFirstRowIndex(0);
|
||||
pageFilter.setLastRowIndex(10);
|
||||
pageFilter.setSortAscending(false);
|
||||
pageFilter.setSortedColumn(RequestColumn.REQUEST_APPROVAL_STATUS);
|
||||
pageFilter.getApprovalStatuses().add(ApprovalStatusEnum.APPROVED);
|
||||
try {
|
||||
requestsList = appApi.searchApplicationRequests((ApplicationNameVersionOrIdToken)apptoken, "", pageFilter);
|
||||
|
||||
} catch (Exception e) {
|
||||
System.err.println("getApplicationRequests() failed while fetching the details of the request to be updated: "
|
||||
+ e.getMessage());
|
||||
System.exit(-1);
|
||||
}
|
||||
|
||||
if (requestsList == null) {
|
||||
System.err.println("getApplicationRequests() failed: returned null as result");
|
||||
System.exit(-1);
|
||||
}
|
||||
|
||||
for (RequestSummary request : requestsList) {
|
||||
Request thisreq = null;
|
||||
Component thiscomp = null;
|
||||
String Name = " ";
|
||||
try {
|
||||
thisreq = requestApi.getRequest(request.getId());
|
||||
} catch (Exception e) {
|
||||
System.err.println("getRequest failed: "
|
||||
+ e.getMessage());
|
||||
System.exit(-1);
|
||||
}//try....catch
|
||||
|
||||
try {
|
||||
thiscomp = colaApi.getCatalogComponent(request.getComponentId());
|
||||
} catch (Exception e) {
|
||||
System.err.println("getCatalogComponent() failed: "
|
||||
+ e.getMessage());
|
||||
System.exit(-1);
|
||||
}//try....catch
|
||||
|
||||
try {
|
||||
Name = thiscomp.getNameVersion().getName().trim();
|
||||
} catch (Exception e) {
|
||||
System.err.println("Missing component data : Name, caught exception: " + e.getMessage());
|
||||
}
|
||||
|
||||
|
||||
if (Name.equals("IP Plan Approval")) {
|
||||
try {
|
||||
ApprovalStatus = thisreq.getApprovalStatus().toString();
|
||||
} catch (Exception e) {
|
||||
System.err.println("Failed to create request data: ApprovalStatus, caught exception: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
} //for (RequestSummary request : requestsList)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Write the application status in an xml file
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
String OSName = null;
|
||||
String delimiter = null;
|
||||
OSName = System.getProperty("os.name");
|
||||
if (OSName.contains("Windows")) delimiter = "\\";
|
||||
else delimiter = "/";
|
||||
outFilePath = Path + delimiter + applicationName + "_CM.xml";
|
||||
PrintWriter outFile = null;
|
||||
|
||||
try {
|
||||
outFile = new PrintWriter(outFilePath);
|
||||
} catch (Exception e) {
|
||||
System.err.println("\nUnable to create output file writer : " + e.getMessage());
|
||||
System.exit(-1);
|
||||
}
|
||||
outFile.println("<ApplicationData>");
|
||||
outFile.println("<Application>" + applicationName + "</Application>");
|
||||
outFile.println("<ApprovedStatus>" + ApprovalStatus + "</ApprovedStatus>");
|
||||
outFile.println("<ValidationStatus>" + ValidationStatus + "</ValidationStatus>");
|
||||
outFile.println("</ApplicationData>");
|
||||
outFile.flush();
|
||||
outFile.close();
|
||||
|
||||
|
||||
System.exit(0);
|
||||
|
||||
} catch (SOAPFaultException e) {
|
||||
System.err.println("GetCodeCenterApplication failed in main: " + e.getMessage());
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
GetAssociateAndValidateResult.jar will read the Application's (passed in as argument) Validate and IP Approval status and writes the data into an
|
||||
output file in xml format. The file generated will be the same as application name with "_CM.xml" suffix.
|
||||
|
||||
How to Execute:
|
||||
java -jar GetAssociateAndValidateResult.jar <Code Center server URL> <Code Center Username> <Password> <Code Center application> <output path>
|
||||
|
||||
Input Parameters:
|
||||
IN arg[0] - Code Center server URL
|
||||
IN arg[1] - User ID
|
||||
IN arg[2] - Password
|
||||
IN arg[3] - Application (IP Plan) name
|
||||
OUT arg[4] - Output Path without filename
|
||||
|
||||
Example:
|
||||
Windows> java -jar GetAssociateAndValidateResult.jar http://sccodecenter.intel.com abc@intel.com abc "My App" "C:\Results\CCXML"
|
||||
Linux> java -jar GetAssociateAndValidateResult.jar http://sccodecenter.intel.com abc@intel.com abc "My App" "/Results/CCXML"
|
||||
|
||||
Output:
|
||||
Windows: C:\Results\CCXML\My App_CM.xml
|
||||
Linux: /Results/CCXML/My App_CM.xml
|
||||
BIN
DevOps/ProtexAutomation/GetScanResult/GetScanResult.jar
Normal file
BIN
DevOps/ProtexAutomation/GetScanResult/GetScanResult.jar
Normal file
Binary file not shown.
266
DevOps/ProtexAutomation/GetScanResult/GetScanResult.java
Normal file
266
DevOps/ProtexAutomation/GetScanResult/GetScanResult.java
Normal file
@@ -0,0 +1,266 @@
|
||||
|
||||
|
||||
import java.util.List;
|
||||
import java.text.DateFormat;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.io.PrintWriter;
|
||||
|
||||
//import org.apache.cxf.common.util.SortedArraySet;
|
||||
|
||||
|
||||
|
||||
import com.blackducksoftware.sdk.fault.SdkFault;
|
||||
import com.blackducksoftware.sdk.protex.client.util.BDProtexSample;
|
||||
import com.blackducksoftware.sdk.protex.client.util.ProtexServerProxy;
|
||||
import com.blackducksoftware.sdk.protex.project.Project;
|
||||
import com.blackducksoftware.sdk.protex.project.ProjectApi;
|
||||
import com.blackducksoftware.sdk.protex.project.bom.BomApi;
|
||||
import com.blackducksoftware.sdk.protex.project.bom.BomLicenseInfo;
|
||||
import com.blackducksoftware.sdk.protex.project.codetree.CodeTreeApi;
|
||||
import com.blackducksoftware.sdk.protex.project.codetree.CodeTreeNode;
|
||||
import com.blackducksoftware.sdk.protex.project.codetree.CodeTreeNodeRequest;
|
||||
import com.blackducksoftware.sdk.protex.project.codetree.CodeTreeNodeType;
|
||||
import com.blackducksoftware.sdk.protex.project.codetree.NodeCount;
|
||||
import com.blackducksoftware.sdk.protex.project.codetree.NodeCountType;
|
||||
import com.blackducksoftware.sdk.protex.project.codetree.discovery.CodeMatchDiscovery;
|
||||
import com.blackducksoftware.sdk.protex.project.codetree.discovery.CodeMatchType;
|
||||
import com.blackducksoftware.sdk.protex.project.codetree.discovery.DiscoveryApi;
|
||||
import com.blackducksoftware.sdk.protex.project.codetree.discovery.IdentificationStatus;
|
||||
import com.blackducksoftware.sdk.protex.project.codetree.identification.IdentificationApi;
|
||||
|
||||
/**
|
||||
* This sample program retrieves scan results and store the results in XML format in the output
|
||||
* file which is passed as input argument 4
|
||||
*
|
||||
* Retrieves below info:
|
||||
* - Total files analyzed
|
||||
* - Total file skipped
|
||||
* - Total files with pending identifications
|
||||
* - Total original code files
|
||||
* - List of inbound licenses
|
||||
* - OBL
|
||||
*/
|
||||
public class GetScanResult extends BDProtexSample {
|
||||
|
||||
private static String translateXmlEntities(String line) {
|
||||
|
||||
if ( null == line ) {
|
||||
return "";
|
||||
}
|
||||
|
||||
//this MUST go first
|
||||
return line.replaceAll("&", "&")
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">")
|
||||
.replaceAll("'", "'")
|
||||
.replaceAll("\"", """);
|
||||
}
|
||||
|
||||
private static void usage() {
|
||||
System.out.println("Input Parameters:" );
|
||||
System.out.println("arg[0] - Protex server URL");
|
||||
System.out.println("arg[1] - Protex user ID");
|
||||
System.out.println("arg[2] - Password");
|
||||
System.out.println("arg[3] - Project ID");
|
||||
System.out.println("arg[4] - Location of output xml file");
|
||||
}
|
||||
|
||||
|
||||
/**************************************************************************************
|
||||
*
|
||||
* @param args
|
||||
* @throws Exception
|
||||
*/
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
// check and save parameters
|
||||
if (args.length < 5) {
|
||||
System.err.println("Not enough parameters!");
|
||||
usage();
|
||||
System.exit(-1);
|
||||
}
|
||||
|
||||
String serverUri = args[0];
|
||||
String username = args[1];
|
||||
String password = args[2];
|
||||
String projectId = args[3];
|
||||
String outPath = args[4];
|
||||
|
||||
ProjectApi projectApi = null;
|
||||
CodeTreeApi codetreeApi = null;
|
||||
DiscoveryApi discoveryApi = null;
|
||||
BomApi bomApi = null;
|
||||
|
||||
// get service and service port
|
||||
try {
|
||||
Long connectionTimeout = 120 * 1000L;
|
||||
ProtexServerProxy myProtexServer = new ProtexServerProxy(serverUri, username, password,
|
||||
connectionTimeout);
|
||||
|
||||
projectApi = myProtexServer.getProjectApi(5 * connectionTimeout);
|
||||
codetreeApi = myProtexServer.getCodeTreeApi(15 * connectionTimeout);
|
||||
discoveryApi = myProtexServer.getDiscoveryApi(15 * connectionTimeout);
|
||||
bomApi = myProtexServer.getBomApi(30 * connectionTimeout);
|
||||
|
||||
} catch (RuntimeException e) {
|
||||
System.err.println("Connection to server '" + serverUri + "' failed: " + e.getMessage());
|
||||
System.exit(-1);
|
||||
}
|
||||
|
||||
//get the license list
|
||||
List<BomLicenseInfo> licenses = null;
|
||||
try {
|
||||
licenses = bomApi.getBomLicenseInfo(projectId);
|
||||
} catch (SdkFault e) {
|
||||
System.err.println("\ngetLicenseInfo failed: " + e.getMessage());
|
||||
System.exit(-1);
|
||||
}
|
||||
// Check for valid return
|
||||
if (licenses == null) {
|
||||
System.err.println("\ngetLicenseInfo: unexpected return object");
|
||||
System.exit(-1);
|
||||
}
|
||||
///////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// code tree nodes
|
||||
///////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
int DEPTH = 1; //pulling just the parent results in all 0 counts!??
|
||||
CodeTreeNodeRequest nodeRequest = new CodeTreeNodeRequest();
|
||||
nodeRequest.setDepth(DEPTH);
|
||||
nodeRequest.getCounts().add(NodeCountType.PENDING_ID_CODE_MATCH);
|
||||
nodeRequest.getCounts().add(NodeCountType.PENDING_REVIEW);
|
||||
nodeRequest.getCounts().add(NodeCountType.VIOLATIONS);
|
||||
nodeRequest.getCounts().add(NodeCountType.NO_DISCOVERIES);
|
||||
nodeRequest.getCounts().add(NodeCountType.FILES);
|
||||
nodeRequest.getCounts().add(NodeCountType.DISCOVERED_COMPONENTS);
|
||||
nodeRequest.getIncludedNodeTypes().add(CodeTreeNodeType.EXPANDED_ARCHIVE);
|
||||
nodeRequest.getIncludedNodeTypes().add(CodeTreeNodeType.FILE);
|
||||
nodeRequest.getIncludedNodeTypes().add(CodeTreeNodeType.FOLDER);
|
||||
nodeRequest.setIncludeParentNode(true);
|
||||
|
||||
// get CodeTree
|
||||
String root = "/";
|
||||
int TOP_ONLY = 0;
|
||||
Long analyzedFiles = null;
|
||||
Long skippedFiles = null;
|
||||
Long discoveriesPending = null;
|
||||
Long noDiscoveries = null;
|
||||
Long discoveredComponents = null;
|
||||
Integer bomComponents = null;
|
||||
Integer bomLicenses = null;
|
||||
Long pendingReview = null;
|
||||
Long licenseViolations = null;
|
||||
|
||||
//PartialCodeTree partialCodeTree = null;
|
||||
List<CodeTreeNode> partialCodeTree = null;
|
||||
try {
|
||||
partialCodeTree = codetreeApi.getCodeTreeNodes(projectId, root, nodeRequest);
|
||||
for ( CodeTreeNode node : partialCodeTree) {
|
||||
if ( ! node.getName().equals("") ) continue;
|
||||
|
||||
List<NodeCount> countList = node.getNodeCounts();
|
||||
for (NodeCount count: countList) {
|
||||
Long value = count.getCount();
|
||||
NodeCountType type = count.getCountType();
|
||||
if ( NodeCountType.PENDING_ID_CODE_MATCH == type ) {
|
||||
discoveriesPending = value;
|
||||
} else if ( NodeCountType.PENDING_REVIEW == type ) {
|
||||
pendingReview = value;
|
||||
} else if ( NodeCountType.VIOLATIONS == type ) {
|
||||
licenseViolations = value;
|
||||
} else if ( NodeCountType.NO_DISCOVERIES == type ) {
|
||||
noDiscoveries = value;
|
||||
} else if ( NodeCountType.FILES == type ) {
|
||||
analyzedFiles = value;
|
||||
} else if ( NodeCountType.DISCOVERED_COMPONENTS == type ) {
|
||||
discoveredComponents = value;
|
||||
}
|
||||
|
||||
}//for (NodeCount
|
||||
}//for ( CodeTreeNode node
|
||||
|
||||
skippedFiles = codetreeApi.getSkippedFileCount(projectId);
|
||||
|
||||
} catch (SdkFault e) {
|
||||
System.err.println("getCodeTree(TOP_ONLY) failed: " + e.getMessage());
|
||||
System.exit(-1);
|
||||
}
|
||||
|
||||
Project project = null;
|
||||
String analyzedDate = null;
|
||||
String projectName = null;
|
||||
project = projectApi.getProjectById(projectId);
|
||||
if (project != null) {
|
||||
DateFormat formatter = new SimpleDateFormat("dd MMM, yyyy hh:mm:ss a");
|
||||
analyzedDate = formatter.format(project.getLastAnalyzedDate().getTime());
|
||||
projectName = project.getName();
|
||||
}
|
||||
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// BOM (file) counts
|
||||
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
try {
|
||||
bomComponents = bomApi.getBomComponentCount(projectId);
|
||||
} catch (SdkFault e) {
|
||||
System.err.println("getBomComponentCount() failed: " + e.getMessage());
|
||||
System.exit(-1);
|
||||
}
|
||||
try {
|
||||
bomLicenses = bomApi.getBomLicenseCount(projectId);
|
||||
} catch (SdkFault e) {
|
||||
System.err.println("getBomLicenseCount() failed: " + e.getMessage());
|
||||
System.exit(-1);
|
||||
}
|
||||
|
||||
|
||||
|
||||
{
|
||||
|
||||
PrintWriter outFile = null;
|
||||
try {
|
||||
outFile = new PrintWriter(outPath);
|
||||
} catch (Exception e) {
|
||||
System.err.println("\nUnable to create output file writer : " + e.getMessage());
|
||||
System.exit(-1);
|
||||
}
|
||||
|
||||
|
||||
outFile.println("<Project name=\"" + projectName + "\" id=\"" + projectId + "\" >");
|
||||
outFile.println("<ServerUrl>" + serverUri +"</ServerUrl>");
|
||||
outFile.println("<LastAnalyzed>" + analyzedDate +"</LastAnalyzed>");
|
||||
outFile.println("<ScanFileInfo>");
|
||||
outFile.println("\t<Analyzed>" + analyzedFiles + "</Analyzed>");
|
||||
outFile.println("\t<Skipped>" + skippedFiles + "</Skipped>");
|
||||
outFile.println("\t<PendingID>" + discoveriesPending + "</PendingID>");
|
||||
outFile.println("\t<NoDiscoveries>" + noDiscoveries + "</NoDiscoveries>" );
|
||||
outFile.println("</ScanFileInfo>");
|
||||
outFile.println("<Components>");
|
||||
outFile.println("\t<DiscoveredComponents>" + discoveredComponents + "</DiscoveredComponents>");
|
||||
outFile.println("</Components>");
|
||||
|
||||
outFile.println("<BOM>");
|
||||
outFile.println("\t<TotalComponents>" + bomComponents + "</TotalComponents>");
|
||||
outFile.println("\t<TotalLicenses>" + bomLicenses + "</TotalLicenses>");
|
||||
outFile.println("\t<LicenseList>");
|
||||
if (licenses.size() == 0) {
|
||||
outFile.println("\t\t<None/>");
|
||||
} else {
|
||||
for (BomLicenseInfo license : licenses) {
|
||||
String licensename = translateXmlEntities(license.getName());
|
||||
if ( ! licensename.equals("Unspecified") ) {
|
||||
outFile.println("\t\t<License>" + licensename + "</License>");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
outFile.println("\t</LicenseList>");
|
||||
outFile.println("\t<PendingReview>" + pendingReview + "</PendingReview>");
|
||||
outFile.println("\t<LicenseViolations>" + licenseViolations + "</LicenseViolations>");
|
||||
outFile.println("</BOM>");
|
||||
outFile.println("</Project>\n");
|
||||
|
||||
outFile.flush();
|
||||
outFile.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
20
DevOps/ProtexAutomation/GetScanResult/ReadMe.txt
Normal file
20
DevOps/ProtexAutomation/GetScanResult/ReadMe.txt
Normal file
@@ -0,0 +1,20 @@
|
||||
GetScanResult.java collects the scan analysis summary (# files scanned; # Pending identification; # Licencen conflicts; etc)
|
||||
of a protex Project passed is as argument. If the project is scanned, the analysis are written to the outfile passed in as
|
||||
argument. Else, throws an exception
|
||||
|
||||
How to Execute:
|
||||
java -jar GetScanResult.jar <Protex server URL> <User ID> <User Password> <Project ID> <Output Path\Filename>
|
||||
|
||||
Input Parameters:
|
||||
IN arg[0] - Protex server URL
|
||||
IN arg[1] - the username for this server
|
||||
IN arg[2] - password
|
||||
IN arg[3] - Project ID
|
||||
OUT arg[4] - location of output xml file
|
||||
|
||||
Example:
|
||||
java -jar GetScanResult.jar http://jfipscn01.intel.com abc@intel.com abc c_test_k_5271 c:\ScanResults\Project_Scan_result.xml
|
||||
|
||||
Output:
|
||||
c:\ScanResults\Project_Scan_result.xml (Will contain scan result)
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
RunAssociateAndValidateProtexProject.java will dis-associate the application from previously associated Protex project and
|
||||
re-associate the application to the project name passed as argument and execute validate. This script does the data integrity
|
||||
check between the application and Protex project
|
||||
|
||||
How to Execute:
|
||||
java -jar RunAssociateAndValidateProtexProject.jar <Code Center server URL> <Code Center Username> <Password> <Code Center application> <Project Name> <Protex Server ID>
|
||||
|
||||
Input Parameters:
|
||||
IN arg[0] - Code Center server URL
|
||||
IN arg[1] - User ID
|
||||
IN arg[2] - Password
|
||||
IN arg[3] - Application (IP Plan) name
|
||||
IN arg[4] - Protex Project name
|
||||
IN arg[5] - Protex Server ID
|
||||
|
||||
Example:
|
||||
java -jar RunAssociateAndValidateProtexProject.jar http://sccodecenter.intel.com abc@intel.com abc "My App" "My Project" JF1
|
||||
|
||||
=======================================================================================================================
|
||||
|
||||
Protex Server ID Protex Server URL
|
||||
BA1 http://baipscn01.intel.com
|
||||
GK1 http://gkipscn01.intel.com
|
||||
HD1 http://hdipscn01.intel.com
|
||||
IL1 http://iilipscn01.intel.com
|
||||
JF1 http://jfipscn01.intel.com
|
||||
JF2 http://jfipscn02.intel.com
|
||||
JF03 http://jfipscn03.intel.com
|
||||
NN01 http://nnsipscn01.intel.com
|
||||
SC2 http://scipscn02.intel.com
|
||||
SC3 http://scipscn03.intel.com
|
||||
SH1 http://shipscn01.intel.com
|
||||
Binary file not shown.
@@ -0,0 +1,142 @@
|
||||
|
||||
import javax.xml.ws.soap.SOAPFaultException;
|
||||
|
||||
import com.blackducksoftware.sdk.codecenter.administration.data.ServerNameToken;
|
||||
import com.blackducksoftware.sdk.codecenter.application.ApplicationApi;
|
||||
import com.blackducksoftware.sdk.codecenter.application.data.Application;
|
||||
import com.blackducksoftware.sdk.codecenter.application.data.ApplicationNameVersionToken;
|
||||
import com.blackducksoftware.sdk.codecenter.application.data.ProjectNameToken;
|
||||
import com.blackducksoftware.sdk.codecenter.client.util.BDSCodeCenterSample;
|
||||
import com.blackducksoftware.sdk.codecenter.client.util.CodeCenterServerProxyV7_0;
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//This sample file dis-associates any previous association with Protex project
|
||||
//and associates with the Project passed in as argument and validates with project
|
||||
//RETURNS 0 FOR SUCCESS AND 1 FOR FAILURE
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
public class RunAssociateAndValidateProtexProject extends BDSCodeCenterSample {
|
||||
|
||||
private static ApplicationApi appApi = null;
|
||||
|
||||
private static void usage() {
|
||||
System.out.println("Input Parameters:" );
|
||||
System.out.println("arg[0] - Code Center server URL");
|
||||
System.out.println("arg[1] - Code Center user ID");
|
||||
System.out.println("arg[2] - Password");
|
||||
System.out.println("arg[3] - Application Name");
|
||||
System.out.println("arg[4] - Protex Project Name");
|
||||
System.out.println("arg[5] - Protex Server ID (Readme file under RunAssociateAndValidateProject folder has all server ID details");
|
||||
}
|
||||
|
||||
|
||||
/***************************************************************************************************
|
||||
* main()
|
||||
* @param args
|
||||
* @throws Exception
|
||||
**************************************************************************************************/
|
||||
public static void main(String[] args) throws Exception {
|
||||
// check and save parameters
|
||||
if (args.length < 6) {
|
||||
System.err.println("\n\nNot enough parameters!");
|
||||
usage();
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
String serverUri = args[0];
|
||||
String username = args[1];
|
||||
String password = args[2];
|
||||
// Set the attachment Id
|
||||
String applicationName = args[3];
|
||||
String projectName = args[4];
|
||||
String projectServer = args[5];
|
||||
|
||||
|
||||
try {
|
||||
Long connectionTimeout = 120 * 1000L;
|
||||
CodeCenterServerProxyV7_0 myCodeCenterServer = new CodeCenterServerProxyV7_0(serverUri, username, password,
|
||||
connectionTimeout);
|
||||
// Try some longer timeouts.
|
||||
// yes this is a blanket hack
|
||||
// revisit this later to see if timeouts can be reduced to normal.
|
||||
appApi = myCodeCenterServer.getApplicationApi();
|
||||
appApi = myCodeCenterServer.getApplicationApi( 0L ); //workaround from bd. call this twice and use infinite timeout
|
||||
|
||||
} catch (RuntimeException e) {
|
||||
System.err.println("\nConnection to server '" + serverUri + "' failed: " + e.getMessage());
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
try {
|
||||
ServerNameToken protexServerToken = new ServerNameToken();
|
||||
ProjectNameToken protexProjectToken = new ProjectNameToken();
|
||||
try {
|
||||
protexServerToken.setName(projectServer);
|
||||
protexProjectToken.setServerId(protexServerToken);
|
||||
protexProjectToken.setName(projectName);
|
||||
} catch (Exception e) {
|
||||
System.err.println("Caught exception setting up Protex project token : " + e.getMessage());
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// get the application object
|
||||
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
Application thisapp = null;
|
||||
ApplicationNameVersionToken apptoken = new ApplicationNameVersionToken();
|
||||
try {
|
||||
apptoken.setName(applicationName);
|
||||
apptoken.setVersion("Unspecified");
|
||||
thisapp = appApi.getApplication(apptoken);
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
apptoken.setVersion("unspecified");
|
||||
thisapp = appApi.getApplication(apptoken);
|
||||
} catch (Exception e1) {
|
||||
System.err.println("get APP " + applicationName + " caught exception : " + e1.getMessage());
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
if ( null == thisapp ) {
|
||||
System.err.println("FAILED: to get app for " + applicationName );
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
//Disassociate current application project pair
|
||||
try {
|
||||
appApi.disassociateProtexProject(apptoken);
|
||||
} catch (Exception e) {
|
||||
System.err.println("\ndisassociate() call in main() for application " + applicationName + " caught exception: " + e.getMessage());
|
||||
}
|
||||
//Associate application to new project
|
||||
try {
|
||||
appApi.associateProtexProject(apptoken, protexProjectToken);
|
||||
} catch (Exception e) {
|
||||
System.err.println("\nassociate() call in main() for application " + applicationName + " caught exception: " + e.getMessage());
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
//validate the Application Project pair
|
||||
String ValidationStatus = "ERROR";
|
||||
try {
|
||||
appApi.validate(apptoken, true, true);
|
||||
ValidationStatus = "PASSED";
|
||||
} catch (Exception e) {
|
||||
System.err.println("API exception: appApi.validate() for " + applicationName + " : " + e.getMessage());
|
||||
if ( -1 != e.getMessage().indexOf("not synchronized") ) {
|
||||
ValidationStatus = "NotSynched";
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println(ValidationStatus);
|
||||
System.exit(0);
|
||||
|
||||
} catch (SOAPFaultException e) {
|
||||
System.err.println("GetCodeCenterApplication failed in main: " + e.getMessage());
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
42
DevOps/ProtexAutomation/ScanProtexProject/ReadMe.txt
Normal file
42
DevOps/ProtexAutomation/ScanProtexProject/ReadMe.txt
Normal file
@@ -0,0 +1,42 @@
|
||||
ScanProtexProject.bat will take the user credentials, Protex server URL and project ID as input. The bat uses bdstool
|
||||
to initiate the scan. After the 1st scan, rerun of this .bat file will only scan changes in code base will be scanned.
|
||||
If a forced scan is needed, then open the ScanProtexProject.bat in edit more, and update to below line
|
||||
call bdstool analyze --force
|
||||
|
||||
Prerequisite:
|
||||
Protex client MUST be installed prior to executing the script
|
||||
|
||||
How to Execute:
|
||||
Windows OS:
|
||||
1) Open a DOS Window
|
||||
ScanProtexProject.bat <Protex server URL> <User ID> <User Password> <Project ID> <Scan Folder Path>
|
||||
|
||||
Linux OS
|
||||
1) Open a bash windows
|
||||
sh ScanProtexProject.sh <Protex server URL> <User ID> <User Password> <Project ID> <Scan Folder Path>
|
||||
Input Parameters:
|
||||
IN arg[0] - Protex server URL
|
||||
IN arg[1] - User ID
|
||||
IN arg[2] - Password
|
||||
IN arg[3] - Protex project ID
|
||||
IN arg[4] - Source files Path
|
||||
|
||||
Example:
|
||||
ScanProtexProject.bat https://jfipscn01.intel.com abc@intel.com abc c_test_k_5271 c:\ScanSource
|
||||
sh ScanProtexProject.sh https://jfipscn01.intel.com abc@intel.com abc c_test_k_5271 ~/ScanSource
|
||||
================================================================================================================================
|
||||
Protex Server ID Protex Server URL
|
||||
BA1 https://baipscn01.intel.com
|
||||
GK1 https://gkipscn01.intel.com
|
||||
IL1 https://iilipscn01.intel.com
|
||||
JF1 https://jfipscn01.intel.com
|
||||
JF2 https://jfipscn02.intel.com
|
||||
JF03 https://jfipscn03.intel.com
|
||||
JF04 https://jfipscn04.intel.com
|
||||
JF05 https://jfipscn05.intel.com
|
||||
JF06 https://jfipscn06.intel.com
|
||||
NN01 https://nnsipscn01.intel.com
|
||||
SC2 https://scipscn02.intel.com
|
||||
SC3 https://scipscn03.intel.com
|
||||
SH1 https://shipscn01.intel.com
|
||||
MU01 https://imuipscn01.intel.com
|
||||
@@ -0,0 +1,38 @@
|
||||
@echo off
|
||||
if "%1" == "" GOTO ENDFILE
|
||||
if "%2" == "" GOTO ENDFILE
|
||||
if "%3" == "" GOTO ENDFILE
|
||||
if "%4" == "" GOTO ENDFILE
|
||||
if "%5" == "" GOTO ENDFILE
|
||||
|
||||
|
||||
Rem set environmental values to enable login to the Protex server
|
||||
|
||||
|
||||
Rem Set the server URL
|
||||
SET BDSSERVER=%1
|
||||
|
||||
Rem Set the login name
|
||||
SET BDSUSER=%2
|
||||
|
||||
Rem Set the password
|
||||
SET BDSPASSWORD=%3
|
||||
|
||||
pushd "%5"
|
||||
call bdstool login
|
||||
call bdstool new-project %4 --verbose
|
||||
call bdstool analyze
|
||||
call bdstool logout
|
||||
goto DONE
|
||||
|
||||
:ENDFILE
|
||||
echo "Arugument Missing"
|
||||
echo "Input Parameters:" );
|
||||
echo "arg[1] - Protex server URL e.g http://scipscn03.intel.com");
|
||||
echo "arg[2] - Protex user ID e.g abc@intel.com");
|
||||
echo "arg[3] - Password e.g abc");
|
||||
echo "arg[4] - Project ID e.g c_byt_beta_audio_6009");
|
||||
echo "arg[5] - Source Code location e.g \"C:\\MySource\\ScanDir\"");
|
||||
|
||||
:DONE
|
||||
popd
|
||||
@@ -0,0 +1,32 @@
|
||||
#!/bin/bash
|
||||
|
||||
if [ $# -ne 5 ]; then
|
||||
echo "Arugument Missing"
|
||||
echo "Input Parameters:"
|
||||
echo "arg[1] - Protex server URL"
|
||||
echo "arg[2] - Protex user ID e.g abc@intel.com"
|
||||
echo "arg[3] - Password e.g abc"
|
||||
echo "arg[4] - Project ID e.g c_byt_beta_audio_6009"
|
||||
echo "arg[5] - Source Code location e.g /home/sourcefiles"
|
||||
exit
|
||||
fi
|
||||
|
||||
# set environmental values to enable login to the Protex server
|
||||
|
||||
# Set the server URL
|
||||
export BDSSERVER=$1
|
||||
|
||||
# Set the login name
|
||||
export BDSUSER=$2
|
||||
|
||||
# Set the password
|
||||
SET BDSPASSWORD=$3
|
||||
|
||||
pushd $5
|
||||
bdstool login
|
||||
bdstool new-project $4 --verbose
|
||||
bdstool analyze
|
||||
bdstool logout
|
||||
popd
|
||||
|
||||
exit
|
||||
201
LICENSE
201
LICENSE
@@ -1,201 +0,0 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2017 Intel Corporation
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -1,7 +1,7 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio 14
|
||||
VisualStudioVersion = 14.0.23107.0
|
||||
VisualStudioVersion = 14.0.25420.1
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MeshService", "MeshService\MeshService.vcxproj", "{CE5AD78C-DBDF-4D81-9A69-41B1DF683115}"
|
||||
EndProject
|
||||
@@ -9,24 +9,60 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MeshConsole", "MeshConsole\
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug_NoOpenSSL|x64 = Debug_NoOpenSSL|x64
|
||||
Debug_NoOpenSSL|x86 = Debug_NoOpenSSL|x86
|
||||
Debug|x64 = Debug|x64
|
||||
Debug|x86 = Debug|x86
|
||||
Library_Debug_NoOpenSSL|x64 = Library_Debug_NoOpenSSL|x64
|
||||
Library_Debug_NoOpenSSL|x86 = Library_Debug_NoOpenSSL|x86
|
||||
Library_Release_NoOpenSSL|x64 = Library_Release_NoOpenSSL|x64
|
||||
Library_Release_NoOpenSSL|x86 = Library_Release_NoOpenSSL|x86
|
||||
Release_NoOpenSSL|x64 = Release_NoOpenSSL|x64
|
||||
Release_NoOpenSSL|x86 = Release_NoOpenSSL|x86
|
||||
Release|x64 = Release|x64
|
||||
Release|x86 = Release|x86
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{CE5AD78C-DBDF-4D81-9A69-41B1DF683115}.Debug_NoOpenSSL|x64.ActiveCfg = Debug_NoOpenSSL|x64
|
||||
{CE5AD78C-DBDF-4D81-9A69-41B1DF683115}.Debug_NoOpenSSL|x64.Build.0 = Debug_NoOpenSSL|x64
|
||||
{CE5AD78C-DBDF-4D81-9A69-41B1DF683115}.Debug_NoOpenSSL|x86.ActiveCfg = Debug_NoOpenSSL|Win32
|
||||
{CE5AD78C-DBDF-4D81-9A69-41B1DF683115}.Debug_NoOpenSSL|x86.Build.0 = Debug_NoOpenSSL|Win32
|
||||
{CE5AD78C-DBDF-4D81-9A69-41B1DF683115}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{CE5AD78C-DBDF-4D81-9A69-41B1DF683115}.Debug|x64.Build.0 = Debug|x64
|
||||
{CE5AD78C-DBDF-4D81-9A69-41B1DF683115}.Debug|x86.ActiveCfg = Debug|Win32
|
||||
{CE5AD78C-DBDF-4D81-9A69-41B1DF683115}.Debug|x86.Build.0 = Debug|Win32
|
||||
{CE5AD78C-DBDF-4D81-9A69-41B1DF683115}.Library_Debug_NoOpenSSL|x64.ActiveCfg = Debug_NoOpenSSL|x64
|
||||
{CE5AD78C-DBDF-4D81-9A69-41B1DF683115}.Library_Debug_NoOpenSSL|x86.ActiveCfg = Debug_NoOpenSSL|Win32
|
||||
{CE5AD78C-DBDF-4D81-9A69-41B1DF683115}.Library_Release_NoOpenSSL|x64.ActiveCfg = Release_NoOpenSSL|x64
|
||||
{CE5AD78C-DBDF-4D81-9A69-41B1DF683115}.Library_Release_NoOpenSSL|x86.ActiveCfg = Release_NoOpenSSL|Win32
|
||||
{CE5AD78C-DBDF-4D81-9A69-41B1DF683115}.Release_NoOpenSSL|x64.ActiveCfg = Release|x64
|
||||
{CE5AD78C-DBDF-4D81-9A69-41B1DF683115}.Release_NoOpenSSL|x64.Build.0 = Release|x64
|
||||
{CE5AD78C-DBDF-4D81-9A69-41B1DF683115}.Release_NoOpenSSL|x86.ActiveCfg = Release_NoOpenSSL|Win32
|
||||
{CE5AD78C-DBDF-4D81-9A69-41B1DF683115}.Release_NoOpenSSL|x86.Build.0 = Release_NoOpenSSL|Win32
|
||||
{CE5AD78C-DBDF-4D81-9A69-41B1DF683115}.Release|x64.ActiveCfg = Release|x64
|
||||
{CE5AD78C-DBDF-4D81-9A69-41B1DF683115}.Release|x64.Build.0 = Release|x64
|
||||
{CE5AD78C-DBDF-4D81-9A69-41B1DF683115}.Release|x86.ActiveCfg = Release|Win32
|
||||
{CE5AD78C-DBDF-4D81-9A69-41B1DF683115}.Release|x86.Build.0 = Release|Win32
|
||||
{E377F156-BAED-4086-B534-3CC43164607A}.Debug_NoOpenSSL|x64.ActiveCfg = Debug_NoOpenSSL|x64
|
||||
{E377F156-BAED-4086-B534-3CC43164607A}.Debug_NoOpenSSL|x64.Build.0 = Debug_NoOpenSSL|x64
|
||||
{E377F156-BAED-4086-B534-3CC43164607A}.Debug_NoOpenSSL|x86.ActiveCfg = Debug_NoOpenSSL|Win32
|
||||
{E377F156-BAED-4086-B534-3CC43164607A}.Debug_NoOpenSSL|x86.Build.0 = Debug_NoOpenSSL|Win32
|
||||
{E377F156-BAED-4086-B534-3CC43164607A}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{E377F156-BAED-4086-B534-3CC43164607A}.Debug|x64.Build.0 = Debug|x64
|
||||
{E377F156-BAED-4086-B534-3CC43164607A}.Debug|x86.ActiveCfg = Debug|Win32
|
||||
{E377F156-BAED-4086-B534-3CC43164607A}.Debug|x86.Build.0 = Debug|Win32
|
||||
{E377F156-BAED-4086-B534-3CC43164607A}.Library_Debug_NoOpenSSL|x64.ActiveCfg = Library_Debug_NoOpenSSL|x64
|
||||
{E377F156-BAED-4086-B534-3CC43164607A}.Library_Debug_NoOpenSSL|x64.Build.0 = Library_Debug_NoOpenSSL|x64
|
||||
{E377F156-BAED-4086-B534-3CC43164607A}.Library_Debug_NoOpenSSL|x86.ActiveCfg = Library_Debug_NoOpenSSL|Win32
|
||||
{E377F156-BAED-4086-B534-3CC43164607A}.Library_Debug_NoOpenSSL|x86.Build.0 = Library_Debug_NoOpenSSL|Win32
|
||||
{E377F156-BAED-4086-B534-3CC43164607A}.Library_Release_NoOpenSSL|x64.ActiveCfg = Library_Release_NoOpenSSL|x64
|
||||
{E377F156-BAED-4086-B534-3CC43164607A}.Library_Release_NoOpenSSL|x64.Build.0 = Library_Release_NoOpenSSL|x64
|
||||
{E377F156-BAED-4086-B534-3CC43164607A}.Library_Release_NoOpenSSL|x86.ActiveCfg = Library_Release_NoOpenSSL|Win32
|
||||
{E377F156-BAED-4086-B534-3CC43164607A}.Library_Release_NoOpenSSL|x86.Build.0 = Library_Release_NoOpenSSL|Win32
|
||||
{E377F156-BAED-4086-B534-3CC43164607A}.Release_NoOpenSSL|x64.ActiveCfg = Release_NoOpenSSL|x64
|
||||
{E377F156-BAED-4086-B534-3CC43164607A}.Release_NoOpenSSL|x64.Build.0 = Release_NoOpenSSL|x64
|
||||
{E377F156-BAED-4086-B534-3CC43164607A}.Release_NoOpenSSL|x86.ActiveCfg = Release_NoOpenSSL|Win32
|
||||
{E377F156-BAED-4086-B534-3CC43164607A}.Release_NoOpenSSL|x86.Build.0 = Release_NoOpenSSL|Win32
|
||||
{E377F156-BAED-4086-B534-3CC43164607A}.Release|x64.ActiveCfg = Release|x64
|
||||
{E377F156-BAED-4086-B534-3CC43164607A}.Release|x64.Build.0 = Release|x64
|
||||
{E377F156-BAED-4086-B534-3CC43164607A}.Release|x86.ActiveCfg = Release|Win32
|
||||
|
||||
18
compileall
18
compileall
@@ -1,19 +1,19 @@
|
||||
make clean
|
||||
make linux ARCHID=5
|
||||
make linux ARCHID=5 -j8
|
||||
make clean
|
||||
make linux ARCHID=6
|
||||
make linux ARCHID=6 -j8
|
||||
make clean
|
||||
make linux ARCHID=7
|
||||
make linux ARCHID=7 -j8
|
||||
make clean
|
||||
make linux ARCHID=9
|
||||
make linux ARCHID=9 -j8
|
||||
make clean
|
||||
make linux ARCHID=13
|
||||
make linux ARCHID=13 -j8
|
||||
make clean
|
||||
make linux ARCHID=15
|
||||
make linux ARCHID=15 -j8
|
||||
make clean
|
||||
make linux ARCHID=18
|
||||
make linux ARCHID=18 -j8
|
||||
make clean
|
||||
make linux ARCHID=19
|
||||
make linux ARCHID=19 -j8
|
||||
make clean
|
||||
make linux ARCHID=20
|
||||
make linux ARCHID=20 -j8
|
||||
make clean
|
||||
|
||||
BIN
lib-jpeg-turbo/linux/armhf/libturbojpeg.a
Normal file
BIN
lib-jpeg-turbo/linux/armhf/libturbojpeg.a
Normal file
Binary file not shown.
Binary file not shown.
BIN
lib-jpeg-turbo/linux/x86-64/v80/libturbojpeg.a
Normal file
BIN
lib-jpeg-turbo/linux/x86-64/v80/libturbojpeg.a
Normal file
Binary file not shown.
BIN
lib-jpeg-turbo/linux/x86/libturbojpeg.a
Normal file
BIN
lib-jpeg-turbo/linux/x86/libturbojpeg.a
Normal file
Binary file not shown.
32
makefile
32
makefile
@@ -1,3 +1,12 @@
|
||||
# To built libturbojpeg.a
|
||||
#
|
||||
# Get the file "libjpeg-turbo-1.4.2.tar.gz", extract it. For Linux 64bit compile:
|
||||
# ./configure
|
||||
# For Linux 32bit compile
|
||||
# ./configure --build=i686-pc-linux-gnu "CFLAGS=-m32" "CXXFLAGS=-m32" "LDFLAGS=-m32"
|
||||
# Then do "make -j8" and get the resulting file /.libs/libturbojpeg.a
|
||||
#
|
||||
#
|
||||
# To build MeshAgent2 on Linux you first got to download the dev libraries to compile the agent, we need x11, txt, ext and jpeg. To install, do this:
|
||||
#
|
||||
# sudo apt-get install libx11-dev libxtst-dev libxext-dev libjpeg-dev
|
||||
@@ -25,13 +34,14 @@
|
||||
# make linux ARCHID=18 # Linux x86 64 bit POKY
|
||||
# make linux ARCHID=19 # Linux x86 32 bit NOKVM
|
||||
# make linux ARCHID=20 # Linux x86 64 bit NOKVM
|
||||
# make linux ARCHID=25 # Linux ARM 32 bit HardFloat (Raspberry PI2, etc)
|
||||
# make linux ARCHID=25 # Linux ARM 32 bit HardFloat (Raspberry Pi, etc)
|
||||
# make pi KVM=1 ARCHID=25 # Linux ARM 32 bit HardFloat, compiled on the Pi.
|
||||
#
|
||||
|
||||
# Microstack & Microscript
|
||||
SOURCES = microstack/ILibAsyncServerSocket.c microstack/ILibAsyncSocket.c microstack/ILibAsyncUDPSocket.c microstack/ILibParsers.c microstack/ILibMulticastSocket.c
|
||||
SOURCES += microstack/ILibRemoteLogging.c microstack/ILibWebClient.c microstack/ILibWebRTC.c microstack/ILibWebServer.c microstack/ILibCrypto.c
|
||||
SOURCES += microstack/ILibWrapperWebRTC.c microstack/md5.c microstack/sha1.c microstack/ILibSimpleDataStore.c microstack/ILibProcessPipe.c microstack/ILibIPAddressMonitor.c
|
||||
SOURCES += microstack/ILibWrapperWebRTC.c microstack/ILibSimpleDataStore.c microstack/ILibProcessPipe.c microstack/ILibIPAddressMonitor.c
|
||||
SOURCES += microscript/duktape.c microscript/duk_module_duktape.c microscript/ILibAsyncSocket_Duktape.c microscript/ILibDuktape_DuplexStream.c microscript/ILibDuktape_Helpers.c
|
||||
SOURCES += microscript/ILibDuktape_http.c microscript/ILibDuktape_net.c microscript/ILibDuktape_ReadableStream.c microscript/ILibDuktape_WritableStream.c
|
||||
SOURCES += microscript/ILibDuktapeModSearch.c microscript/ILibParsers_Duktape.c microscript/ILibWebClient_Duktape.c microscript/ILibDuktape_WebRTC.c
|
||||
@@ -39,7 +49,7 @@ SOURCES += microscript/ILibWebServer_Duktape.c microscript/ILibDuktape_SimpleDat
|
||||
SOURCES += microscript/ILibDuktape_fs.c microscript/ILibDuktape_SHA256.c microscript/ILibduktape_EventEmitter.c
|
||||
SOURCES += microscript/ILibDuktape_EncryptionStream.c microscript/ILibDuktape_Polyfills.c microscript/ILibDuktape_Dgram.c
|
||||
SOURCES += microscript/ILibDuktape_ScriptContainer.c microscript/ILibDuktape_MemoryStream.c microscript/ILibDuktape_NetworkMonitor.c
|
||||
SOURCES += microscript/ILibDuktape_ChildProcess.c microscript/ILibDuktape_HECI.c microscript/ILibDuktape_HttpStream.c
|
||||
SOURCES += microscript/ILibDuktape_ChildProcess.c microscript/ILibDuktape_HECI.c microscript/ILibDuktape_HttpStream.c microscript/ILibDuktape_Debugger.c
|
||||
|
||||
# Mesh Agent core
|
||||
SOURCES += meshcore/agentcore.c meshconsole/main.c meshcore/meshinfo.c
|
||||
@@ -178,7 +188,11 @@ ifeq ($(KVM),1)
|
||||
# Mesh Agent KVM, this is only included in builds that have KVM support
|
||||
SOURCES += meshcore/KVM/Linux/linux_kvm.c meshcore/KVM/Linux/linux_events.c meshcore/KVM/Linux/linux_tile.c meshcore/KVM/Linux/linux_compression.c
|
||||
CFLAGS += -D_LINKVM
|
||||
LDFLAGS += -lX11 -lXtst -lXext -ljpeg
|
||||
ifneq ($(JPEGVER),)
|
||||
LDFLAGS += -lX11 -lXtst -lXext -l:lib-jpeg-turbo/linux/$(ARCHNAME)/$(JPEGVER)/libturbojpeg.a
|
||||
else
|
||||
LDFLAGS += -lX11 -lXtst -lXext -l:lib-jpeg-turbo/linux/$(ARCHNAME)/libturbojpeg.a
|
||||
endif
|
||||
endif
|
||||
|
||||
ifeq ($(LMS),1)
|
||||
@@ -198,7 +212,7 @@ CWATCHDOG := -DILibChain_WATCHDOG_TIMEOUT=$(WatchDog)
|
||||
endif
|
||||
|
||||
ifeq ($(NOTLS),1)
|
||||
SOURCES += microstack/sha384-512.c microstack/sha224-256.c
|
||||
SOURCES += microstack/nossl/sha384-512.c microstack/nossl/sha224-256.c microstack/nossl/md5.c microstack/nossl/sha1.c
|
||||
CFLAGS += -DMICROSTACK_NOTLS
|
||||
LINUXSSL =
|
||||
else
|
||||
@@ -209,7 +223,7 @@ endif
|
||||
|
||||
ifeq ($(DEBUG),1)
|
||||
# Debug Build, include Symbols
|
||||
CFLAGS += -g -rdynamic -D_DEBUG
|
||||
CFLAGS += -g -rdynamic -D_DEBUG -DDUK_USE_DEBUGGER_SUPPORT -DDUK_USE_INTERRUPT_COUNTER -DDUK_USE_DEBUGGER_INSPECT -DDUK_USE_DEBUGGER_PAUSE_UNCAUGHT
|
||||
STRIP = $(NOECHO) $(NOOP)
|
||||
else
|
||||
CFLAGS += -Os
|
||||
@@ -240,9 +254,15 @@ clean:
|
||||
|
||||
cleanbin:
|
||||
rm -f $(EXENAME)_x86
|
||||
rm -f $(EXENAME)_x86_nokvm
|
||||
rm -f $(EXENAME)_x86-64
|
||||
rm -f $(EXENAME)_x86-64_nokvm
|
||||
rm -f $(EXENAME)_arm
|
||||
rm -f $(EXENAME)_mips
|
||||
rm -f $(EXENAME)_pogo
|
||||
rm -f $(EXENAME)_poky
|
||||
rm -f $(EXENAME)_poky64
|
||||
|
||||
|
||||
depend: $(SOURCES)
|
||||
$(CC) -M $(CFLAGS) $(SOURCES) $(HEADERS) > depend
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup Label="ProjectConfigurations">
|
||||
<ProjectConfiguration Include="Debug_NoOpenSSL|Win32">
|
||||
<Configuration>Debug_NoOpenSSL</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Debug_NoOpenSSL|x64">
|
||||
<Configuration>Debug_NoOpenSSL</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Debug|Win32">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
@@ -9,6 +17,30 @@
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Library_Debug_NoOpenSSL|Win32">
|
||||
<Configuration>Library_Debug_NoOpenSSL</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Library_Debug_NoOpenSSL|x64">
|
||||
<Configuration>Library_Debug_NoOpenSSL</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Library_Release_NoOpenSSL|Win32">
|
||||
<Configuration>Library_Release_NoOpenSSL</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Library_Release_NoOpenSSL|x64">
|
||||
<Configuration>Library_Release_NoOpenSSL</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release_NoOpenSSL|Win32">
|
||||
<Configuration>Release_NoOpenSSL</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release_NoOpenSSL|x64">
|
||||
<Configuration>Release_NoOpenSSL</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|Win32">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
@@ -28,6 +60,7 @@
|
||||
<ClCompile Include="..\microscript\duk_module_duktape.c" />
|
||||
<ClCompile Include="..\microscript\ILibDuktapeModSearch.c" />
|
||||
<ClCompile Include="..\microscript\ILibDuktape_ChildProcess.c" />
|
||||
<ClCompile Include="..\microscript\ILibDuktape_Debugger.c" />
|
||||
<ClCompile Include="..\microscript\ILibDuktape_Dgram.c" />
|
||||
<ClCompile Include="..\microscript\ILibDuktape_DuplexStream.c" />
|
||||
<ClCompile Include="..\microscript\ILibDuktape_EncryptionStream.c" />
|
||||
@@ -76,6 +109,7 @@
|
||||
<ClInclude Include="..\microscript\duk_module_duktape.h" />
|
||||
<ClInclude Include="..\microscript\ILibDuktapeModSearch.h" />
|
||||
<ClInclude Include="..\microscript\ILibDuktape_ChildProcess.h" />
|
||||
<ClInclude Include="..\microscript\ILibDuktape_Debugger.h" />
|
||||
<ClInclude Include="..\microscript\ILibDuktape_Dgram.h" />
|
||||
<ClInclude Include="..\microscript\ILibDuktape_DuplexStream.h" />
|
||||
<ClInclude Include="..\microscript\ILibDuktape_EncryptionStream.h" />
|
||||
@@ -125,24 +159,72 @@
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug_NoOpenSSL|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Library_Debug_NoOpenSSL|Win32'" Label="Configuration">
|
||||
<ConfigurationType>DynamicLibrary</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release_NoOpenSSL|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Library_Release_NoOpenSSL|Win32'" Label="Configuration">
|
||||
<ConfigurationType>DynamicLibrary</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug_NoOpenSSL|x64'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Library_Debug_NoOpenSSL|x64'" Label="Configuration">
|
||||
<ConfigurationType>DynamicLibrary</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release_NoOpenSSL|x64'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Library_Release_NoOpenSSL|x64'" Label="Configuration">
|
||||
<ConfigurationType>DynamicLibrary</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||
<ImportGroup Label="ExtensionSettings">
|
||||
</ImportGroup>
|
||||
@@ -151,39 +233,105 @@
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug_NoOpenSSL|Win32'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Library_Debug_NoOpenSSL|Win32'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release_NoOpenSSL|Win32'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Library_Release_NoOpenSSL|Win32'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug_NoOpenSSL|x64'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Library_Debug_NoOpenSSL|x64'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release_NoOpenSSL|x64'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Library_Release_NoOpenSSL|x64'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<PropertyGroup Label="UserMacros" />
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<OutDir>$(SolutionDir)$(Configuration)\</OutDir>
|
||||
<IntDir>$(SolutionDir)$(Configuration)\$(TargetName)\$(Platform)\OBJ\</IntDir>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug_NoOpenSSL|Win32'">
|
||||
<OutDir>$(SolutionDir)$(Configuration)\</OutDir>
|
||||
<IntDir>$(SolutionDir)$(Configuration)\$(TargetName)\$(Platform)\OBJ\</IntDir>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Library_Debug_NoOpenSSL|Win32'">
|
||||
<OutDir>$(SolutionDir)$(Configuration)\</OutDir>
|
||||
<IntDir>$(SolutionDir)$(Configuration)\$(TargetName)\$(Platform)\OBJ\</IntDir>
|
||||
<TargetExt>.dll</TargetExt>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<OutDir>$(SolutionDir)$(Configuration)\</OutDir>
|
||||
<IntDir>$(SolutionDir)$(Configuration)\$(TargetName)\$(Platform)\OBJ\</IntDir>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release_NoOpenSSL|Win32'">
|
||||
<OutDir>$(SolutionDir)$(Configuration)\</OutDir>
|
||||
<IntDir>$(SolutionDir)$(Configuration)\$(TargetName)\$(Platform)\OBJ\</IntDir>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Library_Release_NoOpenSSL|Win32'">
|
||||
<OutDir>$(SolutionDir)$(Configuration)\</OutDir>
|
||||
<IntDir>$(SolutionDir)$(Configuration)\$(TargetName)\$(Platform)\OBJ\</IntDir>
|
||||
<TargetExt>.dll</TargetExt>
|
||||
<PostBuildEventUseInBuild>false</PostBuildEventUseInBuild>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<OutDir>$(SolutionDir)$(Configuration)\</OutDir>
|
||||
<IntDir>$(SolutionDir)$(Configuration)\$(TargetName)\$(Platform)\OBJ\</IntDir>
|
||||
<TargetName>$(ProjectName)64</TargetName>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug_NoOpenSSL|x64'">
|
||||
<OutDir>$(SolutionDir)$(Configuration)\</OutDir>
|
||||
<IntDir>$(SolutionDir)$(Configuration)\$(TargetName)\$(Platform)\OBJ\</IntDir>
|
||||
<TargetName>$(ProjectName)64</TargetName>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Library_Debug_NoOpenSSL|x64'">
|
||||
<OutDir>$(SolutionDir)$(Configuration)\</OutDir>
|
||||
<IntDir>$(SolutionDir)$(Configuration)\$(TargetName)\$(Platform)\OBJ\</IntDir>
|
||||
<TargetName>$(ProjectName)64</TargetName>
|
||||
<TargetExt>.dll</TargetExt>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<OutDir>$(SolutionDir)$(Configuration)\</OutDir>
|
||||
<IntDir>$(SolutionDir)$(Configuration)\$(TargetName)\$(Platform)\OBJ\</IntDir>
|
||||
<TargetName>$(ProjectName)64</TargetName>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release_NoOpenSSL|x64'">
|
||||
<OutDir>$(SolutionDir)$(Configuration)\</OutDir>
|
||||
<IntDir>$(SolutionDir)$(Configuration)\$(TargetName)\$(Platform)\OBJ\</IntDir>
|
||||
<TargetName>$(ProjectName)64</TargetName>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Library_Release_NoOpenSSL|x64'">
|
||||
<OutDir>$(SolutionDir)$(Configuration)\</OutDir>
|
||||
<IntDir>$(SolutionDir)$(Configuration)\$(TargetName)\$(Platform)\OBJ\</IntDir>
|
||||
<TargetName>$(ProjectName)64</TargetName>
|
||||
<TargetExt>.dll</TargetExt>
|
||||
<PostBuildEventUseInBuild>false</PostBuildEventUseInBuild>
|
||||
</PropertyGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<PreprocessorDefinitions>MESH_AGENTID=1;NOLMSCOMMANDER;_DEBUG;MICROSTACK_PROXY;_LINKVM;WIN32;WINSOCK2;_WINSOCK_DEPRECATED_NO_WARNINGS;_MSC_PLATFORM_TOOLSET_$(PlatformToolset);MICROSTACK_TLS_DETECT;MICROSTACK_NO_STDAFX;_REMOTELOGGING;_REMOTELOGGINGSERVER;ILibChain_WATCHDOG_TIMEOUT=600000;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<PreprocessorDefinitions>MESH_AGENTID=1;DUK_USE_DATE_NOW_WINDOWS;NOLMSCOMMANDER;_DEBUG;MICROSTACK_PROXY;_LINKVM;WIN32;WINSOCK2;_WINSOCK_DEPRECATED_NO_WARNINGS;_MSC_PLATFORM_TOOLSET_$(PlatformToolset);MICROSTACK_TLS_DETECT;MICROSTACK_NO_STDAFX;_REMOTELOGGING;_REMOTELOGGINGSERVER;ILibChain_WATCHDOG_TIMEOUT=600000;DUK_USE_DEBUGGER_SUPPORT;DUK_USE_INTERRUPT_COUNTER;DUK_USE_DEBUGGER_INSPECT;DUK_USE_DEBUGGER_PAUSE_UNCAUGHT;DUK_USE_DEBUGGER_DUMPHEAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AdditionalIncludeDirectories>..\openssl\include;..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
|
||||
<ExceptionHandling>Async</ExceptionHandling>
|
||||
@@ -194,11 +342,41 @@
|
||||
<OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug_NoOpenSSL|Win32'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<PreprocessorDefinitions>MESH_AGENTID=1;DUK_USE_DATE_NOW_WINDOWS;NOLMSCOMMANDER;_DEBUG;MICROSTACK_PROXY;_LINKVM;WIN32;WINSOCK2;_WINSOCK_DEPRECATED_NO_WARNINGS;_MSC_PLATFORM_TOOLSET_$(PlatformToolset);MICROSTACK_TLS_DETECT;MICROSTACK_NO_STDAFX;_REMOTELOGGING;_REMOTELOGGINGSERVER;ILibChain_WATCHDOG_TIMEOUT=600000;MICROSTACK_NOTLS;DUK_USE_DEBUGGER_SUPPORT;DUK_USE_INTERRUPT_COUNTER;DUK_USE_DEBUGGER_INSPECT;DUK_USE_DEBUGGER_PAUSE_UNCAUGHT;DUK_USE_DEBUGGER_DUMPHEAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AdditionalIncludeDirectories>..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
|
||||
<ExceptionHandling>Async</ExceptionHandling>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<AdditionalDependencies>SetupAPI.lib;Bcrypt.lib;Crypt32.lib;DbgHelp.lib;Gdiplus.lib;Iphlpapi.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
<AdditionalOptions> /ignore:4099 %(AdditionalOptions)</AdditionalOptions>
|
||||
<OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Library_Debug_NoOpenSSL|Win32'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<PreprocessorDefinitions>MESH_AGENTID=1;DUK_USE_DATE_NOW_WINDOWS;NOLMSCOMMANDER;_DEBUG;MICROSTACK_PROXY;_LINKVM;WIN32;WINSOCK2;_WINSOCK_DEPRECATED_NO_WARNINGS;_MSC_PLATFORM_TOOLSET_$(PlatformToolset);MICROSTACK_TLS_DETECT;MICROSTACK_NO_STDAFX;_REMOTELOGGING;_REMOTELOGGINGSERVER;ILibChain_WATCHDOG_TIMEOUT=600000;MICROSTACK_NOTLS;MeshLibInterface;DUK_USE_DEBUGGER_SUPPORT;DUK_USE_INTERRUPT_COUNTER;DUK_USE_DEBUGGER_INSPECT;DUK_USE_DEBUGGER_PAUSE_UNCAUGHT;DUK_USE_DEBUGGER_DUMPHEAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AdditionalIncludeDirectories>..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
|
||||
<ExceptionHandling>Async</ExceptionHandling>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<AdditionalDependencies>SetupAPI.lib;Bcrypt.lib;Crypt32.lib;DbgHelp.lib;Gdiplus.lib;Iphlpapi.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
<AdditionalOptions> /ignore:4099 %(AdditionalOptions)</AdditionalOptions>
|
||||
<OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<PreprocessorDefinitions>MESH_AGENTID=1;NOLMSCOMMANDER;MICROSTACK_PROXY;_LINKVM;WIN32;WINSOCK2;_WINSOCK_DEPRECATED_NO_WARNINGS;_MSC_PLATFORM_TOOLSET_$(PlatformToolset);MICROSTACK_TLS_DETECT;MICROSTACK_NO_STDAFX;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<PreprocessorDefinitions>MESH_AGENTID=1;DUK_USE_DATE_NOW_WINDOWS;NOLMSCOMMANDER;MICROSTACK_PROXY;_LINKVM;WIN32;WINSOCK2;_WINSOCK_DEPRECATED_NO_WARNINGS;_MSC_PLATFORM_TOOLSET_$(PlatformToolset);MICROSTACK_TLS_DETECT;MICROSTACK_NO_STDAFX;DUK_USE_DEBUGGER_SUPPORT;DUK_USE_INTERRUPT_COUNTER;DUK_USE_DEBUGGER_INSPECT;DUK_USE_DEBUGGER_PAUSE_UNCAUGHT;DUK_USE_DEBUGGER_DUMPHEAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AdditionalIncludeDirectories>..\openssl\include;..\</AdditionalIncludeDirectories>
|
||||
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
|
||||
<ExceptionHandling>Async</ExceptionHandling>
|
||||
@@ -212,11 +390,47 @@
|
||||
<Command>"$(OutputPath)$(TargetFileName)" ..\modules\PostBuild.js</Command>
|
||||
</PostBuildEvent>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release_NoOpenSSL|Win32'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<PreprocessorDefinitions>MESH_AGENTID=1;DUK_USE_DATE_NOW_WINDOWS;NOLMSCOMMANDER;MICROSTACK_PROXY;_LINKVM;WIN32;WINSOCK2;_WINSOCK_DEPRECATED_NO_WARNINGS;_MSC_PLATFORM_TOOLSET_$(PlatformToolset);MICROSTACK_TLS_DETECT;MICROSTACK_NO_STDAFX;MICROSTACK_NOTLS;DUK_USE_DEBUGGER_SUPPORT;DUK_USE_INTERRUPT_COUNTER;DUK_USE_DEBUGGER_INSPECT;DUK_USE_DEBUGGER_PAUSE_UNCAUGHT;DUK_USE_DEBUGGER_DUMPHEAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AdditionalIncludeDirectories>..\</AdditionalIncludeDirectories>
|
||||
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
|
||||
<ExceptionHandling>Async</ExceptionHandling>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<AdditionalDependencies>SetupAPI.lib;Bcrypt.lib;Crypt32.lib;DbgHelp.lib;Gdiplus.lib;Iphlpapi.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
<AdditionalOptions> /ignore:4099 %(AdditionalOptions)</AdditionalOptions>
|
||||
<OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
|
||||
</Link>
|
||||
<PostBuildEvent>
|
||||
<Command>"$(OutputPath)$(TargetFileName)" ..\modules\PostBuild.js</Command>
|
||||
</PostBuildEvent>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Library_Release_NoOpenSSL|Win32'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<PreprocessorDefinitions>MESH_AGENTID=1;DUK_USE_DATE_NOW_WINDOWS;NOLMSCOMMANDER;MICROSTACK_PROXY;_LINKVM;WIN32;WINSOCK2;_WINSOCK_DEPRECATED_NO_WARNINGS;_MSC_PLATFORM_TOOLSET_$(PlatformToolset);MICROSTACK_TLS_DETECT;MICROSTACK_NO_STDAFX;MICROSTACK_NOTLS;MeshLibInterface;DUK_USE_DEBUGGER_SUPPORT;DUK_USE_INTERRUPT_COUNTER;DUK_USE_DEBUGGER_INSPECT;DUK_USE_DEBUGGER_PAUSE_UNCAUGHT;DUK_USE_DEBUGGER_DUMPHEAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AdditionalIncludeDirectories>..\</AdditionalIncludeDirectories>
|
||||
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
|
||||
<ExceptionHandling>Async</ExceptionHandling>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<AdditionalDependencies>SetupAPI.lib;Bcrypt.lib;Crypt32.lib;DbgHelp.lib;Gdiplus.lib;Iphlpapi.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
<AdditionalOptions> /ignore:4099 %(AdditionalOptions)</AdditionalOptions>
|
||||
<OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
|
||||
</Link>
|
||||
<PostBuildEvent>
|
||||
<Command>"$(OutputPath)$(TargetFileName)" ..\modules\PostBuild.js</Command>
|
||||
</PostBuildEvent>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<PreprocessorDefinitions>MESH_AGENTID=2;NOLMSCOMMANDER;MICROSTACK_PROXY;_DEBUG;WIN32;WIN64;WINSOCK2;_WINSOCK_DEPRECATED_NO_WARNINGS;_MSC_PLATFORM_TOOLSET_$(PlatformToolset);MICROSTACK_TLS_DETECT;MICROSTACK_NO_STDAFX;_REMOTELOGGING;_REMOTELOGGINGSERVER;ILibChain_WATCHDOG_TIMEOUT=600000;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<PreprocessorDefinitions>MESH_AGENTID=2;DUK_USE_DATE_NOW_WINDOWS;_LINKVM;NOLMSCOMMANDER;MICROSTACK_PROXY;_DEBUG;WIN32;WIN64;WINSOCK2;_WINSOCK_DEPRECATED_NO_WARNINGS;_MSC_PLATFORM_TOOLSET_$(PlatformToolset);MICROSTACK_TLS_DETECT;MICROSTACK_NO_STDAFX;_REMOTELOGGING;_REMOTELOGGINGSERVER;ILibChain_WATCHDOG_TIMEOUT=600000;DUK_USE_DEBUGGER_SUPPORT;DUK_USE_INTERRUPT_COUNTER;DUK_USE_DEBUGGER_INSPECT;DUK_USE_DEBUGGER_PAUSE_UNCAUGHT;DUK_USE_DEBUGGER_DUMPHEAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AdditionalIncludeDirectories>..\openssl\include;..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
|
||||
<ExceptionHandling>Async</ExceptionHandling>
|
||||
@@ -227,11 +441,41 @@
|
||||
<AdditionalOptions> /ignore:4099 %(AdditionalOptions)</AdditionalOptions>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug_NoOpenSSL|x64'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<PreprocessorDefinitions>MESH_AGENTID=2;DUK_USE_DATE_NOW_WINDOWS;_LINKVM;NOLMSCOMMANDER;MICROSTACK_PROXY;_DEBUG;WIN32;WIN64;WINSOCK2;_WINSOCK_DEPRECATED_NO_WARNINGS;_MSC_PLATFORM_TOOLSET_$(PlatformToolset);MICROSTACK_TLS_DETECT;MICROSTACK_NO_STDAFX;_REMOTELOGGING;_REMOTELOGGINGSERVER;ILibChain_WATCHDOG_TIMEOUT=600000;MICROSTACK_NOTLS;DUK_USE_DEBUGGER_SUPPORT;DUK_USE_INTERRUPT_COUNTER;DUK_USE_DEBUGGER_INSPECT;DUK_USE_DEBUGGER_PAUSE_UNCAUGHT;DUK_USE_DEBUGGER_DUMPHEAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AdditionalIncludeDirectories>..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
|
||||
<ExceptionHandling>Async</ExceptionHandling>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<AdditionalDependencies>SetupAPI.lib;Bcrypt.lib;Crypt32.lib;DbgHelp.lib;Gdiplus.lib;Iphlpapi.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
<OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
|
||||
<AdditionalOptions> /ignore:4099 %(AdditionalOptions)</AdditionalOptions>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Library_Debug_NoOpenSSL|x64'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<PreprocessorDefinitions>MESH_AGENTID=2;DUK_USE_DATE_NOW_WINDOWS;_LINKVM;NOLMSCOMMANDER;MICROSTACK_PROXY;_DEBUG;WIN32;WIN64;WINSOCK2;_WINSOCK_DEPRECATED_NO_WARNINGS;_MSC_PLATFORM_TOOLSET_$(PlatformToolset);MICROSTACK_TLS_DETECT;MICROSTACK_NO_STDAFX;_REMOTELOGGING;_REMOTELOGGINGSERVER;ILibChain_WATCHDOG_TIMEOUT=600000;MICROSTACK_NOTLS;MeshLibInterface;DUK_USE_DEBUGGER_SUPPORT;DUK_USE_INTERRUPT_COUNTER;DUK_USE_DEBUGGER_INSPECT;DUK_USE_DEBUGGER_PAUSE_UNCAUGHT;DUK_USE_DEBUGGER_DUMPHEAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AdditionalIncludeDirectories>..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
|
||||
<ExceptionHandling>Async</ExceptionHandling>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<AdditionalDependencies>SetupAPI.lib;Bcrypt.lib;Crypt32.lib;DbgHelp.lib;Gdiplus.lib;Iphlpapi.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
<OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
|
||||
<AdditionalOptions> /ignore:4099 %(AdditionalOptions)</AdditionalOptions>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<PreprocessorDefinitions>MESH_AGENTID=2;NOLMSCOMMANDER;MICROSTACK_PROXY;_LINKVM;WIN32;WIN64;WINSOCK2;_WINSOCK_DEPRECATED_NO_WARNINGS;_MSC_PLATFORM_TOOLSET_$(PlatformToolset);MICROSTACK_TLS_DETECT;MICROSTACK_NO_STDAFX;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<PreprocessorDefinitions>MESH_AGENTID=2;DUK_USE_DATE_NOW_WINDOWS;NOLMSCOMMANDER;MICROSTACK_PROXY;_LINKVM;WIN32;WIN64;WINSOCK2;_WINSOCK_DEPRECATED_NO_WARNINGS;_MSC_PLATFORM_TOOLSET_$(PlatformToolset);MICROSTACK_TLS_DETECT;MICROSTACK_NO_STDAFX;DUK_USE_DEBUGGER_SUPPORT;DUK_USE_INTERRUPT_COUNTER;DUK_USE_DEBUGGER_INSPECT;DUK_USE_DEBUGGER_PAUSE_UNCAUGHT;DUK_USE_DEBUGGER_DUMPHEAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AdditionalIncludeDirectories>..\openssl\include;..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
|
||||
<ExceptionHandling>Async</ExceptionHandling>
|
||||
@@ -245,6 +489,42 @@
|
||||
<Command>"$(OutputPath)$(TargetFileName)" ..\modules\PostBuild.js</Command>
|
||||
</PostBuildEvent>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release_NoOpenSSL|x64'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<PreprocessorDefinitions>MESH_AGENTID=2;DUK_USE_DATE_NOW_WINDOWS;NOLMSCOMMANDER;MICROSTACK_PROXY;_LINKVM;WIN32;WIN64;WINSOCK2;_WINSOCK_DEPRECATED_NO_WARNINGS;_MSC_PLATFORM_TOOLSET_$(PlatformToolset);MICROSTACK_TLS_DETECT;MICROSTACK_NO_STDAFX;MICROSTACK_NOTLS;DUK_USE_DEBUGGER_SUPPORT;DUK_USE_INTERRUPT_COUNTER;DUK_USE_DEBUGGER_INSPECT;DUK_USE_DEBUGGER_PAUSE_UNCAUGHT;DUK_USE_DEBUGGER_DUMPHEAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AdditionalIncludeDirectories>..\openssl\include;..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
|
||||
<ExceptionHandling>Async</ExceptionHandling>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<AdditionalDependencies>SetupAPI.lib;DbgHelp.lib;Gdiplus.lib;Iphlpapi.lib;Bcrypt.lib;Crypt32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
<OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
|
||||
<AdditionalOptions> /ignore:4099 %(AdditionalOptions)</AdditionalOptions>
|
||||
</Link>
|
||||
<PostBuildEvent>
|
||||
<Command>"$(OutputPath)$(TargetFileName)" ..\modules\PostBuild.js</Command>
|
||||
</PostBuildEvent>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Library_Release_NoOpenSSL|x64'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<PreprocessorDefinitions>MESH_AGENTID=2;DUK_USE_DATE_NOW_WINDOWS;NOLMSCOMMANDER;MICROSTACK_PROXY;_LINKVM;WIN32;WIN64;WINSOCK2;_WINSOCK_DEPRECATED_NO_WARNINGS;_MSC_PLATFORM_TOOLSET_$(PlatformToolset);MICROSTACK_TLS_DETECT;MICROSTACK_NO_STDAFX;MICROSTACK_NOTLS;MeshLibInterface;DUK_USE_DEBUGGER_SUPPORT;DUK_USE_INTERRUPT_COUNTER;DUK_USE_DEBUGGER_INSPECT;DUK_USE_DEBUGGER_PAUSE_UNCAUGHT;DUK_USE_DEBUGGER_DUMPHEAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<AdditionalIncludeDirectories>..\openssl\include;..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
|
||||
<ExceptionHandling>Async</ExceptionHandling>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<AdditionalDependencies>SetupAPI.lib;DbgHelp.lib;Gdiplus.lib;Iphlpapi.lib;Bcrypt.lib;Crypt32.lib;ws2_32.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
<OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
|
||||
<AdditionalOptions> /ignore:4099 %(AdditionalOptions)</AdditionalOptions>
|
||||
</Link>
|
||||
<PostBuildEvent>
|
||||
<Command>"$(OutputPath)$(TargetFileName)" ..\modules\PostBuild.js</Command>
|
||||
</PostBuildEvent>
|
||||
</ItemDefinitionGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
</ImportGroup>
|
||||
|
||||
@@ -145,6 +145,9 @@
|
||||
<ClInclude Include="..\microscript\duk_module_duktape.h">
|
||||
<Filter>Microscript</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="..\microscript\ILibDuktape_Debugger.h">
|
||||
<Filter>Microscript</Filter>
|
||||
</ClInclude>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="..\microscript\duktape.c">
|
||||
@@ -277,6 +280,9 @@
|
||||
<ClCompile Include="..\microscript\duk_module_duktape.c">
|
||||
<Filter>Microscript</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="..\microscript\ILibDuktape_Debugger.c">
|
||||
<Filter>Microscript</Filter>
|
||||
</ClCompile>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ResourceCompile Include="MeshConsole.rc" />
|
||||
|
||||
@@ -63,6 +63,31 @@ void BreakSink(int s)
|
||||
}
|
||||
#endif
|
||||
|
||||
#if defined(WIN32) && defined(MeshLibInterface)
|
||||
extern void ILibDuktape_ScriptContainer_GetEmbeddedJS_Raw(char *exePath, char **script, int *scriptLen);
|
||||
typedef void(__stdcall *ExternalDispatch)(void *data);
|
||||
__declspec(dllexport) ExternalDispatch ExternalDispatchSink = NULL;
|
||||
__declspec(dllexport) int mainEx(int argc, char **argv, ExternalDispatch ptr)
|
||||
{
|
||||
int retCode = 0;
|
||||
char *js = NULL;
|
||||
int jsLen = 0;
|
||||
|
||||
ExternalDispatchSink = ptr;
|
||||
ILibDuktape_ScriptContainer_GetEmbeddedJS_Raw(argv[0], &js, &jsLen);
|
||||
|
||||
agentHost = MeshAgent_Create(0);
|
||||
agentHost->exePath = (char*)ILibMemory_AllocateA(strnlen_s(argv[0], _MAX_PATH) + 1);
|
||||
memcpy_s(agentHost->exePath, ILibMemory_AllocateA_Size(agentHost->exePath), argv[0], ILibMemory_AllocateA_Size(agentHost->exePath) - 1);
|
||||
|
||||
agentHost->meshCoreCtx_embeddedScript = js;
|
||||
agentHost->meshCoreCtx_embeddedScriptLen = jsLen;
|
||||
while (MeshAgent_Start(agentHost, argc, argv) != 0);
|
||||
retCode = agentHost->exitCode;
|
||||
MeshAgent_Destroy(agentHost);
|
||||
return(retCode);
|
||||
}
|
||||
#endif
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
@@ -70,18 +95,50 @@ int main(int argc, char **argv)
|
||||
char *integratedJavaScript = NULL;
|
||||
int integratedJavaScriptLen = 0;
|
||||
int retCode = 0;
|
||||
int capabilities = 0;
|
||||
|
||||
ILibDuktape_ScriptContainer_CheckEmbedded(argv, &integratedJavaScript, &integratedJavaScriptLen);
|
||||
#if defined (_POSIX)
|
||||
#ifndef _NOILIBSTACKDEBUG
|
||||
char* crashMemory = ILib_POSIX_InstallCrashHandler(argv[0]);
|
||||
#endif
|
||||
#endif
|
||||
|
||||
if (argc > 2 && memcmp(argv[1], "-faddr", 6) == 0)
|
||||
|
||||
ILibDuktape_ScriptContainer_CheckEmbedded(&integratedJavaScript, &integratedJavaScriptLen);
|
||||
|
||||
if (argc > 2 && strcasecmp(argv[1], "-faddr") == 0)
|
||||
{
|
||||
uint64_t addrOffset;
|
||||
util_hexToBuf(argv[2] + 2, (int)(strnlen_s(argv[2], 130) - 2), (char*)&addrOffset);
|
||||
ILibChain_DebugOffset(ILibScratchPad, sizeof(ILibScratchPad), addrOffset);
|
||||
#if !defined(WIN32)
|
||||
uint64_t addrOffset = 0;
|
||||
sscanf(argv[2] + 2, "%016"PRIx64, &addrOffset);
|
||||
#elif defined(WIN64)
|
||||
uint64_t addrOffset = 0;
|
||||
sscanf_s(argv[2] + 2, "%016llx", &addrOffset);
|
||||
#else
|
||||
uint32_t addrOffset = 0;
|
||||
sscanf_s(argv[2] + 2, "%x", &addrOffset);
|
||||
#endif
|
||||
|
||||
ILibChain_DebugOffset(ILibScratchPad, sizeof(ILibScratchPad), (uint64_t)addrOffset);
|
||||
printf("%s", ILibScratchPad);
|
||||
return(0);
|
||||
}
|
||||
|
||||
if (argc > 2 && strcasecmp(argv[1], "-fdelta") == 0)
|
||||
{
|
||||
uint64_t delta = 0;
|
||||
#ifdef WIN32
|
||||
sscanf_s(argv[2], "%lld", &delta);
|
||||
#else
|
||||
sscanf(argv[2], "%"PRIu64, &delta);
|
||||
#endif
|
||||
ILibChain_DebugDelta(ILibScratchPad, sizeof(ILibScratchPad), delta);
|
||||
printf("%s", ILibScratchPad);
|
||||
return(0);
|
||||
}
|
||||
|
||||
if (argc > 1 && strcasecmp(argv[1], "connect") == 0) { capabilities = MeshCommand_AuthInfo_CapabilitiesMask_TEMPORARY; }
|
||||
|
||||
if (integratedJavaScriptLen == 0)
|
||||
{
|
||||
if (argc >= 2 && strnlen_s(argv[1], 9) >= 8 && strncmp(argv[1], "-update:", 8) == 0)
|
||||
@@ -112,15 +169,12 @@ int main(int argc, char **argv)
|
||||
act.sa_flags = 0;
|
||||
sigaction(SIGPIPE, &act, NULL);
|
||||
}
|
||||
#ifndef _NOILIBSTACKDEBUG
|
||||
char* crashMemory = ILib_POSIX_InstallCrashHandler(argv[0]);
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifdef WIN32
|
||||
__try
|
||||
{
|
||||
agentHost = MeshAgent_Create();
|
||||
agentHost = MeshAgent_Create(capabilities);
|
||||
agentHost->meshCoreCtx_embeddedScript = integratedJavaScript;
|
||||
agentHost->meshCoreCtx_embeddedScriptLen = integratedJavaScriptLen;
|
||||
while (MeshAgent_Start(agentHost, argc, argv) != 0);
|
||||
@@ -133,7 +187,7 @@ int main(int argc, char **argv)
|
||||
}
|
||||
_CrtDumpMemoryLeaks();
|
||||
#else
|
||||
agentHost = MeshAgent_Create();
|
||||
agentHost = MeshAgent_Create(capabilities);
|
||||
agentHost->meshCoreCtx_embeddedScript = integratedJavaScript;
|
||||
agentHost->meshCoreCtx_embeddedScriptLen = integratedJavaScriptLen;
|
||||
while (MeshAgent_Start(agentHost, argc, argv) != 0);
|
||||
|
||||
@@ -42,6 +42,8 @@ int TILE_HEIGHT = 0;
|
||||
int TILE_WIDTH_COUNT = 0;
|
||||
int TILE_HEIGHT_COUNT = 0;
|
||||
int COMPRESSION_RATIO = 0;
|
||||
int SCALING_FACTOR = 1024; // Scaling factor, 1024 = 100%
|
||||
int SCALING_FACTOR_NEW = 1024; // Desired scaling factor, 1024 = 100%
|
||||
int FRAME_RATE_TIMER = 0;
|
||||
struct tileInfo_t **g_tileInfo = NULL;
|
||||
pthread_t kvmthread = (pthread_t)NULL;
|
||||
@@ -429,8 +431,9 @@ int kvm_server_inputdata(char* block, int blocklen)
|
||||
}
|
||||
case MNG_KVM_COMPRESSION: // Compression
|
||||
{
|
||||
if (size != 6) break;
|
||||
set_tile_compression((int)block[4], (int)block[5]);
|
||||
if (size >= 10) { int fr = ((int)ntohs(((unsigned short*)(block + 8))[0])); if (fr >= 20 && fr <= 5000) FRAME_RATE_TIMER = fr; }
|
||||
if (size >= 8) { int ns = ((int)ntohs(((unsigned short*)(block + 6))[0])); if (ns >= 64 && ns <= 4096) SCALING_FACTOR_NEW = ns; }
|
||||
if (size >= 6) { set_tile_compression((int)block[4], (int)block[5]); }
|
||||
COMPRESSION_RATIO = 100;
|
||||
break;
|
||||
}
|
||||
@@ -458,6 +461,12 @@ int kvm_server_inputdata(char* block, int blocklen)
|
||||
g_remotepause = block[4];
|
||||
break;
|
||||
}
|
||||
case MNG_KVM_FRAME_RATE_TIMER:
|
||||
{
|
||||
int fr = ((int)ntohs(((unsigned short*)(block))[2]));
|
||||
if (fr >= 20 && fr <= 5000) FRAME_RATE_TIMER = fr;
|
||||
break;
|
||||
}
|
||||
case MNG_KVM_GET_DISPLAYS:
|
||||
{
|
||||
kvm_send_display_list();
|
||||
@@ -470,12 +479,6 @@ int kvm_server_inputdata(char* block, int blocklen)
|
||||
change_display = 1;
|
||||
break;
|
||||
}
|
||||
case MNG_KVM_FRAME_RATE_TIMER:
|
||||
{
|
||||
int fr = ((int)ntohs(((unsigned short*)(block))[2]));
|
||||
if (fr > 20 && fr < 2000) FRAME_RATE_TIMER = fr;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return size;
|
||||
}
|
||||
@@ -510,10 +513,10 @@ void* kvm_server_mainloop(void* parm)
|
||||
int x, y, height, width, r, c, count = 0;
|
||||
long long desktopsize = 0;
|
||||
long long tilesize = 0;
|
||||
long long prev_timestamp = 0;
|
||||
long long cur_timestamp = 0;
|
||||
long long time_diff = 50;
|
||||
struct timeb tp;
|
||||
//long long prev_timestamp = 0;
|
||||
//long long cur_timestamp = 0;
|
||||
//long long time_diff = 50;
|
||||
//struct timeb tp;
|
||||
void *desktop = NULL;
|
||||
XImage *image = NULL;
|
||||
eventdisplay = NULL;
|
||||
@@ -536,6 +539,7 @@ void* kvm_server_mainloop(void* parm)
|
||||
|
||||
while (!g_shutdown) {
|
||||
|
||||
/*
|
||||
//printf("KVM/Loop");
|
||||
ftime(&tp);
|
||||
cur_timestamp = tp.time * 1000 + tp.millitm;
|
||||
@@ -547,6 +551,7 @@ void* kvm_server_mainloop(void* parm)
|
||||
usleep(time_diff * 1000);
|
||||
prev_timestamp = cur_timestamp;
|
||||
//printf("...\n");
|
||||
*/
|
||||
|
||||
for (r = 0; r < TILE_HEIGHT_COUNT; r++) {
|
||||
for (c = 0; c < TILE_WIDTH_COUNT; c++) {
|
||||
@@ -660,6 +665,10 @@ void* kvm_server_mainloop(void* parm)
|
||||
XCloseDisplay(imagedisplay);
|
||||
imagedisplay = NULL;
|
||||
}
|
||||
|
||||
// We can't go full speed here, we need to slow this down.
|
||||
height = FRAME_RATE_TIMER;
|
||||
while (!g_shutdown && height > 0) { if (height > 50) { height -= 50; usleep(50000); } else { usleep(height * 1000); height = 0; } }
|
||||
}
|
||||
|
||||
close(slave2master[1]);
|
||||
|
||||
@@ -322,10 +322,7 @@ int getTileAt(int x, int y, void** buffer, long long *bufferSize, void *desktop,
|
||||
if (firstTime) {
|
||||
// Re-adjust the compression ratio.
|
||||
COMPRESSION_RATIO = (int)(((double)COMPRESSION_RATIO/(double)retval) * 60000);//Magic number: 60000 ~= 65500
|
||||
if (COMPRESSION_RATIO <= 1) {
|
||||
COMPRESSION_RATIO = 2;
|
||||
}
|
||||
|
||||
if (COMPRESSION_RATIO <= 1) { COMPRESSION_RATIO = 2; }
|
||||
firstTime = 0;
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ limitations under the License.
|
||||
*/
|
||||
|
||||
#if defined(_LINKVM)
|
||||
#pragma warning(disable: 4996)
|
||||
|
||||
#include <stdio.h>
|
||||
#include "kvm.h"
|
||||
@@ -1114,7 +1115,7 @@ void kvm_cleanup()
|
||||
if (gChildProcess != NULL)
|
||||
{
|
||||
ILibRemoteLogging_printf(ILibChainGetLogger(gILibChain), ILibRemoteLogging_Modules_Agent_KVM, ILibRemoteLogging_Flags_VerbosityLevel_1, "KVM.c/kvm_cleanup: Attempting to kill child process");
|
||||
free(ILibProcessPipe_Process_KillEx(gChildProcess));
|
||||
ILibProcessPipe_Process_SoftKill(gChildProcess);
|
||||
gChildProcess = NULL;
|
||||
}
|
||||
else
|
||||
|
||||
@@ -585,6 +585,8 @@ void teardown_gdiplus()
|
||||
void set_tile_compression(int type, int level)
|
||||
{
|
||||
encCompression = level;
|
||||
if (encCompression < 1) { encCompression = 1; } // Guard against bad values.
|
||||
if (encCompression > 90) { encCompression = 90; }
|
||||
if (tilebuffer == NULL) { KVMDEBUG("set_tile_compression(), tilebuffer == NULL.", 0); return; }
|
||||
KVMDEBUG("set_tile_compression() type", type);
|
||||
KVMDEBUG("set_tile_compression() level", level);
|
||||
|
||||
@@ -139,14 +139,6 @@ typedef enum MeshCommand_AuthInfo_PlatformType
|
||||
MeshCommand_AuthInfo_PlatformType_DISK = 5,
|
||||
MeshCommand_AuthInfo_PlatformType_ROUTER = 6
|
||||
}MeshCommand_BinaryPacket_AuthInfo_PlatformType;
|
||||
typedef enum MeshCommand_AuthInfo_CapabilitiesMask
|
||||
{
|
||||
MeshCommand_AuthInfo_CapabilitiesMask_DESKTOP = 0x01,
|
||||
MeshCommand_AuthInfo_CapabilitiesMask_TERMINAL = 0x02,
|
||||
MeshCommand_AuthInfo_CapabilitiesMask_FILES = 0x04,
|
||||
MeshCommand_AuthInfo_CapabilitiesMask_CONSOLE = 0x08,
|
||||
MeshCommand_AuthInfo_CapabilitiesMask_JAVASCRIPT= 0x10
|
||||
}MeshCommand_AuthInfo_CapabilitiesMask;
|
||||
typedef struct MeshCommand_BinaryPacket_AuthInfo
|
||||
{
|
||||
unsigned short command;
|
||||
@@ -870,12 +862,18 @@ duk_ret_t ILibDuktape_MeshAgent_ServerUrl(duk_context *ctx)
|
||||
duk_ret_t ILibDuktape_MeshAgent_isControlChannelConnected(duk_context *ctx)
|
||||
{
|
||||
duk_push_this(ctx); // [agent]
|
||||
duk_get_prop_string(ctx, -1, MESH_AGENT_PTR); // [agent][ptr]
|
||||
MeshAgentHostContainer *agent = (MeshAgentHostContainer*)duk_get_pointer(ctx, -1);
|
||||
MeshAgentHostContainer *agent = (MeshAgentHostContainer*)Duktape_GetPointerProperty(ctx, -1, MESH_AGENT_PTR);
|
||||
|
||||
if (agent != NULL)
|
||||
{
|
||||
duk_push_boolean(ctx, agent->serverAuthState == 3 ? 1 : 0);
|
||||
return(1);
|
||||
}
|
||||
else
|
||||
{
|
||||
return(0);
|
||||
}
|
||||
}
|
||||
duk_ret_t ILibDuktape_MeshAgent_eval(duk_context *ctx)
|
||||
{
|
||||
duk_size_t evalStrLen;
|
||||
@@ -902,7 +900,7 @@ void ILibDuktape_MeshAgent_dumpCoreModuleEx(void *chain, void *user)
|
||||
CoreModule = (char*)ILibMemory_Allocate(CoreModuleLen, 0, NULL, NULL);
|
||||
ILibSimpleDataStore_Get(agentHost->masterDb, "CoreModule", CoreModule, CoreModuleLen);
|
||||
|
||||
if (ILibDuktape_ScriptContainer_CompileJavaScript(agentHost->meshCoreCtx, CoreModule + 4, CoreModuleLen - 4) != 0 ||
|
||||
if (ILibDuktape_ScriptContainer_CompileJavaScriptEx(agentHost->meshCoreCtx, CoreModule + 4, CoreModuleLen - 4, "CoreModule.js", 13) != 0 ||
|
||||
ILibDuktape_ScriptContainer_ExecuteByteCode(agentHost->meshCoreCtx) != 0)
|
||||
{
|
||||
ILibRemoteLogging_printf(ILibChainGetLogger(agentHost->chain), ILibRemoteLogging_Modules_Microstack_Generic | ILibRemoteLogging_Modules_ConsolePrint,
|
||||
@@ -923,6 +921,7 @@ duk_ret_t ILibDuktape_MeshAgent_dumpCoreModule(duk_context *ctx)
|
||||
ILibChain_RunOnMicrostackThreadEx(agent->chain, ILibDuktape_MeshAgent_dumpCoreModuleEx, agent);
|
||||
return(0);
|
||||
}
|
||||
|
||||
void ILibDuktape_MeshAgent_PUSH(duk_context *ctx, void *chain)
|
||||
{
|
||||
MeshAgentHostContainer *agent;
|
||||
@@ -967,6 +966,7 @@ void ILibDuktape_MeshAgent_PUSH(duk_context *ctx, void *chain)
|
||||
ILibDuktape_EventEmitter_CreateEventEx(emitter, "Ready");
|
||||
ILibDuktape_EventEmitter_CreateEventEx(emitter, "Connected");
|
||||
ILibDuktape_EventEmitter_CreateEventEx(emitter, "Command");
|
||||
ILibDuktape_EventEmitter_CreateEventEx(emitter, "DesktopSessionChanged");
|
||||
|
||||
ILibDuktape_CreateEventWithGetter(ctx, "isControlChannelConnected", ILibDuktape_MeshAgent_isControlChannelConnected);
|
||||
ILibDuktape_EventEmitter_AddHook(emitter, "Ready", ILibDuktape_MeshAgent_Ready);
|
||||
@@ -994,6 +994,8 @@ void ILibDuktape_MeshAgent_PUSH(duk_context *ctx, void *chain)
|
||||
}
|
||||
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "GenerateCertificate", ILibDuktape_MeshAgent_GenerateCertificate, 1);
|
||||
duk_push_pointer(ctx, agent->masterDb); duk_put_prop_string(ctx, -2, "\xFF_MasterDB");
|
||||
|
||||
ILibRemoteLogging_printf(ILibChainGetLogger(agent->chain), ILibRemoteLogging_Modules_Microstack_Generic, ILibRemoteLogging_Flags_VerbosityLevel_1, "Acquired MeshAgent");
|
||||
}
|
||||
void ILibDuktape_MeshAgent_Init(duk_context* ctx, void *chain, MeshAgentHostContainer *agent)
|
||||
@@ -1021,7 +1023,7 @@ char* MeshAgent_MakeAbsolutePath(char *basePath, char *localPath)
|
||||
{
|
||||
// Use Same executable Name, but different extension
|
||||
sz = (int)basePathLen;
|
||||
if (ntohl(((unsigned int*)(basePath + sz - 4))[0]) == EXE_IDENTIFIER)
|
||||
if (sz>=4 && ntohl(((unsigned int*)(basePath + sz - 4))[0]) == EXE_IDENTIFIER)
|
||||
{
|
||||
// BasePath ends with .exe
|
||||
memcpy_s(ILibScratchPad2, sizeof(ILibScratchPad2), basePath, sz - 4);
|
||||
@@ -1257,7 +1259,7 @@ char* ScriptEngine_Restart(MeshAgentHostContainer *agent, char *contextGUID, cha
|
||||
|
||||
if (ctx != NULL)
|
||||
{
|
||||
if (ILibDuktape_ScriptContainer_CompileJavaScript(ctx, buffer, bufferLen) != 0 || ILibDuktape_ScriptContainer_ExecuteByteCode(ctx) != 0)
|
||||
if (ILibDuktape_ScriptContainer_CompileJavaScriptEx(ctx, buffer, bufferLen, "CoreModule.js", 13) != 0 || ILibDuktape_ScriptContainer_ExecuteByteCode(ctx) != 0)
|
||||
{
|
||||
sprintf_s(ILibScratchPad, sizeof(ILibScratchPad), "%s", (char*)duk_safe_to_string(ctx, -1));
|
||||
duk_pop(ctx);
|
||||
@@ -1411,8 +1413,6 @@ int GenerateSHA384FileHash(char *filePath, char *fileHash)
|
||||
return(0);
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Called when the connection of the mesh server is fully authenticated
|
||||
void MeshServer_ServerAuthenticated(ILibWebClient_StateObject WebStateObject, MeshAgentHostContainer *agent) {
|
||||
int len = 0;
|
||||
@@ -1437,6 +1437,29 @@ void MeshServer_ServerAuthenticated(ILibWebClient_StateObject WebStateObject, Me
|
||||
}
|
||||
}
|
||||
|
||||
void MeshServer_SendAgentInfo(MeshAgentHostContainer* agent, ILibWebClient_StateObject WebStateObject) {
|
||||
int hostnamelen = (int)strnlen_s(agent->hostname, sizeof(agent->hostname));
|
||||
|
||||
// Send to the server information about this agent
|
||||
MeshCommand_BinaryPacket_AuthInfo *info = (MeshCommand_BinaryPacket_AuthInfo*)ILibScratchPad2;
|
||||
memset(info, 0, sizeof(MeshCommand_BinaryPacket_AuthInfo)); // Required because if hash are SHA384, they will not fully fill the struct.
|
||||
info->command = htons(MeshCommand_AuthInfo);
|
||||
info->infoVersion = htonl(1);
|
||||
info->agentId = htonl(MESH_AGENTID);
|
||||
info->agentVersion = htonl(agent->version);
|
||||
info->platformType = htonl(((agent->batteryState != MeshAgentHost_BatteryInfo_NONE) && (agent->batteryState != MeshAgentHost_BatteryInfo_UNKNOWN)) ? MeshCommand_AuthInfo_PlatformType_LAPTOP : MeshCommand_AuthInfo_PlatformType_DESKTOP);
|
||||
memcpy_s(info->MeshID, sizeof(info->MeshID), agent->meshId, sizeof(agent->meshId));
|
||||
info->capabilities = htonl(agent->capabilities);
|
||||
info->hostnameLen = htons(hostnamelen);
|
||||
memcpy_s(info->hostname, sizeof(ILibScratchPad2) - sizeof(MeshCommand_BinaryPacket_AuthInfo), agent->hostname, hostnamelen);
|
||||
|
||||
// Send mesh agent information to the server
|
||||
ILibWebClient_WebSocket_Send(WebStateObject, ILibWebClient_WebSocket_DataType_BINARY, (char*)info, sizeof(MeshCommand_BinaryPacket_AuthInfo) + hostnamelen, ILibAsyncSocket_MemoryOwnership_USER, ILibWebClient_WebSocket_FragmentFlag_Complete);
|
||||
agent->retryTime = 0;
|
||||
printf("Connected.\n");
|
||||
if (agent->serverAuthState == 3) { MeshServer_ServerAuthenticated(WebStateObject, agent); }
|
||||
}
|
||||
|
||||
// Process MeshCentral server commands.
|
||||
void MeshServer_ProcessCommand(ILibWebClient_StateObject WebStateObject, MeshAgentHostContainer *agent, char *cmd, int cmdLen)
|
||||
{
|
||||
@@ -1521,7 +1544,7 @@ void MeshServer_ProcessCommand(ILibWebClient_StateObject WebStateObject, MeshAge
|
||||
X509_pubkey_digest(serverCert, EVP_sha384(), (unsigned char*)ILibScratchPad, (unsigned int*)&hashlen); // OpenSSL 1.1, SHA384
|
||||
if (memcmp(ILibScratchPad, agent->serverHash, UTIL_SHA384_HASHSIZE) != 0) {
|
||||
X509_pubkey_digest(serverCert, EVP_sha256(), (unsigned char*)ILibScratchPad, (unsigned int*)&hashlen); // OpenSSL 1.1, SHA256 (For older .mshx policy file)
|
||||
if (memcmp(ILibScratchPad, agent->serverHash, 32) != 0) {
|
||||
if (memcmp(ILibScratchPad, agent->serverHash, UTIL_SHA256_HASHSIZE) != 0) {
|
||||
printf("Server certificate mismatch\r\n"); break; // TODO: Disconnect
|
||||
}
|
||||
}
|
||||
@@ -1539,28 +1562,15 @@ void MeshServer_ProcessCommand(ILibWebClient_StateObject WebStateObject, MeshAge
|
||||
rsa_pubkey = EVP_PKEY_get1_RSA(evp_pubkey);
|
||||
if (RSA_verify(NID_sha384, (unsigned char*)ILibScratchPad, UTIL_SHA384_HASHSIZE, (unsigned char*)AuthVerify->signature, AuthVerify->signatureLen, rsa_pubkey) == 1)
|
||||
{
|
||||
int hostnamelen = (int)strnlen_s(agent->hostname, sizeof(agent->hostname));
|
||||
// Server signature verified, we are good to go.
|
||||
agent->serverAuthState += 1;
|
||||
|
||||
// Send to the server information about this agent (TODO: Replace this with a struct)
|
||||
MeshCommand_BinaryPacket_AuthInfo *info = (MeshCommand_BinaryPacket_AuthInfo*)ILibScratchPad2;
|
||||
memset(info, 0, sizeof(MeshCommand_BinaryPacket_AuthInfo)); // Required because if hash are SHA384, they will not fully fill the struct.
|
||||
info->command = htons(MeshCommand_AuthInfo);
|
||||
info->infoVersion = htonl(1);
|
||||
info->agentId = htonl(MESH_AGENTID);
|
||||
info->agentVersion = htonl(agent->version);
|
||||
info->platformType = htonl(((agent->batteryState != MeshAgentHost_BatteryInfo_NONE) && (agent->batteryState != MeshAgentHost_BatteryInfo_UNKNOWN)) ? MeshCommand_AuthInfo_PlatformType_LAPTOP : MeshCommand_AuthInfo_PlatformType_DESKTOP);
|
||||
memcpy_s(info->MeshID, sizeof(info->MeshID), agent->meshId, sizeof(agent->meshId));
|
||||
info->capabilities = htonl(MeshCommand_AuthInfo_CapabilitiesMask_CONSOLE | MeshCommand_AuthInfo_CapabilitiesMask_JAVASCRIPT);
|
||||
info->hostnameLen = htons(hostnamelen);
|
||||
memcpy_s(info->hostname, sizeof(ILibScratchPad2) - sizeof(MeshCommand_BinaryPacket_AuthInfo), agent->hostname, hostnamelen);
|
||||
// Store the server's TLS cert hash so in the future, we can skip server auth.
|
||||
util_keyhash2(peer, ILibScratchPad);
|
||||
ILibSimpleDataStore_PutEx(agent->masterDb, "ServerTlsCertHash", 17, ILibScratchPad, UTIL_SHA384_HASHSIZE);
|
||||
|
||||
// Send mesh agent information to the server
|
||||
ILibWebClient_WebSocket_Send(WebStateObject, ILibWebClient_WebSocket_DataType_BINARY, (char*)info, sizeof(MeshCommand_BinaryPacket_AuthInfo) + hostnamelen, ILibAsyncSocket_MemoryOwnership_USER, ILibWebClient_WebSocket_FragmentFlag_Complete);
|
||||
agent->retryTime = 0;
|
||||
printf("Connected.\n");
|
||||
if (agent->serverAuthState == 3) { MeshServer_ServerAuthenticated(WebStateObject, agent); }
|
||||
// Send our agent information to the server
|
||||
MeshServer_SendAgentInfo(agent, WebStateObject);
|
||||
} else {
|
||||
printf("Invalid server signature\r\n");
|
||||
// TODO: Disconnect
|
||||
@@ -1823,7 +1833,7 @@ void MeshServer_ControlChannel_IdleTimeout(ILibWebClient_StateObject WebStateObj
|
||||
MeshAgentHostContainer *agent = (MeshAgentHostContainer*)user;
|
||||
ILibWebClient_WebSocket_Ping(WebStateObject);
|
||||
ILibWebClient_SetTimeout(WebStateObject, agent->controlChannel_idleTimeout_seconds, MeshServer_ControlChannel_IdleTimeout, user);
|
||||
ILibRemoteLogging_printf(ILibChainGetLogger(agent->chain), ILibRemoteLogging_Modules_Agent_GuardPost | ILibRemoteLogging_Modules_ConsolePrint, ILibRemoteLogging_Flags_VerbosityLevel_1, "AgentCore/MeshServer_ControlChannel_IdleTimeout(): Sending Ping");
|
||||
ILibRemoteLogging_printf(ILibChainGetLogger(agent->chain), ILibRemoteLogging_Modules_Agent_GuardPost , ILibRemoteLogging_Flags_VerbosityLevel_1, "AgentCore/MeshServer_ControlChannel_IdleTimeout(): Sending Ping");
|
||||
}
|
||||
ILibWebClient_WebSocket_PingResponse MeshServer_ControlChannel_PingSink(ILibWebClient_StateObject WebStateObject, void *user)
|
||||
{
|
||||
@@ -1833,7 +1843,7 @@ void MeshServer_ControlChannel_PongSink(ILibWebClient_StateObject WebStateObject
|
||||
{
|
||||
#ifdef _REMOTELOGGING
|
||||
MeshAgentHostContainer *agent = (MeshAgentHostContainer*)user;
|
||||
ILibRemoteLogging_printf(ILibChainGetLogger(agent->chain), ILibRemoteLogging_Modules_Agent_GuardPost | ILibRemoteLogging_Modules_ConsolePrint, ILibRemoteLogging_Flags_VerbosityLevel_1, "AgentCore/MeshServer_ControlChannel_IdleTimeout(): Received Pong");
|
||||
ILibRemoteLogging_printf(ILibChainGetLogger(agent->chain), ILibRemoteLogging_Modules_Agent_GuardPost , ILibRemoteLogging_Flags_VerbosityLevel_1, "AgentCore/MeshServer_ControlChannel_IdleTimeout(): Received Pong");
|
||||
#endif
|
||||
}
|
||||
void MeshServer_OnResponse(ILibWebClient_StateObject WebStateObject, int InterruptFlag, struct packetheader *header, char *bodyBuffer, int *beginPointer, int endPointer, ILibWebClient_ReceiveStatus recvStatus, void *user1, void *user2, int *PAUSE)
|
||||
@@ -1849,6 +1859,7 @@ void MeshServer_OnResponse(ILibWebClient_StateObject WebStateObject, int Interru
|
||||
break;
|
||||
case ILibWebClient_ReceiveStatus_Connection_Established: // New connection established.
|
||||
{
|
||||
int len;
|
||||
int idleLen;
|
||||
if ((idleLen = ILibSimpleDataStore_Get(agent->masterDb, "controlChannelIdleTimeout", NULL, 0)) != 0)
|
||||
{
|
||||
@@ -1884,16 +1895,30 @@ void MeshServer_OnResponse(ILibWebClient_StateObject WebStateObject, int Interru
|
||||
memcpy_s(serveridcmd->serverId, sizeof(serveridcmd->serverId), agent->serverHash, sizeof(agent->serverHash)); // Place our mesh agent nonce
|
||||
ILibWebClient_WebSocket_Send(WebStateObject, ILibWebClient_WebSocket_DataType_BINARY, (char*)serveridcmd, sizeof(MeshCommand_BinaryPacket_ServerId), ILibAsyncSocket_MemoryOwnership_USER, ILibWebClient_WebSocket_FragmentFlag_Complete);
|
||||
|
||||
// Start authentication by sending a auth nonce & server TLS cert hash.
|
||||
// Check to see if we already have a validated TLS cert hash
|
||||
{
|
||||
MeshCommand_BinaryPacket_AuthRequest *ar = (MeshCommand_BinaryPacket_AuthRequest*)ILibScratchPad2;
|
||||
util_keyhash2(peer, ar->serverHash); // Hash the server certificate public key and place it
|
||||
|
||||
len = ILibSimpleDataStore_GetEx(agent->masterDb, "ServerTlsCertHash", 17, ILibScratchPad, sizeof(ILibScratchPad));
|
||||
if ((len == UTIL_SHA384_HASHSIZE) && (memcmp(ILibScratchPad, ar->serverHash, UTIL_SHA384_HASHSIZE) == 0)) {
|
||||
// The TLS certificate of this server is correct, no need to authenticate further.
|
||||
unsigned short response = htons(MeshCommand_AuthConfirm); // Send indication to the server that it's already authenticated
|
||||
agent->serverAuthState = 1;
|
||||
ILibWebClient_WebSocket_Send(WebStateObject, ILibWebClient_WebSocket_DataType_BINARY, (char*)&response, 2, ILibAsyncSocket_MemoryOwnership_USER, ILibWebClient_WebSocket_FragmentFlag_Complete);
|
||||
}
|
||||
|
||||
// Start authentication by sending a auth nonce & server TLS cert hash - If we indicated AuthConfirm already, the server will use this data but not respond to it.
|
||||
// Send 384 bits SHA384 hash of TLS cert public key + 384 bits nonce
|
||||
util_random(sizeof(agent->agentNonce), agent->agentNonce); // Generate a new mesh agent connection nonce
|
||||
MeshCommand_BinaryPacket_AuthRequest *ar = (MeshCommand_BinaryPacket_AuthRequest*)ILibScratchPad2;
|
||||
|
||||
ar->command = htons(MeshCommand_AuthRequest); // MeshCommand_AuthRequest (1), server hash + nonce
|
||||
util_keyhash2(peer, ar->serverHash); // Hash the server certificate public key and place it
|
||||
if (peer != NULL) { X509_free(peer); }
|
||||
memcpy_s(ar->serverNonce, sizeof(ar->serverNonce), agent->agentNonce, sizeof(agent->agentNonce)); // Place our mesh agent nonce
|
||||
ILibWebClient_WebSocket_Send(WebStateObject, ILibWebClient_WebSocket_DataType_BINARY, (char*)ar, sizeof(MeshCommand_BinaryPacket_AuthRequest), ILibAsyncSocket_MemoryOwnership_USER, ILibWebClient_WebSocket_FragmentFlag_Complete);
|
||||
|
||||
// If we know this is a good server, send our agent information right now.
|
||||
if (agent->serverAuthState == 1) { MeshServer_SendAgentInfo(agent, WebStateObject); }
|
||||
}
|
||||
#endif
|
||||
break;
|
||||
}
|
||||
@@ -1926,6 +1951,7 @@ void MeshServer_OnResponse(ILibWebClient_StateObject WebStateObject, int Interru
|
||||
// If there are no headers, this is a connection error. Log it and try again...
|
||||
if (header == NULL)
|
||||
{
|
||||
if (ILibIsChainBeingDestroyed(agent->chain)) { return; }
|
||||
ILibRemoteLogging_printf(ILibChainGetLogger(ILibWebClient_GetChainFromWebStateObject(WebStateObject)), ILibRemoteLogging_Modules_Agent_GuardPost, ILibRemoteLogging_Flags_VerbosityLevel_1, "Agent Host Container: Mesh Server Connection Error, trying again later.");
|
||||
printf("Mesh Server Connection Error\n");
|
||||
if (agent->multicastServerUrl != NULL) { free(agent->multicastServerUrl); agent->multicastServerUrl = NULL; }
|
||||
@@ -1980,14 +2006,14 @@ void MeshServer_ConnectEx(MeshAgentHostContainer *agent)
|
||||
agent->serverIndex = (rval % rs->NumResults) + 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
#ifdef MICROSTACK_PROXY
|
||||
if (agent->triedNoProxy_Index == agent->serverIndex)
|
||||
#endif
|
||||
{
|
||||
agent->serverIndex = (agent->serverIndex % rs->NumResults) + 1;
|
||||
//if (agent->serverIndex == 1)
|
||||
//{
|
||||
// printf("Aborting...\r\n");
|
||||
// ILibDestructParserResults(rs);
|
||||
// return;
|
||||
//}
|
||||
agent->triedNoProxy_Index = agent->serverIndex - 1;
|
||||
}
|
||||
}
|
||||
|
||||
f = ILibParseString_GetResultIndex(rs, agent->serverIndex);
|
||||
@@ -2002,7 +2028,7 @@ void MeshServer_ConnectEx(MeshAgentHostContainer *agent)
|
||||
serverUrlLen = (int)strlen(serverUrl);
|
||||
} else {
|
||||
// Multicast discovery packet to try to find our server
|
||||
if ((agent->multicastDiscovery != NULL) && (ILibSimpleDataStore_Get(agent->masterDb, "ServerID", ILibScratchPad2, sizeof(ILibScratchPad2)) == 97)) { ILibMulticastSocket_Broadcast(agent->multicastDiscovery, ILibScratchPad2, 96, 1); }
|
||||
if ((agent->multicastDiscovery2 != NULL) && (ILibSimpleDataStore_Get(agent->masterDb, "ServerID", ILibScratchPad2, sizeof(ILibScratchPad2)) == 97)) { ILibMulticastSocket_Broadcast(agent->multicastDiscovery2, ILibScratchPad2, 96, 1); }
|
||||
ILibDestructParserResults(rs);
|
||||
MeshServer_Connect(agent);
|
||||
return;
|
||||
@@ -2061,7 +2087,7 @@ void MeshServer_ConnectEx(MeshAgentHostContainer *agent)
|
||||
ILibRemoteLogging_printf(ILibChainGetLogger(agent->chain), ILibRemoteLogging_Modules_Agent_GuardPost, ILibRemoteLogging_Flags_VerbosityLevel_1, "AgentCore: Attempting connection to: %s", serverUrl);
|
||||
ILibDestructParserResults(rs);
|
||||
|
||||
if ((len = ILibSimpleDataStore_Get(agent->masterDb, "ServerID", ILibScratchPad2, sizeof(ILibScratchPad2))) == 0) { printf("ServerID entry not found in Db!\n"); return; }
|
||||
if ((len = ILibSimpleDataStore_Get(agent->masterDb, "ServerID", ILibScratchPad2, sizeof(ILibScratchPad2))) == 0) { printf("ServerID entry not found in Db!\n"); free(host); free(path); return; }
|
||||
rs = ILibParseString(ILibScratchPad2, 0, len, ",", 1);
|
||||
f = ILibParseString_GetResultIndex(rs, agent->serverIndex);
|
||||
if (f == NULL)
|
||||
@@ -2070,6 +2096,7 @@ void MeshServer_ConnectEx(MeshAgentHostContainer *agent)
|
||||
printf("ServerID Count Mismatch\r\n");
|
||||
ILibRemoteLogging_printf(ILibChainGetLogger(agent->chain), ILibRemoteLogging_Modules_Agent_GuardPost, ILibRemoteLogging_Flags_VerbosityLevel_1, "AgentCore: ServerID Count Mismatch. Hash Count = %d, Server Index = %d", rs->NumResults, agent->serverIndex);
|
||||
ILibDestructParserResults(rs);
|
||||
free(host); free(path);
|
||||
return;
|
||||
}
|
||||
f->datalength = ILibTrimString(&(f->data), f->datalength);
|
||||
@@ -2078,6 +2105,7 @@ void MeshServer_ConnectEx(MeshAgentHostContainer *agent)
|
||||
printf("ServerID too big\r\n");
|
||||
ILibRemoteLogging_printf(ILibChainGetLogger(agent->chain), ILibRemoteLogging_Modules_Agent_GuardPost, ILibRemoteLogging_Flags_VerbosityLevel_1, "AgentCore: ServerID too big. Was %d bytes, but expected %d bytes", f->datalength / 2, sizeof(agent->serverHash) - 1);
|
||||
ILibDestructParserResults(rs);
|
||||
free(host); free(path);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -2114,6 +2142,24 @@ void MeshServer_ConnectEx(MeshAgentHostContainer *agent)
|
||||
#ifdef MICROSTACK_PROXY
|
||||
unsigned short proxyPort = 80;
|
||||
int delimiter = ILibString_LastIndexOf(ILibScratchPad, len, ":", 1);
|
||||
|
||||
if (agent->triedNoProxy_Index < agent->serverIndex && agent->proxyServer != NULL)
|
||||
{
|
||||
printf("Disabling Proxy: %s\n", ILibScratchPad);
|
||||
agent->triedNoProxy_Index++;
|
||||
agent->proxyServer = NULL;
|
||||
|
||||
if (duk_peval_string(agent->meshCoreCtx, "require('global-tunnel');") == 0)
|
||||
{
|
||||
duk_get_prop_string(agent->meshCoreCtx, -1, "end"); // [tunnel][end]
|
||||
duk_swap_top(agent->meshCoreCtx, -2); // [end][this]
|
||||
duk_pcall_method(agent->meshCoreCtx, 0); // [undefined]
|
||||
}
|
||||
duk_pop(agent->meshCoreCtx); // ...
|
||||
}
|
||||
else
|
||||
{
|
||||
printf("Using proxy: %s\n", ILibScratchPad);
|
||||
if (delimiter > 0)
|
||||
{
|
||||
ILibScratchPad[delimiter] = 0;
|
||||
@@ -2125,10 +2171,16 @@ void MeshServer_ConnectEx(MeshAgentHostContainer *agent)
|
||||
{
|
||||
memcpy_s(&(ILibDuktape_GetNewGlobalTunnel(agent->meshCoreCtx)->proxyServer), sizeof(struct sockaddr_in6), agent->proxyServer, sizeof(struct sockaddr_in6));
|
||||
}
|
||||
}
|
||||
#else
|
||||
ILibRemoteLogging_printf(ILibChainGetLogger(agent->chain), ILibRemoteLogging_Modules_Agent_GuardPost | ILibRemoteLogging_Modules_ConsolePrint, ILibRemoteLogging_Flags_VerbosityLevel_1, "AgentCore.MeshServer_ConnectEx(): Proxy Specified, but support was not enabled in this build");
|
||||
#endif
|
||||
}
|
||||
else
|
||||
{
|
||||
// No Proxy was specified
|
||||
agent->triedNoProxy_Index++;
|
||||
}
|
||||
agent->serverConnectionState = 1; // We are trying to connect
|
||||
}
|
||||
else
|
||||
@@ -2293,7 +2345,7 @@ void agentDumpKeysSink(ILibSimpleDataStore sender, char* Key, int KeyLen, void *
|
||||
}
|
||||
}
|
||||
|
||||
MeshAgentHostContainer* MeshAgent_Create()
|
||||
MeshAgentHostContainer* MeshAgent_Create(MeshCommand_AuthInfo_CapabilitiesMask capabilities)
|
||||
{
|
||||
MeshAgentHostContainer* retVal = (MeshAgentHostContainer*)ILibMemory_Allocate(sizeof(MeshAgentHostContainer), 0, NULL, NULL);
|
||||
#ifdef WIN32
|
||||
@@ -2303,6 +2355,7 @@ MeshAgentHostContainer* MeshAgent_Create()
|
||||
retVal->agentID = (AgentIdentifiers)MESH_AGENTID;
|
||||
retVal->chain = ILibCreateChainEx(3 * sizeof(void*));
|
||||
retVal->pipeManager = ILibProcessPipe_Manager_Create(retVal->chain);
|
||||
retVal->capabilities = capabilities | MeshCommand_AuthInfo_CapabilitiesMask_CONSOLE | MeshCommand_AuthInfo_CapabilitiesMask_JAVASCRIPT;
|
||||
gethostname(retVal->hostname, (int)sizeof(retVal->hostname));
|
||||
|
||||
#ifdef WIN32
|
||||
@@ -2347,6 +2400,8 @@ void MeshAgent_ChainEnd(void *chain, void *user)
|
||||
void MeshAgent_RunScriptOnly_Finalizer(duk_context *ctx, void *user)
|
||||
{
|
||||
MeshAgentHostContainer *agentHost = (MeshAgentHostContainer*)user;
|
||||
agentHost->exitCode = ILibDuktape_Process_GetExitCode(ctx);
|
||||
|
||||
agentHost->meshCoreCtx = NULL;
|
||||
if (ILibIsChainBeingDestroyed(agentHost->chain) == 0)
|
||||
{
|
||||
@@ -2396,10 +2451,57 @@ int MeshAgent_AgentMode(MeshAgentHostContainer *agentHost, int paramLen, char **
|
||||
#endif
|
||||
#ifdef _POSIX
|
||||
int options = 0;
|
||||
|
||||
if (paramLen >= 2)
|
||||
{
|
||||
if ((strcmp(param[1], "stop") == 0 || strcmp(param[1], "-s") == 0))
|
||||
{
|
||||
// Stop
|
||||
FILE *fd = NULL;
|
||||
char str[15];
|
||||
pid_t pid = 0;
|
||||
size_t len;
|
||||
|
||||
/*
|
||||
#if defined(__APPLE__) && defined(_DAEMON) && defined(_LINKVM)
|
||||
installOsx(0);
|
||||
#endif
|
||||
*/
|
||||
|
||||
#ifdef _ANDROID
|
||||
fd = fopen("/data/usr/tmp/meshagent.pid", "r");
|
||||
#else
|
||||
fd = fopen("/var/run/meshagent.pid", "r");
|
||||
#endif
|
||||
if (fd == NULL) fd = fopen(".meshagent.pid", "r");
|
||||
if (fd != NULL)
|
||||
{
|
||||
len = fread(str, sizeof(char), 15, fd);
|
||||
if (len > 0)
|
||||
{
|
||||
sscanf(str, "%d\r\n", &pid);
|
||||
if (pid > 0 && kill(pid, SIGKILL) == 0) printf("Mesh agent stopped.\r\n"); else printf("Mesh agent not running.\r\n");
|
||||
#ifdef _ANDROID
|
||||
remove("/data/usr/tmp/meshagent.pid");
|
||||
#else
|
||||
remove("/var/run/meshagent.pid");
|
||||
remove(".meshagent.pid");
|
||||
#endif
|
||||
}
|
||||
fclose(fd);
|
||||
exit(EXIT_SUCCESS);
|
||||
}
|
||||
else
|
||||
{
|
||||
printf("Unable to find process id file.\r\n");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
// We are a Mesh Agent
|
||||
printf("MeshCentral2 Agent\r\n"); // MESH_AGENT_VERSION
|
||||
if (agentHost->masterDb == NULL) { agentHost->masterDb = ILibSimpleDataStore_Create(MeshAgent_MakeAbsolutePath(agentHost->exePath, ".db")); }
|
||||
#ifndef WIN32
|
||||
if (agentHost->masterDb == NULL)
|
||||
@@ -2413,17 +2515,17 @@ int MeshAgent_AgentMode(MeshAgentHostContainer *agentHost, int paramLen, char **
|
||||
switch (agentHost->dbRetryCount)
|
||||
{
|
||||
case 10:
|
||||
printf("Unable to open database... Giving up...\r\n");
|
||||
return(0);
|
||||
printf("Unable to open database.\r\n");
|
||||
return 0;
|
||||
default:
|
||||
printf("Unable to open database... Trying again later...\r\n");
|
||||
printf("Unable to open database (%d/10)...\r\n", agentHost->dbRetryCount + 1);
|
||||
agentHost->dbRetryCount++;
|
||||
ILibLifeTime_AddEx(ILibGetBaseTimer(agentHost->chain), data, 2000, MeshAgent_AgentMost_dbRetryCallback, NULL);
|
||||
return(1);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
#else
|
||||
if (agentHost->masterDb == NULL) { printf("Unable to open database...\r\n"); return(0); }
|
||||
if (agentHost->masterDb == NULL) { printf("Unable to open database.\r\n"); return(0); }
|
||||
#endif
|
||||
agentHost->httpClientManager = ILibCreateWebClient(3, agentHost->chain);
|
||||
|
||||
@@ -2454,8 +2556,33 @@ int MeshAgent_AgentMode(MeshAgentHostContainer *agentHost, int paramLen, char **
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifndef MICROSTACK_NOTLS
|
||||
// Check the local MacAddresses, to see if we need to reset our NodeId
|
||||
duk_context *tmpCtx = ILibDuktape_ScriptContainer_InitializeJavaScriptEngineEx(0, 0, agentHost->chain, NULL, NULL, agentHost->exePath, NULL, NULL, NULL);
|
||||
if (duk_peval_string(tmpCtx, "function _getMac() { var ret = ''; var ni = require('os').networkInterfaces(); for (var f in ni) { for (var i in ni[f]) { if(ni[f][i].type == 'ethernet' || ni[f][i].type == 'wireless') {ret += ('[' + ni[f][i].mac + ']');} } } return(ret); }; _getMac();") == 0)
|
||||
{
|
||||
int len;
|
||||
duk_size_t macLen;
|
||||
char *mac = (char*)duk_get_lstring(tmpCtx, -1, &macLen);
|
||||
if ((len = ILibSimpleDataStore_Get(agentHost->masterDb, "LocalMacAddresses", NULL, 0)) == 0)
|
||||
{
|
||||
ILibSimpleDataStore_PutEx(agentHost->masterDb, "LocalMacAddresses", 17, mac, (int)macLen);
|
||||
}
|
||||
else
|
||||
{
|
||||
char *curr = ILibMemory_AllocateA(len);
|
||||
ILibSimpleDataStore_Get(agentHost->masterDb, "LocalMacAddresses", curr, len);
|
||||
int i = 0;
|
||||
while (i < len)
|
||||
{
|
||||
if (ILibString_IndexOf(mac, (int)macLen, curr + i, 19) >= 0) { break; }
|
||||
i += 19;
|
||||
}
|
||||
if (i >= len) { resetNodeId = 1; ILibSimpleDataStore_PutEx(agentHost->masterDb, "LocalMacAddresses", 17, mac, (int)macLen); }
|
||||
}
|
||||
}
|
||||
duk_destroy_heap(tmpCtx);
|
||||
|
||||
// Load the mesh agent certificates
|
||||
if ((resetNodeId == 1 || agent_LoadCertificates(agentHost) != 0) && agent_GenerateCertificates(agentHost, NULL) != 0) { printf("Certificate error\r\n"); }
|
||||
if (agent_VerifyMeshCertificates(agentHost) != 0) { printf("Certificate validation error\r\n"); }
|
||||
@@ -2506,16 +2633,40 @@ int MeshAgent_AgentMode(MeshAgentHostContainer *agentHost, int paramLen, char **
|
||||
if (RegCreateKey(HKEY_CURRENT_USER, TEXT("Software\\Open Source\\MeshAgent2"), &hKey) == ERROR_SUCCESS)
|
||||
#endif
|
||||
{
|
||||
int i, len;
|
||||
char* tmp = NULL;
|
||||
|
||||
// Save the NodeId
|
||||
util_tohex(agentHost->g_selfid, UTIL_SHA384_HASHSIZE, ILibScratchPad);
|
||||
RegSetValueExA(hKey, "NodeId", 0, REG_SZ, ILibScratchPad, (int)strlen(ILibScratchPad));
|
||||
len = ILibBase64Encode(agentHost->g_selfid, UTIL_SHA384_HASHSIZE, &tmp);
|
||||
if ((len > 0) && (tmp != NULL)) {
|
||||
for (i = 0; i < len; i++) { if (tmp[i] == '+') { tmp[i] = '@'; } else if (tmp[i] == '/') { tmp[i] = '$'; } } // Replace + --> @ and / --> $
|
||||
RegSetValueExA(hKey, "NodeId", 0, REG_SZ, tmp, len);
|
||||
free(tmp);
|
||||
tmp = NULL;
|
||||
}
|
||||
else { RegDeleteKeyA(hKey, "NodeId"); }
|
||||
|
||||
// Save the AgentHash
|
||||
util_tohex(agentHost->agentHash, UTIL_SHA384_HASHSIZE, ILibScratchPad);
|
||||
RegSetValueExA(hKey, "AgentHash", 0, REG_SZ, ILibScratchPad, (int)strlen(ILibScratchPad));
|
||||
|
||||
// Save the MeshId
|
||||
if (ILibSimpleDataStore_Get(agentHost->masterDb, "MeshID", NULL, 0) == 0) { RegDeleteKeyA(hKey, "MeshId"); } else {
|
||||
len = ILibSimpleDataStore_Get(agentHost->masterDb, "MeshID", ILibScratchPad2, (int)sizeof(ILibScratchPad2));
|
||||
if (len > 0) {
|
||||
len = ILibBase64Encode(ILibScratchPad2, len, &tmp);
|
||||
if ((len > 0) && (tmp != NULL)) {
|
||||
for (i = 0; i < len; i++) { if (tmp[i] == '+') { tmp[i] = '@'; } else if (tmp[i] == '/') { tmp[i] = '$'; } } // Replace + --> @ and / --> $
|
||||
RegSetValueExA(hKey, "MeshId", 0, REG_SZ, tmp, len);
|
||||
free(tmp);
|
||||
tmp = NULL;
|
||||
}
|
||||
else { RegDeleteKeyA(hKey, "MeshId"); }
|
||||
}
|
||||
else { RegDeleteKeyA(hKey, "MeshId"); }
|
||||
}
|
||||
|
||||
// Save a bunch of values in the registry
|
||||
if (ILibSimpleDataStore_Get(agentHost->masterDb, "MeshID", NULL, 0) == 0) { RegDeleteKeyA(hKey, "MeshId"); } else { util_tohex(ILibScratchPad2, ILibSimpleDataStore_Get(agentHost->masterDb, "MeshID", ILibScratchPad2, (int)sizeof(ILibScratchPad2)), ILibScratchPad); RegSetValueExA(hKey, "MeshId", 0, REG_SZ, ILibScratchPad, (int)strlen(ILibScratchPad)); } // Save the MeshId
|
||||
if ((pLen = ILibSimpleDataStore_Get(agentHost->masterDb, "MeshServer", ILibScratchPad2, (int)sizeof(ILibScratchPad2))) == 0) { RegDeleteKeyA(hKey, "MeshServerUrl"); } else { RegSetValueExA(hKey, "MeshServerUrl", 0, REG_SZ, (BYTE*)ILibScratchPad2, (int)strlen(ILibScratchPad2)); } // Save the mesh server URL
|
||||
if ((pLen = ILibSimpleDataStore_Get(agentHost->masterDb, "ServerID", ILibScratchPad2, (int)sizeof(ILibScratchPad2))) == 0) { RegDeleteKeyA(hKey, "MeshServerId"); } else { RegSetValueExA(hKey, "MeshServerId", 0, REG_SZ, (BYTE*)ILibScratchPad2, (int)strlen(ILibScratchPad2)); } // Save the mesh server id
|
||||
if ((pLen = ILibSimpleDataStore_Get(agentHost->masterDb, "WebProxy", ILibScratchPad2, (int)sizeof(ILibScratchPad2))) == 0) { RegDeleteKeyA(hKey, "Proxy"); } else { RegSetValueExA(hKey, "Proxy", 0, REG_SZ, (BYTE*)ILibScratchPad2, (int)strlen(ILibScratchPad2)); } // Save the proxy
|
||||
@@ -2539,48 +2690,6 @@ int MeshAgent_AgentMode(MeshAgentHostContainer *agentHost, int paramLen, char **
|
||||
else if ((strcmp(param[1], "restart") == 0 || strcmp(param[1], "-r") == 0)) options = 3;
|
||||
}
|
||||
|
||||
// Stop
|
||||
if (options & 2)
|
||||
{
|
||||
FILE *fd = NULL;
|
||||
char str[15];
|
||||
pid_t pid = 0;
|
||||
size_t len;
|
||||
|
||||
/*
|
||||
#if defined(__APPLE__) && defined(_DAEMON) && defined(_LINKVM)
|
||||
installOsx(0);
|
||||
#endif
|
||||
*/
|
||||
|
||||
#ifdef _ANDROID
|
||||
fd = fopen("/data/usr/tmp/meshagent.pid", "r");
|
||||
#else
|
||||
fd = fopen("/var/run/meshagent.pid", "r");
|
||||
#endif
|
||||
if (fd == NULL) fd = fopen(".meshagent.pid", "r");
|
||||
if (fd != NULL)
|
||||
{
|
||||
len = fread(str, sizeof(char), 15, fd);
|
||||
if (len > 0)
|
||||
{
|
||||
sscanf(str, "%d\r\n", &pid);
|
||||
if (pid > 0 && kill(pid, SIGKILL) == 0) printf("Mesh agent stopped.\r\n"); else printf("Mesh agent not running.\r\n");
|
||||
#ifdef _ANDROID
|
||||
remove("/data/usr/tmp/meshagent.pid");
|
||||
#else
|
||||
remove("/var/run/meshagent.pid");
|
||||
remove(".meshagent.pid");
|
||||
#endif
|
||||
}
|
||||
fclose(fd);
|
||||
}
|
||||
else
|
||||
{
|
||||
printf("Unable to find process id file.\r\n");
|
||||
}
|
||||
}
|
||||
|
||||
// Start
|
||||
if (options & 1)
|
||||
{
|
||||
@@ -2627,7 +2736,7 @@ int MeshAgent_AgentMode(MeshAgentHostContainer *agentHost, int paramLen, char **
|
||||
|
||||
#endif
|
||||
|
||||
if (parseCommands == 0 || paramLen == 1 || ((paramLen == 2) && (strcmp(param[1], "run") == 0)))
|
||||
if (parseCommands == 0 || paramLen == 1 || ((paramLen == 2) && (strcmp(param[1], "run") == 0 || strcmp(param[1], "connect") == 0)))
|
||||
{
|
||||
#ifdef WIN32
|
||||
char* updateFilePath = MeshAgent_MakeAbsolutePath(agentHost->exePath, ".update.exe");
|
||||
@@ -2666,7 +2775,7 @@ int MeshAgent_AgentMode(MeshAgentHostContainer *agentHost, int paramLen, char **
|
||||
CoreModule = (char*)ILibMemory_Allocate(CoreModuleLen, 0, NULL, NULL);
|
||||
ILibSimpleDataStore_Get(agentHost->masterDb, "CoreModule", CoreModule, CoreModuleLen);
|
||||
|
||||
if (ILibDuktape_ScriptContainer_CompileJavaScript(agentHost->meshCoreCtx, CoreModule + 4, CoreModuleLen - 4) != 0 ||
|
||||
if (ILibDuktape_ScriptContainer_CompileJavaScriptEx(agentHost->meshCoreCtx, CoreModule + 4, CoreModuleLen - 4, "CoreModule.js", 13) != 0 ||
|
||||
ILibDuktape_ScriptContainer_ExecuteByteCode(agentHost->meshCoreCtx) != 0)
|
||||
{
|
||||
ILibRemoteLogging_printf(ILibChainGetLogger(agentHost->chain), ILibRemoteLogging_Modules_Microstack_Generic | ILibRemoteLogging_Modules_ConsolePrint,
|
||||
@@ -2708,10 +2817,14 @@ int MeshAgent_AgentMode(MeshAgentHostContainer *agentHost, int paramLen, char **
|
||||
multicastAddr4.sin_port = htons(16989);
|
||||
ILibInet_pton(AF_INET, MESH_MCASTv4_GROUP, &(multicastAddr4.sin_addr));
|
||||
|
||||
// Multicast socket on fixed port, will receive multicast from the server.
|
||||
agentHost->multicastDiscovery = ILibMulticastSocket_Create(agentHost->chain, 1024, MESH_AGENT_PORT, &multicastAddr4, &multicastAddr6, UDPSocket_OnData, agentHost, 1);
|
||||
if (agentHost->multicastDiscovery == NULL) { ILIBMARKPOSITION(219); return 1; }
|
||||
}
|
||||
|
||||
// Multicast socket on a random port, used to multicast to the server and receive server unicast responses.
|
||||
agentHost->multicastDiscovery2 = ILibMulticastSocket_Create(agentHost->chain, 1024, 0, &multicastAddr4, &multicastAddr6, UDPSocket_OnData, agentHost, 1);
|
||||
if (agentHost->multicastDiscovery2 == NULL) { ILIBMARKPOSITION(219); return 1; }
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
@@ -2724,6 +2837,23 @@ void MeshAgent_ScriptMode_UncaughtExceptionSink(duk_context *ctx, char *msg, voi
|
||||
//ScriptEngine_Exit((MeshAgentHostContainer*)user, MeshAgent_JavaCore_ContextGuid, 254);
|
||||
}
|
||||
|
||||
void MeshAgent_ScriptMode_MeshDesktop_PUSH(duk_context *ctx, void *chain)
|
||||
{
|
||||
duk_push_heap_stash(ctx); // [stash]
|
||||
MeshAgentHostContainer *agent = (MeshAgentHostContainer*)Duktape_GetPointerProperty(ctx, -1, "\xFF_MeshDesktop_AgentPtr");
|
||||
duk_pop(ctx);
|
||||
|
||||
duk_push_object(ctx);
|
||||
ILibDuktape_WriteID(ctx, "MeshDesktop");
|
||||
if (agent != NULL)
|
||||
{
|
||||
duk_push_pointer(ctx, agent);
|
||||
duk_put_prop_string(ctx, -2, MESH_AGENT_PTR);
|
||||
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "getRemoteDesktopStream", ILibDuktape_MeshAgent_getRemoteDesktop, 0);
|
||||
}
|
||||
}
|
||||
|
||||
void MeshAgent_ScriptMode(MeshAgentHostContainer *agentHost, int argc, char **argv)
|
||||
{
|
||||
char *jsFile;
|
||||
@@ -2831,9 +2961,20 @@ void MeshAgent_ScriptMode(MeshAgentHostContainer *agentHost, int argc, char **ar
|
||||
|
||||
agentHost->meshCoreCtx = ILibDuktape_ScriptContainer_InitializeJavaScriptEngineEx(secFlags, execTimeout, agentHost->chain, scriptArgs, connectAgent != 0 ? agentHost->masterDb : NULL, agentHost->exePath, agentHost->pipeManager, connectAgent == 0 ? MeshAgent_RunScriptOnly_Finalizer : NULL, agentHost);
|
||||
ILibDuktape_SetNativeUncaughtExceptionHandler(agentHost->meshCoreCtx, MeshAgent_ScriptMode_UncaughtExceptionSink, agentHost);
|
||||
if (connectAgent != 0) { ILibDuktape_MeshAgent_Init(agentHost->meshCoreCtx, agentHost->chain, agentHost); }
|
||||
if (connectAgent != 0)
|
||||
{
|
||||
ILibDuktape_MeshAgent_Init(agentHost->meshCoreCtx, agentHost->chain, agentHost);
|
||||
}
|
||||
else
|
||||
{
|
||||
duk_push_heap_stash(agentHost->meshCoreCtx); // [stash]
|
||||
duk_push_pointer(agentHost->meshCoreCtx, agentHost); // [stash][ptr]
|
||||
duk_put_prop_string(agentHost->meshCoreCtx, -2, "\xFF_MeshDesktop_AgentPtr"); // [stash]
|
||||
duk_pop(agentHost->meshCoreCtx); // ...
|
||||
ILibDuktape_ModSearch_AddHandler(agentHost->meshCoreCtx, "meshDesktop", MeshAgent_ScriptMode_MeshDesktop_PUSH);
|
||||
}
|
||||
|
||||
if (ILibDuktape_ScriptContainer_CompileJavaScript(agentHost->meshCoreCtx, jsFile, jsFileLen) != 0 || ILibDuktape_ScriptContainer_ExecuteByteCode(agentHost->meshCoreCtx) != 0)
|
||||
if (ILibDuktape_ScriptContainer_CompileJavaScriptEx(agentHost->meshCoreCtx, jsFile, jsFileLen, agentHost->meshCoreCtx_embeddedScript == NULL ? scriptArgs[0] : "[embedded].js", 0) != 0 || ILibDuktape_ScriptContainer_ExecuteByteCode(agentHost->meshCoreCtx) != 0)
|
||||
{
|
||||
if (strcmp(duk_safe_to_string(agentHost->meshCoreCtx, -1), "Process.exit() forced script termination") != 0)
|
||||
{
|
||||
@@ -2850,6 +2991,7 @@ void MeshAgent_ScriptMode(MeshAgentHostContainer *agentHost, int argc, char **ar
|
||||
// If in agent mode, setup the chain to be a mesh agent
|
||||
if (connectAgent != 0)
|
||||
{
|
||||
printf("MeshCentral2 Agent\r\n"); // MESH_AGENT_VERSION
|
||||
if (MeshAgent_AgentMode(agentHost, argc, argv, 0) == 0)
|
||||
{
|
||||
ILibStopChain(agentHost->chain); // Agent Error, stop the chain
|
||||
@@ -2863,6 +3005,7 @@ void MeshAgent_ScriptMode_Dispatched(void *chain, void *user)
|
||||
}
|
||||
void MeshAgent_AgentMode_Dispatched(void *chain, void *user)
|
||||
{
|
||||
printf("MeshCentral2 Agent\r\n"); // MESH_AGENT_VERSION
|
||||
if (MeshAgent_AgentMode((MeshAgentHostContainer*)((void**)user)[0], ((int*)((void**)user)[1])[0], (char**)((void**)user)[2], 1) == 0)
|
||||
{
|
||||
ILibStopChain(((MeshAgentHostContainer*)((void**)user)[0])->chain);
|
||||
@@ -2882,8 +3025,15 @@ int MeshAgent_Start(MeshAgentHostContainer *agentHost, int paramLen, char **para
|
||||
int x;
|
||||
#endif
|
||||
|
||||
#if defined(WIN32) && defined(_LINKVM) && !defined(WINSERVICE)
|
||||
SetProcessDPIAware();
|
||||
#endif
|
||||
|
||||
if ((paramLen == 1 && strcmp(param[0], "--slave") == 0) || (paramLen == 2 && strcmp(param[1], "--slave") == 0)) { MeshAgent_Slave(agentHost); return 0; }
|
||||
if (paramLen == 2 && strcmp(param[1], "--netinfo") == 0) { char* data; int len = MeshInfo_GetSystemInformation(&data); if (len > 0) { printf("%s\r\n", data); } return 0; }
|
||||
if (paramLen == 2 && strcmp(param[1], "--netinfo") == 0) { char* data; int len = MeshInfo_GetSystemInformation(&data); if (len > 0) { printf("%s\r\n", data); free(data); } return 0; }
|
||||
|
||||
if (agentHost->exePath == NULL)
|
||||
{
|
||||
agentHost->exePath = exePath;
|
||||
exePath[0] = 0;
|
||||
|
||||
@@ -2899,6 +3049,7 @@ int MeshAgent_Start(MeshAgentHostContainer *agentHost, int paramLen, char **para
|
||||
if (x < 0 || x >= 1024) ILIBCRITICALEXIT(246);
|
||||
exePath[x] = 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
// Perform a self SHA384 Hash
|
||||
GenerateSHA384FileHash(agentHost->exePath, agentHost->agentHash);
|
||||
@@ -2956,6 +3107,12 @@ int MeshAgent_Start(MeshAgentHostContainer *agentHost, int paramLen, char **para
|
||||
ILibStartChain(agentHost->chain);
|
||||
agentHost->chain = NULL; // Mesh agent has exited, set the chain to NULL
|
||||
|
||||
// Close the database
|
||||
if (agentHost->masterDb != NULL) {
|
||||
ILibSimpleDataStore_Close(agentHost->masterDb);
|
||||
agentHost->masterDb = NULL;
|
||||
}
|
||||
|
||||
// Check if we need to perform self-update (performSelfUpdate should indicate startup type on Liunx: 1 = systemd, 2 = upstart, 3 = sysv-init)
|
||||
if (agentHost->performSelfUpdate != 0)
|
||||
{
|
||||
@@ -2979,7 +3136,7 @@ int MeshAgent_Start(MeshAgentHostContainer *agentHost, int paramLen, char **para
|
||||
|
||||
// Build the argument list
|
||||
str[0] = 0;
|
||||
for (i = 1; i < paramLen; i++) ptr += sprintf_s(str + ptr, 4096 - ptr, " %s", param[i]);
|
||||
for (i = 1; i < paramLen && ptr >= 0; i++) ptr += sprintf_s(str + ptr, 4096 - ptr, " %s", param[i]);
|
||||
|
||||
#ifdef WIN32
|
||||
// Windows version
|
||||
@@ -3134,7 +3291,7 @@ void MeshAgent_PerformSelfUpdate(char* selfpath, char* exepath, int argc, char *
|
||||
|
||||
// Built the argument list
|
||||
ILibScratchPad[0] = 0;
|
||||
for (i = 2; i < argc; i++) ptr += sprintf_s(ILibScratchPad + ptr, 4096 - ptr, " %s", argv[i]);
|
||||
for (i = 2; i < argc && ptr >= 0; i++) ptr += sprintf_s(ILibScratchPad + ptr, 4096 - ptr, " %s", argv[i]);
|
||||
sprintf_s(ILibScratchPad2, 60000, "%s%s &", exepath, ILibScratchPad);
|
||||
|
||||
// Now run the updated process
|
||||
|
||||
@@ -50,6 +50,18 @@ typedef char JS_ENGINE_CONTEXT[16];
|
||||
#include "microstack/ILibProcessPipe.h"
|
||||
#include "microstack/ILibCrypto.h"
|
||||
|
||||
#define ILibDuktape_MeshAgent_LoggedOnUsers "\xFF_MeshAgent_LoggedOnUsers"
|
||||
|
||||
typedef enum MeshCommand_AuthInfo_CapabilitiesMask
|
||||
{
|
||||
MeshCommand_AuthInfo_CapabilitiesMask_DESKTOP = 0x01,
|
||||
MeshCommand_AuthInfo_CapabilitiesMask_TERMINAL = 0x02,
|
||||
MeshCommand_AuthInfo_CapabilitiesMask_FILES = 0x04,
|
||||
MeshCommand_AuthInfo_CapabilitiesMask_CONSOLE = 0x08,
|
||||
MeshCommand_AuthInfo_CapabilitiesMask_JAVASCRIPT = 0x10,
|
||||
MeshCommand_AuthInfo_CapabilitiesMask_TEMPORARY = 0x20
|
||||
}MeshCommand_AuthInfo_CapabilitiesMask;
|
||||
|
||||
typedef enum AgentIdentifiers
|
||||
{
|
||||
AGENTID_UNKNOWN = 0, //!< Self-update not supported
|
||||
@@ -148,10 +160,12 @@ typedef struct MeshAgentHostContainer
|
||||
|
||||
int localScript;
|
||||
int version;
|
||||
int capabilities; // Extra agent capabilities indicated to the server from MeshCommand_AuthInfo_CapabilitiesMask
|
||||
char hostname[255];
|
||||
char serveruri[1024];
|
||||
AgentIdentifiers agentID;
|
||||
int serverIndex;
|
||||
int triedNoProxy_Index;
|
||||
int retryTime;
|
||||
MeshAgentHost_BatteryInfo batteryState;
|
||||
char meshId[UTIL_SHA384_HASHSIZE];
|
||||
@@ -175,6 +189,7 @@ typedef struct MeshAgentHostContainer
|
||||
char g_selfid[UTIL_SHA384_HASHSIZE];
|
||||
void* microLMS;
|
||||
void* multicastDiscovery;
|
||||
void* multicastDiscovery2;
|
||||
char* multicastServerUrl;
|
||||
int serverConnectionState;
|
||||
int exitCode;
|
||||
@@ -186,7 +201,7 @@ typedef struct MeshAgentHostContainer
|
||||
#endif
|
||||
}MeshAgentHostContainer;
|
||||
|
||||
MeshAgentHostContainer* MeshAgent_Create();
|
||||
MeshAgentHostContainer* MeshAgent_Create(MeshCommand_AuthInfo_CapabilitiesMask capabilities);
|
||||
void MeshAgent_Destroy(MeshAgentHostContainer* agent);
|
||||
|
||||
int MeshAgent_Start(MeshAgentHostContainer *agent, int argc, char **argv);
|
||||
|
||||
@@ -191,7 +191,10 @@ int __fastcall utilx_readfile2(char* filename, char** data)
|
||||
{
|
||||
len = fread((*data) + count, 1, 1023, pFile);
|
||||
count += len;
|
||||
if (len == 1023) *data = realloc(*data, count + 1024);
|
||||
if (len == 1023)
|
||||
{
|
||||
if ((*data = realloc(*data, count + 1024)) == NULL) { ILIBCRITICALEXIT(254); }
|
||||
}
|
||||
} while (len == 100);
|
||||
(*data)[count] = 0;
|
||||
fclose(pFile);
|
||||
@@ -419,12 +422,12 @@ int MeshInfo_GetSystemInformation(char** data)
|
||||
int ptr = 0;
|
||||
|
||||
// Setup the response
|
||||
*data = (char*)malloc(65536);
|
||||
if ((*data = (char*)malloc(65536)) == NULL) { ILIBCRITICALEXIT(254); }
|
||||
ptr += snprintf(*data + ptr, 65536 - ptr, "{\"netif\":[");
|
||||
ptr += info_GetLocalInterfaces(*data + ptr, 65536 - ptr);
|
||||
ptr += snprintf(*data + ptr, 65536 - ptr, "]}");
|
||||
(*data)[ptr] = 0;
|
||||
*data = realloc(*data, ptr + 1);
|
||||
if ((*data = realloc(*data, ptr + 1)) == NULL) { ILIBCRITICALEXIT(254); }
|
||||
|
||||
return ptr;
|
||||
}
|
||||
@@ -587,4 +590,3 @@ int MeshInfo_PowerState(enum AgentPowerStateActions flg, int force)
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
Binary file not shown.
@@ -100,15 +100,15 @@ END
|
||||
|
||||
IDD_INSTALLDIALOG DIALOGEX 0, 100, 317, 148
|
||||
STYLE DS_SETFONT | DS_MODALFRAME | DS_3DLOOK | DS_FIXEDSYS | DS_CENTER | WS_POPUP | WS_CAPTION
|
||||
CAPTION "Mesh Agent v2 Installer"
|
||||
CAPTION "Mesh Agent v2"
|
||||
FONT 8, "MS Shell Dlg", 400, 0, 0x1
|
||||
BEGIN
|
||||
PUSHBUTTON "Close",IDCANCEL,260,127,50,14
|
||||
LTEXT "Click the buttons below to install or uninstall the mesh agent. When installed, this software runs in the background allowing this computer to be managed and controlled by a remote administrator.",IDC_STATIC,7,7,275,28
|
||||
GROUPBOX "Installation Information",IDC_STATIC,7,38,303,87
|
||||
PUSHBUTTON "Install / Update",IDC_INSTALLBUTTON,7,127,77,14
|
||||
PUSHBUTTON "Uninstall",IDC_UNINSTALLBUTTON,87,127,77,14
|
||||
ICON IDI_ICON1,IDC_STATIC,288,7,21,20
|
||||
PUSHBUTTON "Install / Update",IDC_INSTALLBUTTON,7,127,65,14
|
||||
PUSHBUTTON "Uninstall",IDC_UNINSTALLBUTTON,75,127,65,14
|
||||
ICON IDI_ICON1,IDC_STATIC,288,7,20,20
|
||||
LTEXT "Current Agent Status",IDC_STATIC,14,51,70,8
|
||||
LTEXT "Unknown",IDC_STATUSTEXT,127,51,175,8,0,WS_EX_RIGHT
|
||||
LTEXT "New Agent Version",IDC_STATIC,14,63,62,8
|
||||
@@ -121,6 +121,7 @@ BEGIN
|
||||
LTEXT "Unknown",IDC_SERVERID,127,111,175,8,0,WS_EX_RIGHT
|
||||
LTEXT "New Server Location",IDC_STATIC,14,75,67,8
|
||||
LTEXT "Unknown",IDC_SERVERLOCATION,127,75,175,8,0,WS_EX_RIGHT
|
||||
PUSHBUTTON "Connect",IDC_CONNECTBUTTON,143,127,65,14
|
||||
END
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup Label="ProjectConfigurations">
|
||||
<ProjectConfiguration Include="Debug_NoOpenSSL|Win32">
|
||||
<Configuration>Debug_NoOpenSSL</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Debug_NoOpenSSL|x64">
|
||||
<Configuration>Debug_NoOpenSSL</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Debug|Win32">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
@@ -9,6 +17,14 @@
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release_NoOpenSSL|Win32">
|
||||
<Configuration>Release_NoOpenSSL</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release_NoOpenSSL|x64">
|
||||
<Configuration>Release_NoOpenSSL</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|Win32">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
@@ -32,83 +48,190 @@
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release_NoOpenSSL|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug_NoOpenSSL|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release_NoOpenSSL|x64'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug_NoOpenSSL|x64'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<CharacterSet>MultiByte</CharacterSet>
|
||||
<PlatformToolset>v140</PlatformToolset>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||
<ImportGroup Label="ExtensionSettings">
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release_NoOpenSSL|Win32'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug_NoOpenSSL|Win32'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release_NoOpenSSL|x64'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug_NoOpenSSL|x64'" Label="PropertySheets">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<PropertyGroup Label="UserMacros" />
|
||||
<PropertyGroup>
|
||||
<_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug_NoOpenSSL|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(SolutionDir)$(Configuration)\$(TargetName)\$(Platform)\OBJ\</IntDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug_NoOpenSSL|Win32'">$(SolutionDir)$(Configuration)\$(TargetName)\$(Platform)\OBJ\</IntDir>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</LinkIncremental>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug_NoOpenSSL|Win32'">false</LinkIncremental>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)$(Configuration)\</OutDir>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Debug_NoOpenSSL|x64'">$(SolutionDir)$(Configuration)\</OutDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">$(SolutionDir)$(Configuration)\$(TargetName)\$(Platform)\OBJ\</IntDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Debug_NoOpenSSL|x64'">$(SolutionDir)$(Configuration)\$(TargetName)\$(Platform)\OBJ\</IntDir>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</LinkIncremental>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Debug_NoOpenSSL|x64'">false</LinkIncremental>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release_NoOpenSSL|Win32'">$(SolutionDir)$(Configuration)\</OutDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">$(SolutionDir)$(Configuration)\$(TargetName)\$(Platform)\OBJ\</IntDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release_NoOpenSSL|Win32'">$(SolutionDir)$(Configuration)\$(TargetName)\$(Platform)\OBJ\</IntDir>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">false</LinkIncremental>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release_NoOpenSSL|Win32'">false</LinkIncremental>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)$(Configuration)\</OutDir>
|
||||
<OutDir Condition="'$(Configuration)|$(Platform)'=='Release_NoOpenSSL|x64'">$(SolutionDir)$(Configuration)\</OutDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release|x64'">$(SolutionDir)$(Configuration)\$(TargetName)\$(Platform)\OBJ\</IntDir>
|
||||
<IntDir Condition="'$(Configuration)|$(Platform)'=='Release_NoOpenSSL|x64'">$(SolutionDir)$(Configuration)\$(TargetName)\$(Platform)\OBJ\</IntDir>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</LinkIncremental>
|
||||
<LinkIncremental Condition="'$(Configuration)|$(Platform)'=='Release_NoOpenSSL|x64'">false</LinkIncremental>
|
||||
<CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
|
||||
<CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug_NoOpenSSL|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
|
||||
<CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
|
||||
<CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug_NoOpenSSL|Win32'" />
|
||||
<CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" />
|
||||
<CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug_NoOpenSSL|Win32'" />
|
||||
<CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
|
||||
<CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Debug_NoOpenSSL|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
|
||||
<CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
|
||||
<CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Debug_NoOpenSSL|x64'" />
|
||||
<CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" />
|
||||
<CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Debug_NoOpenSSL|x64'" />
|
||||
<CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
|
||||
<CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release_NoOpenSSL|Win32'">AllRules.ruleset</CodeAnalysisRuleSet>
|
||||
<CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
|
||||
<CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release_NoOpenSSL|Win32'" />
|
||||
<CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" />
|
||||
<CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release_NoOpenSSL|Win32'" />
|
||||
<CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
|
||||
<CodeAnalysisRuleSet Condition="'$(Configuration)|$(Platform)'=='Release_NoOpenSSL|x64'">AllRules.ruleset</CodeAnalysisRuleSet>
|
||||
<CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
|
||||
<CodeAnalysisRules Condition="'$(Configuration)|$(Platform)'=='Release_NoOpenSSL|x64'" />
|
||||
<CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release|x64'" />
|
||||
<CodeAnalysisRuleAssemblies Condition="'$(Configuration)|$(Platform)'=='Release_NoOpenSSL|x64'" />
|
||||
<PostBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">false</PostBuildEventUseInBuild>
|
||||
<PostBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug_NoOpenSSL|Win32'">false</PostBuildEventUseInBuild>
|
||||
<TargetName Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">$(ProjectName)</TargetName>
|
||||
<TargetName Condition="'$(Configuration)|$(Platform)'=='Debug_NoOpenSSL|Win32'">$(ProjectName)</TargetName>
|
||||
<PostBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</PostBuildEventUseInBuild>
|
||||
<PostBuildEventUseInBuild Condition="'$(Configuration)|$(Platform)'=='Debug_NoOpenSSL|x64'">false</PostBuildEventUseInBuild>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<PostBuildEventUseInBuild>true</PostBuildEventUseInBuild>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release_NoOpenSSL|Win32'">
|
||||
<PostBuildEventUseInBuild>true</PostBuildEventUseInBuild>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<PostBuildEventUseInBuild>true</PostBuildEventUseInBuild>
|
||||
<TargetName>$(ProjectName)64</TargetName>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release_NoOpenSSL|x64'">
|
||||
<PostBuildEventUseInBuild>true</PostBuildEventUseInBuild>
|
||||
<TargetName>$(ProjectName)64</TargetName>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<TargetName>$(ProjectName)64</TargetName>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug_NoOpenSSL|x64'">
|
||||
<TargetName>$(ProjectName)64</TargetName>
|
||||
</PropertyGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<ClCompile>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<AdditionalIncludeDirectories>..\openssl\include;..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>MESH_AGENTID=3;NOLMSCOMMANDER;MICROSTACK_PROXY;_LINKVM;WIN32;_WINSERVICE;_DEBUG;_CONSOLE;MEMORY_CHECK;__STDC__;WINSOCK2;ILibWebServer_SESSION_TRACKING;MICROSTACK_NO_STDAFX;MICROSTACK_PROXY;MICROSTACK_TLS_DETECT;_REMOTELOGGING;_REMOTELOGGINGSERVER;_MSC_PLATFORM_TOOLSET_$(PlatformToolset);ILibChain_WATCHDOG_TIMEOUT=600000;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<PreprocessorDefinitions>MESH_AGENTID=3;DUK_USE_DATE_NOW_WINDOWS;NOLMSCOMMANDER;MICROSTACK_PROXY;_LINKVM;WIN32;_WINSERVICE;_DEBUG;_CONSOLE;MEMORY_CHECK;__STDC__;WINSOCK2;ILibWebServer_SESSION_TRACKING;MICROSTACK_NO_STDAFX;MICROSTACK_PROXY;MICROSTACK_TLS_DETECT;_REMOTELOGGING;_REMOTELOGGINGSERVER;_MSC_PLATFORM_TOOLSET_$(PlatformToolset);ILibChain_WATCHDOG_TIMEOUT=600000;DUK_USE_DEBUGGER_SUPPORT;DUK_USE_INTERRUPT_COUNTER;DUK_USE_DEBUGGER_INSPECT;DUK_USE_DEBUGGER_PAUSE_UNCAUGHT;DUK_USE_DEBUGGER_DUMPHEAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<MinimalRebuild>true</MinimalRebuild>
|
||||
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
|
||||
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<DebugInformationFormat>EditAndContinue</DebugInformationFormat>
|
||||
<ExceptionHandling>Async</ExceptionHandling>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<AdditionalDependencies>SetupAPI.lib;DbgHelp.lib;Gdiplus.lib;Iphlpapi.lib;ws2_32.lib;Setupapi.lib;Psapi.lib;Crypt32.lib;Wintrust.lib;Version.lib;Wtsapi32.lib;Winhttp.lib;..\openssl\libstatic\libcrypto32MTd.lib;..\openssl\libstatic\libssl32MTd.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<TargetMachine>MachineX86</TargetMachine>
|
||||
<Profile>false</Profile>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
<GenerateMapFile>
|
||||
</GenerateMapFile>
|
||||
<MapExports>
|
||||
</MapExports>
|
||||
<AssemblyDebug>true</AssemblyDebug>
|
||||
<AdditionalOptions> /ignore:4099 %(AdditionalOptions)</AdditionalOptions>
|
||||
<OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
|
||||
</Link>
|
||||
<PostBuildEvent>
|
||||
<Command>signtool.exe sign /sha1 fd5940d8fd585545614fea6da455f25d224b00c9 /d "MeshService" /du "http://opentools.homeip.net" "$(TargetPath)"</Command>
|
||||
</PostBuildEvent>
|
||||
<Manifest>
|
||||
<AdditionalManifestFiles>$(ProjectDir)dpiaware.manifest %(AdditionalManifestFiles)</AdditionalManifestFiles>
|
||||
</Manifest>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug_NoOpenSSL|Win32'">
|
||||
<ClCompile>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<AdditionalIncludeDirectories>..\openssl\include;..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>MESH_AGENTID=3;DUK_USE_DATE_NOW_WINDOWS;NOLMSCOMMANDER;MICROSTACK_PROXY;_LINKVM;WIN32;_WINSERVICE;_DEBUG;_CONSOLE;MEMORY_CHECK;__STDC__;WINSOCK2;ILibWebServer_SESSION_TRACKING;MICROSTACK_NO_STDAFX;MICROSTACK_PROXY;MICROSTACK_TLS_DETECT;_REMOTELOGGING;_REMOTELOGGINGSERVER;_MSC_PLATFORM_TOOLSET_$(PlatformToolset);ILibChain_WATCHDOG_TIMEOUT=600000;DUK_USE_DEBUGGER_SUPPORT;DUK_USE_INTERRUPT_COUNTER;DUK_USE_DEBUGGER_INSPECT;DUK_USE_DEBUGGER_PAUSE_UNCAUGHT;DUK_USE_DEBUGGER_DUMPHEAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<MinimalRebuild>true</MinimalRebuild>
|
||||
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
|
||||
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
|
||||
@@ -147,7 +270,7 @@
|
||||
<ClCompile>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<AdditionalIncludeDirectories>..\openssl\include;..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>MESH_AGENTID=4;MICROSTACK_PROXY;_WINSERVICE;NOLMSCOMMANDER;WIN32;WIN64;_LINKVM;_DEBUG;_CONSOLE;MEMORY_CHECK;MICROSTACK_NO_STDAFX;MICROSTACK_PROXY;__STDC__;_CRT_SECURE_NO_WARNINGS;WINSOCK2;ILibWebServer_SESSION_TRACKING;_REMOTELOGGING;_REMOTELOGGINGSERVER;MICROSTACK_TLS_DETECT;_MSC_PLATFORM_TOOLSET_$(PlatformToolset);ILibChain_WATCHDOG_TIMEOUT=600000;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<PreprocessorDefinitions>MESH_AGENTID=4;DUK_USE_DATE_NOW_WINDOWS;MICROSTACK_PROXY;_WINSERVICE;NOLMSCOMMANDER;WIN32;WIN64;_LINKVM;_DEBUG;_CONSOLE;MEMORY_CHECK;MICROSTACK_NO_STDAFX;MICROSTACK_PROXY;__STDC__;_CRT_SECURE_NO_WARNINGS;WINSOCK2;ILibWebServer_SESSION_TRACKING;_REMOTELOGGING;_REMOTELOGGINGSERVER;MICROSTACK_TLS_DETECT;_MSC_PLATFORM_TOOLSET_$(PlatformToolset);ILibChain_WATCHDOG_TIMEOUT=600000;DUK_USE_DEBUGGER_SUPPORT;DUK_USE_INTERRUPT_COUNTER;DUK_USE_DEBUGGER_INSPECT;DUK_USE_DEBUGGER_PAUSE_UNCAUGHT;DUK_USE_DEBUGGER_DUMPHEAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<MinimalRebuild>true</MinimalRebuild>
|
||||
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
|
||||
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
|
||||
@@ -170,13 +293,84 @@
|
||||
<PostBuildEvent>
|
||||
<Command>signtool.exe sign /sha1 fd5940d8fd585545614fea6da455f25d224b00c9 /d "MeshService" /du "http://opentools.homeip.net" "$(TargetPath)"</Command>
|
||||
</PostBuildEvent>
|
||||
<Manifest>
|
||||
<AdditionalManifestFiles>$(ProjectDir)dpiaware.manifest %(AdditionalManifestFiles)</AdditionalManifestFiles>
|
||||
</Manifest>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug_NoOpenSSL|x64'">
|
||||
<Midl>
|
||||
<TargetEnvironment>X64</TargetEnvironment>
|
||||
</Midl>
|
||||
<ClCompile>
|
||||
<Optimization>Disabled</Optimization>
|
||||
<AdditionalIncludeDirectories>..\openssl\include;..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>MESH_AGENTID=4;DUK_USE_DATE_NOW_WINDOWS;MICROSTACK_PROXY;_WINSERVICE;NOLMSCOMMANDER;WIN32;WIN64;_LINKVM;_DEBUG;_CONSOLE;MEMORY_CHECK;MICROSTACK_NO_STDAFX;MICROSTACK_PROXY;__STDC__;_CRT_SECURE_NO_WARNINGS;WINSOCK2;ILibWebServer_SESSION_TRACKING;_REMOTELOGGING;_REMOTELOGGINGSERVER;MICROSTACK_TLS_DETECT;_MSC_PLATFORM_TOOLSET_$(PlatformToolset);ILibChain_WATCHDOG_TIMEOUT=600000;DUK_USE_DEBUGGER_SUPPORT;DUK_USE_INTERRUPT_COUNTER;DUK_USE_DEBUGGER_INSPECT;DUK_USE_DEBUGGER_PAUSE_UNCAUGHT;DUK_USE_DEBUGGER_DUMPHEAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<MinimalRebuild>true</MinimalRebuild>
|
||||
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
|
||||
<RuntimeLibrary>MultiThreadedDebug</RuntimeLibrary>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
<ExceptionHandling>Async</ExceptionHandling>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<AdditionalDependencies>SetupAPI.lib;DbgHelp.lib;Iphlpapi.lib;ws2_32.lib;Setupapi.lib;Psapi.lib;Crypt32.lib;Wintrust.lib;Version.lib;Wtsapi32.lib;Gdiplus.lib;Winhttp.lib;Ncrypt.lib;..\openssl\libstatic\libcrypto64MTd.lib;..\openssl\libstatic\libssl64MTd.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<TargetMachine>MachineX64</TargetMachine>
|
||||
<Profile>true</Profile>
|
||||
<AdditionalOptions> /ignore:4099 %(AdditionalOptions)</AdditionalOptions>
|
||||
<OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
|
||||
<ProgramDatabaseFile>$(OutDir)$(TargetName).pdb</ProgramDatabaseFile>
|
||||
</Link>
|
||||
<PostBuildEvent>
|
||||
<Command>signtool.exe sign /sha1 fd5940d8fd585545614fea6da455f25d224b00c9 /d "MeshService" /du "http://opentools.homeip.net" "$(TargetPath)"</Command>
|
||||
</PostBuildEvent>
|
||||
<Manifest>
|
||||
<AdditionalManifestFiles>$(ProjectDir)dpiaware.manifest %(AdditionalManifestFiles)</AdditionalManifestFiles>
|
||||
</Manifest>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<ClCompile>
|
||||
<Optimization>Full</Optimization>
|
||||
<IntrinsicFunctions>true</IntrinsicFunctions>
|
||||
<AdditionalIncludeDirectories>..\openssl\include;..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>MESH_AGENTID=3;NOLMSCOMMANDER;MICROSTACK_PROXY;_LINKVM;WIN32;NDEBUG;_WINSERVICE;_CONSOLE;_LINKVM;WINSOCK2;MICROSTACK_NO_STDAFX;MICROSTACK_PROXY;MICROSTACK_TLS_DETECT;_MSC_PLATFORM_TOOLSET_$(PlatformToolset);%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<PreprocessorDefinitions>MESH_AGENTID=3;DUK_USE_DATE_NOW_WINDOWS;NOLMSCOMMANDER;MICROSTACK_PROXY;_LINKVM;WIN32;NDEBUG;_WINSERVICE;_CONSOLE;WINSOCK2;MICROSTACK_NO_STDAFX;MICROSTACK_TLS_DETECT;_MSC_PLATFORM_TOOLSET_$(PlatformToolset);DUK_USE_DEBUGGER_SUPPORT;DUK_USE_INTERRUPT_COUNTER;DUK_USE_DEBUGGER_INSPECT;DUK_USE_DEBUGGER_PAUSE_UNCAUGHT;DUK_USE_DEBUGGER_DUMPHEAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
|
||||
<FunctionLevelLinking>true</FunctionLevelLinking>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
<CallingConvention>Cdecl</CallingConvention>
|
||||
<OmitFramePointers>true</OmitFramePointers>
|
||||
<ExceptionHandling>Async</ExceptionHandling>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<AdditionalDependencies>SetupAPI.lib;Crypt32.lib;DbgHelp.lib;Iphlpapi.lib;ws2_32.lib;Setupapi.lib;Psapi.lib;Wintrust.lib;Version.lib;Wtsapi32.lib;Gdiplus.lib;Winhttp.lib;..\openssl\libstatic\libcrypto32MT.lib;..\openssl\libstatic\libssl32MT.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
<OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
<TargetMachine>MachineX86</TargetMachine>
|
||||
<AdditionalOptions> /ignore:4099 %(AdditionalOptions)</AdditionalOptions>
|
||||
</Link>
|
||||
<PostBuildEvent>
|
||||
<Command>REM signtool.exe sign /sha1 fd5940d8fd585545614fea6da455f25d224b00c9 /d "MeshService" /du "http://opentools.homeip.net" /t http://timestamp.comodoca.com/authenticode "$(TargetPath)"
|
||||
"$(OutputPath)$(TargetFileName)" ..\modules\PostBuild.js</Command>
|
||||
</PostBuildEvent>
|
||||
<Manifest>
|
||||
<AdditionalManifestFiles>$(ProjectDir)dpiaware.manifest %(AdditionalManifestFiles)</AdditionalManifestFiles>
|
||||
</Manifest>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release_NoOpenSSL|Win32'">
|
||||
<ClCompile>
|
||||
<Optimization>Full</Optimization>
|
||||
<IntrinsicFunctions>true</IntrinsicFunctions>
|
||||
<AdditionalIncludeDirectories>..\openssl\include;..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>MESH_AGENTID=3;DUK_USE_DATE_NOW_WINDOWS;NOLMSCOMMANDER;MICROSTACK_PROXY;_LINKVM;WIN32;NDEBUG;_WINSERVICE;_CONSOLE;_LINKVM;WINSOCK2;MICROSTACK_NO_STDAFX;MICROSTACK_PROXY;MICROSTACK_TLS_DETECT;_MSC_PLATFORM_TOOLSET_$(PlatformToolset);DUK_USE_DEBUGGER_SUPPORT;DUK_USE_INTERRUPT_COUNTER;DUK_USE_DEBUGGER_INSPECT;DUK_USE_DEBUGGER_PAUSE_UNCAUGHT;DUK_USE_DEBUGGER_DUMPHEAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
|
||||
<FunctionLevelLinking>true</FunctionLevelLinking>
|
||||
<PrecompiledHeader>
|
||||
@@ -213,7 +407,7 @@
|
||||
<Optimization>MinSpace</Optimization>
|
||||
<IntrinsicFunctions>true</IntrinsicFunctions>
|
||||
<AdditionalIncludeDirectories>..\openssl\include;..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>MESH_AGENTID=4;NOLMSCOMMANDER;MICROSTACK_PROXY;WIN32;WIN64;_WINSERVICE;NDEBUG;_LINKVM;_CONSOLE;MICROSTACK_NO_STDAFX;MICROSTACK_PROXY;WINSOCK2;MICROSTACK_TLS_DETECT;_MSC_PLATFORM_TOOLSET_$(PlatformToolset);%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<PreprocessorDefinitions>MESH_AGENTID=4;DUK_USE_DATE_NOW_WINDOWS;NOLMSCOMMANDER;MICROSTACK_PROXY;WIN32;WIN64;_WINSERVICE;NDEBUG;_LINKVM;_CONSOLE;MICROSTACK_NO_STDAFX;MICROSTACK_PROXY;WINSOCK2;MICROSTACK_TLS_DETECT;_MSC_PLATFORM_TOOLSET_$(PlatformToolset);DUK_USE_DEBUGGER_SUPPORT;DUK_USE_INTERRUPT_COUNTER;DUK_USE_DEBUGGER_INSPECT;DUK_USE_DEBUGGER_PAUSE_UNCAUGHT;DUK_USE_DEBUGGER_DUMPHEAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
|
||||
<FunctionLevelLinking>true</FunctionLevelLinking>
|
||||
<PrecompiledHeader>
|
||||
@@ -237,11 +431,52 @@
|
||||
<Command>REM signtool.exe sign /sha1 fd5940d8fd585545614fea6da455f25d224b00c9 /d "MeshService" /du "http://opentools.homeip.net" /t http://timestamp.comodoca.com/authenticode "$(TargetPath)"
|
||||
"$(OutputPath)$(TargetFileName)" ..\modules\PostBuild.js</Command>
|
||||
</PostBuildEvent>
|
||||
<Manifest>
|
||||
<AdditionalManifestFiles>$(ProjectDir)dpiaware.manifest %(AdditionalManifestFiles)</AdditionalManifestFiles>
|
||||
</Manifest>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release_NoOpenSSL|x64'">
|
||||
<Midl>
|
||||
<TargetEnvironment>X64</TargetEnvironment>
|
||||
</Midl>
|
||||
<ClCompile>
|
||||
<Optimization>MinSpace</Optimization>
|
||||
<IntrinsicFunctions>true</IntrinsicFunctions>
|
||||
<AdditionalIncludeDirectories>..\openssl\include;..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
<PreprocessorDefinitions>MESH_AGENTID=4;DUK_USE_DATE_NOW_WINDOWS;NOLMSCOMMANDER;MICROSTACK_PROXY;WIN32;WIN64;_WINSERVICE;NDEBUG;_LINKVM;_CONSOLE;MICROSTACK_NO_STDAFX;MICROSTACK_PROXY;WINSOCK2;MICROSTACK_TLS_DETECT;_MSC_PLATFORM_TOOLSET_$(PlatformToolset);DUK_USE_DEBUGGER_SUPPORT;DUK_USE_INTERRUPT_COUNTER;DUK_USE_DEBUGGER_INSPECT;DUK_USE_DEBUGGER_PAUSE_UNCAUGHT;DUK_USE_DEBUGGER_DUMPHEAP;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||
<RuntimeLibrary>MultiThreaded</RuntimeLibrary>
|
||||
<FunctionLevelLinking>true</FunctionLevelLinking>
|
||||
<PrecompiledHeader>
|
||||
</PrecompiledHeader>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
|
||||
<ExceptionHandling>Async</ExceptionHandling>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<AdditionalDependencies>SetupAPI.lib;DbgHelp.lib;Iphlpapi.lib;ws2_32.lib;Setupapi.lib;Psapi.lib;Crypt32.lib;Wintrust.lib;Version.lib;Wtsapi32.lib;Gdiplus.lib;Winhttp.lib;Ncrypt.lib;..\openssl\libstatic\libcrypto64MT.lib;..\openssl\libstatic\libssl64MT.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
<TargetMachine>MachineX64</TargetMachine>
|
||||
<AdditionalOptions> /ignore:4099 %(AdditionalOptions)</AdditionalOptions>
|
||||
<OutputFile>$(OutDir)$(TargetName)$(TargetExt)</OutputFile>
|
||||
<ProgramDatabaseFile>$(OutDir)$(TargetName).pdb</ProgramDatabaseFile>
|
||||
</Link>
|
||||
<PostBuildEvent>
|
||||
<Command>REM signtool.exe sign /sha1 fd5940d8fd585545614fea6da455f25d224b00c9 /d "MeshService" /du "http://opentools.homeip.net" /t http://timestamp.comodoca.com/authenticode "$(TargetPath)"
|
||||
"$(OutputPath)$(TargetFileName)" ..\modules\PostBuild.js</Command>
|
||||
</PostBuildEvent>
|
||||
<Manifest>
|
||||
<AdditionalManifestFiles>$(ProjectDir)dpiaware.manifest %(AdditionalManifestFiles)</AdditionalManifestFiles>
|
||||
</Manifest>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemGroup>
|
||||
<ResourceCompile Include="MeshService.rc">
|
||||
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">false</ExcludedFromBuild>
|
||||
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Debug_NoOpenSSL|x64'">false</ExcludedFromBuild>
|
||||
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release|x64'">false</ExcludedFromBuild>
|
||||
<ExcludedFromBuild Condition="'$(Configuration)|$(Platform)'=='Release_NoOpenSSL|x64'">false</ExcludedFromBuild>
|
||||
</ResourceCompile>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
@@ -258,6 +493,7 @@
|
||||
<ClCompile Include="..\microscript\duk_module_duktape.c" />
|
||||
<ClCompile Include="..\microscript\ILibDuktapeModSearch.c" />
|
||||
<ClCompile Include="..\microscript\ILibDuktape_ChildProcess.c" />
|
||||
<ClCompile Include="..\microscript\ILibDuktape_Debugger.c" />
|
||||
<ClCompile Include="..\microscript\ILibDuktape_Dgram.c" />
|
||||
<ClCompile Include="..\microscript\ILibDuktape_DuplexStream.c" />
|
||||
<ClCompile Include="..\microscript\ILibDuktape_EncryptionStream.c" />
|
||||
@@ -308,6 +544,7 @@
|
||||
<ClInclude Include="..\microscript\duk_module_duktape.h" />
|
||||
<ClInclude Include="..\microscript\ILibDuktapeModSearch.h" />
|
||||
<ClInclude Include="..\microscript\ILibDuktape_ChildProcess.h" />
|
||||
<ClInclude Include="..\microscript\ILibDuktape_Debugger.h" />
|
||||
<ClInclude Include="..\microscript\ILibDuktape_Dgram.h" />
|
||||
<ClInclude Include="..\microscript\ILibDuktape_DuplexStream.h" />
|
||||
<ClInclude Include="..\microscript\ILibDuktape_EncryptionStream.h" />
|
||||
|
||||
@@ -163,6 +163,9 @@
|
||||
<ClCompile Include="..\microscript\duk_module_duktape.c">
|
||||
<Filter>Microscript</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="..\microscript\ILibDuktape_Debugger.c">
|
||||
<Filter>Microscript</Filter>
|
||||
</ClCompile>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="..\microscript\duk_config.h">
|
||||
@@ -298,5 +301,8 @@
|
||||
<ClInclude Include="..\microscript\duk_module_duktape.h">
|
||||
<Filter>Microscript</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="..\microscript\ILibDuktape_Debugger.h">
|
||||
<Filter>Microscript</Filter>
|
||||
</ClInclude>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -48,6 +48,8 @@ int ClearWindowsFirewall(wchar_t* processname);
|
||||
#define _CRTDBG_MAP_ALLOC
|
||||
#endif
|
||||
|
||||
#include <WtsApi32.h>
|
||||
|
||||
TCHAR* serviceFile = TEXT("Mesh Agent");
|
||||
TCHAR* serviceFileOld = TEXT("Mesh Agent v2");
|
||||
TCHAR* serviceName = TEXT("Mesh Agent background service");
|
||||
@@ -88,7 +90,7 @@ BOOL IsAdmin()
|
||||
return admin;
|
||||
}
|
||||
|
||||
void WINAPI ServiceControlHandler( DWORD controlCode )
|
||||
DWORD WINAPI ServiceControlHandler( DWORD controlCode, DWORD eventType, void *eventData, void* eventContext )
|
||||
{
|
||||
switch (controlCode)
|
||||
{
|
||||
@@ -99,12 +101,161 @@ void WINAPI ServiceControlHandler( DWORD controlCode )
|
||||
serviceStatus.dwCurrentState = SERVICE_STOP_PENDING;
|
||||
SetServiceStatus( serviceStatusHandle, &serviceStatus );
|
||||
if (agent != NULL) { MeshAgent_Stop(agent); }
|
||||
return;
|
||||
return(0);
|
||||
case SERVICE_CONTROL_POWEREVENT:
|
||||
switch (eventType)
|
||||
{
|
||||
case PBT_APMPOWERSTATUSCHANGE: // Power status has changed.
|
||||
break;
|
||||
case PBT_APMRESUMEAUTOMATIC: // Operation is resuming automatically from a low - power state.This message is sent every time the system resumes.
|
||||
break;
|
||||
case PBT_APMRESUMESUSPEND: // Operation is resuming from a low - power state.This message is sent after PBT_APMRESUMEAUTOMATIC if the resume is triggered by user input, such as pressing a key.
|
||||
break;
|
||||
case PBT_APMSUSPEND: // System is suspending operation.
|
||||
break;
|
||||
case PBT_POWERSETTINGCHANGE: // Power setting change event has been received.
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case SERVICE_CONTROL_SESSIONCHANGE:
|
||||
if (agent == NULL)
|
||||
{
|
||||
break; // If there isn't an agent, no point in doing anything, cuz nobody will hear us
|
||||
}
|
||||
|
||||
switch (eventType)
|
||||
{
|
||||
case WTS_CONSOLE_CONNECT: // The session identified by lParam was connected to the console terminal or RemoteFX session.
|
||||
break;
|
||||
case WTS_CONSOLE_DISCONNECT: // The session identified by lParam was disconnected from the console terminal or RemoteFX session.
|
||||
break;
|
||||
case WTS_REMOTE_CONNECT: // The session identified by lParam was connected to the remote terminal.
|
||||
break;
|
||||
case WTS_REMOTE_DISCONNECT: // The session identified by lParam was disconnected from the remote terminal.
|
||||
break;
|
||||
case WTS_SESSION_LOGON: // A user has logged on to the session identified by lParam.
|
||||
case WTS_SESSION_LOGOFF: // A user has logged off the session identified by lParam.
|
||||
break;
|
||||
case WTS_SESSION_LOCK: // The session identified by lParam has been locked.
|
||||
break;
|
||||
case WTS_SESSION_UNLOCK: // The session identified by lParam has been unlocked.
|
||||
break;
|
||||
case WTS_SESSION_REMOTE_CONTROL:// The session identified by lParam has changed its remote controlled status.To determine the status, call GetSystemMetrics and check the SM_REMOTECONTROL metric.
|
||||
break;
|
||||
case WTS_SESSION_CREATE: // Reserved for future use.
|
||||
case WTS_SESSION_TERMINATE: // Reserved for future use.
|
||||
break;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
SetServiceStatus( serviceStatusHandle, &serviceStatus );
|
||||
return(0);
|
||||
}
|
||||
|
||||
|
||||
// Add the uninstallation icon in the Windows Control Panel.
|
||||
void WINAPI AddUninstallIcon()
|
||||
{
|
||||
/*
|
||||
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\MeshAgent]
|
||||
"DisplayName"="Mesh Agent Service - Remote Control Software"
|
||||
"Publisher"="MeshCentral"
|
||||
"MajorVersion"="2"
|
||||
"MinorVersion"="13"
|
||||
"InstallLocation"="C:\\Program Files\\Mesh Agent"
|
||||
"UninstallString"="C:\\Program Files\\Mesh Agent\\meshuninstaller.bat"
|
||||
"DisplayIcon"="C:\\Program Files\\Mesh Agent\\MeshAgent.exe"
|
||||
"DisplayVersion"="2.1.3"
|
||||
"URLInfoAbout"="http://www.meshcentral.com/"
|
||||
"VersionMajor"=dword:00000002
|
||||
"VersionMinor"=dword:00000013
|
||||
"EstimatedSize"=dword:00208000
|
||||
"NoModify"=dword:00000001
|
||||
"NoRepair"=dword:00000001
|
||||
*/
|
||||
|
||||
int i;
|
||||
HKEY hKey;
|
||||
if (RegCreateKey(HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\MeshCentralAgent", &hKey) == ERROR_SUCCESS)
|
||||
{
|
||||
LPCTSTR str;
|
||||
char targetexe[_MAX_PATH + 40];
|
||||
size_t targetexelen = 0;
|
||||
|
||||
str = "MeshCentral Agent - Remote Control Software\0";
|
||||
RegSetValueEx(hKey, "DisplayName", 0, REG_SZ, (LPBYTE)str, (DWORD)strlen(str)+1);
|
||||
|
||||
str = "Open Source\0";
|
||||
RegSetValueEx(hKey, "Publisher", 0, REG_SZ, (LPBYTE)str, (DWORD)strlen(str) + 1);
|
||||
|
||||
str = "1\0";
|
||||
RegSetValueEx(hKey, "MajorVersion", 0, REG_SZ, (LPBYTE)str, (DWORD)strlen(str) + 1);
|
||||
|
||||
str = "0\0";
|
||||
RegSetValueEx(hKey, "MinorVersion", 0, REG_SZ, (LPBYTE)str, (DWORD)strlen(str) + 1);
|
||||
|
||||
// Install location
|
||||
if (SHGetFolderPathA(NULL, CSIDL_PROGRAM_FILES | CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, targetexe) != S_FALSE) {
|
||||
targetexelen = strnlen_s(targetexe, _MAX_PATH + 40);
|
||||
if (targetexelen <= MAX_PATH) {
|
||||
memcpy_s(targetexe + targetexelen, _MAX_PATH + 40 - targetexelen, "\\Mesh Agent\\\0", 13);
|
||||
RegSetValueEx(hKey, "InstallLocation", 0, REG_SZ, (LPBYTE)targetexe, (DWORD)strlen(targetexe) + 1);
|
||||
}
|
||||
}
|
||||
|
||||
// Uninstall command
|
||||
if (SHGetFolderPathA(NULL, CSIDL_PROGRAM_FILES | CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, targetexe) != S_FALSE) {
|
||||
targetexelen = strnlen_s(targetexe, _MAX_PATH + 40);
|
||||
if (targetexelen <= MAX_PATH) {
|
||||
memcpy_s(targetexe + targetexelen, _MAX_PATH + 40 - targetexelen, "\\Mesh Agent\\MeshAgent.exe -fulluninstall\0", 41);
|
||||
RegSetValueEx(hKey, "UninstallString", 0, REG_SZ, (LPBYTE)targetexe, (DWORD)strlen(targetexe) + 1);
|
||||
}
|
||||
}
|
||||
|
||||
// Display icon
|
||||
if (SHGetFolderPathA(NULL, CSIDL_PROGRAM_FILES | CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, targetexe) != S_FALSE) {
|
||||
targetexelen = strnlen_s(targetexe, _MAX_PATH + 40);
|
||||
if (targetexelen <= MAX_PATH) {
|
||||
memcpy_s(targetexe + targetexelen, _MAX_PATH + 40 - targetexelen, "\\Mesh Agent\\MeshAgent.exe\0", 26);
|
||||
RegSetValueEx(hKey, "DisplayIcon", 0, REG_SZ, (LPBYTE)targetexe, (DWORD)strlen(targetexe) + 1);
|
||||
}
|
||||
}
|
||||
|
||||
str = "1.0.0\0";
|
||||
RegSetValueEx(hKey, "DisplayVersion", 0, REG_SZ, (LPBYTE)str, (DWORD)strlen(str) + 1);
|
||||
|
||||
str = "http://www.meshcentral.com/\0"; // TODO - Change this to .msg content
|
||||
RegSetValueEx(hKey, "URLInfoAbout", 0, REG_SZ, (LPBYTE)str, (DWORD)strlen(str) + 1);
|
||||
|
||||
i = 2;
|
||||
RegSetValueEx(hKey, "VersionMajor", 0, REG_DWORD, (BYTE*)&i, (DWORD)4);
|
||||
|
||||
i = 13;
|
||||
RegSetValueEx(hKey, "VersionMinor", 0, REG_DWORD, (BYTE*)&i, (DWORD)4);
|
||||
|
||||
i = 0x00208000;
|
||||
RegSetValueEx(hKey, "EstimatedSize", 0, REG_DWORD, (BYTE*)&i, (DWORD)4);
|
||||
|
||||
i = 1;
|
||||
RegSetValueEx(hKey, "NoModify", 0, REG_DWORD, (BYTE*)&i, (DWORD)4);
|
||||
RegSetValueEx(hKey, "NoRepair", 0, REG_DWORD, (BYTE*)&i, (DWORD)4);
|
||||
|
||||
RegCloseKey(hKey);
|
||||
}
|
||||
else
|
||||
{
|
||||
printf("Error writing to registry, try running as administrator.");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
void WINAPI RemoveUninstallIcon()
|
||||
{
|
||||
RegDeleteKey(HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\MeshCentralAgent");
|
||||
}
|
||||
|
||||
|
||||
@@ -127,7 +278,7 @@ void WINAPI ServiceMain(DWORD argc, LPTSTR *argv)
|
||||
serviceStatus.dwServiceSpecificExitCode = NO_ERROR;
|
||||
serviceStatus.dwCheckPoint = 0;
|
||||
serviceStatus.dwWaitHint = 0;
|
||||
serviceStatusHandle = RegisterServiceCtrlHandler(serviceName, ServiceControlHandler);
|
||||
serviceStatusHandle = RegisterServiceCtrlHandlerExA(serviceName, (LPHANDLER_FUNCTION_EX)ServiceControlHandler, NULL);
|
||||
|
||||
if (serviceStatusHandle)
|
||||
{
|
||||
@@ -136,7 +287,7 @@ void WINAPI ServiceMain(DWORD argc, LPTSTR *argv)
|
||||
SetServiceStatus(serviceStatusHandle, &serviceStatus);
|
||||
|
||||
// Service running
|
||||
serviceStatus.dwControlsAccepted |= (SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN);
|
||||
serviceStatus.dwControlsAccepted |= (SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN | SERVICE_ACCEPT_POWEREVENT | SERVICE_ACCEPT_SESSIONCHANGE);
|
||||
serviceStatus.dwCurrentState = SERVICE_RUNNING;
|
||||
SetServiceStatus( serviceStatusHandle, &serviceStatus);
|
||||
|
||||
@@ -156,7 +307,7 @@ void WINAPI ServiceMain(DWORD argc, LPTSTR *argv)
|
||||
|
||||
__try
|
||||
{
|
||||
agent = MeshAgent_Create();
|
||||
agent = MeshAgent_Create(0);
|
||||
MeshAgent_Start(agent, 1, selfexe_ptr);
|
||||
agent = NULL;
|
||||
}
|
||||
@@ -252,7 +403,7 @@ BOOL InstallService()
|
||||
}
|
||||
else
|
||||
{
|
||||
ILIBMESSAGE2("Mesh service was not Installed Successfully. Error Code %d", (int)GetLastError());
|
||||
ILIBMESSAGE("Mesh service was not Installed Successfully.");
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -409,21 +560,22 @@ int StopService(LPCSTR servicename)
|
||||
return r;
|
||||
}
|
||||
|
||||
int RunProcess(char* exe)
|
||||
int RunProcess(char* exe, int waitForExit)
|
||||
{
|
||||
BOOL r;
|
||||
BOOL r = TRUE;
|
||||
int count = 50;
|
||||
DWORD exitcode;
|
||||
STARTUPINFOA info = {sizeof(info)};
|
||||
PROCESS_INFORMATION processInfo;
|
||||
if (CreateProcessA(NULL, exe, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &info, &processInfo) == 0) return 0;
|
||||
if (waitForExit != 0) {
|
||||
do
|
||||
{
|
||||
Sleep(100);
|
||||
r = GetExitCodeProcess(processInfo.hProcess, &exitcode);
|
||||
if (exitcode == STILL_ACTIVE) r = 0;
|
||||
} while (r == 0 && count-- > 0);
|
||||
}
|
||||
while (r == 0 && count-- > 0);
|
||||
CloseHandle(processInfo.hProcess);
|
||||
CloseHandle(processInfo.hThread);
|
||||
return r;
|
||||
@@ -457,8 +609,20 @@ void fullinstall(int uninstallonly, char* proxy, int proxylen, char* tag, int ta
|
||||
int setup1len;
|
||||
int setup2len;
|
||||
|
||||
if (IsAdmin() == FALSE) { printf("Requires administrator permissions.\r\n"); return; }
|
||||
if (uninstallonly != 0) { printf("Performing uninstall...\r\n"); } else { printf("Performing install...\r\n"); }
|
||||
|
||||
// Stop and remove the service
|
||||
StopService(serviceFile);
|
||||
|
||||
// Wait for the service to stop
|
||||
int serviceStateLoopCount = 0;;
|
||||
int serviceState;
|
||||
do {
|
||||
serviceStateLoopCount++;
|
||||
Sleep(100);
|
||||
serviceState = GetServiceState(serviceFile);
|
||||
} while ((serviceState == 3) && (serviceStateLoopCount < 100));
|
||||
UninstallService(serviceFile);
|
||||
UninstallService(serviceFileOld);
|
||||
|
||||
@@ -474,8 +638,21 @@ void fullinstall(int uninstallonly, char* proxy, int proxylen, char* tag, int ta
|
||||
targetexelen += 25;
|
||||
}
|
||||
|
||||
// Check if we are uninstalling ourself
|
||||
if ((uninstallonly != 0) && (targetexelen == selfexelen) && (memcmp(selfexe, targetexe, targetexelen) == 0)) {
|
||||
// Copy ourself to a temp folder and run full uninstall.
|
||||
char tempPath[_MAX_PATH + 40];
|
||||
int tempPathLen = GetTempPathA(_MAX_PATH, tempPath);
|
||||
memcpy_s(tempPath + tempPathLen, _MAX_PATH + 40 - tempPathLen, "MeshAgent.exe\0", 15);
|
||||
remove(tempPath);
|
||||
util_CopyFile(selfexe, tempPath, FALSE);
|
||||
memcpy_s(tempPath + tempPathLen, _MAX_PATH + 40 - tempPathLen, "MeshAgent.exe -fulluninstall\0", 30);
|
||||
RunProcess(tempPath, 0); // Don't wait for the process to terminate since we want to self-delete.
|
||||
return;
|
||||
}
|
||||
|
||||
// Call uninstall, this will remove the firewall rules.
|
||||
RunProcess(targetexe2);
|
||||
RunProcess(targetexe2, 1);
|
||||
|
||||
#ifdef _MINCORE
|
||||
// Remove the MeshAgent registry keys
|
||||
@@ -487,12 +664,21 @@ void fullinstall(int uninstallonly, char* proxy, int proxylen, char* tag, int ta
|
||||
RegDeleteKey(HKEY_CURRENT_USER, "Software\\Open Source\\MeshAgent2");
|
||||
#endif
|
||||
|
||||
// Remove the uninstall icon from the control panel if present
|
||||
RemoveUninstallIcon();
|
||||
|
||||
// Check if selfexe is already located at the target, if so, skip to copy steps.
|
||||
if (targetexelen != selfexelen || memcmp(selfexe, targetexe, targetexelen) != 0)
|
||||
if ((uninstallonly != 0) || (targetexelen != selfexelen) || (memcmp(selfexe, targetexe, targetexelen) != 0))
|
||||
{
|
||||
// Remove the target executable.
|
||||
// Remove the target executable, wait if needed
|
||||
int selfExeDelLoopCount = 0;;
|
||||
int selfExeDel;
|
||||
targetexe[targetexelen] = 0;
|
||||
remove(targetexe);
|
||||
do {
|
||||
Sleep(100);
|
||||
selfExeDelLoopCount++;
|
||||
selfExeDel = remove(targetexe);
|
||||
} while ((selfExeDel != 0) && (selfExeDel != -1) && (selfExeDelLoopCount < 100));
|
||||
|
||||
// Remove "[Executable].msh" file
|
||||
if ((setup2len = (int)strnlen_s(targetexe, _MAX_PATH + 40)) < 4 || setup2len > 259) return;
|
||||
@@ -648,6 +834,9 @@ void fullinstall(int uninstallonly, char* proxy, int proxylen, char* tag, int ta
|
||||
}
|
||||
}
|
||||
|
||||
// Add the uninstall icon in the control panel
|
||||
AddUninstallIcon();
|
||||
|
||||
/*
|
||||
#if defined(_LINKVM)
|
||||
// Setup the SendSAS permission
|
||||
@@ -657,9 +846,9 @@ void fullinstall(int uninstallonly, char* proxy, int proxylen, char* tag, int ta
|
||||
|
||||
// Attempt to start the updated service up again
|
||||
memcpy(targetexe + targetexelen, "\" -install", 11);
|
||||
r = RunProcess(targetexe2);
|
||||
r = RunProcess(targetexe2, 1);
|
||||
memcpy(targetexe + targetexelen, "\" -start", 9);
|
||||
r = RunProcess(targetexe2);
|
||||
r = RunProcess(targetexe2, 1);
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -706,18 +895,32 @@ int main(int argc, char* argv[])
|
||||
|
||||
//CoInitializeEx(NULL, COINIT_MULTITHREADED);
|
||||
|
||||
if (argc > 2 && memcmp(argv[1], "-faddr", 6) == 0)
|
||||
if (argc > 2 && strcasecmp(argv[1], "-faddr") == 0)
|
||||
{
|
||||
uint64_t addrOffset;
|
||||
util_hexToBuf(argv[2] + 2, (int)strnlen_s(argv[2], 130) - 2, (char*)&addrOffset);
|
||||
ILibChain_DebugOffset(ILibScratchPad, sizeof(ILibScratchPad), addrOffset);
|
||||
#ifdef WIN64
|
||||
uint64_t addrOffset = 0;
|
||||
sscanf_s(argv[2] + 2, "%016llx", &addrOffset);
|
||||
#else
|
||||
uint32_t addrOffset = 0;
|
||||
sscanf_s(argv[2] + 2, "%x", &addrOffset);
|
||||
#endif
|
||||
ILibChain_DebugOffset(ILibScratchPad, sizeof(ILibScratchPad), (uint64_t)addrOffset);
|
||||
printf("%s", ILibScratchPad);
|
||||
return(0);
|
||||
}
|
||||
|
||||
if (argc > 2 && strcasecmp(argv[1], "-fdelta") == 0)
|
||||
{
|
||||
uint64_t delta = 0;
|
||||
sscanf_s(argv[2], "%lld", &delta);
|
||||
ILibChain_DebugDelta(ILibScratchPad, sizeof(ILibScratchPad), delta);
|
||||
printf("%s", ILibScratchPad);
|
||||
return(0);
|
||||
}
|
||||
|
||||
char *integratedJavaScript;
|
||||
int integragedJavaScriptLen;
|
||||
ILibDuktape_ScriptContainer_CheckEmbedded(argv, &integratedJavaScript, &integragedJavaScriptLen);
|
||||
ILibDuktape_ScriptContainer_CheckEmbedded(&integratedJavaScript, &integragedJavaScriptLen);
|
||||
|
||||
CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
|
||||
|
||||
@@ -765,7 +968,6 @@ int main(int argc, char* argv[])
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
#ifdef _MINCORE
|
||||
if (argc > 1 && strcasecmp(argv[1], "-signcheck") == 0)
|
||||
{
|
||||
@@ -776,17 +978,20 @@ int main(int argc, char* argv[])
|
||||
return 0;
|
||||
}
|
||||
#else
|
||||
else if (integratedJavaScript != NULL || (argc > 1 && ((strcasecmp(argv[1], "run") == 0) || (strcasecmp(argv[1], "--slave") == 0))))
|
||||
|
||||
if (integratedJavaScript != NULL || (argc > 0 && strcasecmp(argv[0], "--slave") == 0) || (argc > 1 && ((strcasecmp(argv[1], "run") == 0) || (strcasecmp(argv[1], "connect") == 0) || (strcasecmp(argv[1], "--slave") == 0))))
|
||||
{
|
||||
// Run the mesh agent in console mode, since the agent is compiled for windows service, the KVM will not work right. This is only good for testing.
|
||||
SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE); // Set SIGNAL on windows to listen for Ctrl-C
|
||||
|
||||
__try
|
||||
{
|
||||
agent = MeshAgent_Create();
|
||||
int capabilities = 0;
|
||||
if (argc > 1 && ((strcasecmp(argv[1], "connect") == 0))) { capabilities = MeshCommand_AuthInfo_CapabilitiesMask_TEMPORARY; }
|
||||
agent = MeshAgent_Create(capabilities);
|
||||
agent->meshCoreCtx_embeddedScript = integratedJavaScript;
|
||||
agent->meshCoreCtx_embeddedScriptLen = integragedJavaScriptLen;
|
||||
if (integratedJavaScript != NULL || (argc > 1 && strcasecmp(argv[1], "run") == 0)) { agent->runningAsConsole = 1; }
|
||||
if (integratedJavaScript != NULL || (argc > 1 && (strcasecmp(argv[1], "run") == 0 || strcasecmp(argv[1], "connect") == 0))) { agent->runningAsConsole = 1; }
|
||||
MeshAgent_Start(agent, argc, argv);
|
||||
retCode = agent->exitCode;
|
||||
MeshAgent_Destroy(agent);
|
||||
@@ -1050,7 +1255,7 @@ int main(int argc, char* argv[])
|
||||
}
|
||||
else
|
||||
{
|
||||
printf("Error writing to registry, try running this as administrator.");
|
||||
printf("Error writing to registry, try running as administrator.");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -1062,9 +1267,12 @@ int main(int argc, char* argv[])
|
||||
// See if we need to run as a script engine
|
||||
if (argc >= 2 && ILibString_EndsWith(argv[1], -1, ".js", 3) != 0)
|
||||
{
|
||||
SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE); // Set SIGNAL on windows to listen for Ctrl-C
|
||||
|
||||
__try
|
||||
{
|
||||
agent = MeshAgent_Create();
|
||||
agent = MeshAgent_Create(0);
|
||||
agent->runningAsConsole = 1;
|
||||
MeshAgent_Start(agent, argc, argv);
|
||||
MeshAgent_Destroy(agent);
|
||||
}
|
||||
@@ -1076,9 +1284,9 @@ int main(int argc, char* argv[])
|
||||
else
|
||||
{
|
||||
#ifdef _MINCORE
|
||||
printf("Mesh Agent available switches:\r\n start Start the service.\r\n restart Restart the service.\r\n stop Stop the service.\r\n state Display the running state of the service.\r\n -signcheck Perform self-check.\r\n -install Install the service from this location.\r\n -uninstall Remove the service from this location.\r\n -nodeidhex Return the current agent identifier.\r\n -proxy:host:port Specifiy an HTTPS proxy (after -fullinstall only).\r\n -tag:xxx Specifiy a agent tag (after -fullinstall only).\r\n\r\n -resetnodeid Reset the NodeID next time the service is started.");
|
||||
printf("Mesh Agent available switches:\r\n run Start as a console agent.\r\n connect Start as a temporary console agent.\r\n restart Restart the service.\r\n stop Stop the service.\r\n state Display the running state of the service.\r\n -signcheck Perform self-check.\r\n -install Install the service from this location.\r\n -uninstall Remove the service from this location.\r\n -nodeidhex Return the current agent identifier.\r\n -proxy:host:port Specifiy an HTTPS proxy (after -fullinstall only).\r\n -tag:xxx Specifiy a agent tag (after -fullinstall only).\r\n\r\n -resetnodeid Reset the NodeID next time the service is started.");
|
||||
#else
|
||||
printf("Mesh Agent available switches:\r\n start Start the service.\r\n restart Restart the service.\r\n stop Stop the service.\r\n state Display the running state of the service.\r\n -signcheck Perform self-check.\r\n -install Install the service from this location.\r\n -uninstall Remove the service from this location.\r\n -nodeidhex Return the current agent identifier.\r\n -fullinstall Copy agent into program files, install and launch.\r\n -fulluninstall Stop agent and clean up the program files location.\r\n -proxy:host:port Specifiy an HTTPS proxy (after -fullinstall only).\r\n -tag:xxx Specifiy a agent tag (after -fullinstall only).\r\n -resetnodeid Reset the NodeID next time the service is started.");
|
||||
printf("Mesh Agent available switches:\r\n run Start as a console agent.\r\n connect Start as a temporary console agent.\r\n start Start the service.\r\n restart Restart the service.\r\n stop Stop the service.\r\n state Display the running state of the service.\r\n -signcheck Perform self-check.\r\n -install Install the service from this location.\r\n -uninstall Remove the service from this location.\r\n -nodeidhex Return the current agent identifier.\r\n -fullinstall Copy agent into program files, install and launch.\r\n -fulluninstall Stop agent and clean up the program files location.\r\n -proxy:host:port Specifiy an HTTPS proxy (after -fullinstall only).\r\n -tag:xxx Specifiy a agent tag (after -fullinstall only).\r\n -resetnodeid Reset the NodeID next time the service is started.");
|
||||
#endif
|
||||
}
|
||||
}
|
||||
@@ -1182,6 +1390,42 @@ char* getMshSettings(char* fileName, char* selfexe, char** meshname, char** mesh
|
||||
|
||||
#ifndef _MINCORE
|
||||
|
||||
// Start as a temporary mesh agent.
|
||||
DWORD WINAPI StartTempAgent(_In_ LPVOID lpParameter)
|
||||
{
|
||||
CONTEXT winException;
|
||||
char selfexe[_MAX_PATH];
|
||||
char *selfexe_ptr[] = { selfexe };
|
||||
WCHAR str[_MAX_PATH];
|
||||
size_t len;
|
||||
char *integratedJavaScript;
|
||||
int integragedJavaScriptLen;
|
||||
ILibDuktape_ScriptContainer_CheckEmbedded(&integratedJavaScript, &integragedJavaScriptLen);
|
||||
|
||||
CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
|
||||
|
||||
// Get our own executable name
|
||||
if (GetModuleFileNameW(NULL, str, _MAX_PATH) > 5) { wcstombs_s(&len, selfexe, _MAX_PATH, str, _MAX_PATH); }
|
||||
|
||||
__try
|
||||
{
|
||||
agent = MeshAgent_Create(MeshCommand_AuthInfo_CapabilitiesMask_TEMPORARY);
|
||||
agent->meshCoreCtx_embeddedScript = integratedJavaScript;
|
||||
agent->meshCoreCtx_embeddedScriptLen = integragedJavaScriptLen;
|
||||
agent->runningAsConsole = 1;
|
||||
MeshAgent_Start(agent, 1, selfexe_ptr);
|
||||
//retCode = agent->exitCode;
|
||||
MeshAgent_Destroy(agent);
|
||||
}
|
||||
__except (ILib_WindowsExceptionFilter(GetExceptionCode(), GetExceptionInformation(), &winException))
|
||||
{
|
||||
ILib_WindowsExceptionDebug(&winException);
|
||||
}
|
||||
|
||||
CoUninitialize();
|
||||
return(0);
|
||||
}
|
||||
|
||||
// Message handler for dialog box.
|
||||
INT_PTR CALLBACK DialogHandler(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
|
||||
{
|
||||
@@ -1242,7 +1486,7 @@ INT_PTR CALLBACK DialogHandler(HWND hDlg, UINT message, WPARAM wParam, LPARAM lP
|
||||
|
||||
if ((dwSize = GetFileVersionInfoSize(selfexe, NULL)))
|
||||
{
|
||||
pVersionInfo = malloc(dwSize);
|
||||
if ((pVersionInfo = malloc(dwSize)) == NULL) { ILIBCRITICALEXIT(254); }
|
||||
if (GetFileVersionInfo(selfexe, 0, dwSize, pVersionInfo))
|
||||
{
|
||||
if (VerQueryValue(pVersionInfo, TEXT("\\"), (LPVOID*)&pFileInfo, &pLenFileInfo))
|
||||
@@ -1274,6 +1518,11 @@ INT_PTR CALLBACK DialogHandler(HWND hDlg, UINT message, WPARAM wParam, LPARAM lP
|
||||
SetWindowTextA(GetDlgItem(hDlg, IDC_SERVERLOCATION), (serverurl != NULL) ? serverurl : "(None)");
|
||||
SetWindowTextA(GetDlgItem(hDlg, IDC_SERVERID), (serverid != NULL) ? serverid : "(None)");
|
||||
free(mshfile);
|
||||
if (meshid == NULL) { EnableWindow(GetDlgItem(hDlg, IDC_CONNECTBUTTON), FALSE); }
|
||||
}
|
||||
else
|
||||
{
|
||||
EnableWindow(GetDlgItem(hDlg, IDC_CONNECTBUTTON), FALSE);
|
||||
}
|
||||
|
||||
return (INT_PTR)TRUE;
|
||||
@@ -1306,6 +1555,14 @@ INT_PTR CALLBACK DialogHandler(HWND hDlg, UINT message, WPARAM wParam, LPARAM lP
|
||||
|
||||
return (INT_PTR)TRUE;
|
||||
}
|
||||
else if (LOWORD(wParam) == IDC_CONNECTBUTTON) {
|
||||
EnableWindow(GetDlgItem(hDlg, IDC_INSTALLBUTTON), FALSE);
|
||||
EnableWindow(GetDlgItem(hDlg, IDC_UNINSTALLBUTTON), FALSE);
|
||||
EnableWindow(GetDlgItem(hDlg, IDC_CONNECTBUTTON), FALSE);
|
||||
SetWindowTextA(GetDlgItem(hDlg, IDC_STATUSTEXT), "Running as temporary agent");
|
||||
CreateThread(NULL, 0, &StartTempAgent, NULL, 0, NULL);
|
||||
return (INT_PTR)TRUE;
|
||||
}
|
||||
break;
|
||||
}
|
||||
return (INT_PTR)FALSE;
|
||||
@@ -1321,4 +1578,3 @@ HANDLE WINAPI CreateSemaphoreW(_In_opt_ LPSECURITY_ATTRIBUTES lpSemaphoreAttrib
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
@@ -13,6 +13,8 @@
|
||||
#define IDC_HASHTEXT 1007
|
||||
#define IDC_HASHTEXT2 1008
|
||||
#define IDC_POLICYTEXT 1008
|
||||
#define IDC_UNINSTALLBUTTON2 1009
|
||||
#define IDC_CONNECTBUTTON 1009
|
||||
#define IDC_HASHTEXT3 1011
|
||||
#define IDC_SERVERID 1011
|
||||
#define IDC_SERVERLOCATION 1012
|
||||
|
||||
@@ -30,7 +30,92 @@ limitations under the License.
|
||||
#endif
|
||||
|
||||
#define ILibDuktape_ModSearch_ModuleFile (void*)0xFF
|
||||
#define ILibDuktape_ModSearch_ModuleObject (void*)0xFE
|
||||
#define ILibDuktape_ModSearch_JSInclude "\xFF_ModSearch_JSINCLUDE"
|
||||
#define ILibDuktape_ModSearch_ModulePath "\xFF_ModSearch_Path"
|
||||
|
||||
duk_ret_t ILibDuktape_ModSearch_GetJSModule(duk_context *ctx, char *id)
|
||||
{
|
||||
ILibHashtable table = NULL;
|
||||
int idLen = (int)strnlen_s(id, 1024);
|
||||
char *retVal = NULL;
|
||||
|
||||
duk_push_heap_stash(ctx); // [stash]
|
||||
if (duk_has_prop_string(ctx, -1, "ModSearchTable"))
|
||||
{
|
||||
duk_get_prop_string(ctx, -1, "ModSearchTable"); // [stash][ptr]
|
||||
table = (ILibHashtable)duk_to_pointer(ctx, -1);
|
||||
duk_pop(ctx); // [stash]
|
||||
}
|
||||
else
|
||||
{
|
||||
table = ILibHashtable_Create();
|
||||
duk_push_pointer(ctx, table); // [stash][ptr]
|
||||
duk_put_prop_string(ctx, -2, "ModSearchTable"); // [stash]
|
||||
}
|
||||
duk_pop(ctx); // ...
|
||||
|
||||
retVal = ILibHashtable_Get(table, ILibDuktape_ModSearch_ModuleFile, id, idLen);
|
||||
if (retVal == NULL)
|
||||
{
|
||||
duk_push_heap_stash(ctx);
|
||||
char *mpath;
|
||||
duk_size_t mpathLen;
|
||||
mpath = Duktape_GetStringPropertyValueEx(ctx, -1, ILibDuktape_ModSearch_ModulePath, NULL, &mpathLen);
|
||||
duk_pop(ctx);
|
||||
|
||||
char *fileName = ILibMemory_AllocateA(idLen + 4 + mpathLen + 1);
|
||||
if (mpath == NULL)
|
||||
{
|
||||
sprintf_s(fileName, idLen + 4, "%s.js", id);
|
||||
}
|
||||
else
|
||||
{
|
||||
sprintf_s(fileName, idLen + 5 + mpathLen, "%s/%s.js", mpath, id);
|
||||
}
|
||||
int dataLen = ILibReadFileFromDiskEx(&retVal, fileName);
|
||||
if (dataLen > 0) { duk_push_lstring(ctx, retVal, dataLen); free(retVal); }
|
||||
else
|
||||
{
|
||||
return(0);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
duk_push_string(ctx, retVal);
|
||||
}
|
||||
return(1);
|
||||
}
|
||||
void ILibDuktape_ModSearch_AddModuleObject(duk_context *ctx, char *id, void *heapptr)
|
||||
{
|
||||
int idLen = (int)strnlen_s(id, 1024);
|
||||
ILibHashtable table = NULL;
|
||||
|
||||
duk_push_heap_stash(ctx); // [stash]
|
||||
if (duk_has_prop_string(ctx, -1, "ModSearchTable"))
|
||||
{
|
||||
duk_get_prop_string(ctx, -1, "ModSearchTable"); // [stash][ptr]
|
||||
table = (ILibHashtable)duk_to_pointer(ctx, -1);
|
||||
duk_pop(ctx); // [stash]
|
||||
}
|
||||
else
|
||||
{
|
||||
table = ILibHashtable_Create();
|
||||
duk_push_pointer(ctx, table); // [stash][ptr]
|
||||
duk_put_prop_string(ctx, -2, "ModSearchTable"); // [stash]
|
||||
}
|
||||
|
||||
duk_push_heapptr(ctx, heapptr);
|
||||
duk_put_prop_string(ctx, -2, Duktape_GetStashKey(heapptr));
|
||||
heapptr = ILibHashtable_Put(table, ILibDuktape_ModSearch_ModuleObject, id, idLen, heapptr);
|
||||
|
||||
if (heapptr != NULL)
|
||||
{
|
||||
// Remove the old object that was in the table
|
||||
duk_del_prop_string(ctx, -1, Duktape_GetStashKey(heapptr));
|
||||
}
|
||||
duk_pop(ctx); // ...
|
||||
}
|
||||
int ILibDuktape_ModSearch_AddModule(duk_context *ctx, char *id, char *module, int moduleLen)
|
||||
{
|
||||
ILibHashtable table = NULL;
|
||||
@@ -89,8 +174,20 @@ duk_ret_t mod_Search_Files(duk_context *ctx, char* id)
|
||||
char fileName[255];
|
||||
char *data;
|
||||
int dataLen;
|
||||
char *mpath = NULL;
|
||||
|
||||
duk_push_heap_stash(ctx);
|
||||
mpath = Duktape_GetStringPropertyValue(ctx, -1, ILibDuktape_ModSearch_ModulePath, NULL);
|
||||
duk_pop(ctx);
|
||||
|
||||
if (mpath == NULL)
|
||||
{
|
||||
sprintf_s(fileName, sizeof(fileName), "%s.js", id);
|
||||
}
|
||||
else
|
||||
{
|
||||
sprintf_s(fileName, sizeof(fileName), "%s/%s.js", mpath, id);
|
||||
}
|
||||
dataLen = ILibReadFileFromDiskEx(&data, fileName);
|
||||
if (dataLen > 0)
|
||||
{
|
||||
@@ -118,6 +215,13 @@ duk_ret_t mod_Search_Files(duk_context *ctx, char* id)
|
||||
return DUK_RET_ERROR;
|
||||
}
|
||||
}
|
||||
void ILibDuktape_ModSearch_AddHandler_AlsoIncludeJS(duk_context *ctx, char *js, size_t jsLen)
|
||||
{
|
||||
duk_push_heap_stash(ctx); // [stash]
|
||||
duk_push_lstring(ctx, js, jsLen); // [stash][str]
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_ModSearch_JSInclude); // [stash]
|
||||
duk_pop(ctx); // ...
|
||||
}
|
||||
|
||||
duk_ret_t mod_Search(duk_context *ctx)
|
||||
{
|
||||
@@ -128,6 +232,7 @@ duk_ret_t mod_Search(duk_context *ctx)
|
||||
void *chain;
|
||||
ILibSimpleDataStore mDS = NULL;
|
||||
char *module;
|
||||
void *j;
|
||||
|
||||
if (!duk_is_string(ctx, 0)) { return ILibDuktape_Error(ctx, "mod_search(): Invalid 'ID' parameter"); }
|
||||
id = (char*)duk_get_lstring(ctx, 0, &idLen);
|
||||
@@ -142,8 +247,17 @@ duk_ret_t mod_Search(duk_context *ctx)
|
||||
duk_push_heap_stash(ctx);
|
||||
duk_get_prop_string(ctx, -1, "ModSearchTable");
|
||||
table = (ILibHashtable)duk_to_pointer(ctx, -1);
|
||||
func = (ILibDuktape_ModSearch_PUSH_Object)ILibHashtable_Get(table, NULL, id, (int)idLen);
|
||||
|
||||
// First check if there is a JS override
|
||||
j = ILibHashtable_Get(table, ILibDuktape_ModSearch_ModuleObject, id, (int)idLen);
|
||||
if (j != NULL)
|
||||
{
|
||||
duk_push_heapptr(ctx, j);
|
||||
duk_put_prop_string(ctx, 3, "exports");
|
||||
return(0);
|
||||
}
|
||||
|
||||
func = (ILibDuktape_ModSearch_PUSH_Object)ILibHashtable_Get(table, NULL, id, (int)idLen);
|
||||
if (func == NULL)
|
||||
{
|
||||
if ((module = (char*)ILibHashtable_Get(table, ILibDuktape_ModSearch_ModuleFile, id, (int)idLen)) != NULL)
|
||||
@@ -173,20 +287,32 @@ duk_ret_t mod_Search(duk_context *ctx)
|
||||
}
|
||||
else
|
||||
{
|
||||
sprintf_s(key, sizeof(key), "Module: %s (NOT FOUND in DB)", id);
|
||||
duk_push_string(ctx, key);
|
||||
duk_throw(ctx);
|
||||
return DUK_RET_ERROR;
|
||||
return mod_Search_Files(ctx, id);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// Init this temp value, to detect if the module wants to add JS code
|
||||
duk_push_heap_stash(ctx);
|
||||
duk_del_prop_string(ctx, -1, ILibDuktape_ModSearch_JSInclude);
|
||||
duk_pop(ctx);
|
||||
|
||||
func(ctx, chain);
|
||||
duk_put_prop_string(ctx, 3, "exports");
|
||||
|
||||
duk_push_heap_stash(ctx);
|
||||
if (duk_has_prop_string(ctx, -1, ILibDuktape_ModSearch_JSInclude))
|
||||
{
|
||||
duk_get_prop_string(ctx, -1, ILibDuktape_ModSearch_JSInclude);
|
||||
return(1);
|
||||
}
|
||||
else
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
void ILibDuktape_ModSearch_Destroy(duk_context *ctx, void *user)
|
||||
{
|
||||
duk_push_heap_stash(ctx); // [stash]
|
||||
@@ -202,6 +328,23 @@ void ILibDuktape_ModSearch_Destroy(duk_context *ctx, void *user)
|
||||
duk_pop(ctx);
|
||||
}
|
||||
}
|
||||
|
||||
duk_ret_t ILibDuktape_ModSearch_setModulePath(duk_context *ctx)
|
||||
{
|
||||
if (duk_is_string(ctx, 0))
|
||||
{
|
||||
duk_push_heap_stash(ctx);
|
||||
duk_dup(ctx, 0);
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_ModSearch_ModulePath);
|
||||
}
|
||||
else
|
||||
{
|
||||
return(ILibDuktape_Error(ctx, "Invalid Path"));
|
||||
}
|
||||
|
||||
return(0);
|
||||
}
|
||||
|
||||
void ILibDuktape_ModSearch_Init(duk_context * ctx, void * chain, ILibSimpleDataStore mDB)
|
||||
{
|
||||
duk_module_duktape_init(ctx);
|
||||
@@ -225,5 +368,10 @@ void ILibDuktape_ModSearch_Init(duk_context * ctx, void * chain, ILibSimpleDataS
|
||||
duk_put_prop_string(ctx, -2, "modSearch"); // [globalString]
|
||||
duk_pop(ctx); // ...
|
||||
|
||||
duk_push_global_object(ctx); // [g]
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "setModulePath", ILibDuktape_ModSearch_setModulePath, 1);
|
||||
duk_pop(ctx); // ...
|
||||
|
||||
|
||||
ILibDuktape_Helper_AddHeapFinalizer(ctx, ILibDuktape_ModSearch_Destroy, NULL);
|
||||
}
|
||||
|
||||
@@ -23,7 +23,10 @@ limitations under the License.
|
||||
typedef void (*ILibDuktape_ModSearch_PUSH_Object)(duk_context *ctx, void *chain);
|
||||
|
||||
int ILibDuktape_ModSearch_AddHandler(duk_context *ctx, char *id, ILibDuktape_ModSearch_PUSH_Object handler);
|
||||
void ILibDuktape_ModSearch_AddHandler_AlsoIncludeJS(duk_context *ctx, char *js, size_t jsLen);
|
||||
int ILibDuktape_ModSearch_AddModule(duk_context *ctx, char *id, char *module, int moduleLen);
|
||||
void ILibDuktape_ModSearch_AddModuleObject(duk_context *ctx, char *id, void *heapptr);
|
||||
duk_ret_t ILibDuktape_ModSearch_GetJSModule(duk_context *ctx, char *id);
|
||||
void ILibDuktape_ModSearch_Init(duk_context *ctx, void *chain, ILibSimpleDataStore mDB);
|
||||
|
||||
#endif
|
||||
|
||||
@@ -137,6 +137,8 @@ ILibDuktape_ChildProcess_SubProcess* ILibDuktape_ChildProcess_SpawnedProcess_PUS
|
||||
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "kill", ILibDuktape_ChildProcess_Kill, 0);
|
||||
|
||||
if (ILibProcessPipe_Process_IsDetached(mProcess) == 0)
|
||||
{
|
||||
duk_push_object(ctx);
|
||||
ILibDuktape_WriteID(ctx, "childProcess.subProcess.stdout");
|
||||
duk_dup(ctx, -2);
|
||||
@@ -164,7 +166,11 @@ ILibDuktape_ChildProcess_SubProcess* ILibDuktape_ChildProcess_SpawnedProcess_PUS
|
||||
ILibDuktape_ChildProcess_SubProcess_StdOutHandler,
|
||||
ILibDuktape_ChildProcess_SubProcess_StdErrHandler,
|
||||
ILibDuktape_ChildProcess_SubProcess_SendOK, retVal);
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
if (callback != NULL) { ILibDuktape_EventEmitter_AddOnce(emitter, "exit", callback); }
|
||||
}
|
||||
return(retVal);
|
||||
}
|
||||
|
||||
@@ -189,6 +195,10 @@ duk_ret_t ILibDuktape_ChildProcess_execFile(duk_context *ctx)
|
||||
void *callback = NULL;
|
||||
ILibProcessPipe_Process p = NULL;
|
||||
ILibProcessPipe_SpawnTypes spawnType = ILibProcessPipe_SpawnTypes_DEFAULT;
|
||||
#ifndef WIN32
|
||||
int uid = -1;
|
||||
#endif
|
||||
|
||||
|
||||
for (i = 0; i < nargs; ++i)
|
||||
{
|
||||
@@ -215,6 +225,9 @@ duk_ret_t ILibDuktape_ChildProcess_execFile(duk_context *ctx)
|
||||
{
|
||||
// Options
|
||||
spawnType = (ILibProcessPipe_SpawnTypes)Duktape_GetIntPropertyValue(ctx, i, "type", (int)ILibProcessPipe_SpawnTypes_DEFAULT);
|
||||
#ifndef WIN32
|
||||
uid = Duktape_GetIntPropertyValue(ctx, i, "uid", -1);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@@ -237,7 +250,11 @@ duk_ret_t ILibDuktape_ChildProcess_execFile(duk_context *ctx)
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef WIN32
|
||||
p = ILibProcessPipe_Manager_SpawnProcessEx2(manager, target, args, spawnType, 0);
|
||||
#else
|
||||
p = ILibProcessPipe_Manager_SpawnProcessEx3(manager, target, args, spawnType, (void*)(uint64_t)uid, 0);
|
||||
#endif
|
||||
if (p == NULL)
|
||||
{
|
||||
return(ILibDuktape_Error(ctx, "child_process.execFile(): Could not exec [%s]", target));
|
||||
@@ -263,6 +280,8 @@ void ILibDuktape_ChildProcess_PUSH(duk_context *ctx, void *chain)
|
||||
duk_put_prop_string(ctx, -2, "WINLOGON");
|
||||
duk_push_int(ctx, 3);
|
||||
duk_put_prop_string(ctx, -2, "TERM");
|
||||
duk_push_int(ctx, 4);
|
||||
duk_put_prop_string(ctx, -2, "DETACHED");
|
||||
duk_put_prop_string(ctx, -2, "SpawnTypes");
|
||||
}
|
||||
void ILibDuktape_ChildProcess_Init(duk_context *ctx)
|
||||
|
||||
@@ -21,14 +21,34 @@ limitations under the License.
|
||||
|
||||
#include "microstack/ILibParsers.h"
|
||||
#include "microstack/ILibAsyncServerSocket.h"
|
||||
#include "microstack/ILibSimpleDataStore.h"
|
||||
#include "ILibDuktape_Helpers.h"
|
||||
#include "duktape.h"
|
||||
#include "ILibDuktape_ScriptContainer.h"
|
||||
#include "ILibDuktape_Debugger.h"
|
||||
#include "ILibDuktapeModSearch.h"
|
||||
|
||||
|
||||
#define ILibDuktape_Debugger_SCRIPT_SOURCE "_scriptSourceForDebugger"
|
||||
#define ILibDuktape_Debugger_SCRIPT_PATH "_scriptPathForDebugger"
|
||||
#define ILibDuktape_Debugger_AttachOptions "\xFF_debugger_attachOptions"
|
||||
#define ILibDuktape_Debugger_Options_Rejector "\xFF_rejector"
|
||||
#define ILibDuktape_Debugger_Options_Resolver "\xFF_resolver"
|
||||
#define ILibDuktape_Debugger_DebugObject "_DbgObj"
|
||||
#define ILibDuktape_Debugger_HostChain "_HostChain"
|
||||
#define ILibDuktape_Debugger_MemoryReportInterval "_Debugger_MemoryReporting"
|
||||
extern size_t ILibDuktape_ScriptContainer_TotalAllocations;
|
||||
|
||||
typedef struct ILibDuktape_Debugger
|
||||
{
|
||||
ILibChain_Link *chainedObject;
|
||||
duk_context *ctx;
|
||||
duk_thread_state hoststate;
|
||||
sem_t hostlock;
|
||||
int waitConnection;
|
||||
void *debugThread;
|
||||
int webport;
|
||||
void *interval;
|
||||
char data[sizeof(char*)];
|
||||
#ifdef WIN32
|
||||
SOCKET listener;
|
||||
SOCKET client;
|
||||
@@ -38,7 +58,130 @@ typedef struct ILibDuktape_Debugger
|
||||
#endif
|
||||
}ILibDuktape_Debugger;
|
||||
|
||||
void *DebugWebEngine_Context;
|
||||
void *DebugWebEngine_Chain;
|
||||
void *DebugWebEngine_Thread;
|
||||
|
||||
void ILibDuktape_Debugger_AsyncWaitConn(ILibDuktape_Debugger *dbg);
|
||||
duk_ret_t ILibDuktape_Debugger_MemoryReportingSink(duk_context *ctx)
|
||||
{
|
||||
duk_push_string(ctx, "MemoryAllocations");
|
||||
duk_push_int(ctx, (duk_int_t)ILibDuktape_ScriptContainer_TotalAllocations);
|
||||
duk_debugger_notify(ctx, 2);
|
||||
return(0);
|
||||
}
|
||||
void ILibDuktape_Debugger_StartMemoryReporting(duk_context *ctx)
|
||||
{
|
||||
duk_push_global_object(ctx); // [g]
|
||||
duk_get_prop_string(ctx, -1, "setInterval"); // [g][setInterval]
|
||||
duk_swap_top(ctx, -2); // [setInterVal][this]
|
||||
duk_push_c_function(ctx, ILibDuktape_Debugger_MemoryReportingSink, 0); // [setInterVal][this][func]
|
||||
duk_push_int(ctx, 5000); // [setInterVal][this][func][delay]
|
||||
if (duk_pcall_method(ctx, 2) != 0) { duk_pop(ctx); return; } // [interval]
|
||||
duk_push_heap_stash(ctx); // [interval][stash]
|
||||
duk_swap_top(ctx, -2); // [stash][interval]
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_Debugger_MemoryReportInterval);// [stash]
|
||||
duk_pop(ctx); // ...
|
||||
}
|
||||
void ILibDuktape_Debugger_StopMemoryReporting(duk_context *ctx)
|
||||
{
|
||||
duk_push_heap_stash(ctx);
|
||||
duk_del_prop_string(ctx, -1, ILibDuktape_Debugger_MemoryReportInterval);
|
||||
duk_pop(ctx);
|
||||
}
|
||||
|
||||
void ILibDuktape_Debugger_Socket_finish(void *udata)
|
||||
{
|
||||
ILibDuktape_Debugger *dbg = (ILibDuktape_Debugger*)udata;
|
||||
|
||||
if (dbg->client != ~0)
|
||||
{
|
||||
#ifdef WIN32
|
||||
closesocket(dbg->client);
|
||||
#else
|
||||
shutdown(dbg->client, SHUT_RDWR);
|
||||
close(dbg->client);
|
||||
#endif
|
||||
dbg->client = ~0;
|
||||
}
|
||||
|
||||
ILibDuktape_Debugger_StopMemoryReporting(dbg->ctx);
|
||||
}
|
||||
|
||||
void ILibDuktape_Debugger_Socket_waitconn(void *udata)
|
||||
{
|
||||
ILibDuktape_Debugger *dbg = (ILibDuktape_Debugger*)udata;
|
||||
if (!ILibMemory_CanaryOK(dbg))
|
||||
{
|
||||
printf("INVALID CANARY\n");
|
||||
}
|
||||
|
||||
|
||||
dbg->client = accept(dbg->listener, NULL, NULL);
|
||||
((void**)dbg->data)[0] = dbg;
|
||||
|
||||
if (dbg->client == ~0)
|
||||
{
|
||||
#ifdef WIN32
|
||||
printf("Ooops, invalid socket: %d\n", WSAGetLastError());
|
||||
#else
|
||||
printf("Ooops, invalid socket: %d\n", errno);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
duk_size_t ILibDuktape_Debugger_PeekCB(void *udata)
|
||||
{
|
||||
ILibDuktape_Debugger *dbg = (ILibDuktape_Debugger*)udata;
|
||||
int bytes = 0;
|
||||
#ifndef WIN32
|
||||
char tmp[8];
|
||||
#endif
|
||||
|
||||
// Set the socket to non-blocking mode, because we need to play nice and share the MicroStack thread
|
||||
#if defined(WIN32)
|
||||
|
||||
if (dbg->client == ~0)
|
||||
{
|
||||
return(0);
|
||||
}
|
||||
|
||||
|
||||
//// On Windows must set NON_BLOCK to check this
|
||||
//int flags = 1;
|
||||
//ioctlsocket(dbg->client, FIONBIO, (u_long *)(&flags));
|
||||
|
||||
//bytes = recv(dbg->client, tmp, sizeof(tmp), MSG_PEEK);
|
||||
|
||||
//flags = 0;
|
||||
//ioctlsocket(dbg->client, FIONBIO, (u_long *)(&flags));
|
||||
u_long avail = 0;
|
||||
int rc = ioctlsocket(dbg->client, FIONREAD, &avail);
|
||||
if (rc != 0)
|
||||
{
|
||||
fprintf(stderr, "%s: ioctlsocket() returned %d, closing connection\n",
|
||||
__FILE__, rc);
|
||||
fflush(stderr);
|
||||
return(0);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (avail == 0)
|
||||
{
|
||||
return 0; /* nothing to read */
|
||||
}
|
||||
else
|
||||
{
|
||||
return 1; /* something to read */
|
||||
}
|
||||
}
|
||||
#else
|
||||
// Everything else, use MSG_DONTWAIT
|
||||
bytes = recv(dbg->client, tmp, sizeof(tmp), MSG_PEEK | MSG_DONTWAIT);
|
||||
#endif
|
||||
|
||||
return(bytes > 0 ? 1 : 0);
|
||||
}
|
||||
duk_size_t ILibDuktape_Debugger_ReadCB(void *udata, char *buffer, duk_size_t length)
|
||||
{
|
||||
ILibDuktape_Debugger *dbg = (ILibDuktape_Debugger*)udata;
|
||||
@@ -50,41 +193,554 @@ duk_size_t ILibDuktape_Debugger_WriteCB(void *udata, const char *buffer, duk_siz
|
||||
ILibDuktape_Debugger *dbg = (ILibDuktape_Debugger*)udata;
|
||||
return (duk_size_t)send(dbg->client, buffer, (int)length, 0);
|
||||
}
|
||||
void ILibDuktape_Debugger_DetachCB(void *udata)
|
||||
void ILibDuktape_Debugger_DetachCB(duk_context *ctx, void *udata)
|
||||
{
|
||||
ILibDuktape_Debugger_Socket_finish(udata);
|
||||
ILibDuktape_Debugger_AsyncWaitConn((ILibDuktape_Debugger*)udata);
|
||||
UNREFERENCED_PARAMETER(ctx);
|
||||
}
|
||||
|
||||
void ILibDuktape_Debugger_AsyncWaitConn_PreSelect(void* object, fd_set *readset, fd_set *writeset, fd_set *errorset, int* blocktime)
|
||||
{
|
||||
ILibDuktape_Debugger *dbg = (ILibDuktape_Debugger*)((void**)((ILibChain_Link*)object)->ExtraMemoryPtr)[0];
|
||||
if (dbg == NULL || !ILibMemory_CanaryOK(dbg))
|
||||
{
|
||||
((void**)((ILibChain_Link*)object)->ExtraMemoryPtr)[0] = NULL;
|
||||
ILibChain_SafeRemove(((ILibChain_Link*)object)->ParentChain, object);
|
||||
return;
|
||||
}
|
||||
|
||||
if (dbg->waitConnection != 0 && dbg->listener != (SOCKET)~0)
|
||||
{
|
||||
FD_SET(dbg->listener, readset);
|
||||
}
|
||||
}
|
||||
|
||||
void ILibDuktape_Debugger_AsyncWaitConn_PostSelect(void* object, int slct, fd_set *readset, fd_set *writeset, fd_set *errorset)
|
||||
{
|
||||
ILibDuktape_Debugger *dbg = (ILibDuktape_Debugger*)((void**)((ILibChain_Link*)object)->ExtraMemoryPtr)[0];
|
||||
if (dbg == NULL || !ILibMemory_CanaryOK(dbg)) { return; }
|
||||
|
||||
if (dbg->waitConnection != 0 && dbg->listener != (SOCKET)~0 && FD_ISSET(dbg->listener, readset))
|
||||
{
|
||||
dbg->waitConnection = 0;
|
||||
dbg->client = accept(dbg->listener, NULL, NULL);
|
||||
((void**)dbg->data)[0] = dbg;
|
||||
|
||||
if (dbg->client != ~0)
|
||||
{
|
||||
ILibDuktape_Debugger_StartMemoryReporting(dbg->ctx);
|
||||
duk_debugger_attach(dbg->ctx, ILibDuktape_Debugger_ReadCB, ILibDuktape_Debugger_WriteCB, ILibDuktape_Debugger_PeekCB, NULL, NULL, NULL, ILibDuktape_Debugger_DetachCB, (void*)dbg);
|
||||
}
|
||||
}
|
||||
}
|
||||
void ILibDuktape_Debugger_AsyncWaitConn(ILibDuktape_Debugger *dbg)
|
||||
{
|
||||
if (dbg->chainedObject == NULL)
|
||||
{
|
||||
dbg->chainedObject = ILibChain_Link_Allocate(sizeof(ILibChain_Link), sizeof(void*));
|
||||
((void**)dbg->chainedObject->ExtraMemoryPtr)[0] = dbg;
|
||||
dbg->chainedObject->PreSelectHandler = ILibDuktape_Debugger_AsyncWaitConn_PreSelect;
|
||||
dbg->chainedObject->PostSelectHandler = ILibDuktape_Debugger_AsyncWaitConn_PostSelect;
|
||||
ILibChain_SafeAdd(Duktape_GetChain(dbg->ctx), dbg->chainedObject);
|
||||
}
|
||||
else
|
||||
{
|
||||
ILibForceUnBlockChain(Duktape_GetChain(dbg->ctx));
|
||||
}
|
||||
dbg->waitConnection = 1;
|
||||
}
|
||||
|
||||
void ILibDuktape_Debugger_DestroyEx(void *chain, void *user)
|
||||
{
|
||||
duk_destroy_heap(DebugWebEngine_Context);
|
||||
}
|
||||
|
||||
void DebugWebEngine_RunEx(void *chain, void *user)
|
||||
{
|
||||
ILibChain_OnDestroyEvent_AddHandler(chain, ILibDuktape_Debugger_DestroyEx, NULL);
|
||||
if (duk_peval_string(DebugWebEngine_Context, "process.on('uncaughtException', function(e){console.log('Uncaught:', e);}); var duktape_debugger = require('duktape-debugger'); var dbg = new duktape_debugger(); dbg.run();") == 0)
|
||||
{
|
||||
printf("Debugger Initialized...\n");
|
||||
}
|
||||
else
|
||||
{
|
||||
printf("Unable to launch debugger client: %s\n", duk_safe_to_string(DebugWebEngine_Context, -1));
|
||||
}
|
||||
duk_pop(DebugWebEngine_Context);
|
||||
}
|
||||
|
||||
void DebugWebEngine_Run(void *obj)
|
||||
{
|
||||
ILibChain_RunOnMicrostackThreadEx(DebugWebEngine_Chain, DebugWebEngine_RunEx, NULL);
|
||||
ILibStartChain(DebugWebEngine_Chain);
|
||||
}
|
||||
void ILibDuktape_Debugger_Destroy(void *chain, void *user)
|
||||
{
|
||||
ILibStopChain(DebugWebEngine_Chain);
|
||||
#ifdef WIN32
|
||||
WaitForSingleObject(DebugWebEngine_Thread, INFINITE);
|
||||
#endif
|
||||
}
|
||||
|
||||
duk_ret_t ILibDuktape_Debugger_StartEngine_UpdatePort(duk_context *ctx)
|
||||
{
|
||||
duk_push_current_function(ctx);
|
||||
ILibDuktape_Debugger *dbg = (ILibDuktape_Debugger*)Duktape_GetPointerProperty(ctx, -1, ILibDuktape_Debugger_DebugObject);
|
||||
int port = duk_require_int(ctx, 0);
|
||||
if (dbg != NULL && ILibMemory_CanaryOK(dbg))
|
||||
{
|
||||
dbg->webport = port;
|
||||
sem_post(&(dbg->hostlock));
|
||||
}
|
||||
return(0);
|
||||
}
|
||||
void ILibDuktape_Debugger_hostCooperate_Sink(void *chain, void *user)
|
||||
{
|
||||
ILibDuktape_Debugger *dbg = (ILibDuktape_Debugger*)user;
|
||||
if (ILibMemory_CanaryOK(dbg))
|
||||
{
|
||||
duk_debugger_cooperate(dbg->ctx);
|
||||
}
|
||||
}
|
||||
duk_ret_t ILibDuktape_Debugger_hostCooperate(duk_context *ctx)
|
||||
{
|
||||
duk_push_current_function(ctx);
|
||||
ILibDuktape_Debugger *dbg = (ILibDuktape_Debugger*)Duktape_GetPointerProperty(ctx, -1, ILibDuktape_Debugger_DebugObject);
|
||||
void *chain = Duktape_GetPointerProperty(ctx, -1, ILibDuktape_Debugger_HostChain);
|
||||
if (chain != NULL && dbg != NULL && ILibMemory_CanaryOK(dbg))
|
||||
{
|
||||
ILibChain_RunOnMicrostackThreadEx(chain, ILibDuktape_Debugger_hostCooperate_Sink, dbg);
|
||||
}
|
||||
return(0);
|
||||
}
|
||||
void ILibDuktape_Debugger_detachCleanup_Sink(void *chain, void *user)
|
||||
{
|
||||
ILibDuktape_Debugger *dbg = (ILibDuktape_Debugger*)user;
|
||||
if (ILibMemory_CanaryOK(dbg))
|
||||
{
|
||||
if (dbg->client != (SOCKET)~0 && dbg->waitConnection==0)
|
||||
{
|
||||
ILibDuktape_Debugger_Socket_finish((void*)dbg);
|
||||
ILibDuktape_Debugger_AsyncWaitConn(dbg);
|
||||
}
|
||||
}
|
||||
}
|
||||
duk_ret_t ILibDuktape_Debugger_detachCleanup(duk_context *ctx)
|
||||
{
|
||||
duk_push_current_function(ctx);
|
||||
ILibDuktape_Debugger *dbg = (ILibDuktape_Debugger*)Duktape_GetPointerProperty(ctx, -1, ILibDuktape_Debugger_DebugObject);
|
||||
void *chain = Duktape_GetPointerProperty(ctx, -1, ILibDuktape_Debugger_HostChain);
|
||||
if (chain != NULL && dbg != NULL && ILibMemory_CanaryOK(dbg))
|
||||
{
|
||||
ILibChain_RunOnMicrostackThreadEx(chain, ILibDuktape_Debugger_detachCleanup_Sink, dbg);
|
||||
}
|
||||
return(0);
|
||||
}
|
||||
void ILibDuktape_Debugger_hostGC_sink(void *chain, void *user)
|
||||
{
|
||||
ILibDuktape_Debugger *dbg = (ILibDuktape_Debugger*)user;
|
||||
if (ILibMemory_CanaryOK(dbg))
|
||||
{
|
||||
duk_peval_string(dbg->ctx, "_debugGC();"); duk_pop(dbg->ctx);
|
||||
duk_push_string(dbg->ctx, "MemoryAllocations");
|
||||
duk_push_int(dbg->ctx, (duk_int_t)ILibDuktape_ScriptContainer_TotalAllocations);
|
||||
duk_debugger_notify(dbg->ctx, 2);
|
||||
}
|
||||
}
|
||||
duk_ret_t ILibDuktape_Debugger_hostGC(duk_context *ctx)
|
||||
{
|
||||
duk_push_current_function(ctx);
|
||||
ILibDuktape_Debugger *dbg = (ILibDuktape_Debugger*)Duktape_GetPointerProperty(ctx, -1, ILibDuktape_Debugger_DebugObject);
|
||||
void *chain = Duktape_GetPointerProperty(ctx, -1, ILibDuktape_Debugger_HostChain);
|
||||
if (chain != NULL && dbg != NULL && ILibMemory_CanaryOK(dbg))
|
||||
{
|
||||
ILibChain_RunOnMicrostackThreadEx(chain, ILibDuktape_Debugger_hostGC_sink, dbg);
|
||||
}
|
||||
return(0);
|
||||
|
||||
}
|
||||
void ILibDuktape_Debugger_Start(duk_context *ctx, unsigned short debugPort)
|
||||
void* ILibDuktape_Debugger_StartEngine(duk_context *ctx, int transport, int webport)
|
||||
{
|
||||
ILibDuktape_Debugger *dbg;
|
||||
struct sockaddr_in6 local_int;
|
||||
struct sockaddr_in6 remote_int;
|
||||
int remote_int_size = sizeof(struct sockaddr_in6);
|
||||
char *promise = NULL, *duktapeDebugger = NULL;
|
||||
duk_size_t promiseLen, duktapeDebuggerLen;
|
||||
ILibDuktape_Debugger *retVal = NULL;
|
||||
|
||||
memset(&local_int, 0, sizeof(struct sockaddr_in6));
|
||||
local_int.sin6_family = AF_INET;
|
||||
((struct sockaddr_in*)&local_int)->sin_addr.s_addr = INADDR_ANY;
|
||||
local_int.sin6_port = htons(debugPort);
|
||||
if (ILibDuktape_ScriptContainer_DebuggingOK(ctx) != 0)
|
||||
{
|
||||
// Check to made sure we have the debugger dependencies
|
||||
int argTop = duk_get_top(ctx);
|
||||
if (duk_peval_string(ctx, "getJSModule('promise');") == 0 && duk_peval_string(ctx, "getJSModule('duktape-debugger');") == 0)
|
||||
{
|
||||
promise = (char*)duk_to_lstring(ctx, -2, &promiseLen);
|
||||
duktapeDebugger = (char*)duk_to_lstring(ctx, -1, &duktapeDebuggerLen);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Missing Dependencies, so cannot continue with setup
|
||||
duk_peval_string(ctx, "process.emit('uncaughtException', 'Cannot setup debugger, missing promise and/or duktape-debugger');");
|
||||
duk_set_top(ctx, argTop);
|
||||
return(NULL);
|
||||
}
|
||||
|
||||
duk_push_global_object(ctx); // [obj]
|
||||
duk_push_fixed_buffer(ctx, sizeof(ILibDuktape_Debugger)); // [obj][buf]
|
||||
dbg = (ILibDuktape_Debugger*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
duk_put_prop_string(ctx, -2, "_DbgObj"); // [obj]
|
||||
// Setup WebEngine
|
||||
DebugWebEngine_Chain = ILibCreateChain();
|
||||
DebugWebEngine_Context = ILibDuktape_ScriptContainer_InitializeJavaScriptEngineEx(SCRIPT_ENGINE_NO_DEBUGGER | SCRIPT_ENGINE_NO_MESH_AGENT_ACCESS | SCRIPT_ENGINE_NO_GENERIC_MARSHAL_ACCESS | SCRIPT_ENGINE_NO_PROCESS_SPAWNING, 0, DebugWebEngine_Chain, NULL, NULL, NULL, NULL, NULL, NULL);
|
||||
ILibChain_OnDestroyEvent_AddHandler(Duktape_GetChain(ctx), ILibDuktape_Debugger_Destroy, NULL);
|
||||
|
||||
ILibDuktape_ModSearch_AddModule(DebugWebEngine_Context, "promise", promise, (int)promiseLen);
|
||||
ILibDuktape_ModSearch_AddModule(DebugWebEngine_Context, "duktape-debugger", duktapeDebugger, (int)duktapeDebuggerLen);
|
||||
|
||||
duk_push_heap_stash(ctx);
|
||||
char *src = Duktape_GetStringPropertyValue(ctx, -1, ILibDuktape_Debugger_SCRIPT_SOURCE, NULL);
|
||||
char *srcPath = Duktape_GetStringPropertyValue(ctx, -1, ILibDuktape_Debugger_SCRIPT_PATH, NULL);
|
||||
duk_pop(ctx);
|
||||
|
||||
if (src != NULL)
|
||||
{
|
||||
if (srcPath == NULL)
|
||||
{
|
||||
duk_push_global_object(ctx); // [g]
|
||||
duk_get_prop_string(ctx, -1, "process"); // [g][process]
|
||||
duk_get_prop_string(ctx, -1, "argv0"); // [g][process][argv0]
|
||||
srcPath = (char*)duk_get_string(ctx, -1);
|
||||
duk_pop_n(ctx, 3); // ...
|
||||
}
|
||||
duk_push_global_object(DebugWebEngine_Context); // [g]
|
||||
duk_push_string(DebugWebEngine_Context, src); // [g][str]
|
||||
duk_get_prop_string(DebugWebEngine_Context, -1, "split"); // [g][str][split]
|
||||
duk_swap_top(DebugWebEngine_Context, -2); // [g][split][this]
|
||||
duk_push_string(DebugWebEngine_Context, "\n"); // [g][split][this][\n]
|
||||
duk_pcall_method(DebugWebEngine_Context, 1); // [g][tokens]
|
||||
duk_put_prop_string(DebugWebEngine_Context, -2, "_scriptTokens"); // [g]
|
||||
duk_push_string(DebugWebEngine_Context, srcPath); // [g][path]
|
||||
duk_put_prop_string(DebugWebEngine_Context, -2, "_scriptPath"); // [g]
|
||||
duk_pop(DebugWebEngine_Context); // ...
|
||||
}
|
||||
|
||||
duk_push_heap_stash(ctx); // [stash]
|
||||
retVal = (ILibDuktape_Debugger*)Duktape_PushBuffer(ctx, sizeof(ILibDuktape_Debugger)); // [stash][dbgobj]
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_Debugger_DebugObject); // [stash]
|
||||
duk_pop(ctx); // ...
|
||||
|
||||
memset(dbg, 0, sizeof(ILibDuktape_Debugger));
|
||||
dbg->ctx = ctx;
|
||||
if((dbg->listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) { dbg->listener = (SOCKET)~0; return; }
|
||||
duk_push_global_object(DebugWebEngine_Context); // [g]
|
||||
duk_push_c_function(DebugWebEngine_Context, ILibDuktape_Debugger_StartEngine_UpdatePort, 1); // [g][func]
|
||||
duk_push_pointer(DebugWebEngine_Context, retVal); // [g][func][ptr]
|
||||
duk_put_prop_string(DebugWebEngine_Context, -2, ILibDuktape_Debugger_DebugObject); // [g][func]
|
||||
duk_put_prop_string(DebugWebEngine_Context, -2, "updateWebPort"); // [g]
|
||||
|
||||
bind(dbg->listener, (struct sockaddr*)&local_int, sizeof(struct sockaddr_in6));
|
||||
listen(dbg->listener, 1);
|
||||
dbg->client = accept(dbg->listener, (struct sockaddr*)&remote_int, &remote_int_size);
|
||||
duk_push_c_function(DebugWebEngine_Context, ILibDuktape_Debugger_hostCooperate, 0); // [g][func]
|
||||
duk_push_pointer(DebugWebEngine_Context, retVal); // [g][func][ptr]
|
||||
duk_put_prop_string(DebugWebEngine_Context, -2, ILibDuktape_Debugger_DebugObject); // [g][func]
|
||||
duk_push_pointer(DebugWebEngine_Context, Duktape_GetChain(ctx)); // [g][func][ptr]
|
||||
duk_put_prop_string(DebugWebEngine_Context, -2, ILibDuktape_Debugger_HostChain); // [g][func]
|
||||
duk_put_prop_string(DebugWebEngine_Context, -2, "hostCooperate"); // [g]
|
||||
|
||||
duk_debugger_attach(ctx, ILibDuktape_Debugger_ReadCB, ILibDuktape_Debugger_WriteCB, NULL, NULL, NULL, ILibDuktape_Debugger_DetachCB, (void*)dbg);
|
||||
duk_push_c_function(DebugWebEngine_Context, ILibDuktape_Debugger_hostGC, 0); // [g][func]
|
||||
duk_push_pointer(DebugWebEngine_Context, retVal); // [g][func][ptr]
|
||||
duk_put_prop_string(DebugWebEngine_Context, -2, ILibDuktape_Debugger_DebugObject); // [g][func]
|
||||
duk_push_pointer(DebugWebEngine_Context, Duktape_GetChain(ctx)); // [g][func][ptr]
|
||||
duk_put_prop_string(DebugWebEngine_Context, -2, ILibDuktape_Debugger_HostChain); // [g][func]
|
||||
duk_put_prop_string(DebugWebEngine_Context, -2, "hostGC"); // [g]
|
||||
|
||||
|
||||
duk_push_c_function(DebugWebEngine_Context, ILibDuktape_Debugger_detachCleanup, 0); // [g][func]
|
||||
duk_push_pointer(DebugWebEngine_Context, retVal); // [g][func][ptr]
|
||||
duk_put_prop_string(DebugWebEngine_Context, -2, ILibDuktape_Debugger_DebugObject); // [g][func]
|
||||
duk_push_pointer(DebugWebEngine_Context, Duktape_GetChain(ctx)); // [g][func][ptr]
|
||||
duk_put_prop_string(DebugWebEngine_Context, -2, ILibDuktape_Debugger_HostChain); // [g][func]
|
||||
duk_put_prop_string(DebugWebEngine_Context, -2, "detachCleanup"); // [g]
|
||||
|
||||
|
||||
duk_push_int(DebugWebEngine_Context, transport);
|
||||
duk_put_prop_string(DebugWebEngine_Context, -2, "transport");
|
||||
duk_push_int(DebugWebEngine_Context, webport);
|
||||
duk_put_prop_string(DebugWebEngine_Context, -2, "webport");
|
||||
duk_pop(DebugWebEngine_Context); // ...
|
||||
|
||||
retVal->ctx = ctx;
|
||||
sem_init(&(retVal->hostlock), 0, 0);
|
||||
retVal->webport = webport;
|
||||
|
||||
DebugWebEngine_Thread = ILibSpawnNormalThread(DebugWebEngine_Run, NULL);
|
||||
}
|
||||
|
||||
void ILibDuktape_Debugger_Stop(duk_context *ctx)
|
||||
return(retVal);
|
||||
}
|
||||
duk_ret_t ILibDuktape_Debugger_JSAttach_promise_wait(duk_context *ctx)
|
||||
{
|
||||
char *eventName = (char*)duk_require_string(ctx, 0);
|
||||
if (strcmp(eventName, "resolved") != 0) { return(0); }
|
||||
|
||||
duk_push_heap_stash(ctx);
|
||||
duk_get_prop_string(ctx, -1, ILibDuktape_Debugger_DebugObject);
|
||||
ILibDuktape_Debugger *dbg = (ILibDuktape_Debugger*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
|
||||
listen(dbg->listener, 1);
|
||||
ILibDuktape_Debugger_Socket_waitconn(dbg);
|
||||
ILibDuktape_Debugger_StartMemoryReporting(dbg->ctx);
|
||||
duk_debugger_attach(dbg->ctx, ILibDuktape_Debugger_ReadCB, ILibDuktape_Debugger_WriteCB, ILibDuktape_Debugger_PeekCB, NULL, NULL, NULL, ILibDuktape_Debugger_DetachCB, (void*)dbg);
|
||||
|
||||
return(0);
|
||||
}
|
||||
|
||||
void ILibDuktape_Debugger_JSAttach_PopulateSource(duk_context *ctx, char *source)
|
||||
{
|
||||
if (source != NULL)
|
||||
{
|
||||
duk_push_heap_stash(ctx); // [stash]
|
||||
duk_push_string(ctx, source); // [stash][src]
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_Debugger_SCRIPT_SOURCE); // [stash]
|
||||
duk_pop(ctx); // ...
|
||||
}
|
||||
else
|
||||
{
|
||||
char *script, *scriptPath;
|
||||
int scriptLen;
|
||||
|
||||
duk_push_global_object(ctx); // [g]
|
||||
duk_get_prop_string(ctx, -1, "process"); // [g][process]
|
||||
duk_get_prop_string(ctx, -1, "argv0"); // [g][process][argv0]
|
||||
scriptPath = (char*)duk_to_string(ctx, -1);
|
||||
ILibDuktape_ScriptContainer_CheckEmbeddedEx(scriptPath, &script, &scriptLen);
|
||||
duk_pop_3(ctx); // ...
|
||||
|
||||
if (script != NULL)
|
||||
{
|
||||
duk_push_heap_stash(ctx); // [stash]
|
||||
duk_push_lstring(ctx, script, (duk_size_t)scriptLen); // [stash][src]
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_Debugger_SCRIPT_SOURCE); // [stash]
|
||||
duk_push_string(ctx, "[embedded].js");
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_Debugger_SCRIPT_PATH); // [stash]
|
||||
|
||||
duk_pop(ctx); // ...
|
||||
free(script);
|
||||
}
|
||||
else
|
||||
{
|
||||
duk_push_global_object(ctx); // [g]
|
||||
duk_get_prop_string(ctx, -1, "process"); // [g][process]
|
||||
duk_get_prop_string(ctx, -1, "argv0"); // [g][process][argv0]
|
||||
if (duk_get_length(ctx, -1) == 0)
|
||||
{
|
||||
// JS was not specified on command line
|
||||
if (duk_peval_string(ctx, "require('MeshAgent');") == 0)
|
||||
{
|
||||
int CoreModuleLen = 0;
|
||||
ILibSimpleDataStore *db = (ILibSimpleDataStore*)Duktape_GetPointerProperty(ctx, -1, "\xFF_MasterDB");
|
||||
if (db == NULL || (CoreModuleLen = ILibSimpleDataStore_Get(db, "CoreModule", NULL, 0)) <= 0)
|
||||
{
|
||||
ILibDuktape_Error(ctx, "Could Not retrive CoreModule from MeshAgent"); return;
|
||||
}
|
||||
// [g][process][argv0][MeshAgent]
|
||||
char* CoreModule = ILibMemory_Allocate(CoreModuleLen, 0, NULL, NULL);
|
||||
ILibSimpleDataStore_Get(db, "CoreModule", CoreModule, CoreModuleLen);
|
||||
duk_push_lstring(ctx, CoreModule + 4, CoreModuleLen - 4); // [g][process][argv0][MeshAgent][CoreModule]
|
||||
duk_push_heap_stash(ctx);
|
||||
duk_swap_top(ctx, -2);
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_Debugger_SCRIPT_SOURCE);
|
||||
duk_push_string(ctx, "CoreModule.js");
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_Debugger_SCRIPT_PATH);
|
||||
free(CoreModule);
|
||||
return;
|
||||
}
|
||||
else
|
||||
{
|
||||
ILibDuktape_Error(ctx, "Unable to retrive running java script"); return;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
duk_eval_string(ctx, "require('fs');"); // [g][process][argv0][fs]
|
||||
duk_get_prop_string(ctx, -1, "readFileSync"); // [g][process][argv0][fs][rfs]
|
||||
duk_swap_top(ctx, -2); // [g][process][argv0][rfs][this]
|
||||
duk_dup(ctx, -3); // [g][process][argv0][rfs][this][path]
|
||||
duk_call_method(ctx, 1); // [g][process][argv0][sourceBuffer]
|
||||
}
|
||||
duk_get_prop_string(ctx, -1, "toString"); // [g][process][argv0][sourceBuffer][toString]
|
||||
duk_swap_top(ctx, -2); // [g][process][argv0][toString][this]
|
||||
duk_call_method(ctx, 0); // [g][process][argv0][sourceBuffer]
|
||||
duk_push_heap_stash(ctx); // [g][process][argv0][source][stash]
|
||||
duk_dup(ctx, -2); // [g][process][argv0][source][stash][source]
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_Debugger_SCRIPT_SOURCE); // [g][process][argv0][source][stash]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
duk_ret_t ILibDuktape_Debugger_JSAttach_promise(duk_context *ctx)
|
||||
{
|
||||
int needWait = 0;
|
||||
#ifndef DUK_USE_DEBUGGER_SUPPORT
|
||||
duk_dup(ctx, 1); // [rejector]
|
||||
duk_push_this(ctx); // [rejector][this]
|
||||
duk_push_string(ctx, "No debugger support"); // [rejector][this][err]
|
||||
duk_call_method(ctx, 1); // [ret]
|
||||
return(0);
|
||||
#endif
|
||||
#ifdef WIN32
|
||||
SOCKET listenerSocket;
|
||||
#else
|
||||
int listenerSocket;
|
||||
#endif
|
||||
struct sockaddr_in6 *local_int;
|
||||
struct sockaddr_in6 localBounded;
|
||||
int localBoundedSize = sizeof(struct sockaddr_in6);
|
||||
|
||||
duk_push_heap_stash(ctx); // [stash]
|
||||
if (duk_has_prop_string(ctx, -1, ILibDuktape_Debugger_AttachOptions))
|
||||
{
|
||||
duk_dup(ctx, 1); // [stash][rejector]
|
||||
duk_push_this(ctx); // [stash][rejector][this]
|
||||
duk_push_string(ctx, "attachDebugger() already called"); // [stash][rejector][this][err]
|
||||
duk_call_method(ctx, 1); // [stash][ret]
|
||||
return(0);
|
||||
}
|
||||
else
|
||||
{
|
||||
duk_push_current_function(ctx); // [stash][func]
|
||||
duk_get_prop_string(ctx, -1, "options"); // [stash][func][options]
|
||||
duk_remove(ctx, -2); // [stash][options]
|
||||
duk_dup(ctx, -1); // [stash][options][options]
|
||||
duk_put_prop_string(ctx, -3, ILibDuktape_Debugger_AttachOptions); // [stash][options]
|
||||
duk_dup(ctx, 0); duk_put_prop_string(ctx, -2, ILibDuktape_Debugger_Options_Resolver);
|
||||
duk_dup(ctx, 1); duk_put_prop_string(ctx, -2, ILibDuktape_Debugger_Options_Rejector);
|
||||
}
|
||||
|
||||
int transport = Duktape_GetIntPropertyValue(ctx, -1, "transport", 0);
|
||||
int webport = Duktape_GetIntPropertyValue(ctx, -1, "webport", 0);
|
||||
char *source = Duktape_GetStringPropertyValue(ctx, -1, "source", NULL);
|
||||
|
||||
local_int = Duktape_IPAddress4_FromString("127.0.0.1", transport);
|
||||
#ifdef WIN32
|
||||
if ((listenerSocket = WSASocketW(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_NO_HANDLE_INHERIT)) == -1) { listenerSocket = (SOCKET)~0; }
|
||||
#else
|
||||
if ((listenerSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) { listenerSocket = (SOCKET)~0; }
|
||||
#endif
|
||||
if (listenerSocket == (SOCKET)~0)
|
||||
{
|
||||
// Error creating socket
|
||||
duk_dup(ctx, 1); // [rejector]
|
||||
duk_push_this(ctx); // [rejector][this]
|
||||
duk_push_string(ctx, "Error Creating Debug Transport Socket"); // [rejector][this][err]
|
||||
duk_call_method(ctx, 1);
|
||||
return(0);
|
||||
}
|
||||
bind(listenerSocket, (struct sockaddr*)local_int, sizeof(struct sockaddr_in6));
|
||||
#if defined(WINSOCK2)
|
||||
getsockname(listenerSocket, (struct sockaddr*)&localBounded, (int*)&localBoundedSize);
|
||||
#else
|
||||
getsockname(listenerSocket, (struct sockaddr*)&localBounded, (socklen_t*)&localBoundedSize);
|
||||
#endif
|
||||
transport = (int)ntohs(localBounded.sin6_port);
|
||||
|
||||
if (Duktape_GetIntPropertyValue(ctx, -1, "wait", 0) == 1)
|
||||
{
|
||||
needWait = 1;
|
||||
|
||||
// WaitForDebugger... We'll hookup an event hook, so we can be notified when somebody calls 'then'
|
||||
duk_push_this(ctx); // [promise]
|
||||
duk_get_prop_string(ctx, -1, "_internal"); // [promise][internal]
|
||||
duk_get_prop_string(ctx, -1, "once"); // [promise][internal][once]
|
||||
duk_swap_top(ctx, -2); // [promise][on][this]
|
||||
duk_push_string(ctx, "_eventHook"); // [promise][on][this][eventHook]
|
||||
duk_push_c_function(ctx, ILibDuktape_Debugger_JSAttach_promise_wait, 2);// [promise][on][this][eventHook][func]
|
||||
duk_call_method(ctx, 2);
|
||||
}
|
||||
|
||||
// Before we do anything, we need to setup the source
|
||||
ILibDuktape_Debugger_JSAttach_PopulateSource(ctx, source);
|
||||
|
||||
ILibDuktape_Debugger *dbg;
|
||||
if ((dbg = ILibDuktape_Debugger_StartEngine(ctx, transport, webport)) == NULL)
|
||||
{
|
||||
// error
|
||||
duk_dup(ctx, 1); // [rejector]
|
||||
duk_push_this(ctx); // [rejector][this]
|
||||
duk_push_string(ctx, "Error Starting Debug Engine");// [rejector][this][err]
|
||||
duk_call_method(ctx, 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
// success
|
||||
duk_suspend(ctx, &(dbg->hoststate));
|
||||
dbg->listener = listenerSocket;
|
||||
sem_wait(&(dbg->hostlock));
|
||||
sem_destroy(&(dbg->hostlock));
|
||||
duk_resume(ctx, &(dbg->hoststate));
|
||||
|
||||
if (needWait == 0)
|
||||
{
|
||||
listen(dbg->listener, 1);
|
||||
ILibDuktape_Debugger_AsyncWaitConn(dbg);
|
||||
}
|
||||
|
||||
// Resolve the promise with the bounded WebPort
|
||||
duk_dup(ctx, 0); // [resolver]
|
||||
duk_push_this(ctx); // [resolver][this]
|
||||
duk_push_int(ctx, dbg->webport); // [resolver][this][webport]
|
||||
duk_call_method(ctx, 1);
|
||||
}
|
||||
|
||||
return(0);
|
||||
}
|
||||
duk_ret_t ILibDuktape_Debugger_JSAttach(duk_context *ctx)
|
||||
{
|
||||
int nargs = duk_get_top(ctx);
|
||||
duk_eval_string(ctx, "require('promise');"); // [promisectr]
|
||||
duk_push_c_function(ctx, ILibDuktape_Debugger_JSAttach_promise, 2); // [promisectr][func]
|
||||
if (nargs > 0 && duk_is_object(ctx, 0))
|
||||
{
|
||||
duk_dup(ctx, 0); duk_put_prop_string(ctx, -2, "options");
|
||||
}
|
||||
else
|
||||
{
|
||||
duk_push_object(ctx); duk_put_prop_string(ctx, -2, "options");
|
||||
}
|
||||
duk_new(ctx, 1); // [promise]
|
||||
return(1);
|
||||
}
|
||||
void ILibDuktape_Debugger_Init(duk_context *ctx, unsigned short debugPort)
|
||||
{
|
||||
duk_push_global_object(ctx);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "attachDebugger", ILibDuktape_Debugger_JSAttach, DUK_VARARGS);
|
||||
duk_pop(ctx);
|
||||
}
|
||||
void ILibDuktape_Debugger_SetScriptEx(void *chain, void *user)
|
||||
{
|
||||
if (ILibMemory_CanaryOK(user))
|
||||
{
|
||||
duk_push_global_object(DebugWebEngine_Context);
|
||||
duk_push_lstring(DebugWebEngine_Context, ILibMemory_Extra(user), ILibMemory_ExtraSize(user));
|
||||
duk_put_prop_string(DebugWebEngine_Context, -2, "_scriptPath");
|
||||
duk_pop(DebugWebEngine_Context);
|
||||
|
||||
duk_push_lstring(DebugWebEngine_Context, (char*)user, (duk_size_t)ILibMemory_Size(user)); // [str]
|
||||
duk_get_prop_string(DebugWebEngine_Context, -1, "split"); // [str][split]
|
||||
duk_swap_top(DebugWebEngine_Context, -2); // [split][this]
|
||||
duk_push_string(DebugWebEngine_Context, "\n"); // [split][this][\n]
|
||||
if (duk_pcall_method(DebugWebEngine_Context, 1) == 0)
|
||||
{ // [tokens]
|
||||
duk_push_global_object(DebugWebEngine_Context); // [tokens][g]
|
||||
duk_swap_top(DebugWebEngine_Context, -2); // [g][tokens]
|
||||
duk_put_prop_string(DebugWebEngine_Context, -2, "_scriptTokens"); // [g]
|
||||
}
|
||||
duk_pop(DebugWebEngine_Context);
|
||||
ILibMemory_Free(user);
|
||||
}
|
||||
}
|
||||
void ILibDuktape_Debugger_SetScript(char *js, int jsLen, char *fileName, int fileNameLen)
|
||||
{
|
||||
if (DebugWebEngine_Chain != NULL)
|
||||
{
|
||||
if (fileNameLen <= 0 && fileName != NULL)
|
||||
{
|
||||
fileNameLen = (int)strnlen_s(fileName, _MAX_PATH);
|
||||
}
|
||||
char *jsRef = (char*)ILibMemory_SmartAllocateEx(jsLen, fileNameLen);
|
||||
memcpy_s(jsRef, jsLen, js, jsLen);
|
||||
if (fileNameLen > 0)
|
||||
{
|
||||
memcpy_s(ILibMemory_Extra(jsRef), ILibMemory_ExtraSize(jsRef), fileName, fileNameLen);
|
||||
}
|
||||
ILibChain_RunOnMicrostackThreadEx(DebugWebEngine_Chain, ILibDuktape_Debugger_SetScriptEx, jsRef);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,8 +19,7 @@ limitations under the License.
|
||||
|
||||
#include "duktape.h"
|
||||
|
||||
|
||||
void ILibDuktape_Debugger_Start(duk_context *ctx, unsigned short debugPort);
|
||||
|
||||
void ILibDuktape_Debugger_Init(duk_context *ctx, unsigned short debugPort);
|
||||
void ILibDuktape_Debugger_SetScript(char *js, int jsLen, char *fileName, int fileNameLen);
|
||||
|
||||
#endif
|
||||
@@ -70,11 +70,9 @@ ILibDuktape_DuplexStream * ILibDuktape_DuplexStream_InitEx(duk_context * ctx, IL
|
||||
{
|
||||
ILibDuktape_DuplexStream *retVal;
|
||||
|
||||
duk_push_fixed_buffer(ctx, sizeof(ILibDuktape_DuplexStream)); // [obj][buffer]
|
||||
retVal = (ILibDuktape_DuplexStream*)Duktape_GetBuffer(ctx, -1, NULL); // [obj][buffer]
|
||||
retVal = (ILibDuktape_DuplexStream*)Duktape_PushBuffer(ctx, sizeof(ILibDuktape_DuplexStream)); // [obj][buffer]
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_DuplexStream_bufferPtr); // [obj]
|
||||
|
||||
memset(retVal, 0, sizeof(ILibDuktape_DuplexStream));
|
||||
retVal->user = user;
|
||||
retVal->readableStream = ILibDuktape_ReadableStream_InitEx(ctx, ILibDuktape_DuplexStream_OnPause, ILibDuktape_DuplexStream_OnResume, UnshiftHandler != NULL ? ILibDuktape_DuplexStream_OnUnshift : NULL, retVal);
|
||||
retVal->writableStream = ILibDuktape_WritableStream_Init(ctx, ILibDuktape_DuplexStream_OnWrite, ILibDuktape_DuplexStream_OnEnd, retVal);
|
||||
|
||||
@@ -66,11 +66,11 @@ typedef void(*ILibDuktape_DuplexStream_EndHandler)(ILibDuktape_DuplexStream *str
|
||||
typedef void(*ILibDuktape_DuplexStream_PauseResumeHandler)(ILibDuktape_DuplexStream *sender, void *user);
|
||||
typedef int(*ILibDuktape_DuplexStream_UnshiftHandler)(ILibDuktape_DuplexStream *sender, int unshiftBytes, void *user);
|
||||
|
||||
#define ILibDuktape_DuplexStream_Ready(duplexStream) ILibDuktape_WritableStream_Ready((duplexStream)->writableStream)
|
||||
#define ILibDuktape_DuplexStream_WriteData(duplexStream, buffer, bufferLen) ILibDuktape_readableStream_WriteData((duplexStream)->readableStream, buffer, bufferLen)
|
||||
#define ILibDuktape_DuplexStream_WriteDataEx(duplexStream, streamReserved, buffer, bufferLen) ILibDuktape_readableStream_WriteDataEx((duplexStream)->readableStream, streamReserved, buffer, bufferLen)
|
||||
#define ILibDuktape_DuplexStream_WriteEnd(duplexStream) ILibDuktape_readableStream_WriteEnd((duplexStream)->readableStream)
|
||||
#define ILibDuktape_DuplexStream_Closed(duplexStream) ILibDuktape_readableStream_Closed((duplexStream)->readableStream)
|
||||
#define ILibDuktape_DuplexStream_Ready(duplexStream) if(ILibMemory_CanaryOK(duplexStream)){ILibDuktape_WritableStream_Ready((duplexStream)->writableStream);}
|
||||
#define ILibDuktape_DuplexStream_WriteData(duplexStream, buffer, bufferLen) (ILibMemory_CanaryOK(duplexStream)?(ILibDuktape_readableStream_WriteData((duplexStream)!=NULL?((duplexStream)->readableStream):NULL, buffer, bufferLen)):1)
|
||||
#define ILibDuktape_DuplexStream_WriteDataEx(duplexStream, streamReserved, buffer, bufferLen) (ILibMemory_CanaryOK(duplexStream)?(ILibDuktape_readableStream_WriteDataEx((duplexStream)!=NULL?((duplexStream)->readableStream):NULL, streamReserved, buffer, bufferLen)):1)
|
||||
#define ILibDuktape_DuplexStream_WriteEnd(duplexStream) (ILibMemory_CanaryOK(duplexStream)?ILibDuktape_readableStream_WriteEnd((duplexStream)->readableStream):1)
|
||||
#define ILibDuktape_DuplexStream_Closed(duplexStream) if(ILibMemory_CanaryOK(duplexStream)){ILibDuktape_readableStream_Closed((duplexStream)->readableStream);}
|
||||
|
||||
ILibDuktape_DuplexStream* ILibDuktape_DuplexStream_InitEx(duk_context *ctx, ILibDuktape_DuplexStream_WriteHandler WriteHandler, ILibDuktape_DuplexStream_EndHandler EndHandler, ILibDuktape_DuplexStream_PauseResumeHandler PauseHandler, ILibDuktape_DuplexStream_PauseResumeHandler ResumeHandler, ILibDuktape_DuplexStream_UnshiftHandler UnshiftHandler, void *user);
|
||||
#define ILibDuktape_DuplexStream_Init(ctx, WriteHandler, EndHandler, PauseHandler, ResumeHandler, user) ILibDuktape_DuplexStream_InitEx(ctx, WriteHandler, EndHandler, PauseHandler, ResumeHandler, NULL, user)
|
||||
|
||||
@@ -20,13 +20,22 @@ limitations under the License.
|
||||
#include "duktape.h"
|
||||
#include "microstack/ILibParsers.h"
|
||||
|
||||
typedef enum ILibDuktape_EventEmitter_Types
|
||||
{
|
||||
ILibDuktape_EventEmitter_Type_EXPLICIT = 0,
|
||||
ILibDuktape_EventEmitter_Type_IMPLICIT = 1
|
||||
}ILibDuktape_EventEmitter_Types;
|
||||
|
||||
typedef void(*ILibDuktape_EventEmitter_Handler)(duk_context *ctx, void *object, char *eventName, void *duk_eventArgs);
|
||||
typedef struct ILibDuktape_EventEmitter
|
||||
{
|
||||
duk_context *ctx;
|
||||
void *object;
|
||||
void *tmpObject;
|
||||
void *lastReturnValue;
|
||||
void *retValTable;
|
||||
unsigned int *totalListeners;
|
||||
ILibDuktape_EventEmitter_Types eventType;
|
||||
ILibHashtable eventTable;
|
||||
}ILibDuktape_EventEmitter;
|
||||
typedef void(*ILibDuktape_EventEmitter_HookHandler)(ILibDuktape_EventEmitter *sender, char *eventName, void *hookedCallback);
|
||||
@@ -50,11 +59,16 @@ int ILibDuktape_EventEmitter_HasListeners(ILibDuktape_EventEmitter *emitter, cha
|
||||
|
||||
#define ILibDuktape_EventEmitter_AddOnceEx2(ctx, idx, eventName, func, argCount) ILibDuktape_EventEmitter_AddOnceEx3(ctx, idx, eventName, func)
|
||||
#define ILibDuktape_EventEmitter_SetupEmit(ctx, heapptr, eventName) duk_push_heapptr((ctx), heapptr);duk_get_prop_string((ctx), -1, "emit");duk_swap_top((ctx), -2);duk_push_string((ctx), eventName)
|
||||
#define ILibDuktape_EventEmitter_SetupOn(ctx, heapptr, eventName) duk_push_heapptr((ctx), heapptr);duk_get_prop_string((ctx), -1, "on");duk_swap_top((ctx), -2);duk_push_string((ctx), eventName)
|
||||
#define ILibDuktape_EventEmitter_SetupPrependOnce(ctx, heapptr, eventName) duk_push_heapptr((ctx), heapptr);duk_get_prop_string((ctx), -1, "prependOnceListener");duk_swap_top((ctx), -2);duk_push_string((ctx), eventName)
|
||||
|
||||
int ILibDuktape_EventEmitter_AddOn(ILibDuktape_EventEmitter *emitter, char *eventName, void *heapptr); // Add native event handler
|
||||
int ILibDuktape_EventEmitter_AddOnEx(duk_context *ctx, duk_idx_t idx, char *eventName, duk_c_function func);
|
||||
|
||||
void ILibDuktape_EventEmitter_AddHook(ILibDuktape_EventEmitter *emitter, char *eventName, ILibDuktape_EventEmitter_HookHandler handler);
|
||||
void ILibDuktape_EventEmitter_ClearHook(ILibDuktape_EventEmitter *emitter, char *eventName);
|
||||
|
||||
void ILibDuktape_EventEmitter_ForwardEvent(duk_context *ctx, duk_idx_t eventSourceIndex, char *sourceEventName, duk_idx_t eventTargetIndex, char *targetEventName);
|
||||
void ILibDuktape_EventEmitter_DeleteForwardEvent(duk_context *ctx, duk_idx_t eventSourceIndex, char *sourceEventName);
|
||||
|
||||
#endif
|
||||
|
||||
@@ -24,6 +24,7 @@ limitations under the License.
|
||||
#include "ILibDuktape_GenericMarshal.h"
|
||||
#include "ILibDuktapeModSearch.h"
|
||||
#include "ILibDuktape_Helpers.h"
|
||||
#include "ILibDuktape_EventEmitter.h"
|
||||
#include "microstack/ILibParsers.h"
|
||||
#include "microstack/ILibCrypto.h"
|
||||
#include "microstack/ILibRemoteLogging.h"
|
||||
@@ -36,12 +37,19 @@ limitations under the License.
|
||||
|
||||
#ifdef WIN32
|
||||
#define APICALLTYPE __stdcall
|
||||
|
||||
#else
|
||||
#define APICALLTYPE
|
||||
#include <dlfcn.h>
|
||||
#endif
|
||||
|
||||
#define ILibDuktape_GenericMarshal_VariableType "\xFF_GenericMarshal_VarType"
|
||||
#define ILibDuktape_GenericMarshal_GlobalSet "\xFF_GenericMarshal_GlobalSet"
|
||||
#define ILibDuktape_GenericMarshal_Variable_AutoFree "\xFF_GenericMarshal_Variable_AutoFree"
|
||||
#define ILibDuktape_GenericMarshal_Variable_Parms "\xFF_GenericMarshal_Variable_Parms"
|
||||
#define ILibDuktape_GenericMarshal_StashTable "\xFF_GenericMarshal_StashTable"
|
||||
#define ILibDuktape_GenericMarshal_Variable_EnableAutoFree(ctx, idx) duk_dup(ctx, idx);duk_push_true(ctx);duk_put_prop_string(ctx, -2, ILibDuktape_GenericMarshal_Variable_AutoFree);duk_pop(ctx)
|
||||
#define ILibDuktape_GenericMarshal_Variable_DisableAutoFree(ctx, idx) duk_dup(ctx, idx);duk_push_false(ctx);duk_put_prop_string(ctx, -2, ILibDuktape_GenericMarshal_Variable_AutoFree);duk_pop(ctx)
|
||||
|
||||
typedef PTRSIZE(APICALLTYPE *R0)();
|
||||
typedef PTRSIZE(APICALLTYPE *R1)(PTRSIZE V1);
|
||||
@@ -65,6 +73,7 @@ typedef PTRSIZE(APICALLTYPE *R18)(PTRSIZE V1, PTRSIZE V2, PTRSIZE V3, PTRSIZE V4
|
||||
typedef PTRSIZE(APICALLTYPE *R19)(PTRSIZE V1, PTRSIZE V2, PTRSIZE V3, PTRSIZE V4, PTRSIZE V5, PTRSIZE V6, PTRSIZE V7, PTRSIZE V8, PTRSIZE V9, PTRSIZE V10, PTRSIZE V11, PTRSIZE V12, PTRSIZE V13, PTRSIZE V14, PTRSIZE V15, PTRSIZE V16, PTRSIZE V17, PTRSIZE V18, PTRSIZE V19);
|
||||
typedef PTRSIZE(APICALLTYPE *R20)(PTRSIZE V1, PTRSIZE V2, PTRSIZE V3, PTRSIZE V4, PTRSIZE V5, PTRSIZE V6, PTRSIZE V7, PTRSIZE V8, PTRSIZE V9, PTRSIZE V10, PTRSIZE V11, PTRSIZE V12, PTRSIZE V13, PTRSIZE V14, PTRSIZE V15, PTRSIZE V16, PTRSIZE V17, PTRSIZE V18, PTRSIZE V19, PTRSIZE V20);
|
||||
|
||||
ILibLinkedList GlobalCallbackList = NULL;
|
||||
|
||||
typedef struct Duktape_GenericMarshal_Proxy
|
||||
{
|
||||
@@ -73,6 +82,21 @@ typedef struct Duktape_GenericMarshal_Proxy
|
||||
void *jsProxyObject;
|
||||
}Duktape_GenericMarshal_Proxy;
|
||||
|
||||
typedef struct Duktape_GlobalGeneric_Data
|
||||
{
|
||||
ILibDuktape_EventEmitter *emitter;
|
||||
void *retVal;
|
||||
void *chain;
|
||||
sem_t contextWaiter;
|
||||
int numArgs;
|
||||
PTRSIZE args[];
|
||||
}Duktape_GlobalGeneric_Data;
|
||||
typedef struct Duktape_MarshalledObject
|
||||
{
|
||||
duk_context *ctx;
|
||||
void *heapptr;
|
||||
}Duktape_MarshalledObject;
|
||||
|
||||
void ILibDuktape_GenericMarshal_Variable_PUSH(duk_context *ctx, void *ptr, int size);
|
||||
|
||||
duk_ret_t ILibDuktape_GenericMarshal_Variable_Val_STRING(duk_context *ctx)
|
||||
@@ -94,7 +118,7 @@ duk_ret_t ILibDuktape_GenericMarshal_Variable_Val_HSTRING(duk_context *ctx)
|
||||
{
|
||||
void *ptr;
|
||||
int size;
|
||||
char hexString[255];
|
||||
char hexString[600];
|
||||
|
||||
duk_push_this(ctx); // [var]
|
||||
duk_get_prop_string(ctx, -1, "_ptr"); // [var][ptr]
|
||||
@@ -142,6 +166,7 @@ duk_ret_t ILibDuktape_GenericMarshal_Variable_Val_ASTRING(duk_context *ctx)
|
||||
size = duk_to_int(ctx, -1);
|
||||
|
||||
#ifdef WIN32
|
||||
if (size == 0) { size = (int)wcsnlen_s((const wchar_t*)ptr, sizeof(astr) * 2); }
|
||||
wcstombs_s(&s, astr, sizeof(astr), (const wchar_t*)ptr, size);
|
||||
duk_push_string(ctx, (char*)astr);
|
||||
#else
|
||||
@@ -153,33 +178,12 @@ duk_ret_t ILibDuktape_GenericMarshal_Variable_Val_ASTRING(duk_context *ctx)
|
||||
duk_ret_t ILibDuktape_GenericMarshal_Variable_Val_GET(duk_context *ctx)
|
||||
{
|
||||
void *ptr;
|
||||
int size;
|
||||
|
||||
duk_push_this(ctx); // [var]
|
||||
duk_get_prop_string(ctx, -1, "_ptr"); // [var][ptr]
|
||||
ptr = duk_to_pointer(ctx, -1);
|
||||
duk_get_prop_string(ctx, -2, "_size"); // [var][ptr][size]
|
||||
size = duk_to_int(ctx, -1);
|
||||
|
||||
switch (size)
|
||||
{
|
||||
case 2:
|
||||
duk_push_int(ctx, (int)((unsigned short*)ptr)[0]);
|
||||
break;
|
||||
case 4:
|
||||
duk_push_int(ctx, (int)((unsigned int*)ptr)[0]);
|
||||
break;
|
||||
case 8:
|
||||
#if UINTPTR_MAX == 0xffffffffffffffff
|
||||
duk_push_pointer(ctx, (void*)((uint64_t*)ptr)[0]);
|
||||
#else
|
||||
return(ILibDuktape_Error(ctx, "GenericMarshal.get(): Cannot get 64bit value on 32bit platform"));
|
||||
#endif
|
||||
break;
|
||||
default:
|
||||
duk_push_int(ctx, 0);
|
||||
break;
|
||||
}
|
||||
duk_push_int(ctx, (int)(PTRSIZE)ptr);
|
||||
|
||||
return 1;
|
||||
}
|
||||
@@ -330,32 +334,10 @@ duk_ret_t ILibDuktape_GenericMarshal_Variable_toBuffer(duk_context *ctx)
|
||||
duk_push_buffer_object(ctx, -1, 0, (duk_size_t)bufferLen, DUK_BUFOBJ_NODEJS_BUFFER);
|
||||
return(1);
|
||||
}
|
||||
void ILibDuktape_GenericMarshal_Variable_PUSH(duk_context *ctx, void *ptr, int size)
|
||||
{
|
||||
duk_push_object(ctx); // [var]
|
||||
duk_push_pointer(ctx, ptr); // [var][ptr]
|
||||
duk_put_prop_string(ctx, -2, "_ptr"); // [var]
|
||||
duk_push_int(ctx, size); // [var][size]
|
||||
duk_put_prop_string(ctx, -2, "_size"); // [var]
|
||||
duk_push_true(ctx);
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_GenericMarshal_VariableType);
|
||||
|
||||
ILibDuktape_CreateEventWithGetterAndSetterEx(ctx, "Val", ILibDuktape_GenericMarshal_Variable_Val_GET, ILibDuktape_GenericMarshal_Variable_Val_SET);
|
||||
ILibDuktape_CreateEventWithGetterAndSetterWithIntMetaData(ctx, "_VarSize", 4, "IntVal", ILibDuktape_GenericMarshal_Variable_GetEx, ILibDuktape_GenericMarshal_Variable_SetEx);
|
||||
ILibDuktape_CreateEventWithGetterAndSetterWithIntMetaData(ctx, "_VarSize", 2, "ShortVal", ILibDuktape_GenericMarshal_Variable_GetEx, ILibDuktape_GenericMarshal_Variable_SetEx);
|
||||
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "Deref", ILibDuktape_GenericMarshal_Variable_Deref, DUK_VARARGS);
|
||||
ILibDuktape_CreateEventWithGetter(ctx, "String", ILibDuktape_GenericMarshal_Variable_Val_STRING);
|
||||
ILibDuktape_CreateEventWithGetter(ctx, "AnsiString", ILibDuktape_GenericMarshal_Variable_Val_ASTRING);
|
||||
ILibDuktape_CreateEventWithGetter(ctx, "HexString", ILibDuktape_GenericMarshal_Variable_Val_HSTRING);
|
||||
ILibDuktape_CreateEventWithGetter(ctx, "HexString2", ILibDuktape_GenericMarshal_Variable_Val_HSTRING2);
|
||||
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "toBuffer", ILibDuktape_GenericMarshal_Variable_toBuffer, 0);
|
||||
}
|
||||
duk_ret_t ILibDuktape_GenericMarshal_Variable_Finalizer(duk_context *ctx)
|
||||
{
|
||||
void *ptr = NULL;
|
||||
if (duk_has_prop_string(ctx, 0, "_ptr"))
|
||||
if (duk_has_prop_string(ctx, 0, "_ptr") && Duktape_GetBooleanProperty(ctx, 0, ILibDuktape_GenericMarshal_Variable_AutoFree, 0))
|
||||
{
|
||||
duk_get_prop_string(ctx, 0, "_ptr");
|
||||
ptr = duk_to_pointer(ctx, -1);
|
||||
@@ -368,6 +350,73 @@ duk_ret_t ILibDuktape_GenericMarshal_Variable_Finalizer(duk_context *ctx)
|
||||
|
||||
return 0;
|
||||
}
|
||||
duk_ret_t ILibDuktape_GenericMarshal_Variable_autoFree(duk_context *ctx)
|
||||
{
|
||||
int nargs = duk_get_top(ctx);
|
||||
duk_push_this(ctx); // [variable]
|
||||
if (nargs > 0 && !duk_require_boolean(ctx, 0))
|
||||
{
|
||||
ILibDuktape_GenericMarshal_Variable_DisableAutoFree(ctx, -1);
|
||||
}
|
||||
else
|
||||
{
|
||||
ILibDuktape_GenericMarshal_Variable_EnableAutoFree(ctx, -1);
|
||||
}
|
||||
return(0);
|
||||
}
|
||||
duk_ret_t ILibDuktape_GenericMarshal_Variable_pointerBuffer(duk_context *ctx)
|
||||
{
|
||||
duk_push_this(ctx); // [var]
|
||||
void *ptr = Duktape_GetPointerProperty(ctx, -1, "_ptr");
|
||||
duk_push_fixed_buffer(ctx, sizeof(void*));
|
||||
duk_push_buffer_object(ctx, -1, 0, sizeof(void*), DUK_BUFOBJ_NODEJS_BUFFER);
|
||||
if (ptr != NULL)
|
||||
{
|
||||
memcpy_s(Duktape_GetBuffer(ctx, -2, NULL), sizeof(void*), (void*)&ptr, sizeof(void*));
|
||||
}
|
||||
return(1);
|
||||
}
|
||||
duk_ret_t ILibDuktape_GenericMarshal_Variable_pointerpointer(duk_context *ctx)
|
||||
{
|
||||
duk_push_this(ctx); // [var]
|
||||
void *ptr = Duktape_GetPointerProperty(ctx, -1, "_ptr");
|
||||
duk_push_fixed_buffer(ctx, sizeof(void*)); // [var][ptrptr]
|
||||
void **ptrptr = (void**)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
ptrptr[0] = ptr;
|
||||
|
||||
ILibDuktape_GenericMarshal_Variable_PUSH(ctx, ptrptr, (int)sizeof(void*)); // [var][ptrptr][var2]
|
||||
ILibDuktape_GenericMarshal_Variable_DisableAutoFree(ctx, -1);
|
||||
duk_swap_top(ctx, -2); // [var][var2][ptrptr]
|
||||
duk_put_prop_string(ctx, -2, "_ptrptr"); // [var][var2]
|
||||
return(1);
|
||||
}
|
||||
void ILibDuktape_GenericMarshal_Variable_PUSH(duk_context *ctx, void *ptr, int size)
|
||||
{
|
||||
duk_push_object(ctx); // [var]
|
||||
ILibDuktape_WriteID(ctx, "_GenericMarshal.Variable");
|
||||
duk_push_pointer(ctx, ptr); // [var][ptr]
|
||||
duk_put_prop_string(ctx, -2, "_ptr"); // [var]
|
||||
duk_push_int(ctx, size); // [var][size]
|
||||
duk_put_prop_string(ctx, -2, "_size"); // [var]
|
||||
duk_push_true(ctx);
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_GenericMarshal_VariableType);
|
||||
|
||||
ILibDuktape_CreateEventWithGetterAndSetterEx(ctx, "Val", ILibDuktape_GenericMarshal_Variable_Val_GET, ILibDuktape_GenericMarshal_Variable_Val_SET);
|
||||
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "Deref", ILibDuktape_GenericMarshal_Variable_Deref, DUK_VARARGS);
|
||||
ILibDuktape_CreateEventWithGetter(ctx, "String", ILibDuktape_GenericMarshal_Variable_Val_STRING);
|
||||
ILibDuktape_CreateEventWithGetter(ctx, "AnsiString", ILibDuktape_GenericMarshal_Variable_Val_ASTRING);
|
||||
ILibDuktape_CreateEventWithGetter(ctx, "HexString", ILibDuktape_GenericMarshal_Variable_Val_HSTRING);
|
||||
ILibDuktape_CreateEventWithGetter(ctx, "HexString2", ILibDuktape_GenericMarshal_Variable_Val_HSTRING2);
|
||||
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "toBuffer", ILibDuktape_GenericMarshal_Variable_toBuffer, 0);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "autoFree", ILibDuktape_GenericMarshal_Variable_autoFree, DUK_VARARGS);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "pointerBuffer", ILibDuktape_GenericMarshal_Variable_pointerBuffer, 0);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "getPointerPointer", ILibDuktape_GenericMarshal_Variable_pointerpointer, 0);
|
||||
|
||||
ILibDuktape_CreateFinalizer(ctx, ILibDuktape_GenericMarshal_Variable_Finalizer);
|
||||
}
|
||||
|
||||
duk_ret_t ILibDuktape_GenericMarshal_CreateVariable(duk_context *ctx)
|
||||
{
|
||||
char* ptr;
|
||||
@@ -383,6 +432,23 @@ duk_ret_t ILibDuktape_GenericMarshal_CreateVariable(duk_context *ctx)
|
||||
{
|
||||
str = Duktape_GetBuffer(ctx, 0, &strLen);
|
||||
size = (int)strLen + 1;
|
||||
|
||||
if (duk_is_object(ctx, 1))
|
||||
{
|
||||
if (Duktape_GetBooleanProperty(ctx, 1, "wide", 0) != 0)
|
||||
{
|
||||
#ifdef WIN32
|
||||
wchar_t *wbuffer = (wchar_t*)ILibMemory_AllocateA(((int)strLen * 2) + 2);
|
||||
size_t converted;
|
||||
mbstowcs_s(&converted, wbuffer, (size_t)strLen+1, str, (size_t)strLen);
|
||||
str = (char*)wbuffer;
|
||||
size = (int)ILibMemory_AllocateA_Size(str);
|
||||
strLen = size - 1;
|
||||
#else
|
||||
return(ILibDuktape_Error(ctx, "Not supported on this platform"));
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -396,7 +462,7 @@ duk_ret_t ILibDuktape_GenericMarshal_CreateVariable(duk_context *ctx)
|
||||
ptr[strLen] = 0;
|
||||
}
|
||||
ILibDuktape_GenericMarshal_Variable_PUSH(ctx, ptr, size); // [var]
|
||||
ILibDuktape_CreateFinalizer(ctx, ILibDuktape_GenericMarshal_Variable_Finalizer);
|
||||
ILibDuktape_GenericMarshal_Variable_EnableAutoFree(ctx, -1);
|
||||
|
||||
return 1;
|
||||
}
|
||||
@@ -599,9 +665,7 @@ duk_ret_t ILibDuktape_GenericMarshal_CreateCallbackProxy(duk_context *ctx)
|
||||
Duktape_GenericMarshal_Proxy *ptr;
|
||||
|
||||
duk_push_object(ctx); // [proxy]
|
||||
duk_push_fixed_buffer(ctx, sizeof(Duktape_GenericMarshal_Proxy)); // [proxy][buffer]
|
||||
ptr = (Duktape_GenericMarshal_Proxy*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
memset(ptr, 0, sizeof(Duktape_GenericMarshal_Proxy));
|
||||
ptr = Duktape_PushBuffer(ctx, sizeof(Duktape_GenericMarshal_Proxy)); // [proxy][buffer]
|
||||
duk_put_prop_string(ctx, -2, "_buffer"); // [proxy]
|
||||
|
||||
duk_dup(ctx, 1); // [proxy][parms]
|
||||
@@ -624,16 +688,125 @@ duk_ret_t ILibDuktape_GenericMarshal_CreateCallbackProxy(duk_context *ctx)
|
||||
return 1;
|
||||
}
|
||||
|
||||
PTRSIZE ILibDuktape_GenericMarshal_MethodInvoke_Native(int parms, void *fptr, PTRSIZE *vars)
|
||||
{
|
||||
PTRSIZE retVal = 0;
|
||||
|
||||
switch (parms)
|
||||
{
|
||||
case 0:
|
||||
retVal = ((R0)fptr)();
|
||||
break;
|
||||
case 1:
|
||||
retVal = ((R1)fptr)(vars[0]);
|
||||
break;
|
||||
case 2:
|
||||
retVal = ((R2)fptr)(vars[0], vars[1]);
|
||||
break;
|
||||
case 3:
|
||||
retVal = ((R3)fptr)(vars[0], vars[1], vars[2]);
|
||||
break;
|
||||
case 4:
|
||||
retVal = ((R4)fptr)(vars[0], vars[1], vars[2], vars[3]);
|
||||
break;
|
||||
case 5:
|
||||
retVal = ((R5)fptr)(vars[0], vars[1], vars[2], vars[3], vars[4]);
|
||||
break;
|
||||
case 6:
|
||||
retVal = ((R6)fptr)(vars[0], vars[1], vars[2], vars[3], vars[4], vars[5]);
|
||||
break;
|
||||
case 7:
|
||||
retVal = ((R7)fptr)(vars[0], vars[1], vars[2], vars[3], vars[4], vars[5], vars[6]);
|
||||
break;
|
||||
case 8:
|
||||
retVal = ((R8)fptr)(vars[0], vars[1], vars[2], vars[3], vars[4], vars[5], vars[6], vars[7]);
|
||||
break;
|
||||
case 9:
|
||||
retVal = ((R9)fptr)(vars[0], vars[1], vars[2], vars[3], vars[4], vars[5], vars[6], vars[7], vars[8]);
|
||||
break;
|
||||
case 10:
|
||||
retVal = ((R10)fptr)(vars[0], vars[1], vars[2], vars[3], vars[4], vars[5], vars[6], vars[7], vars[8], vars[9]);
|
||||
break;
|
||||
case 11:
|
||||
retVal = ((R11)fptr)(vars[0], vars[1], vars[2], vars[3], vars[4], vars[5], vars[6], vars[7], vars[8], vars[9], vars[10]);
|
||||
break;
|
||||
case 12:
|
||||
retVal = ((R12)fptr)(vars[0], vars[1], vars[2], vars[3], vars[4], vars[5], vars[6], vars[7], vars[8], vars[9], vars[10], vars[11]);
|
||||
break;
|
||||
case 13:
|
||||
retVal = ((R13)fptr)(vars[0], vars[1], vars[2], vars[3], vars[4], vars[5], vars[6], vars[7], vars[8], vars[9], vars[10], vars[11], vars[12]);
|
||||
break;
|
||||
case 14:
|
||||
retVal = ((R14)fptr)(vars[0], vars[1], vars[2], vars[3], vars[4], vars[5], vars[6], vars[7], vars[8], vars[9], vars[10], vars[11], vars[12], vars[13]);
|
||||
break;
|
||||
case 15:
|
||||
retVal = ((R15)fptr)(vars[0], vars[1], vars[2], vars[3], vars[4], vars[5], vars[6], vars[7], vars[8], vars[9], vars[10], vars[11], vars[12], vars[13], vars[14]);
|
||||
break;
|
||||
case 16:
|
||||
retVal = ((R16)fptr)(vars[0], vars[1], vars[2], vars[3], vars[4], vars[5], vars[6], vars[7], vars[8], vars[9], vars[10], vars[11], vars[12], vars[13], vars[14], vars[15]);
|
||||
break;
|
||||
case 17:
|
||||
retVal = ((R17)fptr)(vars[0], vars[1], vars[2], vars[3], vars[4], vars[5], vars[6], vars[7], vars[8], vars[9], vars[10], vars[11], vars[12], vars[13], vars[14], vars[15], vars[16]);
|
||||
break;
|
||||
case 18:
|
||||
retVal = ((R18)fptr)(vars[0], vars[1], vars[2], vars[3], vars[4], vars[5], vars[6], vars[7], vars[8], vars[9], vars[10], vars[11], vars[12], vars[13], vars[14], vars[15], vars[16], vars[17]);
|
||||
break;
|
||||
case 19:
|
||||
retVal = ((R19)fptr)(vars[0], vars[1], vars[2], vars[3], vars[4], vars[5], vars[6], vars[7], vars[8], vars[9], vars[10], vars[11], vars[12], vars[13], vars[14], vars[15], vars[16], vars[17], vars[18]);
|
||||
break;
|
||||
case 20:
|
||||
retVal = ((R20)fptr)(vars[0], vars[1], vars[2], vars[3], vars[4], vars[5], vars[6], vars[7], vars[8], vars[9], vars[10], vars[11], vars[12], vars[13], vars[14], vars[15], vars[16], vars[17], vars[18], vars[19]);
|
||||
break;
|
||||
}
|
||||
|
||||
return(retVal);
|
||||
}
|
||||
void ILibDuktape_GenericMarshal_MethodInvoke_ThreadSink_Return(void *chain, void *args)
|
||||
{
|
||||
if (!ILibMemory_CanaryOK(args)) { return; }
|
||||
|
||||
PTRSIZE *vars = (PTRSIZE*)((void**)args)[2];
|
||||
ILibDuktape_EventEmitter *e = (ILibDuktape_EventEmitter*)((void**)args)[0];
|
||||
PTRSIZE retVal = (PTRSIZE)((void**)args)[3];
|
||||
|
||||
if (!ILibMemory_CanaryOK(e) || e->ctx == NULL) { return; }
|
||||
|
||||
duk_context *ctx = e->ctx;
|
||||
ILibDuktape_EventEmitter_SetupEmit(e->ctx, e->object, "done"); // [emit][this][done]
|
||||
ILibDuktape_GenericMarshal_Variable_PUSH(e->ctx, (void*)(PTRSIZE)retVal, (int)sizeof(void*)); // [emit][this][done][retVal]
|
||||
if (duk_pcall_method(e->ctx, 2) != 0)
|
||||
{
|
||||
ILibDuktape_Process_UncaughtException(e->ctx); duk_pop(e->ctx);
|
||||
}
|
||||
else
|
||||
{
|
||||
duk_pop(ctx);
|
||||
}
|
||||
ILibMemory_Free(vars);
|
||||
}
|
||||
void ILibDuktape_GenericMarshal_MethodInvoke_ThreadSink(void *args)
|
||||
{
|
||||
void *chain = ((void**)args)[1];
|
||||
PTRSIZE *vars = (PTRSIZE*)((void**)args)[2];
|
||||
int parms = (int)(PTRSIZE)((void**)args)[3];
|
||||
void *fptr = ((void**)args)[4];
|
||||
PTRSIZE retVal = ILibDuktape_GenericMarshal_MethodInvoke_Native(parms, fptr, vars);
|
||||
|
||||
((void**)args)[3] = (void*)retVal;
|
||||
ILibChain_RunOnMicrostackThreadEx(chain, ILibDuktape_GenericMarshal_MethodInvoke_ThreadSink_Return, args);
|
||||
|
||||
}
|
||||
duk_ret_t ILibDuktape_GenericMarshal_MethodInvoke(duk_context *ctx)
|
||||
{
|
||||
void *fptr = NULL;
|
||||
int parms = duk_get_top(ctx);
|
||||
int i;
|
||||
int retVal = -1;
|
||||
PTRSIZE retVal = (PTRSIZE)(-1);
|
||||
if (parms > 20) { return(ILibDuktape_Error(ctx, "Too many parameters")); }
|
||||
PTRSIZE *vars = ILibMemory_AllocateA(sizeof(PTRSIZE)*parms);
|
||||
|
||||
duk_push_current_function(ctx); // [func]
|
||||
int spawnThread = Duktape_GetBooleanProperty(ctx, -1, "_spawnThread", 0);
|
||||
PTRSIZE *vars = spawnThread == 0 ? ILibMemory_AllocateA(sizeof(PTRSIZE)*parms) : ILibMemory_SmartAllocateEx(sizeof(PTRSIZE)*parms, 5 * sizeof(void*));
|
||||
duk_get_prop_string(ctx, -1, "_address"); // [func][addr]
|
||||
fptr = duk_to_pointer(ctx, -1);
|
||||
|
||||
@@ -667,86 +840,67 @@ duk_ret_t ILibDuktape_GenericMarshal_MethodInvoke(duk_context *ctx)
|
||||
}
|
||||
}
|
||||
|
||||
switch (parms)
|
||||
if (parms > 20)
|
||||
{
|
||||
case 0:
|
||||
retVal = (int)((R0)fptr)();
|
||||
break;
|
||||
case 1:
|
||||
retVal = (int)((R1)fptr)(vars[0]);
|
||||
break;
|
||||
case 2:
|
||||
retVal = (int)((R2)fptr)(vars[0], vars[1]);
|
||||
break;
|
||||
case 3:
|
||||
retVal = (int)((R3)fptr)(vars[0], vars[1], vars[2]);
|
||||
break;
|
||||
case 4:
|
||||
retVal = (int)((R4)fptr)(vars[0], vars[1], vars[2], vars[3]);
|
||||
break;
|
||||
case 5:
|
||||
retVal = (int)((R5)fptr)(vars[0], vars[1], vars[2], vars[3], vars[4]);
|
||||
break;
|
||||
case 6:
|
||||
retVal = (int)((R6)fptr)(vars[0], vars[1], vars[2], vars[3], vars[4], vars[5]);
|
||||
break;
|
||||
case 7:
|
||||
retVal = (int)((R7)fptr)(vars[0], vars[1], vars[2], vars[3], vars[4], vars[5], vars[6]);
|
||||
break;
|
||||
case 8:
|
||||
retVal = (int)((R8)fptr)(vars[0], vars[1], vars[2], vars[3], vars[4], vars[5], vars[6], vars[7]);
|
||||
break;
|
||||
case 9:
|
||||
retVal = (int)((R9)fptr)(vars[0], vars[1], vars[2], vars[3], vars[4], vars[5], vars[6], vars[7], vars[8]);
|
||||
break;
|
||||
case 10:
|
||||
retVal = (int)((R10)fptr)(vars[0], vars[1], vars[2], vars[3], vars[4], vars[5], vars[6], vars[7], vars[8], vars[9]);
|
||||
break;
|
||||
case 11:
|
||||
retVal = (int)((R11)fptr)(vars[0], vars[1], vars[2], vars[3], vars[4], vars[5], vars[6], vars[7], vars[8], vars[9], vars[10]);
|
||||
break;
|
||||
case 12:
|
||||
retVal = (int)((R12)fptr)(vars[0], vars[1], vars[2], vars[3], vars[4], vars[5], vars[6], vars[7], vars[8], vars[9], vars[10], vars[11]);
|
||||
break;
|
||||
case 13:
|
||||
retVal = (int)((R13)fptr)(vars[0], vars[1], vars[2], vars[3], vars[4], vars[5], vars[6], vars[7], vars[8], vars[9], vars[10], vars[11], vars[12]);
|
||||
break;
|
||||
case 14:
|
||||
retVal = (int)((R14)fptr)(vars[0], vars[1], vars[2], vars[3], vars[4], vars[5], vars[6], vars[7], vars[8], vars[9], vars[10], vars[11], vars[12], vars[13]);
|
||||
break;
|
||||
case 15:
|
||||
retVal = (int)((R15)fptr)(vars[0], vars[1], vars[2], vars[3], vars[4], vars[5], vars[6], vars[7], vars[8], vars[9], vars[10], vars[11], vars[12], vars[13], vars[14]);
|
||||
break;
|
||||
case 16:
|
||||
retVal = (int)((R16)fptr)(vars[0], vars[1], vars[2], vars[3], vars[4], vars[5], vars[6], vars[7], vars[8], vars[9], vars[10], vars[11], vars[12], vars[13], vars[14], vars[15]);
|
||||
break;
|
||||
case 17:
|
||||
retVal = (int)((R17)fptr)(vars[0], vars[1], vars[2], vars[3], vars[4], vars[5], vars[6], vars[7], vars[8], vars[9], vars[10], vars[11], vars[12], vars[13], vars[14], vars[15], vars[16]);
|
||||
break;
|
||||
case 18:
|
||||
retVal = (int)((R18)fptr)(vars[0], vars[1], vars[2], vars[3], vars[4], vars[5], vars[6], vars[7], vars[8], vars[9], vars[10], vars[11], vars[12], vars[13], vars[14], vars[15], vars[16], vars[17]);
|
||||
break;
|
||||
case 19:
|
||||
retVal = (int)((R19)fptr)(vars[0], vars[1], vars[2], vars[3], vars[4], vars[5], vars[6], vars[7], vars[8], vars[9], vars[10], vars[11], vars[12], vars[13], vars[14], vars[15], vars[16], vars[17], vars[18]);
|
||||
break;
|
||||
case 20:
|
||||
retVal = (int)((R20)fptr)(vars[0], vars[1], vars[2], vars[3], vars[4], vars[5], vars[6], vars[7], vars[8], vars[9], vars[10], vars[11], vars[12], vars[13], vars[14], vars[15], vars[16], vars[17], vars[18], vars[19]);
|
||||
break;
|
||||
default:
|
||||
duk_push_string(ctx, "INVALID NUMBER OF PARAMETERS, MAX of 10");
|
||||
duk_push_string(ctx, "INVALID NUMBER OF PARAMETERS, MAX of 20");
|
||||
duk_throw(ctx);
|
||||
return(DUK_RET_ERROR);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (spawnThread == 0)
|
||||
{
|
||||
retVal = ILibDuktape_GenericMarshal_MethodInvoke_Native(parms, fptr, vars);
|
||||
ILibDuktape_GenericMarshal_Variable_PUSH(ctx, (void*)(PTRSIZE)retVal, (int)sizeof(void*));
|
||||
}
|
||||
else
|
||||
{
|
||||
duk_push_object(ctx); // [ret]
|
||||
ILibDuktape_WriteID(ctx, "GenericMarshal.Variable.DispatcherEvent");
|
||||
ILibDuktape_EventEmitter *e = ILibDuktape_EventEmitter_Create(ctx);
|
||||
ILibDuktape_EventEmitter_CreateEventEx(e, "done");
|
||||
|
||||
void **args = (void**)ILibMemory_Extra(vars);
|
||||
args[0] = e;
|
||||
args[1] = Duktape_GetChain(ctx);
|
||||
args[2] = vars;
|
||||
args[3] = (void*)(PTRSIZE)parms;
|
||||
args[4] = fptr;
|
||||
|
||||
void *thptr = ILibSpawnNormalThread(ILibDuktape_GenericMarshal_MethodInvoke_ThreadSink, args);
|
||||
duk_push_fixed_buffer(ctx, sizeof(void*)); // [ret][buffer]
|
||||
((void**)Duktape_GetBuffer(ctx, -1, NULL))[0] = thptr;
|
||||
duk_push_buffer_object(ctx, -1, 0, sizeof(void*), DUK_BUFOBJ_NODEJS_BUFFER);// [ret][buffer][NodeBuffer]
|
||||
|
||||
duk_swap_top(ctx, -2); // [ret][NodeBuffer][buffer]
|
||||
duk_put_prop_string(ctx, -3, "\xFF_BuffPtr"); // [ret][NodeBuffer]
|
||||
ILibDuktape_CreateReadonlyProperty(ctx, "_ThreadHandle"); // [ret]
|
||||
}
|
||||
}
|
||||
|
||||
duk_push_int(ctx, retVal);
|
||||
return 1;
|
||||
}
|
||||
duk_ret_t ILibDuktape_GenericMarshal_CreateMethod(duk_context *ctx)
|
||||
{
|
||||
void* module = NULL;
|
||||
char* funcName = (char*)duk_require_string(ctx, 0);
|
||||
void* funcAddress = NULL;
|
||||
char* exposedMethod = duk_get_top(ctx) == 1 ? funcName : (char*)duk_require_string(ctx, 1);
|
||||
char* funcName;
|
||||
char* exposedMethod;
|
||||
int threadDispatch = 0;
|
||||
int deref = 0;
|
||||
|
||||
if (duk_is_object(ctx, 0))
|
||||
{
|
||||
funcName = Duktape_GetStringPropertyValue(ctx, 0, "method", NULL);
|
||||
exposedMethod = Duktape_GetStringPropertyValue(ctx, 0, "newName", funcName);
|
||||
threadDispatch = Duktape_GetIntPropertyValue(ctx, 0, "threadDispatch", 0);
|
||||
deref = Duktape_GetIntPropertyValue(ctx, 0, "dereferencePointer", 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
funcName = (char*)duk_require_string(ctx, 0);
|
||||
exposedMethod = duk_get_top(ctx) == 1 ? funcName : (char*)duk_require_string(ctx, 1);
|
||||
}
|
||||
|
||||
duk_push_this(ctx); // [obj]
|
||||
duk_get_prop_string(ctx, -1, "_moduleAddress"); // [obj][module]
|
||||
@@ -767,22 +921,52 @@ duk_ret_t ILibDuktape_GenericMarshal_CreateMethod(duk_context *ctx)
|
||||
duk_throw(ctx);
|
||||
return(DUK_RET_ERROR);
|
||||
}
|
||||
|
||||
else if(deref!=0)
|
||||
{
|
||||
funcAddress = ((void**)funcAddress)[0];
|
||||
}
|
||||
|
||||
duk_push_c_function(ctx, ILibDuktape_GenericMarshal_MethodInvoke, DUK_VARARGS); // [obj][func]
|
||||
duk_push_pointer(ctx, funcAddress); // [obj][func][addr]
|
||||
duk_put_prop_string(ctx, -2, "_address"); // [obj][func]
|
||||
if (threadDispatch != 0) { duk_push_true(ctx); duk_put_prop_string(ctx, -2, "_spawnThread"); } // [obj][func]
|
||||
duk_put_prop_string(ctx, -2, exposedMethod); // [obj]
|
||||
|
||||
return 0;
|
||||
}
|
||||
duk_ret_t ILibDuktape_GenericMarshal_NativeProxy_Finalizer(duk_context *ctx)
|
||||
{
|
||||
#ifdef WIN32
|
||||
HMODULE hm = (HMODULE)Duktape_GetPointerProperty(ctx, 0, "_moduleAddress");
|
||||
if (hm != NULL)
|
||||
{
|
||||
FreeLibrary(hm);
|
||||
}
|
||||
#else
|
||||
void *hm = Duktape_GetPointerProperty(ctx, 0, "_moduleAddress");
|
||||
if (hm != NULL)
|
||||
{
|
||||
dlclose(hm);
|
||||
}
|
||||
#endif
|
||||
return(0);
|
||||
}
|
||||
duk_ret_t ILibDuktape_GenericMarshal_CreateNativeProxy(duk_context *ctx)
|
||||
{
|
||||
void* module = NULL;
|
||||
char* libName = duk_is_string(ctx, 0) ? (char*)duk_require_string(ctx, 0) : NULL;
|
||||
|
||||
#ifdef WIN32
|
||||
if (libName != NULL)
|
||||
{
|
||||
module = (void*)LoadLibraryA((LPCSTR)libName);
|
||||
}
|
||||
else
|
||||
{
|
||||
HMODULE hModule = NULL;
|
||||
GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCTSTR)ILibDuktape_GenericMarshal_CreateNativeProxy, &hModule);
|
||||
module = (void*)hModule;
|
||||
}
|
||||
#else
|
||||
module = dlopen(libName, RTLD_NOW);
|
||||
#endif
|
||||
@@ -802,35 +986,419 @@ duk_ret_t ILibDuktape_GenericMarshal_CreateNativeProxy(duk_context *ctx)
|
||||
duk_push_pointer(ctx, module); // [obj][module]
|
||||
duk_put_prop_string(ctx, -2, "_moduleAddress"); // [obj]
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "CreateMethod", ILibDuktape_GenericMarshal_CreateMethod, DUK_VARARGS); // [obj]
|
||||
if (libName != NULL) { ILibDuktape_CreateFinalizer(ctx, ILibDuktape_GenericMarshal_NativeProxy_Finalizer); }
|
||||
|
||||
return 1;
|
||||
}
|
||||
duk_ret_t ILibDuktape_GenericMarshal_CreateVariableEx(duk_context *ctx)
|
||||
{
|
||||
char* ptr;
|
||||
int nargs = duk_get_top(ctx);
|
||||
char* ptr = NULL;
|
||||
int size;
|
||||
duk_push_current_function(ctx); // [func]
|
||||
duk_get_prop_string(ctx, -1, "_VarSize"); // [func][size]
|
||||
size = duk_to_int(ctx, -1);
|
||||
|
||||
if (nargs == 1)
|
||||
{
|
||||
duk_size_t buflen;
|
||||
ptr = Duktape_GetBuffer(ctx, 0, &buflen);
|
||||
}
|
||||
|
||||
if (ptr == NULL)
|
||||
{
|
||||
ptr = (char*)ILibMemory_Allocate(size, 0, NULL, NULL);
|
||||
ILibDuktape_GenericMarshal_Variable_PUSH(ctx, ptr, size); // [func][size][var]
|
||||
ILibDuktape_CreateFinalizer(ctx, ILibDuktape_GenericMarshal_Variable_Finalizer);
|
||||
|
||||
ILibDuktape_GenericMarshal_Variable_EnableAutoFree(ctx, -1);
|
||||
}
|
||||
else
|
||||
{
|
||||
ILibDuktape_GenericMarshal_Variable_PUSH(ctx, ((void**)ptr)[0], size); // [func][size][var]
|
||||
ILibDuktape_GenericMarshal_Variable_DisableAutoFree(ctx, -1);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
void ILibDuktape_GlobalGenericCallback_ProcessEx(void *chain, void *user)
|
||||
{
|
||||
int i;
|
||||
//void *retVal = NULL;
|
||||
Duktape_GlobalGeneric_Data *data = (Duktape_GlobalGeneric_Data*)user;
|
||||
ILibDuktape_EventEmitter_SetupEmit(data->emitter->ctx, data->emitter->object, "GlobalCallback"); // [emit][this][GlobalCallback]
|
||||
for (i = 0; i < data->numArgs; ++i)
|
||||
{
|
||||
ILibDuktape_GenericMarshal_Variable_PUSH(data->emitter->ctx, (void*)data->args[i], sizeof(void*));
|
||||
}
|
||||
if (duk_pcall_method(data->emitter->ctx, data->numArgs + 1) != 0)
|
||||
{
|
||||
ILibDuktape_Process_UncaughtException(data->emitter->ctx);
|
||||
}
|
||||
|
||||
duk_pop(data->emitter->ctx);
|
||||
|
||||
if (data->emitter->lastReturnValue != NULL)
|
||||
{
|
||||
duk_push_heapptr(data->emitter->ctx, data->emitter->lastReturnValue);
|
||||
data->retVal = Duktape_GetPointerProperty(data->emitter->ctx, -1, "_ptr");
|
||||
duk_pop(data->emitter->ctx);
|
||||
}
|
||||
|
||||
sem_post(&(data->contextWaiter));
|
||||
}
|
||||
void* ILibDuktape_GlobalGenericCallback_Process(int numParms, ...)
|
||||
{
|
||||
void *retVal = NULL;
|
||||
PTRSIZE v;
|
||||
ILibLinkedList_Lock(GlobalCallbackList);
|
||||
Duktape_GlobalGeneric_Data *data;
|
||||
int i = 0, maxCount = ILibLinkedList_GetCount(GlobalCallbackList), count = 0;
|
||||
void *node = ILibLinkedList_GetNode_Head(GlobalCallbackList);
|
||||
Duktape_GlobalGeneric_Data **refList = (Duktape_GlobalGeneric_Data**)ILibMemory_AllocateA(maxCount * sizeof(Duktape_GlobalGeneric_Data*));
|
||||
while (node != NULL)
|
||||
{
|
||||
data = (Duktape_GlobalGeneric_Data*)ILibLinkedList_GetDataFromNode(node);
|
||||
if (!ILibIsRunningOnChainThread(data->chain))
|
||||
{
|
||||
// Need to Context Switch
|
||||
Duktape_GlobalGeneric_Data *user = ILibMemory_Allocate(sizeof(Duktape_GlobalGeneric_Data) + (numParms * sizeof(PTRSIZE)), 0, NULL, NULL);
|
||||
sem_init(&(user->contextWaiter), 0, 0);
|
||||
user->chain = data->chain;
|
||||
user->emitter = data->emitter;
|
||||
user->numArgs = numParms;
|
||||
if (numParms > 0)
|
||||
{
|
||||
va_list vlist;
|
||||
va_start(vlist, numParms);
|
||||
for (i = 0; i < numParms; ++i)
|
||||
{
|
||||
user->args[i] = va_arg(vlist, PTRSIZE);
|
||||
}
|
||||
va_end(vlist);
|
||||
}
|
||||
ILibChain_RunOnMicrostackThreadEx(user->chain, ILibDuktape_GlobalGenericCallback_ProcessEx, user);
|
||||
sem_wait(&(user->contextWaiter));
|
||||
|
||||
if (user->retVal != NULL) { retVal = user->retVal; }
|
||||
sem_destroy(&(user->contextWaiter));
|
||||
free(user);
|
||||
}
|
||||
else
|
||||
{
|
||||
// No need to context switch, so just reference this
|
||||
refList[count++] = data;
|
||||
}
|
||||
node = ILibLinkedList_GetNextNode(node);
|
||||
}
|
||||
ILibLinkedList_UnLock(GlobalCallbackList);
|
||||
|
||||
for (i = 0; i < count; ++i)
|
||||
{
|
||||
ILibDuktape_EventEmitter_SetupEmit(refList[i]->emitter->ctx, refList[i]->emitter->object, "GlobalCallback"); // [emit][this][GlobalCallback]
|
||||
if (numParms > 0)
|
||||
{
|
||||
int z;
|
||||
va_list vlist;
|
||||
va_start(vlist, numParms);
|
||||
for (z = 0; z < numParms; ++z)
|
||||
{
|
||||
v = va_arg(vlist, PTRSIZE);
|
||||
ILibDuktape_GenericMarshal_Variable_PUSH(refList[i]->emitter->ctx, (void*)v, sizeof(void*));
|
||||
ILibDuktape_GenericMarshal_Variable_DisableAutoFree(refList[i]->emitter->ctx, -1);
|
||||
}
|
||||
va_end(vlist);
|
||||
}
|
||||
if (duk_pcall_method(refList[i]->emitter->ctx, numParms + 1) != 0)
|
||||
{
|
||||
ILibDuktape_Process_UncaughtException(refList[i]->emitter->ctx);
|
||||
}
|
||||
else
|
||||
{
|
||||
if ((retVal = refList[i]->emitter->lastReturnValue) != NULL)
|
||||
{
|
||||
duk_push_heapptr(refList[i]->emitter->ctx, refList[i]->emitter->lastReturnValue); // [retVal]
|
||||
if (duk_has_prop_string(refList[i]->emitter->ctx, -1, ILibDuktape_GenericMarshal_VariableType))
|
||||
{
|
||||
retVal = Duktape_GetPointerProperty(refList[i]->emitter->ctx, -1, "_ptr");
|
||||
}
|
||||
duk_pop(refList[i]->emitter->ctx); // ...
|
||||
}
|
||||
}
|
||||
duk_pop(refList[i]->emitter->ctx);
|
||||
}
|
||||
return(retVal);
|
||||
}
|
||||
|
||||
PTRSIZE ILibDuktape_GlobalGenericCallback0()
|
||||
{
|
||||
return (PTRSIZE)ILibDuktape_GlobalGenericCallback_Process(0);
|
||||
}
|
||||
PTRSIZE ILibDuktape_GlobalGenericCallback1(PTRSIZE v1)
|
||||
{
|
||||
return (PTRSIZE)ILibDuktape_GlobalGenericCallback_Process(1, v1);
|
||||
}
|
||||
PTRSIZE ILibDuktape_GlobalGenericCallback2(PTRSIZE v1, PTRSIZE v2)
|
||||
{
|
||||
return (PTRSIZE)ILibDuktape_GlobalGenericCallback_Process(2, v1, v2);
|
||||
}
|
||||
PTRSIZE ILibDuktape_GlobalGenericCallback3(PTRSIZE v1, PTRSIZE v2, PTRSIZE v3)
|
||||
{
|
||||
return (PTRSIZE)ILibDuktape_GlobalGenericCallback_Process(3, v1, v2, v3);
|
||||
}
|
||||
PTRSIZE ILibDuktape_GlobalGenericCallback4(PTRSIZE v1, PTRSIZE v2, PTRSIZE v3, PTRSIZE v4)
|
||||
{
|
||||
return (PTRSIZE)ILibDuktape_GlobalGenericCallback_Process(4, v1, v2, v3, v4);
|
||||
}
|
||||
PTRSIZE ILibDuktape_GlobalGenericCallback5(PTRSIZE v1, PTRSIZE v2, PTRSIZE v3, PTRSIZE v4, PTRSIZE v5)
|
||||
{
|
||||
return (PTRSIZE)ILibDuktape_GlobalGenericCallback_Process(5, v1, v2, v3, v4, v5);
|
||||
}
|
||||
PTRSIZE ILibDuktape_GlobalGenericCallback6(PTRSIZE v1, PTRSIZE v2, PTRSIZE v3, PTRSIZE v4, PTRSIZE v5, PTRSIZE v6)
|
||||
{
|
||||
return (PTRSIZE)ILibDuktape_GlobalGenericCallback_Process(6, v1, v2, v3, v4, v5, v6);
|
||||
}
|
||||
PTRSIZE ILibDuktape_GlobalGenericCallback7(PTRSIZE v1, PTRSIZE v2, PTRSIZE v3, PTRSIZE v4, PTRSIZE v5, PTRSIZE v6, PTRSIZE v7)
|
||||
{
|
||||
return (PTRSIZE)ILibDuktape_GlobalGenericCallback_Process(7, v1, v2, v3, v4, v5, v6, v7);
|
||||
}
|
||||
PTRSIZE ILibDuktape_GlobalGenericCallback8(PTRSIZE v1, PTRSIZE v2, PTRSIZE v3, PTRSIZE v4, PTRSIZE v5, PTRSIZE v6, PTRSIZE v7, PTRSIZE v8)
|
||||
{
|
||||
return (PTRSIZE)ILibDuktape_GlobalGenericCallback_Process(8, v1, v2, v3, v4, v5, v6, v7, v8);
|
||||
}
|
||||
duk_ret_t ILibDuktape_GenericMarshal_GlobalGenericCallback_EventSink(duk_context *ctx)
|
||||
{
|
||||
int nargs = duk_get_top(ctx), i;
|
||||
duk_push_current_function(ctx); // [func]
|
||||
duk_get_prop_string(ctx, -1, "self"); // [func][variable]
|
||||
void *self = duk_get_heapptr(ctx, -1);
|
||||
if (Duktape_GetIntPropertyValue(ctx, -1, ILibDuktape_GenericMarshal_Variable_Parms, -1) == nargs)
|
||||
{
|
||||
ILibDuktape_EventEmitter_SetupEmit(ctx, duk_get_heapptr(ctx, -1), "GlobalCallback"); // [emit][this][GlobalCallback]
|
||||
for (i = 0; i < nargs; ++i) { duk_dup(ctx, i); }
|
||||
duk_pcall_method(ctx, nargs + 1);
|
||||
duk_push_heapptr(ctx, self); // [this]
|
||||
duk_get_prop_string(ctx, -1, "emit_returnValue"); // [this][emit_returnValue]
|
||||
duk_swap_top(ctx, -2); // [emit_returnValue][this]
|
||||
duk_call_method(ctx, 0);
|
||||
return(1);
|
||||
}
|
||||
else
|
||||
{
|
||||
return(0);
|
||||
}
|
||||
}
|
||||
duk_ret_t ILibDuktape_GenericMarshal_ObjectToPtr_Verify(duk_context *ctx)
|
||||
{
|
||||
void *ptr = duk_require_heapptr(ctx, 0);
|
||||
void *var = Duktape_GetPointerProperty(ctx, 1, "_ptr");
|
||||
|
||||
duk_push_boolean(ctx, ptr == var);
|
||||
return(1);
|
||||
}
|
||||
duk_ret_t ILibDuktape_GenericMarshal_GetGlobalGenericCallback(duk_context *ctx)
|
||||
{
|
||||
int numParms = duk_require_int(ctx, 0);
|
||||
|
||||
duk_push_this(ctx); // [GenericMarshal]
|
||||
if (!duk_has_prop_string(ctx, -1, ILibDuktape_GenericMarshal_GlobalSet))
|
||||
{
|
||||
if (GlobalCallbackList == NULL)
|
||||
{
|
||||
GlobalCallbackList = ILibLinkedList_Create();
|
||||
}
|
||||
|
||||
Duktape_GlobalGeneric_Data *data = ILibMemory_Allocate(sizeof(Duktape_GlobalGeneric_Data), 0, NULL, NULL);
|
||||
data->emitter = ILibDuktape_EventEmitter_Create(ctx);
|
||||
data->chain = Duktape_GetChain(ctx);
|
||||
ILibDuktape_EventEmitter_CreateEventEx(data->emitter, "GlobalCallback");
|
||||
|
||||
ILibLinkedList_Lock(GlobalCallbackList);
|
||||
ILibLinkedList_AddTail(GlobalCallbackList, data);
|
||||
ILibLinkedList_UnLock(GlobalCallbackList);
|
||||
duk_push_true(ctx);
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_GenericMarshal_GlobalSet);
|
||||
}
|
||||
|
||||
void *ptr = NULL;
|
||||
switch (numParms)
|
||||
{
|
||||
case 0:
|
||||
ptr = (void*)(R0)ILibDuktape_GlobalGenericCallback0;
|
||||
break;
|
||||
case 1:
|
||||
ptr = (void*)(R1)ILibDuktape_GlobalGenericCallback1;
|
||||
break;
|
||||
case 2:
|
||||
ptr = (void*)(R2)ILibDuktape_GlobalGenericCallback2;
|
||||
break;
|
||||
case 3:
|
||||
ptr = (void*)(R3)ILibDuktape_GlobalGenericCallback3;
|
||||
break;
|
||||
case 4:
|
||||
ptr = (void*)(R4)ILibDuktape_GlobalGenericCallback4;
|
||||
break;
|
||||
case 5:
|
||||
ptr = (void*)(R5)ILibDuktape_GlobalGenericCallback5;
|
||||
break;
|
||||
case 6:
|
||||
ptr = (void*)(R6)ILibDuktape_GlobalGenericCallback6;
|
||||
break;
|
||||
case 7:
|
||||
ptr = (void*)(R7)ILibDuktape_GlobalGenericCallback7;
|
||||
break;
|
||||
case 8:
|
||||
ptr = (void*)(R8)ILibDuktape_GlobalGenericCallback8;
|
||||
break;
|
||||
default:
|
||||
return(ILibDuktape_Error(ctx, "%d callback parameters not currently supported. Max 8", numParms));
|
||||
}
|
||||
ILibDuktape_GenericMarshal_Variable_PUSH(ctx, ptr, (int)sizeof(void*)); // [GenericMarshal][Variable]
|
||||
ILibDuktape_EventEmitter *varEmitter = ILibDuktape_EventEmitter_Create(ctx);
|
||||
ILibDuktape_EventEmitter_CreateEventEx(varEmitter, "GlobalCallback");
|
||||
duk_push_int(ctx, numParms); duk_put_prop_string(ctx, -2, ILibDuktape_GenericMarshal_Variable_Parms);
|
||||
|
||||
duk_get_prop_string(ctx, -2, "on"); // [GenericMarshal][Variable][on]
|
||||
duk_dup(ctx, -3); // [GenericMarshal][Variable][on][this/GM]
|
||||
duk_push_string(ctx, "GlobalCallback"); // [GenericMarshal][Variable][on][this/GM][GlobalCallback]
|
||||
duk_push_c_function(ctx, ILibDuktape_GenericMarshal_GlobalGenericCallback_EventSink, DUK_VARARGS); // [GenericMarshal][Variable][on][this/GM][GlobalCallback][func]
|
||||
duk_dup(ctx, -5); // [GenericMarshal][Variable][on][this/GM][GlobalCallback][func][Variable]
|
||||
duk_put_prop_string(ctx, -2, "self"); // [GenericMarshal][Variable][on][this/GM][GlobalCallback][func]
|
||||
duk_call_method(ctx, 2); duk_pop(ctx); // [GenericMarshal][Variable]
|
||||
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "ObjectToPtr_Verify", ILibDuktape_GenericMarshal_ObjectToPtr_Verify, 2);
|
||||
return(1);
|
||||
}
|
||||
duk_ret_t ILibDuktape_GenericMarshal_Finalizer(duk_context *ctx)
|
||||
{
|
||||
void *tmp = NULL;
|
||||
if (GlobalCallbackList != NULL)
|
||||
{
|
||||
ILibLinkedList_Lock(GlobalCallbackList);
|
||||
void *node = ILibLinkedList_GetNode_Head(GlobalCallbackList);
|
||||
while (node != NULL)
|
||||
{
|
||||
Duktape_GlobalGeneric_Data *data = (Duktape_GlobalGeneric_Data*)ILibLinkedList_GetDataFromNode(node);
|
||||
if (data->chain == Duktape_GetChain(ctx))
|
||||
{
|
||||
free(data);
|
||||
void *next = ILibLinkedList_GetNextNode(node);
|
||||
ILibLinkedList_Remove(node);
|
||||
node = next;
|
||||
}
|
||||
else
|
||||
{
|
||||
node = ILibLinkedList_GetNextNode(node);
|
||||
}
|
||||
}
|
||||
if (ILibLinkedList_GetCount(GlobalCallbackList) == 0) { tmp = GlobalCallbackList; }
|
||||
ILibLinkedList_UnLock(GlobalCallbackList);
|
||||
if (tmp != NULL)
|
||||
{
|
||||
GlobalCallbackList = NULL;
|
||||
}
|
||||
}
|
||||
if (tmp != NULL) { ILibLinkedList_Destroy(tmp); }
|
||||
return(0);
|
||||
}
|
||||
duk_ret_t ILibDuktape_GenericMarshal_WrapObject(duk_context *ctx)
|
||||
{
|
||||
void *hptr = duk_require_heapptr(ctx, 0);
|
||||
|
||||
duk_push_heap_stash(ctx); // [stash]
|
||||
duk_dup(ctx, 0); // [stash][obj]
|
||||
duk_put_prop_string(ctx, -2, Duktape_GetStashKey(duk_get_heapptr(ctx, -1))); // [stash]
|
||||
duk_push_fixed_buffer(ctx, sizeof(Duktape_MarshalledObject));
|
||||
Duktape_MarshalledObject *marshalled = (Duktape_MarshalledObject*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
duk_push_buffer_object(ctx, -1, 0, sizeof(Duktape_MarshalledObject), DUK_BUFOBJ_NODEJS_BUFFER);
|
||||
marshalled->ctx = ctx;
|
||||
marshalled->heapptr = hptr;
|
||||
return(1);
|
||||
}
|
||||
duk_ret_t ILibDuktape_GenericMarshal_UnWrapObject(duk_context *ctx)
|
||||
{
|
||||
duk_size_t len;
|
||||
Duktape_MarshalledObject *marshalled = (Duktape_MarshalledObject*)Duktape_GetBuffer(ctx, 0, &len);
|
||||
if (len != sizeof(Duktape_MarshalledObject) || marshalled->ctx != ctx)
|
||||
{
|
||||
return(ILibDuktape_Error(ctx, "Invalid WrappedObject, cannot UnWrapObject()"));
|
||||
}
|
||||
duk_push_heapptr(ctx, marshalled->heapptr);
|
||||
duk_push_heap_stash(ctx);
|
||||
duk_del_prop_string(ctx, -1, Duktape_GetStashKey(marshalled->heapptr));
|
||||
duk_pop(ctx);
|
||||
return(1);
|
||||
}
|
||||
duk_ret_t ILibDuktape_GenericMarshal_StashObject(duk_context *ctx)
|
||||
{
|
||||
void *ptr = duk_require_heapptr(ctx, 0);
|
||||
|
||||
duk_push_this(ctx); // [Marshal]
|
||||
duk_get_prop_string(ctx, -1, ILibDuktape_GenericMarshal_StashTable); // [Marshal][StashTable]
|
||||
duk_dup(ctx, 0); duk_put_prop_string(ctx, -2, Duktape_GetStashKey(ptr)); // [Marshal][StashTable]
|
||||
ILibDuktape_GenericMarshal_Variable_PUSH(ctx, ptr, sizeof(void*));
|
||||
ILibDuktape_GenericMarshal_Variable_DisableAutoFree(ctx, -1);
|
||||
return(1);
|
||||
}
|
||||
duk_ret_t ILibDuktape_GenericMarshal_UnstashObject(duk_context *ctx)
|
||||
{
|
||||
void *ptr = Duktape_GetPointerProperty(ctx, 0, "_ptr");
|
||||
if (ptr == NULL)
|
||||
{
|
||||
duk_push_null(ctx);
|
||||
}
|
||||
else
|
||||
{
|
||||
duk_push_this(ctx); // [Marshal]
|
||||
duk_get_prop_string(ctx, -1, ILibDuktape_GenericMarshal_StashTable); // [Marshal][StashTable]
|
||||
char *key = Duktape_GetStashKey(ptr);
|
||||
if (duk_has_prop_string(ctx, -1, key))
|
||||
{
|
||||
duk_get_prop_string(ctx, -1, key); // [Marshal][StashTable][obj]
|
||||
if (duk_is_boolean(ctx, 1) && duk_get_boolean(ctx, 1))
|
||||
{
|
||||
duk_del_prop_string(ctx, -2, key); // [Marshal][StashTable][obj]
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
duk_push_null(ctx);
|
||||
}
|
||||
}
|
||||
return(1);
|
||||
}
|
||||
duk_ret_t ILibDuktape_GenericMarshal_ObjectToPtr(duk_context *ctx)
|
||||
{
|
||||
void *ptr = duk_require_heapptr(ctx, 0);
|
||||
|
||||
ILibDuktape_GenericMarshal_Variable_PUSH(ctx, ptr, sizeof(void*)); // [var]
|
||||
ILibDuktape_GenericMarshal_Variable_DisableAutoFree(ctx, -1);
|
||||
return(1);
|
||||
}
|
||||
|
||||
void ILibDuktape_GenericMarshal_Push(duk_context *ctx, void *chain)
|
||||
{
|
||||
duk_push_object(ctx); // [obj]
|
||||
duk_push_object(ctx); // [obj][stashTable]
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_GenericMarshal_StashTable);// [obj]
|
||||
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "CreateVariable", ILibDuktape_GenericMarshal_CreateVariable, 1);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "CreateVariable", ILibDuktape_GenericMarshal_CreateVariable, DUK_VARARGS);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "CreateCallbackProxy", ILibDuktape_GenericMarshal_CreateCallbackProxy, 2);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "CreateNativeProxy", ILibDuktape_GenericMarshal_CreateNativeProxy, 1);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "CreateNativeProxy", ILibDuktape_GenericMarshal_CreateNativeProxy, DUK_VARARGS);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "GetGenericGlobalCallback", ILibDuktape_GenericMarshal_GetGlobalGenericCallback, 1);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "WrapObject", ILibDuktape_GenericMarshal_WrapObject, 1);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "UnWrapObject", ILibDuktape_GenericMarshal_UnWrapObject, 1);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "StashObject", ILibDuktape_GenericMarshal_StashObject, 1);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "UnstashObject", ILibDuktape_GenericMarshal_UnstashObject, DUK_VARARGS);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "ObjectToPtr", ILibDuktape_GenericMarshal_ObjectToPtr, 1);
|
||||
|
||||
ILibDuktape_CreateInstanceMethodWithIntProperty(ctx, "_VarSize", 4, "CreateInteger", ILibDuktape_GenericMarshal_CreateVariableEx, 0);
|
||||
ILibDuktape_CreateInstanceMethodWithIntProperty(ctx, "_VarSize", ((int)sizeof(void*)), "CreatePointer", ILibDuktape_GenericMarshal_CreateVariableEx, 0);
|
||||
ILibDuktape_CreateInstanceMethodWithIntProperty(ctx, "_VarSize", ((int)sizeof(void*)), "CreatePointer", ILibDuktape_GenericMarshal_CreateVariableEx, DUK_VARARGS);
|
||||
ILibDuktape_CreateInstanceMethodWithIntProperty(ctx, "_VarSize", 2, "CreateShort", ILibDuktape_GenericMarshal_CreateVariableEx, 0);
|
||||
ILibDuktape_CreateFinalizer(ctx, ILibDuktape_GenericMarshal_Finalizer);
|
||||
|
||||
duk_push_int(ctx, sizeof(Duktape_MarshalledObject));
|
||||
ILibDuktape_CreateReadonlyProperty(ctx, "WrappedObjectLength");
|
||||
duk_push_int(ctx, sizeof(void*));
|
||||
ILibDuktape_CreateReadonlyProperty(ctx, "PointerSize");
|
||||
}
|
||||
|
||||
void ILibDuktape_GenericMarshal_init(duk_context *ctx)
|
||||
|
||||
@@ -120,6 +120,7 @@ typedef struct ILibDuktape_HECI_Session
|
||||
OVERLAPPED wv;
|
||||
ILibProcessPipe_Manager mgr;
|
||||
HANDLE descriptor;
|
||||
DWORD bytesRead;
|
||||
#else
|
||||
int descriptor;
|
||||
#endif
|
||||
@@ -230,6 +231,13 @@ int ILibDuktape_HECI_linuxInit()
|
||||
|
||||
duk_ret_t ILibDuktape_HECI_SessionFinalizer(duk_context *ctx)
|
||||
{
|
||||
if (duk_has_prop_string(ctx, 0, ILibDuktape_HECI_SessionMemPtr))
|
||||
{
|
||||
duk_get_prop_string(ctx, 0, ILibDuktape_HECI_SessionMemPtr);
|
||||
ILibDuktape_HECI_Session *s = (ILibDuktape_HECI_Session*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
if (s != NULL && s->PendingWrites != NULL) { ILibQueue_Destroy(s->PendingWrites); } // ToDo: If there is anything pending, we need to clear that too
|
||||
if (s != NULL) { s->stream = NULL; }
|
||||
}
|
||||
return(0);
|
||||
}
|
||||
|
||||
@@ -297,7 +305,7 @@ ILibTransport_DoneState ILibDuktape_HECI_Session_WriteHandler_Process(ILibDuktap
|
||||
ssize_t bytesWritten;
|
||||
#endif
|
||||
|
||||
while (ILibQueue_GetCount(session->PendingWrites) > 0)
|
||||
while (session->noPipelining || ILibQueue_GetCount(session->PendingWrites) > 0)
|
||||
{
|
||||
ILibDuktape_HECI_WriteState *state = (ILibDuktape_HECI_WriteState*)ILibQueue_PeekQueue(session->PendingWrites);
|
||||
returnIgnored = state->returnIgnored;
|
||||
@@ -469,15 +477,19 @@ ILibTransport_DoneState ILibDuktape_HECI_Session_WriteSink(ILibDuktape_DuplexStr
|
||||
}
|
||||
void ILibDuktape_HECI_Session_EndSink(ILibDuktape_DuplexStream *stream, void *user)
|
||||
{
|
||||
|
||||
duk_context *ctx = stream->readableStream->ctx;
|
||||
duk_push_this(ctx);
|
||||
duk_get_prop_string(ctx, -1, "disconnect");
|
||||
duk_swap_top(ctx, -2);
|
||||
if (duk_pcall_method(ctx, 0) != 0) { ILibDuktape_Process_UncaughtException(ctx); }
|
||||
duk_pop(ctx);
|
||||
}
|
||||
void ILibDuktape_HECI_Session_PauseSink(ILibDuktape_DuplexStream *sender, void *user)
|
||||
{
|
||||
#ifdef WIN32
|
||||
ILibDuktape_HECI_Session *session = (ILibDuktape_HECI_Session*)user;
|
||||
|
||||
// To Pause, all we need to do is remove our handle
|
||||
ILibProcessPipe_WaitHandle_Remove(session->mgr, session->v.hEvent);
|
||||
// NO-OP Because we are already PAUSED, since we context switched
|
||||
UNREFERENCED_PARAMETER(sender);
|
||||
UNREFERENCED_PARAMETER(user);
|
||||
#else
|
||||
UNREFERENCED_PARAMETER(sender);
|
||||
UNREFERENCED_PARAMETER(user);
|
||||
@@ -485,6 +497,15 @@ void ILibDuktape_HECI_Session_PauseSink(ILibDuktape_DuplexStream *sender, void *
|
||||
}
|
||||
#ifdef WIN32
|
||||
BOOL ILibDuktape_HECI_Session_ReceiveSink(HANDLE event, void* user);
|
||||
void __stdcall ILibDuktape_HECI_Session_ResumeSink2(ULONG_PTR obj)
|
||||
{
|
||||
ILibDuktape_HECI_Session *session = (ILibDuktape_HECI_Session*)obj;
|
||||
BOOL result = ReadFile(session->descriptor, session->buffer, (DWORD)session->bufferSize, &(session->bytesRead), &(session->v));
|
||||
if (result == TRUE || GetLastError() == ERROR_IO_PENDING)
|
||||
{
|
||||
ILibProcessPipe_WaitHandle_Add(session->mgr, session->v.hEvent, session, ILibDuktape_HECI_Session_ReceiveSink);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
void ILibDuktape_HECI_Session_ResumeSink_NoPipeline(void *chain, void *user)
|
||||
{
|
||||
@@ -508,37 +529,34 @@ void ILibDuktape_HECI_Session_ResumeSink(ILibDuktape_DuplexStream *sender, void
|
||||
if (session->noPipelining != 0)
|
||||
{
|
||||
ILibChain_RunOnMicrostackThread(sender->readableStream->chain, ILibDuktape_HECI_Session_ResumeSink_NoPipeline, session);
|
||||
// Note: DO NOT 'return' here, because we still need to QueueUserAPC, to resume the stream on Windows
|
||||
}
|
||||
|
||||
#ifdef WIN32
|
||||
DWORD bytesRead;
|
||||
|
||||
// To Resume, we need to ReadFile, then re-add our waithandle
|
||||
BOOL result = ReadFile(session->descriptor, session->buffer, (DWORD)session->bufferSize, &bytesRead, &(session->v));
|
||||
if (result == TRUE || GetLastError() == ERROR_IO_PENDING)
|
||||
{
|
||||
ILibProcessPipe_WaitHandle_Add(session->mgr, session->v.hEvent, session, ILibDuktape_HECI_Session_ReceiveSink);
|
||||
}
|
||||
// To Resume, we need to first context switch to the Windows Thread
|
||||
QueueUserAPC((PAPCFUNC)ILibDuktape_HECI_Session_ResumeSink2, ILibProcessPipe_Manager_GetWorkerThread(session->mgr), (ULONG_PTR)session);
|
||||
#endif
|
||||
}
|
||||
#ifdef WIN32
|
||||
void ILibDuktape_HECI_Session_ReceiveSink2(void *chain, void *user)
|
||||
{
|
||||
ILibDuktape_HECI_Session *session = (ILibDuktape_HECI_Session*)user;
|
||||
if (!ILibMemory_CanaryOK(session)) { return; }
|
||||
|
||||
ILibDuktape_DuplexStream_WriteData(session->stream, session->buffer, session->bytesRead);
|
||||
if (session->stream != NULL && !session->stream->readableStream->paused)
|
||||
{
|
||||
ILibDuktape_HECI_Session_ResumeSink(session->stream, session->stream->user);
|
||||
}
|
||||
}
|
||||
BOOL ILibDuktape_HECI_Session_ReceiveSink(HANDLE event, void* user)
|
||||
{
|
||||
ILibDuktape_HECI_Session *session = (ILibDuktape_HECI_Session*)user;
|
||||
DWORD bytesRead;
|
||||
|
||||
do
|
||||
if (ILibMemory_CanaryOK(session))
|
||||
{
|
||||
if (GetOverlappedResult(session->descriptor, &(session->v), &bytesRead, FALSE) == FALSE) { break; }
|
||||
ILibDuktape_DuplexStream_WriteData(session->stream, session->buffer, bytesRead);
|
||||
} while (session->stream->readableStream->paused == 0 && ReadFile(session->descriptor, session->buffer, (DWORD)session->bufferSize, &bytesRead, &(session->v)) == TRUE);
|
||||
if (session->stream->readableStream->paused == 0 && GetLastError() != ERROR_IO_PENDING)
|
||||
{
|
||||
// Broken Connection
|
||||
ILibProcessPipe_WaitHandle_Remove(session->mgr, session->v.hEvent); // Remove ourselves from processing loop
|
||||
ILibDuktape_DuplexStream_WriteEnd(session->stream);
|
||||
if (GetOverlappedResult(session->descriptor, &(session->v), &(session->bytesRead), FALSE) == TRUE) { ILibChain_RunOnMicrostackThreadEx(session->chain, ILibDuktape_HECI_Session_ReceiveSink2, session); }
|
||||
}
|
||||
return(TRUE);
|
||||
return(FALSE);
|
||||
}
|
||||
void __stdcall ILibDuktape_HECI_Session_Start(ULONG_PTR obj)
|
||||
{
|
||||
@@ -560,6 +578,7 @@ duk_ret_t ILibDuktape_HECI_create_OnClientConnect(duk_context *ctx)
|
||||
duk_swap_top(ctx, -2); // [emit][this]
|
||||
duk_push_string(ctx, "error"); // [emit][this][error]
|
||||
duk_push_error_object(ctx, DUK_ERR_ERROR, "HECI Connection Error [%d]", statusCode); // [emit][this][error][err]
|
||||
duk_push_int(ctx, statusCode); duk_put_prop_string(ctx, -2, "errno");
|
||||
if (duk_pcall_method(ctx, 2) != 0) { ILibDuktape_Process_UncaughtExceptionEx(ctx, "HECI.session.onError(): "); }
|
||||
duk_pop(ctx); // ...
|
||||
}
|
||||
@@ -572,9 +591,7 @@ duk_ret_t ILibDuktape_HECI_create_OnClientConnect(duk_context *ctx)
|
||||
duk_push_int(ctx, ((int*)buffer)[0]);
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_HECI_MaxBufferSize); // [session]
|
||||
|
||||
duk_push_fixed_buffer(ctx, sizeof(ILibDuktape_HECI_Session) + ((int*)buffer)[0]); // [session][buffer]
|
||||
session = (ILibDuktape_HECI_Session*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
memset(session, 0, sizeof(ILibDuktape_HECI_Session) + ((int*)buffer)[0]);
|
||||
session = (ILibDuktape_HECI_Session*)Duktape_PushBuffer(ctx, sizeof(ILibDuktape_HECI_Session) + ((int*)buffer)[0]); // [session][buffer]
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_HECI_SessionMemPtr); // [session]
|
||||
#ifdef WIN32
|
||||
session->v.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
|
||||
@@ -590,7 +607,6 @@ duk_ret_t ILibDuktape_HECI_create_OnClientConnect(duk_context *ctx)
|
||||
duk_push_current_function(ctx);
|
||||
session->noPipelining = Duktape_GetIntPropertyValue(ctx, -1, ILibDuktape_HECI_Session_NoPipeline, 0);
|
||||
duk_pop(ctx);
|
||||
|
||||
#ifdef _POSIX
|
||||
//printf("Session: %p\n", session);
|
||||
duk_get_prop_string(ctx, -1, ILibDuktape_HECI_Child); // [session][heci]
|
||||
@@ -675,6 +691,51 @@ duk_ret_t ILibDuktape_HECI_Session_connect(duk_context *ctx)
|
||||
duk_pop(ctx); // ...
|
||||
return(0);
|
||||
}
|
||||
#ifdef WIN32
|
||||
void __stdcall ILibDuktape_HECI_Session_CloseSink2(ULONG_PTR obj)
|
||||
{
|
||||
HANDLE h = (HANDLE)obj;
|
||||
CloseHandle(h);
|
||||
}
|
||||
#endif
|
||||
duk_ret_t ILibDuktape_HECI_Session_close(duk_context *ctx)
|
||||
{
|
||||
duk_push_this(ctx); // [session]
|
||||
|
||||
if (duk_has_prop_string(ctx, -1, ILibDuktape_HECI_Child))
|
||||
{
|
||||
duk_get_prop_string(ctx, -1, ILibDuktape_HECI_Child); // [session][heci]
|
||||
duk_get_prop_string(ctx, -1, "disconnect"); // [session][heci][close]
|
||||
duk_swap_top(ctx, -2); // [session][close][this]
|
||||
duk_call_method(ctx, 0);
|
||||
}
|
||||
|
||||
duk_push_this(ctx);
|
||||
#ifdef WIN32
|
||||
ILibDuktape_HECI_Session *session = NULL;
|
||||
if (duk_has_prop_string(ctx, -1, ILibDuktape_HECI_SessionMemPtr))
|
||||
{
|
||||
duk_get_prop_string(ctx, -1, ILibDuktape_HECI_SessionMemPtr); // [HECI][SESSION]
|
||||
session = (ILibDuktape_HECI_Session*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
|
||||
ILibProcessPipe_WaitHandle_Remove(session->mgr, session->v.hEvent);
|
||||
ILibProcessPipe_WaitHandle_Remove(session->mgr, session->wv.hEvent);
|
||||
session->stream = NULL;
|
||||
QueueUserAPC((PAPCFUNC)ILibDuktape_HECI_Session_CloseSink2, ILibProcessPipe_Manager_GetWorkerThread(session->mgr), (ULONG_PTR)session->descriptor);
|
||||
}
|
||||
#else
|
||||
int d = Duktape_GetIntPropertyValue(ctx, -1, ILibDuktape_HECI_Descriptor, -1);
|
||||
HECI_chainLink *hcl = (HECI_chainLink*)Duktape_GetPointerProperty(ctx, -1, ILibDuktape_HECI_ChainLink);
|
||||
if (hcl != NULL)
|
||||
{
|
||||
hcl->descriptor = -1;
|
||||
if (d != -1) { close(d); };
|
||||
duk_del_prop_string(ctx, -1, ILibDuktape_HECI_Descriptor);
|
||||
}
|
||||
#endif
|
||||
|
||||
return(0);
|
||||
}
|
||||
duk_ret_t ILibDuktape_HECI_create(duk_context *ctx)
|
||||
{
|
||||
duk_push_object(ctx); // [Session]
|
||||
@@ -689,6 +750,7 @@ duk_ret_t ILibDuktape_HECI_create(duk_context *ctx)
|
||||
ILibDuktape_EventEmitter_CreateEventEx(emitter, "error");
|
||||
ILibDuktape_CreateProperty_InstanceMethod(ctx, "connect", ILibDuktape_HECI_Session_connect, DUK_VARARGS);
|
||||
ILibDuktape_CreateFinalizer(ctx, ILibDuktape_HECI_SessionFinalizer);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "disconnect", ILibDuktape_HECI_Session_close, 0);
|
||||
return(1);
|
||||
}
|
||||
|
||||
@@ -743,6 +805,8 @@ void ILibDuktape_HECI_NextIoctl(ILibQueue q)
|
||||
{
|
||||
ILibDuktape_HECI_ioctl_data *data = (ILibDuktape_HECI_ioctl_data*)ILibQueue_PeekQueue(q);
|
||||
int res;
|
||||
if (data == NULL) { return; } // This line is unnecessary, because this method is only called on a non-empty Queue, but to satisfy Klockwork...
|
||||
|
||||
data->bytesReceived = 0;
|
||||
|
||||
ResetEvent(data->v.hEvent);
|
||||
@@ -817,9 +881,7 @@ duk_ret_t ILibDuktape_HECI_doIoctl(duk_context *ctx)
|
||||
ILibDuktape_Push_ObjectStash(ctx); // [heci][stash]
|
||||
duk_push_array(ctx); // [heci][stash][array]
|
||||
ILibDuktape_HECI_ioctl_data *data;
|
||||
duk_push_fixed_buffer(ctx, bufferLen + sizeof(ILibDuktape_HECI_ioctl_data)); // [heci][stash][array][state]
|
||||
data = (ILibDuktape_HECI_ioctl_data*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
memset(data, 0, sizeof(ILibDuktape_HECI_ioctl_data));
|
||||
data = (ILibDuktape_HECI_ioctl_data*)Duktape_PushBuffer(ctx, bufferLen + sizeof(ILibDuktape_HECI_ioctl_data));
|
||||
duk_put_prop_index(ctx, -2, 0); // [heci][stash][array]
|
||||
if (outBufferLen > 0)
|
||||
{ // [heci][stash][array][buffer]
|
||||
@@ -954,6 +1016,7 @@ void ILibDuktape_HECI_PostSelect(void* object, int slct, fd_set *readset, fd_set
|
||||
ILibDuktape_DuplexStream_WriteEnd(h->session->stream);
|
||||
}
|
||||
}
|
||||
if (h->descriptor <= 0) { return; }
|
||||
if (FD_ISSET(h->descriptor, writeset))
|
||||
{
|
||||
ILibDuktape_HECI_Session_WriteHandler_Process(h->session);
|
||||
@@ -971,6 +1034,7 @@ void ILibDuktape_HECI_Destroy(void *object)
|
||||
close(h->descriptor);
|
||||
}
|
||||
#endif
|
||||
|
||||
void ILibDuktape_HECI_Push(duk_context *ctx, void *chain)
|
||||
{
|
||||
duk_push_object(ctx); // [HECI]
|
||||
@@ -1011,6 +1075,7 @@ void ILibDuktape_HECI_Push(duk_context *ctx, void *chain)
|
||||
#endif
|
||||
if (chain != NULL) { ILibDuktape_CreateInstanceMethod(ctx, "create", ILibDuktape_HECI_create, 0); }
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "doIoctl", ILibDuktape_HECI_doIoctl, DUK_VARARGS);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "disconnect", ILibDuktape_HECI_Session_close, 0);
|
||||
#ifdef _POSIX
|
||||
duk_push_pointer(ctx, hlink->Q); // [HECI][Q]
|
||||
#else
|
||||
|
||||
@@ -112,7 +112,7 @@ void *Duktape_GetPointerProperty(duk_context *ctx, duk_idx_t i, char* propertyNa
|
||||
char* Duktape_GetStringPropertyValueEx(duk_context *ctx, duk_idx_t i, char* propertyName, char* defaultValue, duk_size_t *len)
|
||||
{
|
||||
char *retVal = defaultValue;
|
||||
if (duk_has_prop_string(ctx, i, propertyName))
|
||||
if (ctx != NULL && duk_has_prop_string(ctx, i, propertyName))
|
||||
{
|
||||
duk_get_prop_string(ctx, i, propertyName);
|
||||
retVal = (char*)duk_get_lstring(ctx, -1, len);
|
||||
@@ -127,7 +127,7 @@ char* Duktape_GetStringPropertyValueEx(duk_context *ctx, duk_idx_t i, char* prop
|
||||
int Duktape_GetIntPropertyValue(duk_context *ctx, duk_idx_t i, char* propertyName, int defaultValue)
|
||||
{
|
||||
int retVal = defaultValue;
|
||||
if (duk_has_prop_string(ctx, i, propertyName))
|
||||
if (ctx!=NULL && duk_has_prop_string(ctx, i, propertyName))
|
||||
{
|
||||
duk_get_prop_string(ctx, i, propertyName);
|
||||
retVal = duk_to_int(ctx, -1);
|
||||
@@ -159,6 +159,7 @@ char *Duktape_GetStashKey(void* value)
|
||||
char* Duktape_GetBuffer(duk_context *ctx, duk_idx_t i, duk_size_t *bufLen)
|
||||
{
|
||||
char *retVal = NULL;
|
||||
duk_size_t len = 0;
|
||||
if (bufLen != NULL) { *bufLen = 0; }
|
||||
|
||||
if (duk_is_string(ctx, i))
|
||||
@@ -167,11 +168,29 @@ char* Duktape_GetBuffer(duk_context *ctx, duk_idx_t i, duk_size_t *bufLen)
|
||||
}
|
||||
else if (duk_is_buffer(ctx, i))
|
||||
{
|
||||
retVal = (char*)duk_require_buffer(ctx, i,bufLen);
|
||||
retVal = (char*)duk_require_buffer(ctx, i, &len);
|
||||
if (ILibMemory_CanaryOK(ILibMemory_FromRaw(retVal)) && ILibMemory_RawSize(ILibMemory_FromRaw(retVal)) == len)
|
||||
{
|
||||
retVal = ILibMemory_FromRaw(retVal);
|
||||
if (bufLen != NULL) { *bufLen = ILibMemory_Size(retVal); }
|
||||
}
|
||||
else if (bufLen != NULL)
|
||||
{
|
||||
*bufLen = len;
|
||||
}
|
||||
}
|
||||
else if(duk_is_buffer_data(ctx, i))
|
||||
{
|
||||
retVal = (char*)duk_require_buffer_data(ctx, i, bufLen);
|
||||
retVal = (char*)duk_require_buffer_data(ctx, i, &len);
|
||||
if (ILibMemory_CanaryOK(ILibMemory_FromRaw(retVal)) && ILibMemory_RawSize(ILibMemory_FromRaw(retVal)) == len)
|
||||
{
|
||||
retVal = ILibMemory_FromRaw(retVal);
|
||||
if (bufLen != NULL) { *bufLen = ILibMemory_Size(retVal); }
|
||||
}
|
||||
else if (bufLen != NULL)
|
||||
{
|
||||
*bufLen = len;
|
||||
}
|
||||
}
|
||||
else if (duk_is_object(ctx, i))
|
||||
{
|
||||
@@ -607,37 +626,7 @@ void *ILibDuktape_Memory_AllocEx(duk_context *ctx, duk_idx_t index, duk_size_t s
|
||||
duk_pop_2(ctx); // ...
|
||||
return(retVal);
|
||||
}
|
||||
void ILibDuktape_ValidatePointer(void *chain, void *ptr)
|
||||
{
|
||||
ILibHashtable_Put(ILibChain_GetBaseHashtable(chain), ptr, NULL, 0, (void*)0xFFFF);
|
||||
}
|
||||
void ILibDuktape_InValidatePointer(void *chain, void *ptr)
|
||||
{
|
||||
ILibHashtable_Remove(ILibChain_GetBaseHashtable(chain), ptr, NULL, 0);
|
||||
}
|
||||
int ILibDuktape_IsPointerValid(void *chain, void *ptr)
|
||||
{
|
||||
return(ILibHashtable_Get(ILibChain_GetBaseHashtable(chain), ptr, NULL, 0) == NULL ? 0 : 1);
|
||||
}
|
||||
duk_ret_t ILibDuktape_PointerValidation_Finalizer(duk_context *ctx)
|
||||
{
|
||||
duk_push_this(ctx);
|
||||
void *chain = Duktape_GetChain(ctx);
|
||||
void *obj = duk_get_heapptr(ctx, -1);
|
||||
ILibDuktape_InValidatePointer(chain, obj);
|
||||
duk_pop(ctx);
|
||||
return(0);
|
||||
}
|
||||
void ILibDuktape_PointerValidation_Init(duk_context *ctx)
|
||||
{
|
||||
void *chain = Duktape_GetChain(ctx);
|
||||
if (!ILibDuktape_IsPointerValid(chain, duk_get_heapptr(ctx, -1)))
|
||||
{
|
||||
// Not set up yet, so set it up
|
||||
ILibDuktape_ValidatePointer(chain, duk_get_heapptr(ctx, -1));
|
||||
ILibDuktape_CreateFinalizer(ctx, ILibDuktape_PointerValidation_Finalizer);
|
||||
}
|
||||
}
|
||||
|
||||
duk_ret_t ILibDuktape_Immediate_Sink(duk_context *ctx)
|
||||
{
|
||||
ILibDuktape_ImmediateHandler userCallback = (ILibDuktape_ImmediateHandler)duk_get_pointer(ctx, 0);
|
||||
@@ -689,6 +678,61 @@ void* ILibDuktape_Immediate(duk_context *ctx, void ** args, int argsLen, ILibDuk
|
||||
if (duk_pcall_method(ctx, 3) != 0) { ILibDuktape_Process_UncaughtExceptionEx(ctx, "ILibDuktape_Immediate => immediate(): "); duk_pop(ctx); return(NULL); }
|
||||
|
||||
|
||||
retval = duk_get_heapptr(ctx, -1); // [immediate]
|
||||
duk_push_heap_stash(ctx); // [immediate][stash]
|
||||
duk_swap_top(ctx, -2); // [stash][immediate]
|
||||
duk_put_prop_string(ctx, -2, Duktape_GetStashKey(retval)); // [stash]
|
||||
duk_pop(ctx); // ...
|
||||
return(retval);
|
||||
}
|
||||
duk_ret_t ILibDuktape_Interval_Sink(duk_context *ctx)
|
||||
{
|
||||
ILibDuktape_ImmediateHandler userCallback = (ILibDuktape_ImmediateHandler)duk_get_pointer(ctx, 0);
|
||||
void **args = NULL;
|
||||
int argsLen, i;
|
||||
|
||||
duk_push_this(ctx); // [immediate]
|
||||
duk_dup(ctx, 1); // [immediate][array]
|
||||
if ((argsLen = (int)duk_get_length(ctx, -1)) > 0)
|
||||
{
|
||||
args = ILibMemory_AllocateA(sizeof(void*)*argsLen);
|
||||
for (i = 0; i < argsLen; ++i)
|
||||
{
|
||||
duk_get_prop_index(ctx, -1, i); // [immediate][array][arg]
|
||||
args[i] = duk_get_pointer(ctx, -1);
|
||||
duk_pop(ctx); // [immediate][array]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (userCallback != NULL) { userCallback(ctx, args, argsLen); }
|
||||
return(0);
|
||||
}
|
||||
void* ILibDuktape_Interval(duk_context *ctx, void **args, int argsLen, int delay, ILibDuktape_IntervalHandler callback)
|
||||
{
|
||||
void *retval = NULL;
|
||||
int i = 0;
|
||||
duk_push_global_object(ctx); // [g]
|
||||
duk_get_prop_string(ctx, -1, "setInterval"); // [g][setInterval]
|
||||
duk_swap_top(ctx, -2); // [setInterval][this]
|
||||
duk_push_c_function(ctx, ILibDuktape_Interval_Sink, DUK_VARARGS); // [setInterval][this][func]
|
||||
duk_push_int(ctx, delay); // [setInterval][this][func][delay]
|
||||
duk_push_pointer(ctx, callback); // [setInterval][this][func][delay][userFunc]
|
||||
duk_push_array(ctx); // [setInterval][this][func][delay][userFunc][array]
|
||||
|
||||
while (args[i] != NULL && i < argsLen)
|
||||
{
|
||||
duk_get_prop_string(ctx, -1, "push"); // [setInterval][this][func][delay][userFunc][array][push]
|
||||
duk_dup(ctx, -2); // [setInterval][this][func][delay][userFunc][array][push][this]
|
||||
duk_push_pointer(ctx, args[i]); // [setInterval][this][func][delay][userFunc][array][push][this][val]
|
||||
if (duk_pcall_method(ctx, 1) != 0) { ILibDuktape_Process_UncaughtExceptionEx(ctx, "ILibDuktape_Immediate => Array.push(): "); }
|
||||
duk_pop(ctx); // [setInterval][this][func][delay][userFunc][array]
|
||||
++i;
|
||||
}
|
||||
|
||||
if (duk_pcall_method(ctx, 4) != 0) { ILibDuktape_Process_UncaughtExceptionEx(ctx, "ILibDuktape_Interval => interval(): "); duk_pop(ctx); return(NULL); }
|
||||
|
||||
|
||||
retval = duk_get_heapptr(ctx, -1); // [immediate]
|
||||
duk_push_heap_stash(ctx); // [immediate][stash]
|
||||
duk_swap_top(ctx, -2); // [stash][immediate]
|
||||
@@ -725,6 +769,142 @@ duk_idx_t duk_push_int_ex(duk_context *ctx, duk_int_t val)
|
||||
return(duk_push_int(ctx, val), duk_get_top_index(ctx));
|
||||
}
|
||||
|
||||
void Duktape_Console_Log_ChainEx(duk_context *ctx, ILibDuktape_LogTypes logType, char *msg, duk_size_t msgLen)
|
||||
{
|
||||
duk_push_global_object(ctx); // [g]
|
||||
duk_get_prop_string(ctx, -1, "console"); // [g][console]
|
||||
switch (logType)
|
||||
{
|
||||
case ILibDuktape_LogType_Error:
|
||||
duk_get_prop_string(ctx, -1, "error"); // [g][console][error]
|
||||
break;
|
||||
case ILibDuktape_LogType_Warn:
|
||||
duk_get_prop_string(ctx, -1, "warn"); // [g][console][warn]
|
||||
break;
|
||||
default:
|
||||
duk_get_prop_string(ctx, -1, "log"); // [g][console][log]
|
||||
break;
|
||||
}
|
||||
duk_swap_top(ctx, -2); // [g][log][this]
|
||||
duk_push_lstring(ctx, msg, msgLen); // [g][log][this][str]
|
||||
duk_pcall_method(ctx, 1); duk_pop(ctx); // [g]
|
||||
duk_pop(ctx); // ...
|
||||
}
|
||||
|
||||
typedef struct Duktape_Console_Log_data
|
||||
{
|
||||
duk_context *ctx;
|
||||
ILibDuktape_LogTypes logType;
|
||||
}Duktape_Console_Log_data;
|
||||
|
||||
void Duktape_Console_Log_Chain(void *chain, void *user)
|
||||
{
|
||||
Duktape_Console_Log_data *data = (Duktape_Console_Log_data*)user;
|
||||
char *msg = (char*)ILibMemory_Extra(data);
|
||||
|
||||
Duktape_Console_Log_ChainEx(data->ctx, data->logType, msg, ILibMemory_Size(msg));
|
||||
|
||||
ILibMemory_Free(user);
|
||||
}
|
||||
void Duktape_Console_Log(duk_context *ctx, void *chain, ILibDuktape_LogTypes logType, char *msg, duk_size_t msgLen)
|
||||
{
|
||||
if (ILibIsRunningOnChainThread(chain))
|
||||
{
|
||||
Duktape_Console_Log_ChainEx(ctx, logType, msg, msgLen);
|
||||
}
|
||||
else
|
||||
{
|
||||
Duktape_Console_Log_data *data = (Duktape_Console_Log_data*)ILibMemory_SmartAllocateEx(sizeof(Duktape_Console_Log_data), msgLen);
|
||||
data->ctx = ctx;
|
||||
data->logType = logType;
|
||||
memcpy_s(ILibMemory_Extra(data), ILibMemory_ExtraSize(data), msg, msgLen);
|
||||
|
||||
ILibChain_RunOnMicrostackThreadEx(chain, Duktape_Console_Log_Chain, data);
|
||||
}
|
||||
}
|
||||
|
||||
char* ILibDuktape_String_AsWide(duk_context *ctx, duk_idx_t idx, duk_size_t *len)
|
||||
{
|
||||
char *src;
|
||||
src = (char*)duk_require_string(ctx, idx);
|
||||
|
||||
#ifdef WIN32
|
||||
size_t inBufferLen = 2 + (2 * MultiByteToWideChar(CP_UTF8, 0, (LPCCH)src, -1, NULL, 0));
|
||||
LPWSTR inBuffer = (LPWSTR)ILibMemory_AllocateTemp(Duktape_GetChain(ctx), inBufferLen);
|
||||
|
||||
int r = MultiByteToWideChar(CP_UTF8, 0, (LPCCH)src, -1, inBuffer, (int)inBufferLen);
|
||||
if (len != NULL)
|
||||
{
|
||||
*len = (duk_size_t)r;
|
||||
}
|
||||
return(r == 0 ? NULL : (char*)inBuffer);
|
||||
#else
|
||||
return(src);
|
||||
#endif
|
||||
}
|
||||
void ILibDuktape_String_PushWideString(duk_context *ctx, char *wstr, size_t wstrlen)
|
||||
{
|
||||
#ifdef WIN32
|
||||
char *tmp;
|
||||
size_t tmpLen;
|
||||
|
||||
tmpLen = 2 + (size_t)WideCharToMultiByte(CP_UTF8, 0, (LPCWCH)wstr, (int)(wstrlen > 0 ? wstrlen : -1), NULL, 0, NULL, NULL);
|
||||
tmp = (char*)ILibMemory_AllocateTemp(Duktape_GetChain(ctx), tmpLen);
|
||||
|
||||
if (WideCharToMultiByte(CP_UTF8, 0, (LPCWCH)wstr, (int)(wstrlen > 0 ? wstrlen : -1), (LPSTR)tmp, (int)tmpLen, NULL, NULL) != 0)
|
||||
{
|
||||
duk_push_string(ctx, tmp);
|
||||
}
|
||||
else
|
||||
{
|
||||
ILibDuktape_Error(ctx, "String_PushWideString() Error: %u", GetLastError());
|
||||
}
|
||||
#else
|
||||
if (wstrlen == 0)
|
||||
{
|
||||
duk_push_string(ctx, wstr);
|
||||
}
|
||||
else
|
||||
{
|
||||
duk_push_lstring(ctx, wstr, wstrlen);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
char *ILibDuktape_String_WideToUTF8(duk_context *ctx, char *wstr)
|
||||
{
|
||||
#ifdef WIN32
|
||||
char *tmp;
|
||||
size_t tmpLen;
|
||||
|
||||
tmpLen = 2 + (size_t)WideCharToMultiByte(CP_UTF8, 0, (LPCWCH)wstr, -1, NULL, 0, NULL, NULL);
|
||||
tmp = (char*)ILibMemory_AllocateTemp(Duktape_GetChain(ctx), tmpLen);
|
||||
WideCharToMultiByte(CP_UTF8, 0, (LPCWCH)wstr, -1, tmp, (int)tmpLen, NULL, NULL);
|
||||
return(tmp);
|
||||
#else
|
||||
// NOP for non-Windows, because should already be UTF8
|
||||
return(wstr);
|
||||
#endif
|
||||
}
|
||||
char *ILibDuktape_String_UTF8ToWide(duk_context *ctx, char *str)
|
||||
{
|
||||
#ifdef WIN32
|
||||
size_t tmpLen = 2 + (2 * MultiByteToWideChar(CP_UTF8, 0, (LPCCH)str, -1, NULL, 0));
|
||||
LPWSTR retVal = (LPWSTR)ILibMemory_AllocateTemp(Duktape_GetChain(ctx), tmpLen);
|
||||
MultiByteToWideChar(CP_UTF8, 0, (LPCCH)str, -1, retVal, (int)tmpLen);
|
||||
return((char*)retVal);
|
||||
#else
|
||||
// NOP on non-Windows, as strings should always be UTF-8 by default
|
||||
return(str);
|
||||
#endif
|
||||
}
|
||||
void ILibDuktape_Log_Object(duk_context *ctx, duk_idx_t i, char *meta)
|
||||
{
|
||||
void *h = duk_get_heapptr(ctx, i);
|
||||
duk_enum(ctx, i, DUK_ENUM_INCLUDE_HIDDEN | DUK_ENUM_INCLUDE_SYMBOLS);
|
||||
while (duk_next(ctx, -1, 1))
|
||||
{
|
||||
printf(" [%s: %p] => %s (%p)\n", (meta==NULL?"OBJ":meta), h, (char*)duk_get_string(ctx, -2), duk_get_heapptr(ctx, -1));
|
||||
duk_pop_2(ctx);
|
||||
}
|
||||
duk_pop(ctx);
|
||||
}
|
||||
@@ -37,6 +37,17 @@ typedef void(*ILibDuktape_HelperEvent)(duk_context *ctx, void *user);
|
||||
#define ILibDuktape_CR2HTTP "\xFF_CR2HTTP"
|
||||
#define ILibDuktape_CR2Options "\xFF_CR2Options"
|
||||
|
||||
typedef enum ILibDuktape_LogTypes
|
||||
{
|
||||
ILibDuktape_LogType_Normal = 0,
|
||||
ILibDuktape_LogType_Warn,
|
||||
ILibDuktape_LogType_Error,
|
||||
ILibDuktape_LogType_Info1,
|
||||
ILibDuktape_LogType_Info2,
|
||||
ILibDuktape_LogType_Info3
|
||||
}ILibDuktape_LogTypes;
|
||||
|
||||
void ILibDuktape_Log_Object(duk_context *ctx, duk_idx_t i, char *meta);
|
||||
char* Duktape_GetContextGuidHex(duk_context *ctx);
|
||||
void *Duktape_GetChain(duk_context *ctx);
|
||||
char *Duktape_GetStashKey(void* value);
|
||||
@@ -53,6 +64,14 @@ struct sockaddr_in6* Duktape_IPAddress6_FromString(char* address, unsigned short
|
||||
void ILibDuktape_SockAddrToOptions(duk_context *ctx, struct sockaddr_in6 *addr);
|
||||
void *ILibDuktape_GetProcessObject(duk_context *ctx);
|
||||
|
||||
char* ILibDuktape_String_AsWide(duk_context *ctx, duk_idx_t idx, duk_size_t *len);
|
||||
void ILibDuktape_String_PushWideString(duk_context *ctx, char *wstr, size_t wstrlen);
|
||||
char *ILibDuktape_String_WideToUTF8(duk_context *ctx, char *wstr);
|
||||
char *ILibDuktape_String_UTF8ToWide(duk_context *ctx, char *str);
|
||||
|
||||
#define Duktape_PushBuffer(ctx, bufSize) ILibMemory_Init(duk_push_fixed_buffer(ctx, (duk_size_t)(bufSize) + sizeof(ILibMemory_Header)), (bufSize), 0, ILibMemory_Types_OTHER)
|
||||
void Duktape_Console_Log(duk_context *ctx, void *chain, ILibDuktape_LogTypes logType, char *msg, duk_size_t msgLen);
|
||||
|
||||
typedef void(*ILibDuktape_NativeUncaughtExceptionHandler)(duk_context *ctx, char *msg, void *user);
|
||||
void ILibDuktape_SetNativeUncaughtExceptionHandler(duk_context *ctx, ILibDuktape_NativeUncaughtExceptionHandler handler, void *user);
|
||||
|
||||
@@ -93,15 +112,11 @@ void ILibDuktape_Helper_AddHeapFinalizer(duk_context *ctx, ILibDuktape_HelperEve
|
||||
|
||||
void ILibDuktape_Push_ObjectStash(duk_context *ctx);
|
||||
|
||||
void ILibDuktape_PointerValidation_Init(duk_context *ctx);
|
||||
void ILibDuktape_ValidatePointer(void *chain, void *ptr);
|
||||
void ILibDuktape_InValidatePointer(void *chain, void *ptr);
|
||||
int ILibDuktape_IsPointerValid(void *chain, void *ptr);
|
||||
#define ILibDuktape_ValidateHeapPointer(ctx, objIdx) ILibDuktape_ValidatePointer(Duktape_GetChain(ctx), duk_get_heapptr(ctx, objIdx))
|
||||
#define ILibDuktape_InValidateHeapPointer(ctx, objIdx) ILibDuktape_InValidatePointer(Duktape_GetChain(ctx), duk_get_heapptr(ctx, objIdx))
|
||||
|
||||
typedef void(*ILibDuktape_ImmediateHandler)(duk_context *ctx, void ** args, int argsLen);
|
||||
typedef ILibDuktape_ImmediateHandler ILibDuktape_IntervalHandler;
|
||||
|
||||
void* ILibDuktape_Immediate(duk_context *ctx, void ** args, int argsLen, ILibDuktape_ImmediateHandler callback);
|
||||
void* ILibDuktape_Interval(duk_context *ctx, void **args, int argsLen, int delay, ILibDuktape_IntervalHandler callback);
|
||||
int ILibDuktape_GetReferenceCount(duk_context *ctx, duk_idx_t i);
|
||||
|
||||
#define ILibDuktape_WriteID(ctx, id) duk_push_string(ctx, id);duk_put_prop_string(ctx, -2, ILibDuktape_OBJID)
|
||||
|
||||
@@ -57,6 +57,7 @@ extern void ILibWebClient_ResetWCDO(struct ILibWebClientDataObject *wcdo);
|
||||
#define ILibDuktape_HTTP2PipedWritable "\xFF_HTTP2PipedWritable"
|
||||
#define ILibDuktape_HTTPStream2Data "\xFF_HTTPStream2Data"
|
||||
#define ILibDuktape_HTTPStream2HTTP "\xFF_HTTPStream2HTTP"
|
||||
#define ILibDuktape_HTTPStream2IMSG "\xFF_HTTPStream2IMSG"
|
||||
#define ILibDuktape_HTTPStream2Socket "\xFF_HTTPStream2Socket"
|
||||
#define ILibDuktape_IMSG2HttpStream "\xFF_IMSG2HttpStream"
|
||||
#define ILibDuktape_IMSG2Ptr "\xFF_IMSG2Ptr"
|
||||
@@ -130,6 +131,7 @@ typedef struct ILibDuktape_HttpStream_ServerResponse_BufferedImplicit_State
|
||||
void *ctx;
|
||||
void *writeStream;
|
||||
void *serverResponseObj;
|
||||
void *serverResponseStream;
|
||||
int endBytes;
|
||||
int chunk;
|
||||
size_t bufferLen;
|
||||
@@ -514,6 +516,9 @@ duk_ret_t ILibDuktape_HttpStream_http_onUpgrade(duk_context *ctx)
|
||||
duk_ret_t ILibDuktape_HttpStream_http_endResponseSink(duk_context *ctx)
|
||||
{
|
||||
duk_push_this(ctx); // [imsg]
|
||||
//ILibDuktape_Log_Object(ctx, -1, "IMSG");
|
||||
|
||||
duk_del_prop_string(ctx, -1, ILibDuktape_IMSG2Ptr);
|
||||
duk_get_prop_string(ctx, -1, ILibDuktape_IMSG2HttpStream); // [imsg][httpstream]
|
||||
duk_get_prop_string(ctx, -1, ILibDuktape_HTTP2CR); // [imsg][httpstream][CR]
|
||||
|
||||
@@ -543,6 +548,24 @@ duk_ret_t ILibDuktape_HttpStream_http_endResponseSink(duk_context *ctx)
|
||||
duk_get_prop_string(ctx, -1, "keepSocketAlive"); // [socket][imsg][httpstream][CR][Agent][keepSocketAlive]
|
||||
duk_swap_top(ctx, -2); // [socket][imsg][httpstream][CR][keepSocketAlive][this]
|
||||
duk_dup(ctx, -6); // [socket][imsg][httpstream][CR][keepSocketAlive][this][socket]
|
||||
|
||||
//printf("End Response -->\n");
|
||||
//if (duk_has_prop_string(ctx, -1, ILibDuktape_Socket2HttpStream))
|
||||
//{
|
||||
// duk_get_prop_string(ctx, -1, ILibDuktape_Socket2HttpStream);
|
||||
// printf(" [Socket: %p] => [HTTPStream: %p]\n", duk_get_heapptr(ctx, -2), duk_get_heapptr(ctx, -1));
|
||||
// ILibDuktape_Log_Object(ctx, -1, "HTTPStream");
|
||||
// duk_pop(ctx);
|
||||
//}
|
||||
//if (duk_has_prop_string(ctx, -1, ILibDuktape_SOCKET2OPTIONS))
|
||||
//{
|
||||
// duk_get_prop_string(ctx, -1, ILibDuktape_SOCKET2OPTIONS);
|
||||
// ILibDuktape_Log_Object(ctx, -1, "OPTIONS");
|
||||
// duk_pop(ctx);
|
||||
//}
|
||||
//ILibDuktape_Log_Object(ctx, -1, "SOCKET");
|
||||
//printf("\n");
|
||||
|
||||
duk_call_method(ctx, 1); duk_pop(ctx); // [socket][imsg][httpstream][CR]
|
||||
return(0);
|
||||
}
|
||||
@@ -671,6 +694,9 @@ duk_ret_t ILibDuktape_HttpStream_http_OnSocketReady(duk_context *ctx)
|
||||
if (data->bodyStream != NULL) { ILibDuktape_readableStream_WriteEnd(data->bodyStream); data->bodyStream = NULL; }
|
||||
duk_pop(ctx); // [socket][clientRequest][HTTPStream]
|
||||
|
||||
ILibDuktape_EventEmitter_DeleteForwardEvent(ctx, -1, "response");
|
||||
ILibDuktape_EventEmitter_DeleteForwardEvent(ctx, -1, "continue");
|
||||
|
||||
// We need to change the events to propagate to the new clientRequest instead of the old one
|
||||
duk_get_prop_string(ctx, -1, "removeAllListeners"); // [socket][clientRequest][HTTPStream][remove]
|
||||
duk_dup(ctx, -2); // [socket][clientRequest][HTTPStream][remove][this]
|
||||
@@ -684,6 +710,8 @@ duk_ret_t ILibDuktape_HttpStream_http_OnSocketReady(duk_context *ctx)
|
||||
duk_dup(ctx, -2); // [socket][clientRequest][HTTPStream][remove][this]
|
||||
duk_push_string(ctx, "upgrade"); // [socket][clientRequest][HTTPStream][remove][this][upgrade]
|
||||
duk_call_method(ctx, 1); duk_pop(ctx); // [socket][clientRequest][HTTPStream]
|
||||
|
||||
|
||||
duk_push_this(ctx); // [socket][clientRequest][HTTPStream][clientRequest]
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_HTTP2CR); // [socket][clientRequest][HTTPStream]
|
||||
|
||||
@@ -996,7 +1024,20 @@ void ILibDuktape_HttpStream_http_request_transform(struct ILibDuktape_Transform
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
duk_ret_t ILibDuktape_ClientRequest_Finalizer(duk_context *ctx)
|
||||
{
|
||||
if (duk_has_prop_string(ctx, 0, ILibDuktape_CR_RequestBuffer))
|
||||
{
|
||||
duk_get_prop_string(ctx, 0, ILibDuktape_CR_RequestBuffer);
|
||||
ILibDuktape_Http_ClientRequest_WriteData *data = (ILibDuktape_Http_ClientRequest_WriteData*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
if (data->buffer != NULL)
|
||||
{
|
||||
free(data->buffer);
|
||||
data->buffer = NULL;
|
||||
}
|
||||
}
|
||||
return(0);
|
||||
}
|
||||
duk_ret_t ILibDuktape_HttpStream_http_request(duk_context *ctx)
|
||||
{
|
||||
char *proto;
|
||||
@@ -1086,7 +1127,7 @@ duk_ret_t ILibDuktape_HttpStream_http_request(duk_context *ctx)
|
||||
ILibDuktape_EventEmitter_CreateEventEx(emitter, "upgrade");
|
||||
ILibDuktape_EventEmitter_CreateEventEx(emitter, "error");
|
||||
ILibDuktape_EventEmitter_AddOnEx(ctx, -1, "socket", ILibDuktape_HttpStream_http_OnSocketReady);
|
||||
|
||||
ILibDuktape_EventEmitter_AddOnEx(ctx, -1, "~", ILibDuktape_ClientRequest_Finalizer);
|
||||
|
||||
|
||||
if (nargs > 1 && duk_is_function(ctx, 1))
|
||||
@@ -1813,7 +1854,7 @@ void ILibDuktape_HttpStream_ServerResponse_WriteImplicitHeaders(void *chain, voi
|
||||
{
|
||||
int retVal;
|
||||
ILibDuktape_HttpStream_ServerResponse_BufferedImplicit_State *state = (ILibDuktape_HttpStream_ServerResponse_BufferedImplicit_State*)user;
|
||||
if (chain != NULL && !ILibDuktape_IsPointerValid(chain, state->serverResponseObj)) { free(user); }
|
||||
if (!ILibMemory_CanaryOK(state->serverResponseStream)) { free(user); return; }
|
||||
|
||||
// We are on Microstack Thread, so we can access the JS object, and write the implicit headers
|
||||
duk_push_heapptr(state->ctx, state->serverResponseObj); // [SR]
|
||||
@@ -1956,6 +1997,7 @@ ILibTransport_DoneState ILibDuktape_HttpStream_ServerResponse_WriteSink(struct I
|
||||
memset(tmp, 0, sizeof(ILibDuktape_HttpStream_ServerResponse_BufferedImplicit_State));
|
||||
tmp->ctx = stream->ctx;
|
||||
tmp->serverResponseObj = stream->obj;
|
||||
tmp->serverResponseStream = stream;
|
||||
tmp->writeStream = state->writeStream;
|
||||
tmp->endBytes = stream->endBytes;
|
||||
tmp->chunk = state->chunkSupported;
|
||||
@@ -1970,6 +2012,7 @@ ILibTransport_DoneState ILibDuktape_HttpStream_ServerResponse_WriteSink(struct I
|
||||
memset(buffered, 0, sizeof(ILibDuktape_HttpStream_ServerResponse_BufferedImplicit_State));
|
||||
buffered->ctx = stream->ctx;
|
||||
buffered->serverResponseObj = stream->obj;
|
||||
buffered->serverResponseStream = stream;
|
||||
buffered->writeStream = state->writeStream;
|
||||
buffered->bufferLen = bufferLen;
|
||||
buffered->endBytes = stream->endBytes;
|
||||
@@ -2059,6 +2102,7 @@ ILibTransport_DoneState ILibDuktape_HttpStream_ServerResponse_WriteSink(struct I
|
||||
data->ctx = stream->ctx;
|
||||
data->endBytes = stream->endBytes;
|
||||
data->serverResponseObj = stream->obj;
|
||||
data->serverResponseStream = stream;
|
||||
data->writeStream = state->writeStream;
|
||||
data->bufferLen = bufferLen;
|
||||
memcpy_s(data->buffer, bufferLen, buffer, bufferLen);
|
||||
@@ -2403,8 +2447,6 @@ void ILibDuktape_HttpStream_ServerResponse_PUSH(duk_context *ctx, void* writeStr
|
||||
duk_remove(ctx, -2); // [resp][http/s.serverResponse]
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_OBJID); // [resp]
|
||||
|
||||
|
||||
ILibDuktape_PointerValidation_Init(ctx);
|
||||
ILibDuktape_WriteID(ctx, "http.serverResponse");
|
||||
duk_push_fixed_buffer(ctx, sizeof(ILibDuktape_HttpStream_ServerResponse_State)); // [resp][state]
|
||||
state = (ILibDuktape_HttpStream_ServerResponse_State*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
@@ -2666,10 +2708,11 @@ int ILibDuktape_HttpStream_IncomingMessage_UnshiftBytes(ILibDuktape_readableStre
|
||||
}
|
||||
void ILibDuktape_HttpStream_DispatchEnd(void *chain, void *user)
|
||||
{
|
||||
if (ILibDuktape_IsPointerValid(chain, ((void**)user)[1]) != 0)
|
||||
if(ILibMemory_CanaryOK(((void**)user)[1]))
|
||||
{
|
||||
duk_context *ctx = (duk_context*)((void**)user)[0];
|
||||
void *heapPtr = ((void**)user)[1];
|
||||
void *heapPtr = ((ILibDuktape_DuplexStream*)((void**)user)[1])->ParentObject;
|
||||
((ILibDuktape_HttpStream_Data*)((void**)user)[2])->bodyStream = NULL;
|
||||
|
||||
duk_push_heapptr(ctx, heapPtr); // [httpStream]
|
||||
duk_get_prop_string(ctx, -1, "emit"); // [httpStream][emit]
|
||||
@@ -2694,7 +2737,7 @@ duk_ret_t ILibDuktape_HttpStream_OnReceive_bodyStreamFinalized(duk_context *ctx)
|
||||
ILibDuktape_HttpStream_Data *data = (ILibDuktape_HttpStream_Data*)Duktape_GetPointerProperty(ctx, 0, ILibDuktape_IMSG2Ptr);
|
||||
if (data != NULL)
|
||||
{
|
||||
if (data->endPropagated == 0) { ILibDuktape_readableStream_WriteEnd(data->bodyStream); }
|
||||
if ((data->endPropagated == 0) && (data->bodyStream != NULL)) { ILibDuktape_readableStream_WriteEnd(data->bodyStream); }
|
||||
data->endPropagated = 1;
|
||||
data->bodyStream = NULL;
|
||||
}
|
||||
@@ -2772,29 +2815,39 @@ void ILibDuktape_HttpStream_OnReceive(ILibWebClient_StateObject WebStateObject,
|
||||
if (val != NULL)
|
||||
{
|
||||
if (valLen == 12 && strncasecmp(val, "100-Continue", 12) == 0)
|
||||
{
|
||||
// Is there a listener for 'checkContinue'?
|
||||
if (ILibDuktape_EventEmitter_HasListenersEx(ctx, -1, "checkContinue"))
|
||||
{
|
||||
duk_push_string(ctx, "checkContinue"); // [emit][this][checkContinue]
|
||||
ILibDuktape_HttpStream_IncomingMessage_PUSH(ctx, header, data->DS->ParentObject); // [emit][this][checkContinue][imsg]
|
||||
data->bodyStream = ILibDuktape_ReadableStream_InitEx(ctx, ILibDuktape_HttpStream_IncomingMessage_PauseSink, ILibDuktape_HttpStream_IncomingMessage_ResumeSink, ILibDuktape_HttpStream_IncomingMessage_UnshiftBytes, data);
|
||||
ILibDuktape_HttpStream_ServerResponse_PUSH(ctx, data->DS->writableStream->pipedReadable, header, data->DS->ParentObject); // [emit][this][checkContinue][imsg][rsp]
|
||||
duk_dup(ctx, -1); // [emit][this][checkContinue][imsg][rsp][rsp]
|
||||
duk_insert(ctx, -6); // [rsp][emit][this][checkContinue][imsg][rsp]
|
||||
if (duk_pcall_method(ctx, 3) != 0) { ILibDuktape_Process_UncaughtExceptionEx(ctx, "http.httpStream.onReceive->checkContinue(): "); } // [rsp][hadListener]
|
||||
else
|
||||
{
|
||||
if (!duk_get_boolean(ctx, -1))
|
||||
{
|
||||
// No listener, so we must immediately send '100 Continue'
|
||||
duk_get_prop_string(ctx, -2, "writeContinue"); // [rsp][hadListener][writeContinue]
|
||||
duk_dup(ctx, -3); // [rsp][hadListener][writeContinue][this]
|
||||
duk_call_method(ctx, 0); duk_pop(ctx); // [rsp][hadListener]
|
||||
}
|
||||
}
|
||||
duk_pop_2(ctx); // ...
|
||||
}
|
||||
else
|
||||
{
|
||||
duk_dup(ctx, -3); duk_dup(ctx, -2); // [emit][this][checkContinue][imsg][httpstream][imsg]
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_HTTPStream2IMSG); duk_pop(ctx); // [emit][this][checkContinue][imsg]
|
||||
|
||||
ILibDuktape_HttpStream_ServerResponse_PUSH(ctx, data->DS->writableStream->pipedReadable, header, data->DS->ParentObject); // [emit][this][checkContinue][imsg][rsp]
|
||||
if (duk_pcall_method(ctx, 3) != 0) { ILibDuktape_Process_UncaughtExceptionEx(ctx, "http.httpStream.onReceive->checkContinue(): "); } // [rsp][hadListener]
|
||||
duk_pop(ctx); // ...
|
||||
}
|
||||
else
|
||||
{
|
||||
// Nobody listening for 'checkContinue', so we need to respond with 100 Continue
|
||||
ILibDuktape_HttpStream_ServerResponse_PUSH(ctx, data->DS->writableStream->pipedReadable, header, data->DS->ParentObject); // [emit][this][rsp]
|
||||
duk_get_prop_string(ctx, -1, "writeContinue"); // [emit][this][rsp][writeContinue]
|
||||
duk_swap_top(ctx, -2); // [emit][this][writeContinue][this]
|
||||
duk_call_method(ctx, 0); duk_pop(ctx); // [emit][this]
|
||||
|
||||
// Since nobody was listening for 'checkContinue', need to process this as a 'request'
|
||||
duk_push_string(ctx, "request"); // [emit][this][request]
|
||||
ILibDuktape_HttpStream_IncomingMessage_PUSH(ctx, header, data->DS->ParentObject); // [emit][this][request][imsg]
|
||||
data->bodyStream = ILibDuktape_ReadableStream_InitEx(ctx, ILibDuktape_HttpStream_IncomingMessage_PauseSink, ILibDuktape_HttpStream_IncomingMessage_ResumeSink, ILibDuktape_HttpStream_IncomingMessage_UnshiftBytes, data);
|
||||
duk_dup(ctx, -3); duk_dup(ctx, -2); // [emit][this][request][imsg][httpstream][imsg]
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_HTTPStream2IMSG); duk_pop(ctx); // [emit][this][request][imsg]
|
||||
|
||||
ILibDuktape_HttpStream_ServerResponse_PUSH(ctx, data->DS->writableStream->pipedReadable, header, data->DS->ParentObject); // [emit][this][request][imsg][rsp]
|
||||
if (duk_pcall_method(ctx, 3) != 0) { ILibDuktape_Process_UncaughtExceptionEx(ctx, "http.httpStream.onReceive->request(): "); }
|
||||
duk_pop(ctx); // ...
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -2852,6 +2905,11 @@ void ILibDuktape_HttpStream_OnReceive(ILibWebClient_StateObject WebStateObject,
|
||||
data->bodyStream = ILibDuktape_ReadableStream_InitEx(ctx, ILibDuktape_HttpStream_IncomingMessage_PauseSink, ILibDuktape_HttpStream_IncomingMessage_ResumeSink, ILibDuktape_HttpStream_IncomingMessage_UnshiftBytes, data);
|
||||
duk_push_pointer(ctx, data);
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_IMSG2Ptr);
|
||||
duk_dup(ctx, -3); // [emit][this][response][imsg][httpstream]
|
||||
duk_dup(ctx, -2); // [emit][this][response][imsg][httpstream][imsg]
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_HTTPStream2IMSG); // [emit][this][response][imsg][httpstream]
|
||||
duk_pop(ctx); // [emit][this][response][imsg]
|
||||
|
||||
ILibDuktape_EventEmitter_AddOnEx(ctx, -1, "~", ILibDuktape_HttpStream_OnReceive_bodyStreamFinalized);
|
||||
if (duk_pcall_method(ctx, 2) != 0) { ILibDuktape_Process_UncaughtExceptionEx(ctx, "http.httpStream.onReceive->response(): "); }
|
||||
duk_pop(ctx);
|
||||
@@ -2874,6 +2932,8 @@ void ILibDuktape_HttpStream_OnReceive(ILibWebClient_StateObject WebStateObject,
|
||||
if (ILibIsRunningOnChainThread(data->chain) != 0)
|
||||
{
|
||||
// We're on the Chain Thread, so we can directly emit the 'end' event
|
||||
data->bodyStream = NULL;
|
||||
|
||||
duk_push_heapptr(ctx, data->DS->ParentObject); // [httpStream]
|
||||
duk_get_prop_string(ctx, -1, "emit"); // [httpStream][emit]
|
||||
duk_swap_top(ctx, -2); // [emit][this]
|
||||
@@ -2884,19 +2944,19 @@ void ILibDuktape_HttpStream_OnReceive(ILibWebClient_StateObject WebStateObject,
|
||||
else
|
||||
{
|
||||
// We're on the wrong thread to dispatch the 'end' event, so we have to context switch
|
||||
void **tmp = (void**)ILibMemory_Allocate(2 * sizeof(void*), 0, NULL, NULL);
|
||||
void **tmp = (void**)ILibMemory_Allocate(3 * sizeof(void*), 0, NULL, NULL);
|
||||
tmp[0] = ctx;
|
||||
tmp[1] = data->DS->ParentObject;
|
||||
tmp[1] = data->DS;
|
||||
tmp[2] = data;
|
||||
ILibChain_RunOnMicrostackThread(data->chain, ILibDuktape_HttpStream_DispatchEnd, tmp);
|
||||
}
|
||||
}
|
||||
}
|
||||
duk_ret_t ILibDuktape_HttpStream_Finalizer(duk_context *ctx)
|
||||
{
|
||||
duk_del_prop_string(ctx, 0, ILibDuktape_HTTPStream2IMSG);
|
||||
duk_get_prop_string(ctx, 0, ILibDuktape_HTTPStream2Data);
|
||||
ILibDuktape_HttpStream_Data *data = (ILibDuktape_HttpStream_Data*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
ILibDuktape_InValidatePointer(Duktape_GetChain(ctx), data);
|
||||
ILibDuktape_InValidateHeapPointer(ctx, 0);
|
||||
|
||||
ILibWebClient_DestroyWebClientDataObject(data->WCDO);
|
||||
return(0);
|
||||
@@ -2934,9 +2994,7 @@ duk_ret_t ILibduktape_HttpStream_create(duk_context *ctx)
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_HTTPStream2HTTP); // [httpStream]
|
||||
ILibDuktape_WriteID(ctx, "http.httpStream");
|
||||
ILibDuktape_EventEmitter *emitter = ILibDuktape_EventEmitter_Create(ctx);
|
||||
duk_push_fixed_buffer(ctx, sizeof(ILibDuktape_HttpStream_Data)); // [httpStream][buffer]
|
||||
data = (ILibDuktape_HttpStream_Data*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
memset(data, 0, sizeof(ILibDuktape_HttpStream_Data));
|
||||
data = (ILibDuktape_HttpStream_Data*)Duktape_PushBuffer(ctx, sizeof(ILibDuktape_HttpStream_Data));
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_HTTPStream2Data); // [httpStream]
|
||||
|
||||
ILibDuktape_EventEmitter_CreateEventEx(emitter, "end");
|
||||
@@ -2960,10 +3018,7 @@ duk_ret_t ILibduktape_HttpStream_create(duk_context *ctx)
|
||||
ILibDuktape_EventEmitter_AddOnEx(ctx, -1, "pipe", ILibDuktape_HttpStream_pipeEvent);
|
||||
|
||||
ILibDuktape_CreateEventWithGetter(ctx, "connectionCloseSpecified", ILibDuktape_HttpStream_connectionCloseSpecified);
|
||||
|
||||
ILibDuktape_CreateFinalizer(ctx, ILibDuktape_HttpStream_Finalizer);
|
||||
ILibDuktape_ValidatePointer(Duktape_GetChain(ctx), data);
|
||||
ILibDuktape_ValidateHeapPointer(ctx, -1);
|
||||
return(1);
|
||||
}
|
||||
duk_ret_t ILibDuktape_HttpStream_Agent_getName(duk_context *ctx)
|
||||
@@ -3113,10 +3168,14 @@ duk_ret_t ILibDuktape_HttpStream_Agent_keepSocketAlive(duk_context *ctx)
|
||||
|
||||
|
||||
duk_get_prop_string(ctx, -1, "requests"); // [key][Agent][requests]
|
||||
//ILibDuktape_Log_Object(ctx, -1, "Agent/Requests");
|
||||
|
||||
if (duk_has_prop_string(ctx, -1, key))
|
||||
{
|
||||
// Has Key, check the Array
|
||||
duk_get_prop_string(ctx, -1, key); // [key][Agent][requests][Array]
|
||||
//ILibDuktape_Log_Object(ctx, -1, "Agent/Request/ArrayIndex");
|
||||
|
||||
duk_get_prop_string(ctx, -1, "shift"); // [key][Agent][requests][Array][shift]
|
||||
duk_swap_top(ctx, -2); // [key][Agent][requests][shift][this]
|
||||
duk_call_method(ctx, 0); // [key][Agent][requests][request]
|
||||
@@ -3485,8 +3544,11 @@ ILibTransport_DoneState ILibDuktape_httpStream_webSocket_EncodedWriteSink(ILibDu
|
||||
char* maskingKey = NULL;
|
||||
int FIN;
|
||||
unsigned char OPCODE;
|
||||
unsigned char RSV;
|
||||
ILibDuktape_WebSocket_State *state = (ILibDuktape_WebSocket_State*)user;
|
||||
|
||||
if (!ILibMemory_CanaryOK(state)) { return(ILibTransport_DoneState_ERROR); }
|
||||
|
||||
if (bufferLen < 2)
|
||||
{
|
||||
// We need at least 2 bytes to read enough of the headers to know how long the frame is
|
||||
@@ -3496,6 +3558,14 @@ ILibTransport_DoneState ILibDuktape_httpStream_webSocket_EncodedWriteSink(ILibDu
|
||||
hdr = ntohs(((unsigned short*)(buffer))[0]);
|
||||
FIN = (hdr & WEBSOCKET_FIN) != 0;
|
||||
OPCODE = (hdr & WEBSOCKET_OPCODE) >> 8;
|
||||
RSV = (hdr & WEBSOCKET_RSV) >> 8;
|
||||
|
||||
if (RSV != 0)
|
||||
{
|
||||
char msg[] = "Reserved Field of Websocket was not ZERO";
|
||||
Duktape_Console_Log(state->ctx, state->chain, ILibDuktape_LogType_Error, msg, sizeof(msg) - 1);
|
||||
return(ILibTransport_DoneState_ERROR);
|
||||
}
|
||||
|
||||
plen = (unsigned char)(hdr & WEBSOCKET_PLEN);
|
||||
if (plen == 126)
|
||||
@@ -3636,7 +3706,8 @@ void ILibDuktape_httpStream_webSocket_EncodedEndSink(ILibDuktape_DuplexStream *s
|
||||
}
|
||||
void ILibDuktape_httpStream_webSocket_EncodedPauseSink_Chain(void *chain, void *user)
|
||||
{
|
||||
if (chain != NULL && !ILibDuktape_IsPointerValid(chain, user)) { return; }
|
||||
if (!ILibMemory_CanaryOK(user)) { return; }
|
||||
|
||||
ILibDuktape_WebSocket_State *state = (ILibDuktape_WebSocket_State*)user;
|
||||
duk_context *ctx = state->decodedStream->writableStream->ctx;
|
||||
|
||||
@@ -3648,7 +3719,7 @@ void ILibDuktape_httpStream_webSocket_EncodedPauseSink_Chain(void *chain, void *
|
||||
}
|
||||
void ILibDuktape_httpStream_webSocket_EncodedPauseSink(ILibDuktape_DuplexStream *sender, void *user)
|
||||
{
|
||||
printf("WebSocket.Encoded.Pause();\n");
|
||||
//printf("WebSocket.Encoded.Pause();\n");
|
||||
ILibDuktape_WebSocket_State *state = (ILibDuktape_WebSocket_State*)user;
|
||||
if (state->decodedStream->writableStream->pipedReadable_native != NULL && state->decodedStream->writableStream->pipedReadable_native->PauseHandler != NULL)
|
||||
{
|
||||
@@ -3669,10 +3740,12 @@ void ILibDuktape_httpStream_webSocket_EncodedPauseSink(ILibDuktape_DuplexStream
|
||||
}
|
||||
void ILibDuktape_httpStream_webSocket_EncodedResumeSink_Chain(void *chain, void *user)
|
||||
{
|
||||
if (chain != NULL && !ILibDuktape_IsPointerValid(chain, user)) { return; }
|
||||
if (!ILibMemory_CanaryOK(user)) { return; }
|
||||
|
||||
ILibDuktape_WebSocket_State *state = (ILibDuktape_WebSocket_State*)user;
|
||||
duk_context *ctx = state->decodedStream->writableStream->ctx;
|
||||
|
||||
if (state->decodedStream->writableStream->pipedReadable == NULL) { return; }
|
||||
duk_push_heapptr(ctx, state->decodedStream->writableStream->pipedReadable); // [readable]
|
||||
duk_get_prop_string(ctx, -1, "resume"); // [readable][resume]
|
||||
duk_swap_top(ctx, -2); // [resume][this]
|
||||
@@ -3681,7 +3754,7 @@ void ILibDuktape_httpStream_webSocket_EncodedResumeSink_Chain(void *chain, void
|
||||
}
|
||||
void ILibDuktape_httpStream_webSocket_EncodedResumeSink(ILibDuktape_DuplexStream *sender, void *user)
|
||||
{
|
||||
printf("WebSocket.Encoded.Resume();\n");
|
||||
//printf("WebSocket.Encoded.Resume();\n");
|
||||
ILibDuktape_WebSocket_State *state = (ILibDuktape_WebSocket_State*)user;
|
||||
if (state->decodedStream->writableStream->pipedReadable_native != NULL && state->decodedStream->writableStream->pipedReadable_native->ResumeHandler != NULL)
|
||||
{
|
||||
@@ -3718,7 +3791,8 @@ void ILibDuktape_httpStream_webSocket_DecodedEndSink(ILibDuktape_DuplexStream *s
|
||||
}
|
||||
void ILibDuktape_httpStream_webSocket_DecodedPauseSink_Chain(void *chain, void *user)
|
||||
{
|
||||
if (chain != NULL && !ILibDuktape_IsPointerValid(chain, user)) { return; }
|
||||
if (!ILibMemory_CanaryOK(user)) { return; }
|
||||
|
||||
ILibDuktape_WebSocket_State *state = (ILibDuktape_WebSocket_State*)user;
|
||||
duk_context *ctx = state->encodedStream->writableStream->ctx;
|
||||
|
||||
@@ -3758,7 +3832,7 @@ void ILibDuktape_httpStream_webSocket_DecodedPauseSink(ILibDuktape_DuplexStream
|
||||
}
|
||||
void ILibDuktape_httpStream_webSocket_DecodedResumeSink_Chain(void *chain, void *user)
|
||||
{
|
||||
if (chain != NULL && !ILibDuktape_IsPointerValid(chain, user)) { return; }
|
||||
if (!ILibMemory_CanaryOK(user)) { return; }
|
||||
ILibDuktape_WebSocket_State *state = (ILibDuktape_WebSocket_State*)user;
|
||||
duk_context *ctx = state->encodedStream->writableStream->ctx;
|
||||
|
||||
@@ -3802,11 +3876,10 @@ int ILibDuktape_httpStream_webSocket_DecodedUnshiftSink(ILibDuktape_DuplexStream
|
||||
|
||||
duk_ret_t ILibDuktape_httpStream_webSocketStream_finalizer(duk_context *ctx)
|
||||
{
|
||||
void *chain = Duktape_GetChain(ctx);
|
||||
duk_get_prop_string(ctx, 0, ILibDuktape_WebSocket_StatePtr);
|
||||
ILibDuktape_WebSocket_State *state = (ILibDuktape_WebSocket_State*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
|
||||
if (state->encodedStream->writableStream->pipedReadable != NULL)
|
||||
if (state->encodedStream != NULL && state->encodedStream->writableStream->pipedReadable != NULL)
|
||||
{
|
||||
duk_push_heapptr(ctx, state->encodedStream->writableStream->pipedReadable); // [readable]
|
||||
duk_get_prop_string(ctx, -1, "unpipe"); // [readable][unpipe]
|
||||
@@ -3815,7 +3888,6 @@ duk_ret_t ILibDuktape_httpStream_webSocketStream_finalizer(duk_context *ctx)
|
||||
duk_call_method(ctx, 1); duk_pop(ctx); // ...
|
||||
}
|
||||
|
||||
ILibDuktape_InValidatePointer(chain, Duktape_GetBuffer(ctx, -1, NULL));
|
||||
return(0);
|
||||
}
|
||||
duk_ret_t ILibDuktape_httpStream_webSocketStream_sendPing(duk_context *ctx)
|
||||
@@ -3856,17 +3928,24 @@ duk_ret_t ILibDuktape_httpStream_webSocketStream_encodedPiped(duk_context *ctx)
|
||||
}
|
||||
return(0);
|
||||
}
|
||||
duk_ret_t ILibDuktape_httpStream_webSocketStream_encoded_Finalizer(duk_context *ctx)
|
||||
{
|
||||
duk_get_prop_string(ctx, 0, ILibDuktape_WSENC2WS);
|
||||
duk_get_prop_string(ctx, -1, ILibDuktape_WebSocket_StatePtr);
|
||||
ILibDuktape_WebSocket_State *state = (ILibDuktape_WebSocket_State*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
|
||||
state->encodedStream = NULL;
|
||||
|
||||
return(0);
|
||||
}
|
||||
duk_ret_t ILibDuktape_httpStream_webSocketStream_new(duk_context *ctx)
|
||||
{
|
||||
ILibDuktape_WebSocket_State *state;
|
||||
duk_push_object(ctx); // [WebSocket]
|
||||
ILibDuktape_WriteID(ctx, "http.WebSocketStream");
|
||||
duk_push_fixed_buffer(ctx, sizeof(ILibDuktape_WebSocket_State)); // [WebSocket][data]
|
||||
state = (ILibDuktape_WebSocket_State*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
memset(state, 0, sizeof(ILibDuktape_WebSocket_State));
|
||||
state = (ILibDuktape_WebSocket_State*)Duktape_PushBuffer(ctx, sizeof(ILibDuktape_WebSocket_State)); // [WebSocket][data]
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_WebSocket_StatePtr); // [WebSocket]
|
||||
ILibDuktape_ValidatePointer(Duktape_GetChain(ctx), state);
|
||||
|
||||
state->ctx = ctx;
|
||||
state->ObjectPtr = duk_get_heapptr(ctx, -1);
|
||||
state->chain = Duktape_GetChain(ctx);
|
||||
@@ -3877,6 +3956,7 @@ duk_ret_t ILibDuktape_httpStream_webSocketStream_new(duk_context *ctx)
|
||||
ILibDuktape_EventEmitter_AddOnEx(ctx, -1, "pipe", ILibDuktape_httpStream_webSocketStream_encodedPiped);
|
||||
duk_dup(ctx, -2); // [WebSocket][Encoded][WebSocket]
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_WSENC2WS); // [WebSocket][Encoded]
|
||||
ILibDuktape_EventEmitter_AddOnceEx3(ctx, -1, "~", ILibDuktape_httpStream_webSocketStream_encoded_Finalizer);
|
||||
|
||||
ILibDuktape_CreateReadonlyProperty(ctx, "encoded"); // [WebSocket]
|
||||
duk_push_object(ctx); // [WebSocket][Decoded]
|
||||
@@ -3925,6 +4005,3 @@ void ILibDuktape_HttpStream_Init(duk_context *ctx)
|
||||
ILibDuktape_ModSearch_AddHandler(ctx, "http", ILibDuktape_HttpStream_http_PUSH);
|
||||
ILibDuktape_ModSearch_AddHandler(ctx, "https", ILibDuktape_HttpStream_https_PUSH);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -153,9 +153,8 @@ duk_ret_t ILibDuktape_MemoryStream_new(duk_context *ctx)
|
||||
|
||||
ILibDuktape_MemoryStream *ms;
|
||||
duk_push_object(ctx); // [ms]
|
||||
duk_push_fixed_buffer(ctx, sizeof(ILibDuktape_MemoryStream)); // [ms][internal]
|
||||
ms = (ILibDuktape_MemoryStream*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
memset(ms, 0, sizeof(ILibDuktape_MemoryStream));
|
||||
ILibDuktape_WriteID(ctx, "memoryStream");
|
||||
ms = (ILibDuktape_MemoryStream*)Duktape_PushBuffer(ctx, sizeof(ILibDuktape_MemoryStream));
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_MemoryStream_Internal); // [ms]
|
||||
ms->buffer = (char*)ILibMemory_Allocate(initial, 0, NULL, NULL);
|
||||
ms->bufferSize = (size_t)initial;
|
||||
|
||||
@@ -19,14 +19,33 @@ limitations under the License.
|
||||
#include "ILibDuktapeModSearch.h"
|
||||
#include "ILibDuktape_DuplexStream.h"
|
||||
#include "ILibDuktape_EventEmitter.h"
|
||||
#include "ILibDuktape_Debugger.h"
|
||||
#include "../microstack/ILibParsers.h"
|
||||
#include "../microstack/ILibCrypto.h"
|
||||
#include "../microstack/ILibRemoteLogging.h"
|
||||
|
||||
|
||||
#define ILibDuktape_Timer_Ptrs "\xFF_DuktapeTimer_PTRS"
|
||||
#define ILibDuktape_Queue_Ptr "\xFF_Queue"
|
||||
#define ILibDuktape_Stream_Buffer "\xFF_BUFFER"
|
||||
#define ILibDuktape_Stream_ReadablePtr "\xFF_ReadablePtr"
|
||||
#define ILibDuktape_Stream_WritablePtr "\xFF_WritablePtr"
|
||||
#define ILibDuktape_Console_Destination "\xFF_Console_Destination"
|
||||
#define ILibDuktape_Console_LOG_Destination "\xFF_Console_Destination"
|
||||
#define ILibDuktape_Console_WARN_Destination "\xFF_Console_WARN_Destination"
|
||||
#define ILibDuktape_Console_ERROR_Destination "\xFF_Console_ERROR_Destination"
|
||||
#define ILibDuktape_Console_INFO_Level "\xFF_Console_INFO_Level"
|
||||
#define ILibDuktape_Console_SessionID "\xFF_Console_SessionID"
|
||||
|
||||
typedef enum ILibDuktape_Console_DestinationFlags
|
||||
{
|
||||
ILibDuktape_Console_DestinationFlags_DISABLED = 0,
|
||||
ILibDuktape_Console_DestinationFlags_StdOut = 1,
|
||||
ILibDuktape_Console_DestinationFlags_ServerConsole = 2,
|
||||
ILibDuktape_Console_DestinationFlags_WebLog = 4,
|
||||
ILibDuktape_Console_DestinationFlags_LogFile = 8
|
||||
}ILibDuktape_Console_DestinationFlags;
|
||||
|
||||
int g_displayStreamPipeMessages = 0;
|
||||
int g_displayFinalizerMessages = 0;
|
||||
|
||||
@@ -176,23 +195,20 @@ duk_ret_t ILibDuktape_Polyfills_Buffer_alloc(duk_context *ctx)
|
||||
}
|
||||
void ILibDuktape_Polyfills_Buffer(duk_context *ctx)
|
||||
{
|
||||
//// Polyfill 'Buffer.slice'
|
||||
//duk_get_prop_string(ctx, -1, "Duktape"); // [g][Duktape]
|
||||
//duk_get_prop_string(ctx, -1, "Buffer"); // [g][Duktape][Buffer]
|
||||
//duk_get_prop_string(ctx, -1, "prototype"); // [g][Duktape][Buffer][prototype]
|
||||
//duk_push_c_function(ctx, ILibDuktape_Pollyfills_Buffer_slice, DUK_VARARGS); // [g][Duktape][Buffer][prototype][func]
|
||||
//duk_put_prop_string(ctx, -2, "slice"); // [g][Duktape][Buffer][prototype]
|
||||
//duk_push_c_function(ctx, ILibDuktape_Polyfills_Buffer_readInt32BE, DUK_VARARGS);// [g][Duktape][Buffer][prototype][func]
|
||||
//duk_put_prop_string(ctx, -2, "readInt32BE"); // [g][Duktape][Buffer][prototype]
|
||||
//duk_pop_3(ctx); // [g]
|
||||
char extras[] =
|
||||
"Object.defineProperty(Buffer.prototype, \"swap32\",\
|
||||
{\
|
||||
value: function swap32()\
|
||||
{\
|
||||
var a = this.readUInt16BE(0);\
|
||||
var b = this.readUInt16BE(2);\
|
||||
this.writeUInt16LE(a, 2);\
|
||||
this.writeUInt16LE(b, 0);\
|
||||
return(this);\
|
||||
}\
|
||||
});";
|
||||
|
||||
//// Polyfill 'Buffer.toString()
|
||||
//duk_get_prop_string(ctx, -1, "Duktape"); // [g][Duktape]
|
||||
//duk_get_prop_string(ctx, -1, "Buffer"); // [g][Duktape][Buffer]
|
||||
//duk_get_prop_string(ctx, -1, "prototype"); // [g][Duktape][Buffer][prototype]
|
||||
//duk_push_c_function(ctx, ILibDuktape_Polyfills_Buffer_toString, DUK_VARARGS); // [g][Duktape][Buffer][prototype][func]
|
||||
//duk_put_prop_string(ctx, -2, "toString"); // [g][Duktape][Buffer][prototype]
|
||||
//duk_pop_3(ctx); // [g]
|
||||
duk_eval_string(ctx, extras); duk_pop(ctx);
|
||||
|
||||
// Polyfill Buffer.from()
|
||||
duk_get_prop_string(ctx, -1, "Buffer"); // [g][Buffer]
|
||||
@@ -271,13 +287,55 @@ void ILibDuktape_Polyfills_String(duk_context *ctx)
|
||||
duk_ret_t ILibDuktape_Polyfills_Console_log(duk_context *ctx)
|
||||
{
|
||||
int numargs = duk_get_top(ctx);
|
||||
int i;
|
||||
int i, x;
|
||||
int len = 0;
|
||||
duk_size_t strLen;
|
||||
char *str;
|
||||
char *PREFIX = NULL;
|
||||
char *DESTINATION = NULL;
|
||||
duk_push_current_function(ctx);
|
||||
ILibDuktape_LogTypes logType = (ILibDuktape_LogTypes)Duktape_GetIntPropertyValue(ctx, -1, "logType", ILibDuktape_LogType_Normal);
|
||||
switch (logType)
|
||||
{
|
||||
case ILibDuktape_LogType_Warn:
|
||||
PREFIX = (char*)"WARNING: "; // LENGTH MUST BE <= 9
|
||||
DESTINATION = ILibDuktape_Console_WARN_Destination;
|
||||
break;
|
||||
case ILibDuktape_LogType_Error:
|
||||
PREFIX = (char*)"ERROR: "; // LENGTH MUST BE <= 9
|
||||
DESTINATION = ILibDuktape_Console_ERROR_Destination;
|
||||
break;
|
||||
case ILibDuktape_LogType_Info1:
|
||||
case ILibDuktape_LogType_Info2:
|
||||
case ILibDuktape_LogType_Info3:
|
||||
duk_push_this(ctx);
|
||||
i = Duktape_GetIntPropertyValue(ctx, -1, ILibDuktape_Console_INFO_Level, 0);
|
||||
duk_pop(ctx);
|
||||
PREFIX = NULL;
|
||||
if (i >= (((int)logType + 1) - (int)ILibDuktape_LogType_Info1))
|
||||
{
|
||||
DESTINATION = ILibDuktape_Console_LOG_Destination;
|
||||
}
|
||||
else
|
||||
{
|
||||
return(0);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
PREFIX = NULL;
|
||||
DESTINATION = ILibDuktape_Console_LOG_Destination;
|
||||
break;
|
||||
}
|
||||
duk_pop(ctx);
|
||||
|
||||
// Calculate total length of string
|
||||
for (i = 0; i < numargs; ++i)
|
||||
{
|
||||
if (duk_is_string(ctx, i))
|
||||
{
|
||||
printf("%s%s", (i == 0 ? "" : ", "), duk_require_string(ctx, i));
|
||||
len += (i == 0 ? 0 : 2);
|
||||
duk_get_lstring(ctx, i, &strLen);
|
||||
len += (int)strLen;
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -286,24 +344,140 @@ duk_ret_t ILibDuktape_Polyfills_Console_log(duk_context *ctx)
|
||||
{
|
||||
duk_pop(ctx);
|
||||
duk_dup(ctx, i);
|
||||
printf("%s", (i == 0 ? "{" : ", {"));
|
||||
len += (i == 0 ? 1 : 3);
|
||||
duk_enum(ctx, -1, DUK_ENUM_OWN_PROPERTIES_ONLY);
|
||||
int propNum = 0;
|
||||
while (duk_next(ctx, -1, 1))
|
||||
{
|
||||
printf("%s%s: %s", ((propNum++ == 0) ? " " : ", "), (char*)duk_to_string(ctx, -2), (char*)duk_to_string(ctx, -1));
|
||||
len += 2;
|
||||
len += (propNum++ == 0 ? 1 : 2);
|
||||
duk_to_lstring(ctx, -2, &strLen); len += (int)strLen;
|
||||
duk_to_lstring(ctx, -1, &strLen); len += (int)strLen;
|
||||
duk_pop_2(ctx);
|
||||
}
|
||||
duk_pop(ctx);
|
||||
printf(" }");
|
||||
len += 2;
|
||||
}
|
||||
else
|
||||
{
|
||||
printf("%s%s", (i == 0 ? "" : ", "), duk_to_string(ctx, -1));
|
||||
len += (i == 0 ? 0 : 2);
|
||||
duk_get_lstring(ctx, -1, &strLen); len += (int)strLen;
|
||||
}
|
||||
}
|
||||
}
|
||||
printf("\n");
|
||||
len += 2; // NULL Terminator and final carriage return
|
||||
strLen = len;
|
||||
|
||||
str = ILibMemory_AllocateA(strLen + ((PREFIX != NULL) ? strnlen_s(PREFIX, 9) : 0));
|
||||
x = (int)(ILibMemory_AllocateA_Size(str) - strLen);
|
||||
if (x != 0)
|
||||
{
|
||||
strLen += sprintf_s(str, strLen, PREFIX);
|
||||
}
|
||||
for (i = 0; i < numargs; ++i)
|
||||
{
|
||||
if (duk_is_string(ctx, i))
|
||||
{
|
||||
x += sprintf_s(str + x, strLen - x, "%s%s", (i == 0 ? "" : ", "), duk_require_string(ctx, i));
|
||||
}
|
||||
else
|
||||
{
|
||||
duk_dup(ctx, i);
|
||||
if (strcmp("[object Object]", duk_to_string(ctx, -1)) == 0)
|
||||
{
|
||||
duk_pop(ctx);
|
||||
duk_dup(ctx, i);
|
||||
x += sprintf_s(str+x, strLen - x, "%s", (i == 0 ? "{" : ", {"));
|
||||
duk_enum(ctx, -1, DUK_ENUM_OWN_PROPERTIES_ONLY);
|
||||
int propNum = 0;
|
||||
while (duk_next(ctx, -1, 1))
|
||||
{
|
||||
x += sprintf_s(str + x, strLen - x, "%s%s: %s", ((propNum++ == 0) ? " " : ", "), (char*)duk_to_string(ctx, -2), (char*)duk_to_string(ctx, -1));
|
||||
duk_pop_2(ctx);
|
||||
}
|
||||
duk_pop(ctx);
|
||||
x += sprintf_s(str + x, strLen - x, " }");
|
||||
}
|
||||
else
|
||||
{
|
||||
x += sprintf_s(str + x, strLen - x, "%s%s", (i == 0 ? "" : ", "), duk_to_string(ctx, -1));
|
||||
}
|
||||
}
|
||||
}
|
||||
x += sprintf_s(str + x, strLen - x, "\n");
|
||||
|
||||
duk_push_this(ctx); // [console]
|
||||
int dest = Duktape_GetIntPropertyValue(ctx, -1, DESTINATION, ILibDuktape_Console_DestinationFlags_StdOut);
|
||||
|
||||
if ((dest & ILibDuktape_Console_DestinationFlags_StdOut) == ILibDuktape_Console_DestinationFlags_StdOut)
|
||||
{
|
||||
#ifdef WIN32
|
||||
DWORD writeLen;
|
||||
WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), (void*)str, x, &writeLen, NULL);
|
||||
#else
|
||||
ignore_result(write(STDOUT_FILENO, str, x));
|
||||
#endif
|
||||
}
|
||||
if ((dest & ILibDuktape_Console_DestinationFlags_WebLog) == ILibDuktape_Console_DestinationFlags_WebLog)
|
||||
{
|
||||
ILibRemoteLogging_printf(ILibChainGetLogger(Duktape_GetChain(ctx)), ILibRemoteLogging_Modules_Microstack_Generic, ILibRemoteLogging_Flags_VerbosityLevel_1, "%s", str);
|
||||
}
|
||||
if ((dest & ILibDuktape_Console_DestinationFlags_ServerConsole) == ILibDuktape_Console_DestinationFlags_ServerConsole)
|
||||
{
|
||||
if (duk_peval_string(ctx, "require('MeshAgent');") == 0)
|
||||
{
|
||||
duk_get_prop_string(ctx, -1, "SendCommand"); // [console][agent][SendCommand]
|
||||
duk_swap_top(ctx, -2); // [console][SendCommand][this]
|
||||
duk_push_object(ctx); // [console][SendCommand][this][options]
|
||||
duk_push_string(ctx, "msg"); duk_put_prop_string(ctx, -2, "action");
|
||||
duk_push_string(ctx, "console"); duk_put_prop_string(ctx, -2, "type");
|
||||
duk_push_string(ctx, str); duk_put_prop_string(ctx, -2, "value");
|
||||
if (duk_has_prop_string(ctx, -4, ILibDuktape_Console_SessionID))
|
||||
{
|
||||
duk_get_prop_string(ctx, -4, ILibDuktape_Console_SessionID);
|
||||
duk_put_prop_string(ctx, -2, "sessionid");
|
||||
}
|
||||
duk_call_method(ctx, 1);
|
||||
}
|
||||
}
|
||||
if ((dest & ILibDuktape_Console_DestinationFlags_LogFile) == ILibDuktape_Console_DestinationFlags_LogFile)
|
||||
{
|
||||
duk_size_t pathLen;
|
||||
char *path;
|
||||
char *tmp = ILibMemory_AllocateA(x + 32);
|
||||
int tmpx = ILibGetLocalTime(tmp + 1, (int)ILibMemory_AllocateA_Size(tmp) - 1) + 1;
|
||||
tmp[0] = '[';
|
||||
tmp[tmpx] = ']';
|
||||
tmp[tmpx + 1] = ':';
|
||||
tmp[tmpx + 2] = ' ';
|
||||
memcpy_s(tmp + tmpx + 3, ILibMemory_AllocateA_Size(tmp) - tmpx - 3, str, x);
|
||||
duk_eval_string(ctx, "require('fs');");
|
||||
duk_get_prop_string(ctx, -1, "writeFileSync"); // [fs][writeFileSync]
|
||||
duk_swap_top(ctx, -2); // [writeFileSync][this]
|
||||
duk_push_heapptr(ctx, ILibDuktape_GetProcessObject(ctx)); // [writeFileSync][this][process]
|
||||
duk_get_prop_string(ctx, -1, "execPath"); // [writeFileSync][this][process][execPath]
|
||||
path = (char*)duk_get_lstring(ctx, -1, &pathLen);
|
||||
if (path != NULL)
|
||||
{
|
||||
if (ILibString_EndsWithEx(path, (int)pathLen, ".exe", 4, 0))
|
||||
{
|
||||
duk_get_prop_string(ctx, -1, "substring"); // [writeFileSync][this][process][execPath][substring]
|
||||
duk_swap_top(ctx, -2); // [writeFileSync][this][process][substring][this]
|
||||
duk_push_int(ctx, 0); // [writeFileSync][this][process][substring][this][0]
|
||||
duk_push_int(ctx, (int)(pathLen - 4)); // [writeFileSync][this][process][substring][this][0][len]
|
||||
duk_call_method(ctx, 2); // [writeFileSync][this][process][path]
|
||||
}
|
||||
duk_get_prop_string(ctx, -1, "concat"); // [writeFileSync][this][process][path][concat]
|
||||
duk_swap_top(ctx, -2); // [writeFileSync][this][process][concat][this]
|
||||
duk_push_string(ctx, ".jlog"); // [writeFileSync][this][process][concat][this][.jlog]
|
||||
duk_call_method(ctx, 1); // [writeFileSync][this][process][logPath]
|
||||
duk_remove(ctx, -2); // [writeFileSync][this][logPath]
|
||||
duk_push_string(ctx, tmp); // [writeFileSync][this][logPath][log]
|
||||
duk_push_object(ctx); // [writeFileSync][this][logPath][log][options]
|
||||
duk_push_string(ctx, "a"); duk_put_prop_string(ctx, -2, "flags");
|
||||
duk_call_method(ctx, 3);
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
duk_ret_t ILibDuktape_Polyfills_Console_enableWebLog(duk_context *ctx)
|
||||
@@ -357,9 +531,49 @@ duk_ret_t ILibDuktape_Polyfills_Console_logRefCount(duk_context *ctx)
|
||||
printf("Reference Count => %s[%p]:%d\n", Duktape_GetStringPropertyValue(ctx, 0, ILibDuktape_OBJID, "UNKNOWN"), duk_require_heapptr(ctx, 0), ILibDuktape_GetReferenceCount(ctx, 0) - 1);
|
||||
return(0);
|
||||
}
|
||||
duk_ret_t ILibDuktape_Polyfills_Console_setDestination(duk_context *ctx)
|
||||
{
|
||||
int nargs = duk_get_top(ctx);
|
||||
int dest = duk_require_int(ctx, 0);
|
||||
|
||||
duk_push_this(ctx); // console
|
||||
if ((dest & ILibDuktape_Console_DestinationFlags_ServerConsole) == ILibDuktape_Console_DestinationFlags_ServerConsole)
|
||||
{
|
||||
// Mesh Server Console
|
||||
if (duk_peval_string(ctx, "require('MeshAgent');") != 0) { return(ILibDuktape_Error(ctx, "Unable to set destination to Mesh Console ")); }
|
||||
duk_pop(ctx);
|
||||
if (nargs > 1)
|
||||
{
|
||||
duk_dup(ctx, 1);
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_Console_SessionID);
|
||||
}
|
||||
else
|
||||
{
|
||||
duk_del_prop_string(ctx, -1, ILibDuktape_Console_SessionID);
|
||||
}
|
||||
}
|
||||
duk_dup(ctx, 0);
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_Console_Destination);
|
||||
return(0);
|
||||
}
|
||||
duk_ret_t ILibDuktape_Polyfills_Console_setInfoLevel(duk_context *ctx)
|
||||
{
|
||||
int val = duk_require_int(ctx, 0);
|
||||
if (val < 0) { return(ILibDuktape_Error(ctx, "Invalid Info Level: %d", val)); }
|
||||
|
||||
duk_push_this(ctx);
|
||||
duk_push_int(ctx, val);
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_Console_INFO_Level);
|
||||
|
||||
return(0);
|
||||
}
|
||||
void ILibDuktape_Polyfills_Console(duk_context *ctx)
|
||||
{
|
||||
// Polyfill console.log()
|
||||
#ifdef WIN32
|
||||
SetConsoleOutputCP(CP_UTF8);
|
||||
#endif
|
||||
|
||||
if (duk_has_prop_string(ctx, -1, "console"))
|
||||
{
|
||||
duk_get_prop_string(ctx, -1, "console"); // [g][console]
|
||||
@@ -371,11 +585,38 @@ void ILibDuktape_Polyfills_Console(duk_context *ctx)
|
||||
duk_put_prop_string(ctx, -3, "console"); // [g][console]
|
||||
}
|
||||
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "log", ILibDuktape_Polyfills_Console_log, DUK_VARARGS);
|
||||
ILibDuktape_CreateInstanceMethodWithIntProperty(ctx, "logType", (int)ILibDuktape_LogType_Normal, "log", ILibDuktape_Polyfills_Console_log, DUK_VARARGS);
|
||||
ILibDuktape_CreateInstanceMethodWithIntProperty(ctx, "logType", (int)ILibDuktape_LogType_Warn, "warn", ILibDuktape_Polyfills_Console_log, DUK_VARARGS);
|
||||
ILibDuktape_CreateInstanceMethodWithIntProperty(ctx, "logType", (int)ILibDuktape_LogType_Error, "error", ILibDuktape_Polyfills_Console_log, DUK_VARARGS);
|
||||
ILibDuktape_CreateInstanceMethodWithIntProperty(ctx, "logType", (int)ILibDuktape_LogType_Info1, "info1", ILibDuktape_Polyfills_Console_log, DUK_VARARGS);
|
||||
ILibDuktape_CreateInstanceMethodWithIntProperty(ctx, "logType", (int)ILibDuktape_LogType_Info2, "info2", ILibDuktape_Polyfills_Console_log, DUK_VARARGS);
|
||||
ILibDuktape_CreateInstanceMethodWithIntProperty(ctx, "logType", (int)ILibDuktape_LogType_Info3, "info3", ILibDuktape_Polyfills_Console_log, DUK_VARARGS);
|
||||
|
||||
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "enableWebLog", ILibDuktape_Polyfills_Console_enableWebLog, 1);
|
||||
ILibDuktape_CreateEventWithGetterAndSetterEx(ctx, "displayStreamPipeMessages", ILibDuktape_Polyfills_Console_displayStreamPipe_getter, ILibDuktape_Polyfills_Console_displayStreamPipe_setter);
|
||||
ILibDuktape_CreateEventWithGetterAndSetterEx(ctx, "displayFinalizerMessages", ILibDuktape_Polyfills_Console_displayFinalizer_getter, ILibDuktape_Polyfills_Console_displayFinalizer_setter);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "logReferenceCount", ILibDuktape_Polyfills_Console_logRefCount, 1);
|
||||
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "setDestination", ILibDuktape_Polyfills_Console_setDestination, DUK_VARARGS);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "setInfoLevel", ILibDuktape_Polyfills_Console_setInfoLevel, 1);
|
||||
|
||||
duk_push_object(ctx);
|
||||
duk_push_int(ctx, ILibDuktape_Console_DestinationFlags_DISABLED); duk_put_prop_string(ctx, -2, "DISABLED");
|
||||
duk_push_int(ctx, ILibDuktape_Console_DestinationFlags_StdOut); duk_put_prop_string(ctx, -2, "STDOUT");
|
||||
duk_push_int(ctx, ILibDuktape_Console_DestinationFlags_ServerConsole); duk_put_prop_string(ctx, -2, "SERVERCONSOLE");
|
||||
duk_push_int(ctx, ILibDuktape_Console_DestinationFlags_WebLog); duk_put_prop_string(ctx, -2, "WEBLOG");
|
||||
duk_push_int(ctx, ILibDuktape_Console_DestinationFlags_LogFile); duk_put_prop_string(ctx, -2, "LOGFILE");
|
||||
ILibDuktape_CreateReadonlyProperty(ctx, "Destinations");
|
||||
|
||||
duk_push_int(ctx, ILibDuktape_Console_DestinationFlags_StdOut | ILibDuktape_Console_DestinationFlags_LogFile);
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_Console_ERROR_Destination);
|
||||
|
||||
duk_push_int(ctx, ILibDuktape_Console_DestinationFlags_StdOut | ILibDuktape_Console_DestinationFlags_LogFile);
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_Console_WARN_Destination);
|
||||
|
||||
duk_push_int(ctx, 0); duk_put_prop_string(ctx, -2, ILibDuktape_Console_INFO_Level);
|
||||
|
||||
duk_pop(ctx); // [g]
|
||||
}
|
||||
duk_ret_t ILibDuktape_ntohl(duk_context *ctx)
|
||||
@@ -448,6 +689,8 @@ duk_ret_t ILibDuktape_Polyfills_timer_finalizer(duk_context *ctx)
|
||||
{
|
||||
// Make sure we remove any timers just in case, so we don't leak resources
|
||||
ILibDuktape_Timer *ptrs;
|
||||
if (duk_has_prop_string(ctx, 0, ILibDuktape_Timer_Ptrs))
|
||||
{
|
||||
duk_get_prop_string(ctx, 0, ILibDuktape_Timer_Ptrs);
|
||||
if (duk_has_prop_string(ctx, 0, "\xFF_callback"))
|
||||
{
|
||||
@@ -460,6 +703,7 @@ duk_ret_t ILibDuktape_Polyfills_timer_finalizer(duk_context *ctx)
|
||||
ptrs = (ILibDuktape_Timer*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
|
||||
ILibLifeTime_Remove(ILibGetBaseTimer(Duktape_GetChain(ctx)), ptrs);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
void ILibDuktape_Polyfills_timer_elapsed(void *obj)
|
||||
@@ -467,8 +711,10 @@ void ILibDuktape_Polyfills_timer_elapsed(void *obj)
|
||||
ILibDuktape_Timer *ptrs = (ILibDuktape_Timer*)obj;
|
||||
int argCount, i;
|
||||
duk_context *ctx = ptrs->ctx;
|
||||
char *funcName;
|
||||
|
||||
duk_push_heapptr(ctx, ptrs->callback); // [func]
|
||||
funcName = Duktape_GetStringPropertyValue(ctx, -1, "name", "unknown_method");
|
||||
duk_push_heapptr(ctx, ptrs->object); // [func][this]
|
||||
duk_push_heapptr(ctx, ptrs->args); // [func][this][argArray]
|
||||
|
||||
@@ -480,6 +726,7 @@ void ILibDuktape_Polyfills_timer_elapsed(void *obj)
|
||||
{
|
||||
duk_del_prop_string(ctx, -2, "\xFF_callback");
|
||||
duk_del_prop_string(ctx, -2, "\xFF_argArray");
|
||||
duk_del_prop_string(ctx, -2, ILibDuktape_Timer_Ptrs);
|
||||
}
|
||||
|
||||
argCount = (int)duk_get_length(ctx, -1);
|
||||
@@ -489,7 +736,7 @@ void ILibDuktape_Polyfills_timer_elapsed(void *obj)
|
||||
duk_swap_top(ctx, -2); // [func][this][arg][argArray]
|
||||
}
|
||||
duk_pop(ctx); // [func][this][...arg...]
|
||||
if (duk_pcall_method(ctx, argCount) != 0) { ILibDuktape_Process_UncaughtExceptionEx(ctx, "timers.onElapsed() callback handler"); }
|
||||
if (duk_pcall_method(ctx, argCount) != 0) { ILibDuktape_Process_UncaughtExceptionEx(ctx, "timers.onElapsed() callback handler on '%s()' ", funcName); }
|
||||
duk_pop(ctx); // ...
|
||||
}
|
||||
duk_ret_t ILibDuktape_Polyfills_timer_set(duk_context *ctx)
|
||||
@@ -582,7 +829,14 @@ void ILibDuktape_Polyfills_timer(duk_context *ctx)
|
||||
ILibDuktape_CreateInstanceMethodWithIntProperty(ctx, "type", ILibDuktape_Timer_Type_INTERVAL, "clearInterval", ILibDuktape_Polyfills_timer_clear, 1);
|
||||
ILibDuktape_CreateInstanceMethodWithIntProperty(ctx, "type", ILibDuktape_Timer_Type_IMMEDIATE, "clearImmediate", ILibDuktape_Polyfills_timer_clear, 1);
|
||||
}
|
||||
|
||||
duk_ret_t ILibDuktape_Polyfills_getJSModule(duk_context *ctx)
|
||||
{
|
||||
if (ILibDuktape_ModSearch_GetJSModule(ctx, (char*)duk_require_string(ctx, 0)) == 0)
|
||||
{
|
||||
return(ILibDuktape_Error(ctx, "getJSModule(): (%s) not found", (char*)duk_require_string(ctx, 0)));
|
||||
}
|
||||
return(1);
|
||||
}
|
||||
duk_ret_t ILibDuktape_Polyfills_addModule(duk_context *ctx)
|
||||
{
|
||||
duk_size_t moduleLen;
|
||||
@@ -595,6 +849,14 @@ duk_ret_t ILibDuktape_Polyfills_addModule(duk_context *ctx)
|
||||
}
|
||||
return(0);
|
||||
}
|
||||
duk_ret_t ILibDuktape_Polyfills_addModuleObject(duk_context *ctx)
|
||||
{
|
||||
void *module = duk_require_heapptr(ctx, 1);
|
||||
char *moduleName = (char*)duk_require_string(ctx, 0);
|
||||
|
||||
ILibDuktape_ModSearch_AddModuleObject(ctx, moduleName, module);
|
||||
return(0);
|
||||
}
|
||||
duk_ret_t ILibDuktape_Queue_Finalizer(duk_context *ctx)
|
||||
{
|
||||
duk_get_prop_string(ctx, 0, ILibDuktape_Queue_Ptr);
|
||||
@@ -645,7 +907,12 @@ duk_ret_t ILibDuktape_Queue_DeQueue(duk_context *ctx)
|
||||
if (peek == 0) { duk_del_prop_string(ctx, -length - 2, Duktape_GetStashKey(h)); }
|
||||
return(length);
|
||||
}
|
||||
|
||||
duk_ret_t ILibDuktape_Queue_isEmpty(duk_context *ctx)
|
||||
{
|
||||
duk_push_this(ctx);
|
||||
duk_push_boolean(ctx, ILibQueue_IsEmpty((ILibQueue)Duktape_GetPointerProperty(ctx, -1, ILibDuktape_Queue_Ptr)));
|
||||
return(1);
|
||||
}
|
||||
duk_ret_t ILibDuktape_Queue_new(duk_context *ctx)
|
||||
{
|
||||
duk_push_object(ctx); // [queue]
|
||||
@@ -656,6 +923,7 @@ duk_ret_t ILibDuktape_Queue_new(duk_context *ctx)
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "enQueue", ILibDuktape_Queue_EnQueue, DUK_VARARGS);
|
||||
ILibDuktape_CreateInstanceMethodWithIntProperty(ctx, "peek", 0, "deQueue", ILibDuktape_Queue_DeQueue, DUK_VARARGS);
|
||||
ILibDuktape_CreateInstanceMethodWithIntProperty(ctx, "peek", 1, "peekQueue", ILibDuktape_Queue_DeQueue, DUK_VARARGS);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "isEmpty", ILibDuktape_Queue_isEmpty, 0);
|
||||
|
||||
return(1);
|
||||
}
|
||||
@@ -687,7 +955,7 @@ ILibTransport_DoneState ILibDuktape_DynamicBuffer_WriteSink(ILibDuktape_DuplexSt
|
||||
void ILibDuktape_DynamicBuffer_WriteSink_ChainThread(void *chain, void *user)
|
||||
{
|
||||
ILibDuktape_DynamicBuffer_ContextSwitchData *data = (ILibDuktape_DynamicBuffer_ContextSwitchData*)user;
|
||||
if (ILibDuktape_IsPointerValid(chain, data->heapptr) != 0)
|
||||
if(ILibMemory_CanaryOK(data->stream))
|
||||
{
|
||||
ILibDuktape_DynamicBuffer_WriteSink(data->stream, data->buffer, data->bufferLen, data->data);
|
||||
ILibDuktape_DuplexStream_Ready(data->stream);
|
||||
@@ -727,7 +995,7 @@ ILibTransport_DoneState ILibDuktape_DynamicBuffer_WriteSink(ILibDuktape_DuplexSt
|
||||
{
|
||||
tmpSize += 4096;
|
||||
}
|
||||
data->buffer = (char*)realloc(data->buffer, tmpSize);
|
||||
if ((data->buffer = (char*)realloc(data->buffer, tmpSize)) == NULL) { ILIBCRITICALEXIT(254); }
|
||||
data->bufferLen = tmpSize;
|
||||
}
|
||||
}
|
||||
@@ -772,7 +1040,6 @@ void ILibDuktape_DynamicBuffer_EndSink(ILibDuktape_DuplexStream *stream, void *u
|
||||
}
|
||||
duk_ret_t ILibDuktape_DynamicBuffer_Finalizer(duk_context *ctx)
|
||||
{
|
||||
ILibDuktape_InValidateHeapPointer(ctx, 0);
|
||||
duk_get_prop_string(ctx, 0, "\xFF_buffer");
|
||||
ILibDuktape_DynamicBuffer_data *data = (ILibDuktape_DynamicBuffer_data*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
free(data->buffer);
|
||||
@@ -818,7 +1085,6 @@ duk_ret_t ILibDuktape_DynamicBuffer_new(duk_context *ctx)
|
||||
ILibDuktape_EventEmitter_CreateEventEx(ILibDuktape_EventEmitter_GetEmitter(ctx, -1), "readable");
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "read", ILibDuktape_DynamicBuffer_read, DUK_VARARGS);
|
||||
ILibDuktape_CreateFinalizer(ctx, ILibDuktape_DynamicBuffer_Finalizer);
|
||||
ILibDuktape_ValidateHeapPointer(ctx, -1);
|
||||
|
||||
return(1);
|
||||
}
|
||||
@@ -934,11 +1200,9 @@ duk_ret_t ILibDuktape_Stream_Push(duk_context *ctx)
|
||||
{
|
||||
duk_push_this(ctx); // [stream]
|
||||
ILibDuktape_readableStream *RS = (ILibDuktape_readableStream*)Duktape_GetPointerProperty(ctx, -1, ILibDuktape_Stream_ReadablePtr);
|
||||
duk_get_prop_string(ctx, -1, ILibDuktape_Stream_Buffer); // [stream][buffer]
|
||||
duk_del_prop_string(ctx, -2, ILibDuktape_Stream_Buffer); // (Deleting here, because unshift will save it again, if necessary)
|
||||
|
||||
duk_size_t bufferLen;
|
||||
char *buffer = (char*)Duktape_GetBuffer(ctx, -1, &bufferLen);
|
||||
char *buffer = (char*)Duktape_GetBuffer(ctx, 0, &bufferLen);
|
||||
|
||||
duk_push_boolean(ctx, !ILibDuktape_readableStream_WriteDataEx(RS, 0, buffer, (int)bufferLen)); // [stream][buffer][retVal]
|
||||
return(1);
|
||||
@@ -970,11 +1234,148 @@ duk_idx_t ILibDuktape_Stream_newReadable(duk_context *ctx)
|
||||
}
|
||||
return(1);
|
||||
}
|
||||
duk_ret_t ILibDuktape_Stream_Writable_WriteSink_Flush(duk_context *ctx)
|
||||
{
|
||||
duk_push_current_function(ctx);
|
||||
ILibTransport_DoneState *retVal = (ILibTransport_DoneState*)Duktape_GetPointerProperty(ctx, -1, "retval");
|
||||
if (retVal != NULL)
|
||||
{
|
||||
*retVal = ILibTransport_DoneState_COMPLETE;
|
||||
}
|
||||
else
|
||||
{
|
||||
duk_push_this(ctx);
|
||||
ILibDuktape_WritableStream *WS = (ILibDuktape_WritableStream*)Duktape_GetPointerProperty(ctx, -1, ILibDuktape_Stream_WritablePtr);
|
||||
ILibDuktape_WritableStream_Ready(WS);
|
||||
}
|
||||
return(0);
|
||||
}
|
||||
ILibTransport_DoneState ILibDuktape_Stream_Writable_WriteSink(struct ILibDuktape_WritableStream *stream, char *buffer, int bufferLen, void *user)
|
||||
{
|
||||
void *h;
|
||||
ILibTransport_DoneState retVal = ILibTransport_DoneState_INCOMPLETE;
|
||||
|
||||
duk_push_this(stream->ctx); // [writable]
|
||||
duk_get_prop_string(stream->ctx, -1, "_write"); // [writable][_write]
|
||||
duk_swap_top(stream->ctx, -2); // [_write][this]
|
||||
if (stream->Reserved)
|
||||
{
|
||||
duk_push_external_buffer(stream->ctx); // [_write][this][extBuffer]
|
||||
duk_insert(stream->ctx, -3); // [extBuffer][_write][this]
|
||||
duk_config_buffer(stream->ctx, -3, buffer, (duk_size_t)bufferLen);
|
||||
duk_push_buffer_object(stream->ctx, -3, 0, (duk_size_t)bufferLen, DUK_BUFOBJ_NODEJS_BUFFER);// [extBuffer][_write][this][buffer]
|
||||
}
|
||||
else
|
||||
{
|
||||
duk_push_lstring(stream->ctx, buffer, (duk_size_t)bufferLen); // [_write][this][string]
|
||||
}
|
||||
duk_push_c_function(stream->ctx, ILibDuktape_Stream_Writable_WriteSink_Flush, DUK_VARARGS); // [_write][this][string/buffer][callback]
|
||||
h = duk_get_heapptr(stream->ctx, -1);
|
||||
duk_push_heap_stash(stream->ctx); // [_write][this][string/buffer][callback][stash]
|
||||
duk_dup(stream->ctx, -2); // [_write][this][string/buffer][callback][stash][callback]
|
||||
duk_put_prop_string(stream->ctx, -2, Duktape_GetStashKey(h)); // [_write][this][string/buffer][callback][stash]
|
||||
duk_pop(stream->ctx); // [_write][this][string/buffer][callback]
|
||||
|
||||
duk_push_pointer(stream->ctx, &retVal); // [_write][this][string/buffer][callback][retval]
|
||||
duk_put_prop_string(stream->ctx, -2, "retval"); // [_write][this][string/buffer][callback]
|
||||
if (duk_pcall_method(stream->ctx, 2) != 0)
|
||||
{
|
||||
ILibDuktape_Process_UncaughtExceptionEx(stream->ctx, "stream.writable.write(): "); retVal = ILibTransport_DoneState_ERROR;
|
||||
}
|
||||
duk_pop(stream->ctx); // ...
|
||||
|
||||
duk_push_heapptr(stream->ctx, h); // [callback]
|
||||
duk_del_prop_string(stream->ctx, -1, "retval");
|
||||
duk_pop(stream->ctx); // ...
|
||||
|
||||
duk_push_heap_stash(stream->ctx);
|
||||
duk_del_prop_string(stream->ctx, -1, Duktape_GetStashKey(h));
|
||||
duk_pop(stream->ctx);
|
||||
|
||||
return(retVal);
|
||||
}
|
||||
void ILibDuktape_Stream_Writable_EndSink(struct ILibDuktape_WritableStream *stream, void *user)
|
||||
{
|
||||
duk_push_this(stream->ctx); // [writable]
|
||||
duk_get_prop_string(stream->ctx, -1, "_final"); // [writable][_final]
|
||||
duk_swap_top(stream->ctx, -2); // [_final][this]
|
||||
if (duk_pcall_method(stream->ctx, 0) != 0) { ILibDuktape_Process_UncaughtExceptionEx(stream->ctx, "stream.writable._final(): "); }
|
||||
duk_pop(stream->ctx); // ...
|
||||
}
|
||||
duk_ret_t ILibDuktape_Stream_newWritable(duk_context *ctx)
|
||||
{
|
||||
ILibDuktape_WritableStream *WS;
|
||||
duk_push_object(ctx); // [Writable]
|
||||
ILibDuktape_WriteID(ctx, "stream.writable");
|
||||
WS = ILibDuktape_WritableStream_Init(ctx, ILibDuktape_Stream_Writable_WriteSink, ILibDuktape_Stream_Writable_EndSink, NULL);
|
||||
WS->JSCreated = 1;
|
||||
|
||||
duk_push_pointer(ctx, WS);
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_Stream_WritablePtr);
|
||||
|
||||
if (duk_is_object(ctx, 0))
|
||||
{
|
||||
void *h = Duktape_GetHeapptrProperty(ctx, 0, "write");
|
||||
if (h != NULL) { duk_push_heapptr(ctx, h); duk_put_prop_string(ctx, -2, "_write"); }
|
||||
h = Duktape_GetHeapptrProperty(ctx, 0, "final");
|
||||
if (h != NULL) { duk_push_heapptr(ctx, h); duk_put_prop_string(ctx, -2, "_final"); }
|
||||
}
|
||||
return(1);
|
||||
}
|
||||
void ILibDuktape_Stream_Duplex_PauseSink(ILibDuktape_DuplexStream *stream, void *user)
|
||||
{
|
||||
ILibDuktape_Stream_PauseSink(stream->readableStream, user);
|
||||
}
|
||||
void ILibDuktape_Stream_Duplex_ResumeSink(ILibDuktape_DuplexStream *stream, void *user)
|
||||
{
|
||||
ILibDuktape_Stream_ResumeSink(stream->readableStream, user);
|
||||
}
|
||||
int ILibDuktape_Stream_Duplex_UnshiftSink(ILibDuktape_DuplexStream *stream, int unshiftBytes, void *user)
|
||||
{
|
||||
return(ILibDuktape_Stream_UnshiftSink(stream->readableStream, unshiftBytes, user));
|
||||
}
|
||||
ILibTransport_DoneState ILibDuktape_Stream_Duplex_WriteSink(ILibDuktape_DuplexStream *stream, char *buffer, int bufferLen, void *user)
|
||||
{
|
||||
return(ILibDuktape_Stream_Writable_WriteSink(stream->writableStream, buffer, bufferLen, user));
|
||||
}
|
||||
void ILibDuktape_Stream_Duplex_EndSink(ILibDuktape_DuplexStream *stream, void *user)
|
||||
{
|
||||
ILibDuktape_Stream_Writable_EndSink(stream->writableStream, user);
|
||||
}
|
||||
duk_ret_t ILibDuktape_Stream_newDuplex(duk_context *ctx)
|
||||
{
|
||||
ILibDuktape_DuplexStream *DS;
|
||||
duk_push_object(ctx); // [Duplex]
|
||||
ILibDuktape_WriteID(ctx, "stream.Duplex");
|
||||
DS = ILibDuktape_DuplexStream_InitEx(ctx, ILibDuktape_Stream_Duplex_WriteSink, ILibDuktape_Stream_Duplex_EndSink, ILibDuktape_Stream_Duplex_PauseSink, ILibDuktape_Stream_Duplex_ResumeSink, ILibDuktape_Stream_Duplex_UnshiftSink, NULL);
|
||||
DS->writableStream->JSCreated = 1;
|
||||
|
||||
duk_push_pointer(ctx, DS->writableStream);
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_Stream_WritablePtr);
|
||||
|
||||
duk_push_pointer(ctx, DS->readableStream);
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_Stream_ReadablePtr);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "push", ILibDuktape_Stream_Push, DUK_VARARGS);
|
||||
ILibDuktape_EventEmitter_AddOnceEx3(ctx, -1, "end", ILibDuktape_Stream_EndSink);
|
||||
|
||||
if (duk_is_object(ctx, 0))
|
||||
{
|
||||
void *h = Duktape_GetHeapptrProperty(ctx, 0, "write");
|
||||
if (h != NULL) { duk_push_heapptr(ctx, h); duk_put_prop_string(ctx, -2, "_write"); }
|
||||
h = Duktape_GetHeapptrProperty(ctx, 0, "final");
|
||||
if (h != NULL) { duk_push_heapptr(ctx, h); duk_put_prop_string(ctx, -2, "_final"); }
|
||||
h = Duktape_GetHeapptrProperty(ctx, 0, "read");
|
||||
if (h != NULL) { duk_push_heapptr(ctx, h); duk_put_prop_string(ctx, -2, "_read"); }
|
||||
}
|
||||
return(1);
|
||||
}
|
||||
void ILibDuktape_Stream_Init(duk_context *ctx, void *chain)
|
||||
{
|
||||
duk_push_object(ctx); // [stream
|
||||
ILibDuktape_WriteID(ctx, "stream");
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "Readable", ILibDuktape_Stream_newReadable, DUK_VARARGS);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "Writable", ILibDuktape_Stream_newWritable, DUK_VARARGS);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "Duplex", ILibDuktape_Stream_newDuplex, DUK_VARARGS);
|
||||
}
|
||||
void ILibDuktape_Polyfills_debugGC2(duk_context *ctx, void ** args, int argsLen)
|
||||
{
|
||||
@@ -996,11 +1397,157 @@ duk_ret_t ILibDuktape_Polyfills_debug(duk_context *ctx)
|
||||
#endif
|
||||
return(0);
|
||||
}
|
||||
#ifndef MICROSTACK_NOTLS
|
||||
duk_ret_t ILibDuktape_PKCS7_getSignedDataBlock(duk_context *ctx)
|
||||
{
|
||||
char *hash = ILibMemory_AllocateA(UTIL_SHA256_HASHSIZE);
|
||||
char *pkeyHash = ILibMemory_AllocateA(UTIL_SHA256_HASHSIZE);
|
||||
unsigned int size, r;
|
||||
BIO *out = NULL;
|
||||
PKCS7 *message = NULL;
|
||||
char* data2 = NULL;
|
||||
STACK_OF(X509) *st = NULL;
|
||||
|
||||
duk_size_t bufferLen;
|
||||
char *buffer = Duktape_GetBuffer(ctx, 0, &bufferLen);
|
||||
|
||||
message = d2i_PKCS7(NULL, (const unsigned char**)&buffer, (long)bufferLen);
|
||||
if (message == NULL) { return(ILibDuktape_Error(ctx, "PKCS7 Error")); }
|
||||
|
||||
// Lets rebuild the original message and check the size
|
||||
size = i2d_PKCS7(message, NULL);
|
||||
if (size < (unsigned int)bufferLen) { PKCS7_free(message); return(ILibDuktape_Error(ctx, "PKCS7 Error")); }
|
||||
|
||||
out = BIO_new(BIO_s_mem());
|
||||
|
||||
// Check the PKCS7 signature, but not the certificate chain.
|
||||
r = PKCS7_verify(message, NULL, NULL, NULL, out, PKCS7_NOVERIFY);
|
||||
if (r == 0) { PKCS7_free(message); BIO_free(out); return(ILibDuktape_Error(ctx, "PKCS7 Verify Error")); }
|
||||
|
||||
// If data block contains less than 32 bytes, fail.
|
||||
size = (unsigned int)BIO_get_mem_data(out, &data2);
|
||||
if (size <= ILibMemory_AllocateA_Size(hash)) { PKCS7_free(message); BIO_free(out); return(ILibDuktape_Error(ctx, "PKCS7 Size Mismatch Error")); }
|
||||
|
||||
|
||||
duk_push_object(ctx); // [val]
|
||||
duk_push_fixed_buffer(ctx, size); // [val][fbuffer]
|
||||
duk_dup(ctx, -1); // [val][fbuffer][dup]
|
||||
duk_put_prop_string(ctx, -3, "\xFF_fixedbuffer"); // [val][fbuffer]
|
||||
duk_swap_top(ctx, -2); // [fbuffer][val]
|
||||
duk_push_buffer_object(ctx, -2, 0, size, DUK_BUFOBJ_NODEJS_BUFFER); // [fbuffer][val][buffer]
|
||||
ILibDuktape_CreateReadonlyProperty(ctx, "data"); // [fbuffer][val]
|
||||
memcpy_s(Duktape_GetBuffer(ctx, -2, NULL), size, data2, size);
|
||||
|
||||
|
||||
// Get the certificate signer
|
||||
st = PKCS7_get0_signers(message, NULL, PKCS7_NOVERIFY);
|
||||
|
||||
// Get a full certificate hash of the signer
|
||||
X509_digest(sk_X509_value(st, 0), EVP_sha256(), (unsigned char*)hash, NULL);
|
||||
X509_pubkey_digest(sk_X509_value(st, 0), EVP_sha256(), (unsigned char*)pkeyHash, NULL);
|
||||
|
||||
sk_X509_free(st);
|
||||
|
||||
// Check certificate hash with first 32 bytes of data.
|
||||
if (memcmp(hash, Duktape_GetBuffer(ctx, -2, NULL), ILibMemory_AllocateA_Size(hash)) != 0) { PKCS7_free(message); BIO_free(out); return(ILibDuktape_Error(ctx, "PKCS7 Certificate Hash Mismatch Error")); }
|
||||
char *tmp = ILibMemory_AllocateA(1 + (ILibMemory_AllocateA_Size(hash) * 2));
|
||||
util_tohex(hash, (int)ILibMemory_AllocateA_Size(hash), tmp);
|
||||
duk_push_object(ctx); // [fbuffer][val][cert]
|
||||
ILibDuktape_WriteID(ctx, "certificate");
|
||||
duk_push_string(ctx, tmp); // [fbuffer][val][cert][fingerprint]
|
||||
ILibDuktape_CreateReadonlyProperty(ctx, "fingerprint"); // [fbuffer][val][cert]
|
||||
util_tohex(pkeyHash, (int)ILibMemory_AllocateA_Size(pkeyHash), tmp);
|
||||
duk_push_string(ctx, tmp); // [fbuffer][val][cert][publickeyhash]
|
||||
ILibDuktape_CreateReadonlyProperty(ctx, "publicKeyHash"); // [fbuffer][val][cert]
|
||||
|
||||
ILibDuktape_CreateReadonlyProperty(ctx, "signingCertificate"); // [fbuffer][val]
|
||||
|
||||
// Approved, cleanup and return.
|
||||
BIO_free(out);
|
||||
PKCS7_free(message);
|
||||
|
||||
return(1);
|
||||
}
|
||||
duk_ret_t ILibDuktape_PKCS7_signDataBlockFinalizer(duk_context *ctx)
|
||||
{
|
||||
char *buffer = Duktape_GetPointerProperty(ctx, 0, "\xFF_signature");
|
||||
if (buffer != NULL) { free(buffer); }
|
||||
return(0);
|
||||
}
|
||||
duk_ret_t ILibDuktape_PKCS7_signDataBlock(duk_context *ctx)
|
||||
{
|
||||
duk_get_prop_string(ctx, 1, "secureContext");
|
||||
duk_get_prop_string(ctx, -1, "\xFF_SecureContext2CertBuffer");
|
||||
struct util_cert *cert = (struct util_cert*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
duk_size_t bufferLen;
|
||||
char *buffer = (char*)Duktape_GetBuffer(ctx, 0, &bufferLen);
|
||||
|
||||
BIO *in = NULL;
|
||||
PKCS7 *message = NULL;
|
||||
char *signature = NULL;
|
||||
int signatureLength = 0;
|
||||
|
||||
// Sign the block
|
||||
in = BIO_new_mem_buf(buffer, (int)bufferLen);
|
||||
message = PKCS7_sign(cert->x509, cert->pkey, NULL, in, PKCS7_BINARY);
|
||||
if (message != NULL)
|
||||
{
|
||||
signatureLength = i2d_PKCS7(message, (unsigned char**)&signature);
|
||||
PKCS7_free(message);
|
||||
}
|
||||
if (in != NULL) BIO_free(in);
|
||||
if (signatureLength <= 0) { return(ILibDuktape_Error(ctx, "PKCS7_signDataBlockError: ")); }
|
||||
|
||||
duk_push_external_buffer(ctx);
|
||||
duk_config_buffer(ctx, -1, signature, signatureLength);
|
||||
duk_push_buffer_object(ctx, -1, 0, signatureLength, DUK_BUFOBJ_NODEJS_BUFFER);
|
||||
duk_push_pointer(ctx, signature);
|
||||
duk_put_prop_string(ctx, -2, "\xFF_signature");
|
||||
ILibDuktape_CreateFinalizer(ctx, ILibDuktape_PKCS7_signDataBlockFinalizer);
|
||||
|
||||
return(1);
|
||||
}
|
||||
void ILibDuktape_PKCS7_Push(duk_context *ctx, void *chain)
|
||||
{
|
||||
duk_push_object(ctx);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "getSignedDataBlock", ILibDuktape_PKCS7_getSignedDataBlock, 1);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "signDataBlock", ILibDuktape_PKCS7_signDataBlock, DUK_VARARGS);
|
||||
}
|
||||
|
||||
extern uint32_t crc32c(uint32_t crc, const unsigned char* buf, uint32_t len);
|
||||
duk_ret_t ILibDuktape_Polyfills_crc32c(duk_context *ctx)
|
||||
{
|
||||
duk_size_t len;
|
||||
char *buffer = Duktape_GetBuffer(ctx, 0, &len);
|
||||
duk_push_int(ctx, crc32c(0, (unsigned char*)buffer, (uint32_t)len));
|
||||
return(1);
|
||||
}
|
||||
#endif
|
||||
duk_ret_t ILibDuktape_Polyfills_Object_hashCode(duk_context *ctx)
|
||||
{
|
||||
duk_push_this(ctx);
|
||||
duk_push_string(ctx, Duktape_GetStashKey(duk_get_heapptr(ctx, -1)));
|
||||
return(1);
|
||||
}
|
||||
void ILibDuktape_Polyfills_object(duk_context *ctx)
|
||||
{
|
||||
// Polyfill Object._hashCode()
|
||||
duk_get_prop_string(ctx, -1, "Object"); // [g][Object]
|
||||
duk_get_prop_string(ctx, -1, "prototype"); // [g][Object][prototype]
|
||||
duk_push_c_function(ctx, ILibDuktape_Polyfills_Object_hashCode, 0); // [g][Object][prototype][func]
|
||||
ILibDuktape_CreateReadonlyProperty(ctx, "_hashCode"); // [g][Object][prototype]
|
||||
duk_pop_2(ctx); // [g]
|
||||
}
|
||||
|
||||
|
||||
void ILibDuktape_Polyfills_Init(duk_context *ctx)
|
||||
{
|
||||
ILibDuktape_ModSearch_AddHandler(ctx, "queue", ILibDuktape_Queue_Push);
|
||||
ILibDuktape_ModSearch_AddHandler(ctx, "DynamicBuffer", ILibDuktape_DynamicBuffer_Push);
|
||||
ILibDuktape_ModSearch_AddHandler(ctx, "stream", ILibDuktape_Stream_Init);
|
||||
#ifndef MICROSTACK_NOTLS
|
||||
ILibDuktape_ModSearch_AddHandler(ctx, "pkcs7", ILibDuktape_PKCS7_Push);
|
||||
#endif
|
||||
|
||||
// Global Polyfills
|
||||
duk_push_global_object(ctx); // [g]
|
||||
@@ -1010,13 +1557,20 @@ void ILibDuktape_Polyfills_Init(duk_context *ctx)
|
||||
ILibDuktape_Polyfills_Console(ctx);
|
||||
ILibDuktape_Polyfills_byte_ordering(ctx);
|
||||
ILibDuktape_Polyfills_timer(ctx);
|
||||
ILibDuktape_Polyfills_object(ctx);
|
||||
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "addModuleObject", ILibDuktape_Polyfills_addModuleObject, 2);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "addModule", ILibDuktape_Polyfills_addModule, 2);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "getJSModule", ILibDuktape_Polyfills_getJSModule, 1);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "_debugCrash", ILibDuktape_Polyfills_debugCrash, 0);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "_debugGC", ILibDuktape_Polyfills_debugGC, 0);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "_debug", ILibDuktape_Polyfills_debug, 0);
|
||||
|
||||
#ifndef MICROSTACK_NOTLS
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "crc32c", ILibDuktape_Polyfills_crc32c, DUK_VARARGS);
|
||||
#endif
|
||||
duk_pop(ctx); // ...
|
||||
|
||||
ILibDuktape_Debugger_Init(ctx, 9091);
|
||||
}
|
||||
|
||||
#ifdef __DOXY__
|
||||
|
||||
@@ -1,256 +0,0 @@
|
||||
#include "duktape.h"
|
||||
|
||||
#if defined(WINSOCK2)
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
#endif
|
||||
|
||||
#include "microstack/ILibParsers.h"
|
||||
#include "microstack/ILibProcessPipe.h"
|
||||
#include "ILibDuktape_ProcessPipe.h"
|
||||
#include "ILibDuktape_Helpers.h"
|
||||
#include "ILibDuktape_DuplexStream.h"
|
||||
#include "ILibDuktapeModSearch.h"
|
||||
|
||||
#define ILibDuktape_ProcessPipe_Process_ErrorStreamPtr "\xFF_ErrorStreamPtr"
|
||||
#define ILibDuktape_ProcessPipe_Process_ErrorStreamPtrNative "\xFF_ErrorStreamPtrNative"
|
||||
#define ILibDuktape_ProcessPipe_Process_PTR "\xFFProcessPtr"
|
||||
|
||||
ILibTransport_DoneState ILibDuktape_ProcessPipe_Process_JSOnWrite(ILibDuktape_DuplexStream *stream, char *buffer, int bufferLen, void *user)
|
||||
{
|
||||
// Called when JavaScript has written bytes to this object
|
||||
|
||||
ILibProcessPipe_Process mProcess = (ILibProcessPipe_Process)user;
|
||||
return(ILibProcessPipe_Process_WriteStdIn(mProcess, buffer, bufferLen, ILibTransport_MemoryOwnership_USER));
|
||||
}
|
||||
void ILibDuktape_ProcessPipe_Process_JSOnEnd(ILibDuktape_DuplexStream *stream, void *user)
|
||||
{
|
||||
// Called when JavaScript has specified that it will no longer write data
|
||||
|
||||
ILibProcessPipe_Process mProcess = (ILibProcessPipe_Process)user;
|
||||
|
||||
if (mProcess != NULL)
|
||||
{
|
||||
ILibProcessPipe_Process_KillEx(mProcess);
|
||||
|
||||
duk_push_heapptr(stream->readableStream->ctx, stream->ParentObject); // [process]
|
||||
duk_del_prop_string(stream->readableStream->ctx, -1, ILibDuktape_ProcessPipe_Process_PTR);
|
||||
duk_pop(stream->readableStream->ctx);
|
||||
ILibProcessPipe_Process_UpdateUserObject(mProcess, NULL);
|
||||
stream->user = NULL;
|
||||
}
|
||||
}
|
||||
void ILibDuktape_ProcessPipe_Process_JSPause(ILibDuktape_DuplexStream *sender, void *user)
|
||||
{
|
||||
// Called when either JavaScript called Pause, or JavaScript has not attached a reader yet
|
||||
|
||||
ILibProcessPipe_Process mProcess = (ILibProcessPipe_Process)user;
|
||||
ILibProcessPipe_Pipe_Pause(ILibProcessPipe_Process_GetStdOut(mProcess));
|
||||
}
|
||||
void ILibDuktape_ProcessPipe_Process_JSResume(ILibDuktape_DuplexStream *sender, void *user)
|
||||
{
|
||||
// Called when JavaScript called Resume
|
||||
|
||||
ILibProcessPipe_Process mProcess = (ILibProcessPipe_Process)user;
|
||||
ILibProcessPipe_Pipe_Resume(ILibProcessPipe_Process_GetStdOut(mProcess));
|
||||
}
|
||||
|
||||
void ILibDuktape_ProcessPipe_Process_OnExit(ILibProcessPipe_Process sender, int exitCode, void* user)
|
||||
{
|
||||
if (user == NULL) { return; }
|
||||
|
||||
// Called when process has exited
|
||||
ILibDuktape_DuplexStream* stream = (ILibDuktape_DuplexStream*)user;
|
||||
ILibProcessPipe_Process_UpdateUserObject(sender, NULL);
|
||||
|
||||
ILibDuktape_DuplexStream_WriteEnd(stream);
|
||||
duk_push_heapptr(stream->readableStream->ctx, stream->ParentObject); // [process]
|
||||
duk_del_prop_string(stream->readableStream->ctx, -1, ILibDuktape_ProcessPipe_Process_PTR);
|
||||
duk_pop(stream->readableStream->ctx);
|
||||
|
||||
}
|
||||
void ILibDuktape_ProcessPipe_Process_OnStdOut(ILibProcessPipe_Process sender, char *buffer, int bufferLen, int* bytesConsumed, void* user)
|
||||
{
|
||||
if (user == NULL) { return; }
|
||||
|
||||
// Called when process has written data
|
||||
ILibDuktape_DuplexStream* ds = (ILibDuktape_DuplexStream*)user;
|
||||
ILibDuktape_DuplexStream_WriteData(ds, buffer, bufferLen);
|
||||
*bytesConsumed = bufferLen;
|
||||
}
|
||||
void ILibDuktape_ProcessPipe_Process_OnStdErr(ILibProcessPipe_Process sender, char *buffer, int bufferLen, int* bytesConsumed, void* user)
|
||||
{
|
||||
if (user == NULL) { return; }
|
||||
|
||||
// Called when process has written error data
|
||||
ILibDuktape_DuplexStream* ds = (ILibDuktape_DuplexStream*)user;
|
||||
ILibDuktape_readableStream *rs;
|
||||
duk_push_heapptr(ds->readableStream->ctx, ds->ParentObject); // [process]
|
||||
duk_get_prop_string(ds->readableStream->ctx, -1, ILibDuktape_ProcessPipe_Process_ErrorStreamPtrNative); // [process][error]
|
||||
rs = (ILibDuktape_readableStream*)duk_get_pointer(ds->readableStream->ctx, -1);
|
||||
|
||||
ILibDuktape_readableStream_WriteData(rs, buffer, bufferLen);
|
||||
*bytesConsumed = bufferLen;
|
||||
}
|
||||
void ILibDuktape_ProcessPipe_Process_OnSendOK(ILibProcessPipe_Process sender, void* user)
|
||||
{
|
||||
if (user == NULL) { return; }
|
||||
//ToDo: Finish this
|
||||
}
|
||||
duk_ret_t ILibDuktape_ProcessPipe_Process_Finalizer(duk_context *ctx)
|
||||
{
|
||||
ILibProcessPipe_Process mProcess;
|
||||
|
||||
duk_dup(ctx, 0);
|
||||
duk_get_prop_string(ctx, -1, ILibDuktape_ProcessPipe_Process_PTR);
|
||||
mProcess = (ILibProcessPipe_Process)duk_get_pointer(ctx, -1);
|
||||
|
||||
if (mProcess != NULL)
|
||||
{
|
||||
ILibProcessPipe_Process_UpdateUserObject(mProcess, NULL);
|
||||
ILibProcessPipe_Process_KillEx(mProcess);
|
||||
}
|
||||
|
||||
if (duk_has_prop_string(ctx, 0, ILibDuktape_DuplexStream_bufferPtr))
|
||||
{
|
||||
duk_get_prop_string(ctx, 0, ILibDuktape_DuplexStream_bufferPtr);
|
||||
memset(Duktape_GetBuffer(ctx, -1, NULL), 0, sizeof(ILibDuktape_DuplexStream));
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
void ILibDuktape_ProcessPipe_ErrorStream_Pause(struct ILibDuktape_readableStream *sender, void *user)
|
||||
{
|
||||
ILibProcessPipe_Process mProcess = (ILibProcessPipe_Process)user;
|
||||
ILibProcessPipe_Pipe_Pause(ILibProcessPipe_Process_GetStdErr(mProcess));
|
||||
}
|
||||
void ILibDuktape_ProcessPipe_ErrorStream_Resume(struct ILibDuktape_readableStream *sender, void *user)
|
||||
{
|
||||
ILibProcessPipe_Process mProcess = (ILibProcessPipe_Process)user;
|
||||
ILibProcessPipe_Pipe_Resume(ILibProcessPipe_Process_GetStdErr(mProcess));
|
||||
}
|
||||
duk_ret_t ILibDuktape_ProcessPipe_ErrorStream_Getter(duk_context *ctx)
|
||||
{
|
||||
duk_push_this(ctx);
|
||||
duk_get_prop_string(ctx, -1, ILibDuktape_ProcessPipe_Process_ErrorStreamPtr);
|
||||
return 1;
|
||||
}
|
||||
duk_ret_t ILibDuktape_ProcessPipe_CreateProcess(duk_context *ctx)
|
||||
{
|
||||
ILibProcessPipe_Manager pipeManager;
|
||||
ILibProcessPipe_Process mProcess;
|
||||
ILibDuktape_DuplexStream* ds;
|
||||
ILibDuktape_readableStream *rs;
|
||||
duk_size_t targetLen;
|
||||
int nargs = duk_get_top(ctx);
|
||||
char *target;
|
||||
char **params = NULL;
|
||||
int i, x;
|
||||
ILibProcessPipe_SpawnTypes asUser = ILibProcessPipe_SpawnTypes_DEFAULT;
|
||||
|
||||
if (nargs < 1) { duk_push_string(ctx, "ProcessPipe.CreateProcess: Invalid number of args"); duk_throw(ctx); return(DUK_RET_ERROR); }
|
||||
|
||||
// Parse Parameters
|
||||
target = (char*)duk_get_lstring(ctx, 0, &targetLen);
|
||||
#ifdef WIN32
|
||||
if (target[0] == '%')
|
||||
{
|
||||
size_t evsize;
|
||||
int pctx = ILibString_IndexOf(target + 1, (int)targetLen - 1, "%", 1);
|
||||
if (pctx > 0)
|
||||
{
|
||||
memcpy_s(ILibScratchPad, sizeof(ILibScratchPad), target + 1, pctx);
|
||||
ILibScratchPad[pctx] = 0;
|
||||
getenv_s(&evsize, ILibScratchPad2, sizeof(ILibScratchPad2), ILibScratchPad);
|
||||
if (evsize > 0)
|
||||
{
|
||||
strncpy_s(ILibScratchPad2 + evsize - 1, sizeof(ILibScratchPad2) - evsize, target + pctx + 2, targetLen - pctx - 2);
|
||||
target = ILibScratchPad2;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
if (nargs > 1)
|
||||
{
|
||||
x = 0;
|
||||
params = (char**)ILibMemory_Allocate((nargs * sizeof(char*)), 0, NULL, NULL);
|
||||
for (i = 1; i < nargs; ++i)
|
||||
{
|
||||
if (duk_is_number(ctx, i))
|
||||
{
|
||||
asUser = (ILibProcessPipe_SpawnTypes)duk_require_int(ctx, i);
|
||||
}
|
||||
else
|
||||
{
|
||||
params[x++] = (char*)duk_require_string(ctx, i);
|
||||
}
|
||||
}
|
||||
params[x] = NULL;
|
||||
}
|
||||
|
||||
duk_push_this(ctx); // [manager]
|
||||
duk_get_prop_string(ctx, -1, "\xFFPipeManager"); // [manager][pipeManager]
|
||||
pipeManager = (ILibProcessPipe_Manager)duk_get_pointer(ctx, -1);
|
||||
|
||||
mProcess = ILibProcessPipe_Manager_SpawnProcessEx(pipeManager, target, params, asUser);
|
||||
if (params != NULL) { free(params); }
|
||||
if (mProcess != NULL)
|
||||
{
|
||||
duk_push_object(ctx); // [manager][pipeManager][retVal]
|
||||
duk_push_pointer(ctx, mProcess); // [manager][pipeManager][retVal][process]
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_ProcessPipe_Process_PTR); // [manager][pipeManager][retVal]
|
||||
ILibDuktape_CreateReadonlyProperty_int(ctx, "pid", ILibProcessPipe_Process_GetPID(mProcess));
|
||||
|
||||
|
||||
ds = ILibDuktape_DuplexStream_Init(ctx, ILibDuktape_ProcessPipe_Process_JSOnWrite,
|
||||
ILibDuktape_ProcessPipe_Process_JSOnEnd, ILibDuktape_ProcessPipe_Process_JSPause,
|
||||
ILibDuktape_ProcessPipe_Process_JSResume, mProcess);
|
||||
ILibDuktape_CreateFinalizer(ctx, ILibDuktape_ProcessPipe_Process_Finalizer);
|
||||
|
||||
ILibProcessPipe_Process_AddHandlers(mProcess, 4096, ILibDuktape_ProcessPipe_Process_OnExit,
|
||||
ILibDuktape_ProcessPipe_Process_OnStdOut, ILibDuktape_ProcessPipe_Process_OnStdErr,
|
||||
ILibDuktape_ProcessPipe_Process_OnSendOK, ds);
|
||||
|
||||
duk_push_object(ctx); // [manager][pipeManager][retVal][error]
|
||||
ILibDuktape_CreateEventWithGetterEx(ctx, "parent", duk_get_heapptr(ctx, -2));
|
||||
rs = ILibDuktape_ReadableStream_Init(ctx, ILibDuktape_ProcessPipe_ErrorStream_Pause, ILibDuktape_ProcessPipe_ErrorStream_Resume, mProcess);
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_ProcessPipe_Process_ErrorStreamPtr); // [manager][pipeManager][retVal]
|
||||
ILibDuktape_CreateEventWithGetter(ctx, "error", ILibDuktape_ProcessPipe_ErrorStream_Getter);
|
||||
duk_push_pointer(ctx, rs); // [manager][pipeManager][retVal][ptr]
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_ProcessPipe_Process_ErrorStreamPtrNative); // [manager][pipeManager][retVal]
|
||||
}
|
||||
else
|
||||
{
|
||||
duk_push_null(ctx);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
duk_ret_t ILibDuktape_ProcessPipe_Finalizer(duk_context *ctx)
|
||||
{
|
||||
ILibProcessPipe_Manager *pipeManager;
|
||||
|
||||
duk_dup(ctx, 0); // [obj]
|
||||
duk_get_prop_string(ctx, -1, "\xFFPipeManager"); // [obj][manager]
|
||||
pipeManager = (ILibProcessPipe_Manager)duk_get_pointer(ctx, -1);
|
||||
|
||||
ILibChain_SafeRemove(((ILibChain_Link*)pipeManager)->ParentChain, pipeManager);
|
||||
|
||||
return 0;
|
||||
}
|
||||
void ILibDuktape_ProcessPipe_PUSH(duk_context *ctx, void *chain)
|
||||
{
|
||||
ILibProcessPipe_Manager pipeManager = ILibProcessPipe_Manager_Create(chain);
|
||||
|
||||
duk_push_object(ctx); // [obj]
|
||||
duk_push_pointer(ctx, pipeManager); // [obj][pipeManager]
|
||||
duk_put_prop_string(ctx, -2, "\xFFPipeManager"); // [obj]
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "CreateProcess", ILibDuktape_ProcessPipe_CreateProcess, DUK_VARARGS);
|
||||
ILibDuktape_CreateFinalizer(ctx, ILibDuktape_ProcessPipe_Finalizer);
|
||||
Duktape_CreateEnum(ctx, "ILibProcessPipe_SpawnTypes", (char*[]) { "DEFAULT", "USER", "WINLOGON", "TERM" }, (int[]) { 0, 1, 2, 3 }, 4);
|
||||
}
|
||||
void ILibDuktape_ProcessPipe_Init(duk_context * ctx, void * chain)
|
||||
{
|
||||
ILibDuktape_ModSearch_AddHandler(ctx, "ILibProcessPipe", ILibDuktape_ProcessPipe_PUSH);
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
#ifndef __DUKTAPE_PROCESSPIPE__
|
||||
#define __DUKTAPE_PROCESSPIPE__
|
||||
|
||||
#include "duktape.h"
|
||||
|
||||
#ifdef __DOXY__
|
||||
/*!
|
||||
\brief An object that is used to spawn child processes to perform various tasks. <b>Note:</b> To use, must <b>require('ILibProcessPipe')</b>
|
||||
*/
|
||||
class ILibProcessPipe
|
||||
{
|
||||
public:
|
||||
/*!
|
||||
\brief Spawns a child process
|
||||
*
|
||||
ILibProcessPipe_Process CreateProcess(target[, spawnType][, ...args]);
|
||||
\param target \<String\> The target module to execute
|
||||
\param spawnType <ILibProcessPipe_SpawnTypes> The optional process type to spawn
|
||||
\param args \<String\> optional paramaters to pass to target on the command line. The first one is argv0, the second is argv1, etc.
|
||||
\returns \<ILibProcessPipe_Process\> stream attached to child process. NULL if the process could not be spawned.
|
||||
*/
|
||||
ILibProcessPipe_Process CreateProcess(target[, spawnType][, ...args]);
|
||||
|
||||
/*!
|
||||
\brief Specifies the type of child process to spawn
|
||||
*/
|
||||
enum class ILibProcessPipe_SpawnTypes
|
||||
{
|
||||
DEFAULT, /*!< Same as parent*/
|
||||
USER, /*!< Currently logged on user*/
|
||||
WINLOGON, /*!< Windows Logon Screen*/
|
||||
TERM /*!< Terminal*/
|
||||
};
|
||||
/*!
|
||||
\implements DuplexStream
|
||||
\brief Stream abstraction for a child process of ILibProcessPipe.
|
||||
*
|
||||
The underyling ReadableStream is attached to the child process's <b>stdIn</b>. \n
|
||||
The underlying WritableStream is attached tot he child process's <b>stdOut</b>.
|
||||
*/
|
||||
class ILibProcessPipe_Process
|
||||
{
|
||||
public:
|
||||
/*!
|
||||
\brief The Child's Process ID
|
||||
*/
|
||||
int pid;
|
||||
/*!
|
||||
\brief The ReadableStream that is attached to the child process's <b>StdErr</b>
|
||||
*/
|
||||
ReadableStream error;
|
||||
|
||||
|
||||
/*!
|
||||
\brief The 'data' event is emitted data is available from the child process's <b>StdOut</b>.
|
||||
\param chunk A chunk of data. Can be a Buffer or a string.
|
||||
*/
|
||||
void data;
|
||||
/*!
|
||||
\brief The 'end' event is emitted when the child process has exited.
|
||||
*/
|
||||
void end;
|
||||
};
|
||||
};
|
||||
#endif
|
||||
|
||||
|
||||
void ILibDuktape_ProcessPipe_Init(duk_context *ctx, void *chain);
|
||||
|
||||
|
||||
#endif
|
||||
@@ -192,6 +192,8 @@ int ILibDuktape_readableStream_WriteData_Flush(struct ILibDuktape_WritableStream
|
||||
if(stream->pipe_pendingCount == 0)
|
||||
#endif
|
||||
{
|
||||
if (stream->emitter->ctx == NULL) { return(1); }
|
||||
|
||||
sem_wait(&(stream->pipeLock));
|
||||
stream->pipeInProgress = 0;
|
||||
unpipeInProgress = stream->unpipeInProgress;
|
||||
@@ -259,7 +261,7 @@ int ILibDuktape_readableStream_WriteDataEx(ILibDuktape_readableStream *stream, i
|
||||
int dispatched = 0;
|
||||
int needPause = 0;
|
||||
|
||||
if (stream == NULL) { return(1); }
|
||||
if (stream == NULL || !ILibMemory_CanaryOK(stream)) { return(1); }
|
||||
|
||||
if (stream->paused != 0)
|
||||
{
|
||||
@@ -416,6 +418,7 @@ void ILibDuktape_readableStream_WriteEnd_ChainSink(void *chain, void *user)
|
||||
int ILibDuktape_readableStream_WriteEnd(ILibDuktape_readableStream *stream)
|
||||
{
|
||||
int retVal = 1;
|
||||
if (!ILibMemory_CanaryOK(stream)) { return(retVal); }
|
||||
|
||||
if (ILibIsRunningOnChainThread(stream->chain) == 0)
|
||||
{
|
||||
@@ -531,7 +534,7 @@ duk_ret_t ILibDuktape_readableStream_resume(duk_context *ctx)
|
||||
ptr = (ILibDuktape_readableStream*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
duk_pop(ctx); // [stream]
|
||||
if (ptr->ResumeHandler == NULL) { return(ILibDuktape_Error(ctx, "Resume not supported")); }
|
||||
|
||||
if (!ptr->paused) { return(0); }
|
||||
if (ILibDuktape_readableStream_resume_flush(ptr) == 0 && ptr->ResumeHandler != NULL) { ptr->paused = 0; ptr->ResumeHandler(ptr, ptr->user); }
|
||||
return 1;
|
||||
}
|
||||
@@ -545,21 +548,20 @@ void ILibDuktape_ReadableStream_pipe_ResumeLater(duk_context *ctx, void **args,
|
||||
}
|
||||
void ILibDuktape_readableStream_pipe_later(duk_context *ctx, void **args, int argsLen)
|
||||
{
|
||||
duk_push_heapptr(ctx, args[0]); // [readable]
|
||||
duk_get_prop_string(ctx, -1, ILibDuktape_readableStream_RSPTRS);
|
||||
ILibDuktape_readableStream *rs = (ILibDuktape_readableStream*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
duk_pop(ctx);
|
||||
|
||||
duk_push_heapptr(ctx, rs->pipeImmediate);
|
||||
duk_del_prop_string(ctx, -1, "dest");
|
||||
duk_pop(ctx);
|
||||
rs->pipeImmediate = NULL;
|
||||
|
||||
ILibDuktape_readableStream *rs = (ILibDuktape_readableStream*)args[0];
|
||||
if (!ILibMemory_CanaryOK(rs)) { return; }
|
||||
|
||||
duk_push_heapptr(ctx, rs->object); // [readable]
|
||||
duk_get_prop_string(ctx, -1, "pipe"); // [readable][pipe]
|
||||
duk_swap_top(ctx, -2); // [pipe][this]
|
||||
duk_push_heapptr(ctx, args[1]); // [pipe][this][writable]
|
||||
if (argsLen > 2) { duk_push_heapptr(ctx, args[2]); } // [pipe][this][writable][options]
|
||||
|
||||
duk_push_heapptr(ctx, rs->pipeImmediate); // [pipe][this][writable][options][immediate]
|
||||
duk_del_prop_string(ctx, -1, "dest");
|
||||
duk_pop(ctx); // [pipe][this][writable][options]
|
||||
rs->pipeImmediate = NULL;
|
||||
|
||||
if (duk_pcall_method(ctx, argsLen - 1) != 0) { ILibDuktape_Process_UncaughtExceptionEx(ctx, "readableStream.pipeLater(): "); }
|
||||
duk_pop(ctx); // ...
|
||||
}
|
||||
@@ -578,11 +580,15 @@ duk_ret_t ILibDuktape_readableStream_pipe(duk_context *ctx)
|
||||
if (rstream->pipeInProgress != 0)
|
||||
{
|
||||
// We must YIELD and try again later, becuase there is an active dispatch going on
|
||||
duk_push_this(ctx);
|
||||
rstream->pipeImmediate = ILibDuktape_Immediate(ctx, (void*[]) { duk_get_heapptr(ctx, -1), duk_get_heapptr(ctx, 0), nargs > 1 ? duk_get_heapptr(ctx, 1) : NULL }, 1 + nargs, ILibDuktape_readableStream_pipe_later);
|
||||
rstream->pipeImmediate = ILibDuktape_Immediate(ctx, (void*[]) { rstream, duk_get_heapptr(ctx, 0), nargs > 1 ? duk_get_heapptr(ctx, 1) : NULL }, 1 + nargs, ILibDuktape_readableStream_pipe_later);
|
||||
duk_push_heapptr(ctx, rstream->pipeImmediate); // [immediate]
|
||||
duk_dup(ctx, 0); // [immediate][ws]
|
||||
duk_put_prop_string(ctx, -2, "dest"); // [immediate]
|
||||
if (nargs > 1)
|
||||
{
|
||||
duk_dup(ctx, 1);
|
||||
duk_put_prop_string(ctx, -2, "opt");
|
||||
}
|
||||
duk_dup(ctx, 0);
|
||||
sem_post(&(rstream->pipeLock));
|
||||
return(1);
|
||||
@@ -668,6 +674,7 @@ void ILibDuktape_readableStream_unpipe_later(duk_context *ctx, void ** args, int
|
||||
data = (ILibDuktape_readableStream*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
duk_pop_2(ctx); // ...
|
||||
|
||||
if (data->emitter->ctx == NULL) { return; }
|
||||
sem_wait(&(data->pipeLock));
|
||||
if (data->pipeInProgress != 0)
|
||||
{
|
||||
@@ -727,7 +734,10 @@ void ILibDuktape_readableStream_unpipe_later(duk_context *ctx, void ** args, int
|
||||
duk_pop(ctx); // ...
|
||||
break;
|
||||
}
|
||||
duk_pop_2(ctx); // [array]
|
||||
else
|
||||
{
|
||||
duk_pop(ctx); // [array]
|
||||
}
|
||||
}
|
||||
duk_pop(ctx); // ...
|
||||
break;
|
||||
@@ -765,6 +775,7 @@ void ILibDuktape_readableStream_unpipe_later(duk_context *ctx, void ** args, int
|
||||
duk_ret_t ILibDuktape_readableStream_unpipe(duk_context *ctx)
|
||||
{
|
||||
int nargs = duk_get_top(ctx);
|
||||
int onlyItem = 0;
|
||||
ILibDuktape_readableStream *data;
|
||||
|
||||
duk_push_this(ctx); // [readable]
|
||||
@@ -772,15 +783,35 @@ duk_ret_t ILibDuktape_readableStream_unpipe(duk_context *ctx)
|
||||
data = (ILibDuktape_readableStream*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
duk_pop(ctx); // [readable]
|
||||
|
||||
if (data->emitter->ctx == NULL) { return(0); }
|
||||
|
||||
sem_wait(&(data->pipeLock));
|
||||
data->unpipeInProgress = 1;
|
||||
if (nargs == 1 && duk_is_object(ctx, 0))
|
||||
{
|
||||
void *w = duk_require_heapptr(ctx, 0);
|
||||
duk_push_heapptr(ctx, data->pipeArray); // [readable][array]
|
||||
int wcount = (int)duk_get_length(ctx, -1);
|
||||
duk_enum(ctx, -1, DUK_ENUM_OWN_PROPERTIES_ONLY); // [readable][array][enum]
|
||||
while (duk_next(ctx, -1, 1))
|
||||
{ // [readable][array][enum][key][val]
|
||||
if (duk_get_heapptr(ctx, -1) == w) { onlyItem = 1; }
|
||||
duk_pop_2(ctx); // [readable][array][enum]
|
||||
if (onlyItem) { break; }
|
||||
}
|
||||
if (onlyItem && wcount > 1) { onlyItem = 0; }
|
||||
duk_pop_2(ctx); // [readable]
|
||||
}
|
||||
sem_post(&(data->pipeLock));
|
||||
|
||||
if (nargs == 0 || onlyItem != 0)
|
||||
{
|
||||
// We need to pause first
|
||||
duk_push_this(ctx); // [readable]
|
||||
duk_get_prop_string(ctx, -1, "pause"); // [readable][pause]
|
||||
duk_dup(ctx, -2); // [readable][pause][this]
|
||||
duk_call_method(ctx, 0); duk_pop(ctx); // [readable]
|
||||
}
|
||||
|
||||
// We must yield, and do this on the next event loop, because we can't unpipe if we're called from a pipe'ed call
|
||||
void *imm = ILibDuktape_Immediate(ctx, (void*[]) { duk_get_heapptr(ctx, -1), nargs == 1 ? duk_get_heapptr(ctx, 0) : NULL }, nargs + 1, ILibDuktape_readableStream_unpipe_later);
|
||||
@@ -867,14 +898,9 @@ ILibDuktape_readableStream* ILibDuktape_ReadableStream_InitEx(duk_context *ctx,
|
||||
ILibDuktape_readableStream *retVal;
|
||||
ILibDuktape_EventEmitter *emitter;
|
||||
|
||||
ILibDuktape_PointerValidation_Init(ctx);
|
||||
duk_push_fixed_buffer(ctx, sizeof(ILibDuktape_readableStream)); // [obj][buffer]
|
||||
duk_dup(ctx, -1); // [obj][buffer][buffer]
|
||||
duk_put_prop_string(ctx, -3, ILibDuktape_readableStream_RSPTRS); // [obj][buffer]
|
||||
retVal = (ILibDuktape_readableStream*)Duktape_GetBuffer(ctx, -1, NULL); // [obj][buffer]
|
||||
memset(retVal, 0, sizeof(ILibDuktape_readableStream));
|
||||
retVal = (ILibDuktape_readableStream*)Duktape_PushBuffer(ctx, sizeof(ILibDuktape_readableStream)); // [obj][buffer]
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_readableStream_RSPTRS); // [obj]
|
||||
|
||||
duk_pop(ctx); // [obj]
|
||||
duk_push_array(ctx); // [obj][array]
|
||||
retVal->pipeArray = duk_get_heapptr(ctx, -1);
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_readableStream_PipeArray); // [obj]
|
||||
|
||||
@@ -80,4 +80,3 @@ int ILibDuktape_readableStream_WriteEnd(ILibDuktape_readableStream *stream);
|
||||
void ILibDuktape_readableStream_Closed(ILibDuktape_readableStream *stream);
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ limitations under the License.
|
||||
#include "../microstack/ILibCrypto.h"
|
||||
|
||||
#define ILibDuktape_MD5_PTR "\xFF_MD5PTR"
|
||||
#define ILibDuktape_SHA1_PTR "\xFF_SHA1PTR"
|
||||
#define ILibDuktape_SHA256_PTR "\xFF_SHA256PTR"
|
||||
#define ILibDuktape_SHA512_PTR "\xFF_SHA512PTR"
|
||||
#define ILibDuktape_SHA256_SIGNER_PTR "\xFF_SHA256_SIGNER_PTR"
|
||||
@@ -30,14 +31,12 @@ limitations under the License.
|
||||
#define ILibDuktape_SHA256_SIGNER_CERT_ALLOC "\xFF_SHA256_SIGNER_CERT_ALLOC"
|
||||
#define ILibDuktape_SHA256_SIGNER_SIGBUFFER "\xFF_SHA256_SIGNER_SIG_BUFFER"
|
||||
|
||||
#ifndef MICROSTACK_NOTLS
|
||||
|
||||
typedef struct ILibDuktape_SHA256_Data
|
||||
{
|
||||
duk_context *ctx;
|
||||
|
||||
void *object;
|
||||
char buffer[33];
|
||||
char buffer[UTIL_SHA256_HASHSIZE];
|
||||
SHA256_CTX shctx;
|
||||
}ILibDuktape_SHA256_Data;
|
||||
typedef struct ILibDuktape_SHA512_Data
|
||||
@@ -45,7 +44,7 @@ typedef struct ILibDuktape_SHA512_Data
|
||||
duk_context *ctx;
|
||||
|
||||
void *object;
|
||||
char buffer[65];
|
||||
char buffer[UTIL_SHA512_HASHSIZE];
|
||||
SHA512_CTX shctx;
|
||||
}ILibDuktape_SHA512_Data;
|
||||
typedef struct ILibDuktape_MD5_Data
|
||||
@@ -53,10 +52,20 @@ typedef struct ILibDuktape_MD5_Data
|
||||
duk_context *ctx;
|
||||
|
||||
void *object;
|
||||
char buffer[33];
|
||||
char buffer[UTIL_MD5_HASHSIZE];
|
||||
MD5_CTX mctx;
|
||||
}ILibDuktape_MD5_Data;
|
||||
|
||||
typedef struct ILibDuktape_SHA1_Data
|
||||
{
|
||||
duk_context *ctx;
|
||||
|
||||
void *object;
|
||||
char buffer[UTIL_SHA1_HASHSIZE];
|
||||
SHA_CTX sctx;
|
||||
}ILibDuktape_SHA1_Data;
|
||||
|
||||
#ifndef MICROSTACK_NOTLS
|
||||
typedef struct ILibDuktape_SHA256_Signer_Data
|
||||
{
|
||||
duk_context *ctx;
|
||||
@@ -67,6 +76,7 @@ typedef struct ILibDuktape_SHA256_Signer_Data
|
||||
void *OnSignature;
|
||||
void *OnSignatureString;
|
||||
}ILibDuktape_SHA256_Signer_Data;
|
||||
#endif
|
||||
|
||||
duk_ret_t ILibDuktape_SHA256_Finalizer(duk_context *ctx)
|
||||
{
|
||||
@@ -93,39 +103,29 @@ ILibTransport_DoneState ILibDuktape_SHA384_Write(struct ILibDuktape_WritableStre
|
||||
void ILibDuktape_SHA256_End(struct ILibDuktape_WritableStream *stream, void *user)
|
||||
{
|
||||
ILibDuktape_SHA256_Data *data = (ILibDuktape_SHA256_Data*)user;
|
||||
data->buffer[32] = 0;
|
||||
SHA256_Final((unsigned char*)data->buffer, &(data->shctx));
|
||||
|
||||
duk_push_external_buffer(data->ctx); // [extBuffer]
|
||||
duk_config_buffer(data->ctx, -1, data->buffer, 32);
|
||||
duk_config_buffer(data->ctx, -1, data->buffer, UTIL_SHA256_HASHSIZE);
|
||||
ILibDuktape_EventEmitter_SetupEmit(data->ctx, data->object, "hash"); // [extBuffer][emit][this]['hash']
|
||||
duk_push_buffer_object(data->ctx, -4, 0, 32, DUK_BUFOBJ_NODEJS_BUFFER); // [extBuffer][emit][this]['hash'][hash]
|
||||
duk_push_buffer_object(data->ctx, -4, 0, UTIL_SHA256_HASHSIZE, DUK_BUFOBJ_NODEJS_BUFFER); // [extBuffer][emit][this]['hash'][hash]
|
||||
if (duk_pcall_method(data->ctx, 2) != 0) { ILibDuktape_Process_UncaughtException(data->ctx); }
|
||||
duk_pop_2(data->ctx); // ...
|
||||
|
||||
ILibDuktape_EventEmitter_SetupEmit(data->ctx, data->object, "hashString"); // [emit][this]['hash']
|
||||
duk_push_string(data->ctx, util_tohex(data->buffer, 32, ILibScratchPad)); // [emit][this]['hash'][hashString]
|
||||
if (duk_pcall_method(data->ctx, 1) != 0) { ILibDuktape_Process_UncaughtException(data->ctx); }
|
||||
duk_pop(data->ctx); // ...
|
||||
}
|
||||
void ILibDuktape_SHA384_End(struct ILibDuktape_WritableStream *stream, void *user)
|
||||
{
|
||||
ILibDuktape_SHA512_Data *data = (ILibDuktape_SHA512_Data*)user;
|
||||
data->buffer[48] = 0;
|
||||
SHA384_Final((unsigned char*)data->buffer, &(data->shctx));
|
||||
|
||||
duk_push_external_buffer(data->ctx); // [extBuffer]
|
||||
duk_config_buffer(data->ctx, -1, data->buffer, 48);
|
||||
duk_config_buffer(data->ctx, -1, data->buffer, UTIL_SHA384_HASHSIZE);
|
||||
ILibDuktape_EventEmitter_SetupEmit(data->ctx, data->object, "hash"); // [extBuffer][emit][this]['hash']
|
||||
duk_push_buffer_object(data->ctx, -4, 0, 48, DUK_BUFOBJ_NODEJS_BUFFER); // [extBuffer][emit][this]['hash'][hash]
|
||||
duk_push_buffer_object(data->ctx, -4, 0, UTIL_SHA384_HASHSIZE, DUK_BUFOBJ_NODEJS_BUFFER); // [extBuffer][emit][this]['hash'][hash]
|
||||
if (duk_pcall_method(data->ctx, 2) != 0) { ILibDuktape_Process_UncaughtException(data->ctx); }
|
||||
duk_pop_2(data->ctx); // ...
|
||||
|
||||
ILibDuktape_EventEmitter_SetupEmit(data->ctx, data->object, "hashString"); // [emit][this]['hashString']
|
||||
duk_push_string(data->ctx, util_tohex(data->buffer, 48, ILibScratchPad)); // [emit][this]['hashString'][hashString]
|
||||
if (duk_pcall_method(data->ctx, 2) != 0) { ILibDuktape_Process_UncaughtException(data->ctx); }
|
||||
duk_pop(data->ctx); // ...
|
||||
}
|
||||
|
||||
#ifndef MICROSTACK_NOTLS
|
||||
duk_ret_t ILibDuktape_SHA256_SIGNER_Finalizer(duk_context *ctx)
|
||||
{
|
||||
ILibDuktape_SHA256_Signer_Data *data;
|
||||
@@ -254,11 +254,8 @@ void ILibDuktape_SHA256_SIGNER_PUSH(duk_context *ctx, void *chain)
|
||||
{
|
||||
ILibDuktape_SHA256_Signer_Data* data;
|
||||
duk_push_object(ctx); // [signer]
|
||||
duk_push_fixed_buffer(ctx, sizeof(ILibDuktape_SHA256_Signer_Data)); // [signer][data]
|
||||
data = (ILibDuktape_SHA256_Signer_Data*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
data = (ILibDuktape_SHA256_Signer_Data*)Duktape_PushBuffer(ctx, sizeof(ILibDuktape_SHA256_Signer_Data));
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_SHA256_SIGNER_PTR); // [signer]
|
||||
|
||||
memset(data, 0, sizeof(ILibDuktape_SHA256_Signer_Data));
|
||||
data->obj = duk_get_heapptr(ctx, -1);
|
||||
data->ctx = ctx;
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "Create", ILibDuktape_SHA256_SIGNER_Create, 1);
|
||||
@@ -267,15 +264,14 @@ void ILibDuktape_SHA256_VERIFY_PUSH(duk_context *ctx, void *chain)
|
||||
{
|
||||
ILibDuktape_SHA256_Signer_Data* data;
|
||||
duk_push_object(ctx); // [signer]
|
||||
duk_push_fixed_buffer(ctx, sizeof(ILibDuktape_SHA256_Signer_Data)); // [signer][data]
|
||||
data = (ILibDuktape_SHA256_Signer_Data*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
data = (ILibDuktape_SHA256_Signer_Data*)Duktape_PushBuffer(ctx, sizeof(ILibDuktape_SHA256_Signer_Data));
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_SHA256_SIGNER_PTR); // [signer]
|
||||
|
||||
memset(data, 0, sizeof(ILibDuktape_SHA256_Signer_Data));
|
||||
data->obj = duk_get_heapptr(ctx, -1);
|
||||
data->ctx = ctx;
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "Create", ILibDuktape_SHA256_VERIFIER_Create, 1);
|
||||
}
|
||||
#endif
|
||||
|
||||
duk_ret_t ILibDuktape_SHA256_syncHash(duk_context *ctx)
|
||||
{
|
||||
ILibDuktape_SHA256_Data *data;
|
||||
@@ -289,20 +285,11 @@ duk_ret_t ILibDuktape_SHA256_syncHash(duk_context *ctx)
|
||||
SHA256_Init(&(data->shctx));
|
||||
SHA256_Update(&(data->shctx), buffer, bufferLen);
|
||||
SHA256_Final((unsigned char*)data->buffer, &(data->shctx));
|
||||
data->buffer[32] = 0;
|
||||
|
||||
duk_push_current_function(ctx);
|
||||
duk_get_prop_string(ctx, -1, "strRet");
|
||||
if (duk_get_boolean(ctx, -1) == 0)
|
||||
{
|
||||
duk_push_external_buffer(ctx);
|
||||
duk_config_buffer(ctx, -1, data->buffer, 32);
|
||||
}
|
||||
else
|
||||
{
|
||||
util_tohex(data->buffer, 32, ILibScratchPad);
|
||||
duk_push_string(ctx, ILibScratchPad);
|
||||
}
|
||||
duk_config_buffer(ctx, -1, data->buffer, UTIL_SHA256_HASHSIZE);
|
||||
duk_push_buffer_object(ctx, -1, 0, UTIL_SHA256_HASHSIZE, DUK_BUFOBJ_NODEJS_BUFFER);
|
||||
|
||||
return(1);
|
||||
}
|
||||
duk_ret_t ILibDuktape_SHA384_syncHash(duk_context *ctx)
|
||||
@@ -318,20 +305,11 @@ duk_ret_t ILibDuktape_SHA384_syncHash(duk_context *ctx)
|
||||
SHA384_Init(&(data->shctx));
|
||||
SHA384_Update(&(data->shctx), buffer, bufferLen);
|
||||
SHA384_Final((unsigned char*)data->buffer, &(data->shctx));
|
||||
data->buffer[48] = 0;
|
||||
|
||||
duk_push_current_function(ctx);
|
||||
duk_get_prop_string(ctx, -1, "strRet");
|
||||
if (duk_get_boolean(ctx, -1) == 0)
|
||||
{
|
||||
duk_push_external_buffer(ctx);
|
||||
duk_config_buffer(ctx, -1, data->buffer, 48);
|
||||
}
|
||||
else
|
||||
{
|
||||
util_tohex(data->buffer, 48, ILibScratchPad);
|
||||
duk_push_string(ctx, ILibScratchPad);
|
||||
}
|
||||
duk_config_buffer(ctx, -1, data->buffer, UTIL_SHA384_HASHSIZE);
|
||||
duk_push_buffer_object(ctx, -1, 0, UTIL_SHA384_HASHSIZE, DUK_BUFOBJ_NODEJS_BUFFER);
|
||||
|
||||
return(1);
|
||||
}
|
||||
|
||||
@@ -345,26 +323,17 @@ ILibTransport_DoneState ILibDuktape_MD5_Write(struct ILibDuktape_WritableStream
|
||||
void ILibDuktape_MD5_End(struct ILibDuktape_WritableStream *stream, void *user)
|
||||
{
|
||||
ILibDuktape_MD5_Data *data = (ILibDuktape_MD5_Data*)user;
|
||||
data->buffer[32] = 0;
|
||||
MD5_Final((unsigned char*)data->buffer, &(data->mctx));
|
||||
|
||||
duk_push_external_buffer(data->ctx); // [extBuffer]
|
||||
duk_config_buffer(data->ctx, -1, data->buffer, 32);
|
||||
duk_config_buffer(data->ctx, -1, data->buffer, UTIL_MD5_HASHSIZE);
|
||||
ILibDuktape_EventEmitter_SetupEmit(data->ctx, data->object, "hash"); // [extBuffer][emit][this]["hash"]
|
||||
duk_push_buffer_object(data->ctx, -4, 0, 32, DUK_BUFOBJ_NODEJS_BUFFER); // [extBuffer][emit][this]["hash"][buffer]
|
||||
if (duk_pcall_method(data->ctx, 2) != 0) // [retVal]
|
||||
duk_push_buffer_object(data->ctx, -4, 0, UTIL_MD5_HASHSIZE, DUK_BUFOBJ_NODEJS_BUFFER); // [extBuffer][emit][this]["hash"][buffer]
|
||||
if (duk_pcall_method(data->ctx, 2) != 0) // [extBuffer][retVal]
|
||||
{
|
||||
ILibDuktape_Process_UncaughtException(data->ctx);
|
||||
}
|
||||
duk_pop_2(data->ctx); // ...
|
||||
|
||||
ILibDuktape_EventEmitter_SetupEmit(data->ctx, data->object, "hashString"); // [emit][this]["hashString"]
|
||||
duk_push_string(data->ctx, util_tohex(data->buffer, 32, ILibScratchPad)); // [emit][this]["hashString"][hashString]
|
||||
if (duk_pcall_method(data->ctx, 2) != 0) // [retVal]
|
||||
{
|
||||
ILibDuktape_Process_UncaughtException(data->ctx);
|
||||
}
|
||||
duk_pop(data->ctx); // ...
|
||||
}
|
||||
duk_ret_t ILibDuktape_MD5_syncHash(duk_context *ctx)
|
||||
{
|
||||
@@ -379,20 +348,11 @@ duk_ret_t ILibDuktape_MD5_syncHash(duk_context *ctx)
|
||||
MD5_Init(&(data->mctx));
|
||||
MD5_Update(&(data->mctx), buffer, bufferLen);
|
||||
MD5_Final((unsigned char*)data->buffer, &(data->mctx));
|
||||
data->buffer[32] = 0;
|
||||
|
||||
duk_push_current_function(ctx);
|
||||
duk_get_prop_string(ctx, -1, "strRet");
|
||||
if (duk_get_boolean(ctx, -1) == 0)
|
||||
{
|
||||
duk_push_external_buffer(ctx);
|
||||
duk_config_buffer(ctx, -1, data->buffer, 32);
|
||||
}
|
||||
else
|
||||
{
|
||||
util_tohex(data->buffer, 32, ILibScratchPad);
|
||||
duk_push_string(ctx, ILibScratchPad);
|
||||
}
|
||||
duk_config_buffer(ctx, -1, data->buffer, UTIL_MD5_HASHSIZE);
|
||||
duk_push_buffer_object(ctx, -1, 0, UTIL_MD5_HASHSIZE, DUK_BUFOBJ_NODEJS_BUFFER);
|
||||
|
||||
return(1);
|
||||
}
|
||||
|
||||
@@ -402,16 +362,14 @@ duk_ret_t ILibDuktape_MD5_Create(duk_context *ctx)
|
||||
ILibDuktape_EventEmitter *emitter;
|
||||
|
||||
duk_push_object(ctx); // [md5]
|
||||
ILibDuktape_WriteID(ctx, "MD5Stream");
|
||||
duk_push_fixed_buffer(ctx, sizeof(ILibDuktape_MD5_Data)); // [md5][buffer]
|
||||
data = (ILibDuktape_MD5_Data*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_MD5_PTR); // [md5]
|
||||
emitter = ILibDuktape_EventEmitter_Create(ctx);
|
||||
|
||||
ILibDuktape_CreateInstanceMethodWithBooleanProperty(ctx, "strRet", 0, "syncHash", ILibDuktape_MD5_syncHash, 1);
|
||||
ILibDuktape_CreateInstanceMethodWithBooleanProperty(ctx, "strRet", 1, "syncHashString", ILibDuktape_MD5_syncHash, 1);
|
||||
|
||||
ILibDuktape_EventEmitter_CreateEventEx(emitter, "hash");
|
||||
ILibDuktape_EventEmitter_CreateEventEx(emitter, "hashString");
|
||||
|
||||
data->ctx = ctx;
|
||||
data->object = duk_get_heapptr(ctx, -1);
|
||||
@@ -426,6 +384,7 @@ duk_ret_t ILibDuktape_SHA256_Create(duk_context *ctx)
|
||||
ILibDuktape_EventEmitter *emitter;
|
||||
|
||||
duk_push_object(ctx); // [sha]
|
||||
ILibDuktape_WriteID(ctx, "SHA256Stream");
|
||||
duk_push_fixed_buffer(ctx, sizeof(ILibDuktape_SHA256_Data)); // [sha][buffer]
|
||||
data = (ILibDuktape_SHA256_Data*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_SHA256_PTR); // [sha]
|
||||
@@ -433,11 +392,8 @@ duk_ret_t ILibDuktape_SHA256_Create(duk_context *ctx)
|
||||
|
||||
ILibDuktape_CreateFinalizer(ctx, ILibDuktape_SHA256_Finalizer);
|
||||
|
||||
ILibDuktape_CreateInstanceMethodWithBooleanProperty(ctx, "strRet", 0, "syncHash", ILibDuktape_SHA256_syncHash, 1);
|
||||
ILibDuktape_CreateInstanceMethodWithBooleanProperty(ctx, "strRet", 1, "syncHashString", ILibDuktape_SHA256_syncHash, 1);
|
||||
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "syncHash", ILibDuktape_SHA256_syncHash, 1);
|
||||
ILibDuktape_EventEmitter_CreateEventEx(emitter, "hash");
|
||||
ILibDuktape_EventEmitter_CreateEventEx(emitter, "hashString");
|
||||
|
||||
data->ctx = ctx;
|
||||
data->object = duk_get_heapptr(ctx, -1);
|
||||
@@ -447,6 +403,70 @@ duk_ret_t ILibDuktape_SHA256_Create(duk_context *ctx)
|
||||
|
||||
return(1);
|
||||
}
|
||||
ILibTransport_DoneState ILibDuktape_SHA512_Write(struct ILibDuktape_WritableStream *stream, char *buffer, int bufferLen, void *user)
|
||||
{
|
||||
ILibDuktape_SHA512_Data *data = (ILibDuktape_SHA512_Data*)user;
|
||||
|
||||
SHA512_Update(&(data->shctx), buffer, bufferLen);
|
||||
return(ILibTransport_DoneState_COMPLETE);
|
||||
}
|
||||
void ILibDuktape_SHA512_End(struct ILibDuktape_WritableStream *stream, void *user)
|
||||
{
|
||||
ILibDuktape_SHA512_Data *data = (ILibDuktape_SHA512_Data*)user;
|
||||
SHA512_Final((unsigned char*)data->buffer, &(data->shctx));
|
||||
|
||||
duk_push_external_buffer(data->ctx); // [extBuffer]
|
||||
duk_config_buffer(data->ctx, -1, data->buffer, UTIL_SHA512_HASHSIZE);
|
||||
ILibDuktape_EventEmitter_SetupEmit(data->ctx, data->object, "hash"); // [extBuffer][emit][this]['hash']
|
||||
duk_push_buffer_object(data->ctx, -4, 0, UTIL_SHA512_HASHSIZE, DUK_BUFOBJ_NODEJS_BUFFER); // [extBuffer][emit][this]['hash'][hash]
|
||||
if (duk_pcall_method(data->ctx, 2) != 0) { ILibDuktape_Process_UncaughtException(data->ctx); }
|
||||
duk_pop_2(data->ctx); // ...
|
||||
}
|
||||
duk_ret_t ILibDuktape_SHA512_syncHash(duk_context *ctx)
|
||||
{
|
||||
ILibDuktape_SHA512_Data *data;
|
||||
duk_size_t bufferLen;
|
||||
char *buffer = Duktape_GetBuffer(ctx, 0, &bufferLen);
|
||||
|
||||
duk_push_this(ctx); // [sha]
|
||||
duk_get_prop_string(ctx, -1, ILibDuktape_SHA512_PTR);
|
||||
data = (ILibDuktape_SHA512_Data*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
|
||||
SHA512_Init(&(data->shctx));
|
||||
SHA512_Update(&(data->shctx), buffer, bufferLen);
|
||||
SHA512_Final((unsigned char*)data->buffer, &(data->shctx));
|
||||
|
||||
duk_push_external_buffer(ctx);
|
||||
duk_config_buffer(ctx, -1, data->buffer, UTIL_SHA512_HASHSIZE);
|
||||
duk_push_buffer_object(ctx, -1, 0, UTIL_SHA512_HASHSIZE, DUK_BUFOBJ_NODEJS_BUFFER);
|
||||
|
||||
return(1);
|
||||
}
|
||||
duk_ret_t ILibDuktape_SHA512_Create(duk_context *ctx)
|
||||
{
|
||||
ILibDuktape_SHA512_Data *data;
|
||||
ILibDuktape_EventEmitter *emitter;
|
||||
|
||||
duk_push_object(ctx); // [sha]
|
||||
ILibDuktape_WriteID(ctx, "SHA512Stream");
|
||||
duk_push_fixed_buffer(ctx, sizeof(ILibDuktape_SHA512_Data)); // [sha][buffer]
|
||||
data = (ILibDuktape_SHA512_Data*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_SHA512_PTR); // [sha]
|
||||
emitter = ILibDuktape_EventEmitter_Create(ctx);
|
||||
|
||||
ILibDuktape_CreateFinalizer(ctx, ILibDuktape_SHA384_Finalizer);
|
||||
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "syncHash", ILibDuktape_SHA512_syncHash, 1);
|
||||
ILibDuktape_EventEmitter_CreateEventEx(emitter, "hash");
|
||||
|
||||
data->ctx = ctx;
|
||||
data->object = duk_get_heapptr(ctx, -1);
|
||||
SHA512_Init(&(data->shctx));
|
||||
|
||||
ILibDuktape_WritableStream_Init(ctx, ILibDuktape_SHA512_Write, ILibDuktape_SHA512_End, data);
|
||||
|
||||
return(1);
|
||||
}
|
||||
duk_ret_t ILibDuktape_SHA384_Create(duk_context *ctx)
|
||||
{
|
||||
ILibDuktape_SHA512_Data *data;
|
||||
@@ -461,11 +481,8 @@ duk_ret_t ILibDuktape_SHA384_Create(duk_context *ctx)
|
||||
|
||||
ILibDuktape_CreateFinalizer(ctx, ILibDuktape_SHA384_Finalizer);
|
||||
|
||||
ILibDuktape_CreateInstanceMethodWithBooleanProperty(ctx, "strRet", 0, "syncHash", ILibDuktape_SHA384_syncHash, 1);
|
||||
ILibDuktape_CreateInstanceMethodWithBooleanProperty(ctx, "strRet", 1, "syncHashString", ILibDuktape_SHA384_syncHash, 1);
|
||||
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "syncHash", ILibDuktape_SHA384_syncHash, 1);
|
||||
ILibDuktape_EventEmitter_CreateEventEx(emitter, "hash");
|
||||
ILibDuktape_EventEmitter_CreateEventEx(emitter, "hashString");
|
||||
|
||||
data->ctx = ctx;
|
||||
data->object = duk_get_heapptr(ctx, -1);
|
||||
@@ -475,6 +492,70 @@ duk_ret_t ILibDuktape_SHA384_Create(duk_context *ctx)
|
||||
|
||||
return(1);
|
||||
}
|
||||
ILibTransport_DoneState ILibDuktape_SHA1_Write(struct ILibDuktape_WritableStream *stream, char *buffer, int bufferLen, void *user)
|
||||
{
|
||||
ILibDuktape_SHA1_Data *data = (ILibDuktape_SHA1_Data*)user;
|
||||
|
||||
SHA1_Update(&(data->sctx), buffer, bufferLen);
|
||||
return(ILibTransport_DoneState_COMPLETE);
|
||||
}
|
||||
void ILibDuktape_SHA1_End(struct ILibDuktape_WritableStream *stream, void *user)
|
||||
{
|
||||
ILibDuktape_SHA1_Data *data = (ILibDuktape_SHA1_Data*)user;
|
||||
SHA1_Final((unsigned char*)data->buffer, &(data->sctx));
|
||||
|
||||
duk_push_external_buffer(data->ctx); // [extBuffer]
|
||||
duk_config_buffer(data->ctx, -1, data->buffer, UTIL_SHA1_HASHSIZE);
|
||||
ILibDuktape_EventEmitter_SetupEmit(data->ctx, data->object, "hash"); // [extBuffer][emit][this]["hash"]
|
||||
duk_push_buffer_object(data->ctx, -4, 0, UTIL_SHA1_HASHSIZE, DUK_BUFOBJ_NODEJS_BUFFER); // [extBuffer][emit][this]["hash"][buffer]
|
||||
if (duk_pcall_method(data->ctx, 2) != 0) // [extBuffer][retVal]
|
||||
{
|
||||
ILibDuktape_Process_UncaughtException(data->ctx);
|
||||
}
|
||||
duk_pop_2(data->ctx); // ...
|
||||
}
|
||||
duk_ret_t ILibDuktape_SHA1_syncHash(duk_context *ctx)
|
||||
{
|
||||
ILibDuktape_SHA1_Data *data;
|
||||
duk_size_t bufferLen;
|
||||
char *buffer = Duktape_GetBuffer(ctx, 0, &bufferLen);
|
||||
|
||||
duk_push_this(ctx); // [sha]
|
||||
duk_get_prop_string(ctx, -1, ILibDuktape_SHA1_PTR);
|
||||
data = (ILibDuktape_SHA1_Data*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
|
||||
SHA1_Init(&(data->sctx));
|
||||
SHA1_Update(&(data->sctx), buffer, bufferLen);
|
||||
SHA1_Final((unsigned char*)data->buffer, &(data->sctx));
|
||||
|
||||
duk_push_external_buffer(ctx);
|
||||
duk_config_buffer(ctx, -1, data->buffer, UTIL_SHA1_HASHSIZE);
|
||||
duk_push_buffer_object(ctx, -1, 0, UTIL_SHA1_HASHSIZE, DUK_BUFOBJ_NODEJS_BUFFER);
|
||||
|
||||
return(1);
|
||||
}
|
||||
duk_ret_t ILibDuktape_SHA1_Create(duk_context *ctx)
|
||||
{
|
||||
ILibDuktape_SHA1_Data *data;
|
||||
ILibDuktape_EventEmitter *emitter;
|
||||
|
||||
duk_push_object(ctx); // [SHA]
|
||||
ILibDuktape_WriteID(ctx, "SHA1Stream");
|
||||
duk_push_fixed_buffer(ctx, sizeof(ILibDuktape_SHA1_Data)); // [SHA][buffer]
|
||||
data = (ILibDuktape_SHA1_Data*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_SHA1_PTR); // [SHA]
|
||||
emitter = ILibDuktape_EventEmitter_Create(ctx);
|
||||
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "syncHash", ILibDuktape_SHA1_syncHash, 1);
|
||||
ILibDuktape_EventEmitter_CreateEventEx(emitter, "hash");
|
||||
|
||||
data->ctx = ctx;
|
||||
data->object = duk_get_heapptr(ctx, -1);
|
||||
SHA1_Init(&(data->sctx));
|
||||
|
||||
ILibDuktape_WritableStream_Init(ctx, ILibDuktape_SHA1_Write, ILibDuktape_SHA1_End, data);
|
||||
return(1);
|
||||
}
|
||||
void ILibDuktape_SHA256_PUSH(duk_context *ctx, void *chain)
|
||||
{
|
||||
duk_push_object(ctx); // [sha]
|
||||
@@ -485,21 +566,34 @@ void ILibDuktape_SHA384_PUSH(duk_context *ctx, void *chain)
|
||||
duk_push_object(ctx); // [sha]
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "create", ILibDuktape_SHA384_Create, 0);
|
||||
}
|
||||
void ILibDuktape_SHA512_PUSH(duk_context *ctx, void *chain)
|
||||
{
|
||||
duk_push_object(ctx); // [sha]
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "create", ILibDuktape_SHA512_Create, 0);
|
||||
}
|
||||
void ILibDuktape_MD5_PUSH(duk_context *ctx, void *chain)
|
||||
{
|
||||
duk_push_object(ctx); // [md5]
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "create", ILibDuktape_MD5_Create, 0);
|
||||
}
|
||||
#endif
|
||||
void ILibDuktape_SHA1_PUSH(duk_context *ctx, void *chain)
|
||||
{
|
||||
duk_push_object(ctx); // [md5]
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "create", ILibDuktape_SHA1_Create, 0);
|
||||
}
|
||||
|
||||
void ILibDuktape_SHA256_Init(duk_context * ctx)
|
||||
{
|
||||
#ifndef MICROSTACK_NOTLS
|
||||
ILibDuktape_ModSearch_AddHandler(ctx, "SHA256Stream_Signer", ILibDuktape_SHA256_SIGNER_PUSH);
|
||||
ILibDuktape_ModSearch_AddHandler(ctx, "SHA256Stream_Verifier", ILibDuktape_SHA256_VERIFY_PUSH);
|
||||
#endif
|
||||
ILibDuktape_ModSearch_AddHandler(ctx, "SHA512Stream", ILibDuktape_SHA512_PUSH);
|
||||
ILibDuktape_ModSearch_AddHandler(ctx, "SHA384Stream", ILibDuktape_SHA384_PUSH);
|
||||
ILibDuktape_ModSearch_AddHandler(ctx, "SHA256Stream", ILibDuktape_SHA256_PUSH);
|
||||
ILibDuktape_ModSearch_AddHandler(ctx, "MD5Stream", ILibDuktape_MD5_PUSH);
|
||||
#endif
|
||||
ILibDuktape_ModSearch_AddHandler(ctx, "SHA1Stream", ILibDuktape_SHA1_PUSH);
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -114,6 +114,7 @@ public:
|
||||
|
||||
typedef enum SCRIPT_ENGINE_SECURITY_FLAGS
|
||||
{
|
||||
SCRIPT_ENGINE_NO_DEBUGGER = 0x20000000,
|
||||
SCRIPT_ENGINE_NO_MESH_AGENT_ACCESS = 0x10000000,
|
||||
SCRIPT_ENGINE_NO_GENERIC_MARSHAL_ACCESS = 0x08000000,
|
||||
SCRIPT_ENGINE_NO_PROCESS_SPAWNING = 0x04000000,
|
||||
@@ -140,7 +141,9 @@ typedef struct SCRIPT_ENGINE_SETTINGS
|
||||
}SCRIPT_ENGINE_SETTINGS;
|
||||
|
||||
|
||||
void ILibDuktape_ScriptContainer_CheckEmbedded(char **argv, char **script, int *scriptLen);
|
||||
void ILibDuktape_ScriptContainer_CheckEmbedded(char **script, int *scriptLen);
|
||||
void ILibDuktape_ScriptContainer_CheckEmbeddedEx(char *exePath, char **script, int *scriptLen);
|
||||
|
||||
void ILibDuktape_ScriptContainer_InitMaster(void *chain, char *exePath, ILibProcessPipe_Manager manager);
|
||||
int ILibDuktape_ScriptContainer_StartSlave(void *chain, ILibProcessPipe_Manager manager);
|
||||
|
||||
@@ -149,12 +152,12 @@ duk_context *ILibDuktape_ScriptContainer_InitializeJavaScriptEngineEx3(duk_conte
|
||||
duk_context *ILibDuktape_ScriptContainer_InitializeJavaScriptEngineEx2(SCRIPT_ENGINE_SETTINGS *settings);
|
||||
#define ILibDuktape_ScriptContainer_InitializeJavaScriptEngineEx(securityFlags, executionTimeout, chain, argList, db, exePath, pipeManager, exitHandler, exitUser) ILibDuktape_ScriptContainer_InitializeJavaScriptEngineEx3(ILibDuktape_ScriptContainer_InitializeJavaScriptEngine_minimal(), (securityFlags), (executionTimeout), (chain), (argList), (db), (exePath), (pipeManager), (exitHandler), (exitUser))
|
||||
#define ILibDuktape_ScriptContainer_InitializeJavaScriptEngine(securityFlags, executionTimeout, chain, pp_argList, db, exitHandler, exitUser) ILibDuktape_ScriptContainer_InitializeJavaScriptEngineEx((securityFlags), (executionTimeout), (chain), (pp_argList), (db), NULL, NULL, (exitHandler), (exitUser))
|
||||
int ILibDuktape_ScriptContainer_DebuggingOK(duk_context *ctx);
|
||||
|
||||
SCRIPT_ENGINE_SETTINGS *ILibDuktape_ScriptContainer_GetSettings(duk_context *ctx);
|
||||
|
||||
int ILibDuktape_ScriptContainer_CompileJavaScript(duk_context *ctx, char *payload, int payloadLen);
|
||||
int ILibDuktape_ScriptContainer_CompileJavaScript_FromFile(duk_context *ctx, char *path, int pathLen);
|
||||
int ILibDuktape_ScriptContainer_CompileJavaScriptEx(duk_context *ctx, char *payload, int payloadLen, char *filename, int filenameLen);
|
||||
#define ILibDuktape_ScriptContainer_CompileJavaScript(ctx, payload, payloadLen) ILibDuktape_ScriptContainer_CompileJavaScriptEx(ctx, payload, payloadLen, NULL, 0)
|
||||
int ILibDuktape_ScriptContainer_ExecuteByteCode(duk_context *ctx);
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
@@ -125,6 +125,10 @@ duk_ret_t ILibDuktape_SimpleDataStore_Get(duk_context *ctx)
|
||||
duk_push_string(ctx, buffer);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
duk_push_buffer_object(ctx, -1, 0, bufferSize, DUK_BUFOBJ_NODEJS_BUFFER);
|
||||
}
|
||||
}
|
||||
|
||||
return 1;
|
||||
|
||||
@@ -91,9 +91,9 @@ duk_idx_t ILibWebRTC_Duktape_Connection_AddRemoteCandidate(duk_context *ctx)
|
||||
if (strcmp(Duktape_GetStringPropertyValue(ctx, 0, "Family", "IPv4"), "IPv4") == 0)
|
||||
{
|
||||
candidate = Duktape_IPAddress4_FromString(Duktape_GetStringPropertyValue(ctx, 0, "Address", "127.0.0.1"), (unsigned short)Duktape_GetIntPropertyValue(ctx, 0, "Port", 65535));
|
||||
}
|
||||
username = ILibWrapper_WebRTC_Connection_GetLocalUsername(connection);
|
||||
ILibORTC_AddRemoteCandidate(ILibWrapper_WebRTC_Connection_GetStunModule(connection), username, candidate);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -115,7 +115,7 @@ ILibTransport_DoneState ILibDuktape_WebRTC_DataChannel_Stream_WriteSink(ILibDukt
|
||||
ILibDuktape_WebRTC_DataChannel *ptrs = (ILibDuktape_WebRTC_DataChannel*)user;
|
||||
if (ptrs->dataChannel != NULL)
|
||||
{
|
||||
return(ILibWrapper_WebRTC_DataChannel_Send(ptrs->dataChannel, buffer, bufferLen));
|
||||
return(ILibWrapper_WebRTC_DataChannel_SendEx(ptrs->dataChannel, buffer, bufferLen, stream->writableStream->Reserved == 1 ? 51 : 53));
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -174,7 +174,7 @@ duk_ret_t ILibDuktape_WebRTC_DataChannel_Finalizer(duk_context *ctx)
|
||||
ILibDuktape_WebRTC_DataChannel *ptrs = (ILibDuktape_WebRTC_DataChannel*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
if (ptrs->dataChannel != NULL)
|
||||
{
|
||||
printf("WebRTC Data Channel Finalizer on Connection: %p\n", ptrs->dataChannel->parent);
|
||||
//printf("WebRTC Data Channel Finalizer on Connection: %p\n", ptrs->dataChannel->parent);
|
||||
ptrs->dataChannel->userData = NULL;
|
||||
ILibWrapper_WebRTC_DataChannel_Close(ptrs->dataChannel);
|
||||
}
|
||||
@@ -221,7 +221,7 @@ duk_ret_t ILibDuktape_WebRTC_ConnectionFactory_Finalizer(duk_context *ctx)
|
||||
duk_get_prop_string(ctx, 0, ILibDuktape_WebRTC_ConnectionFactoryPtr);
|
||||
factory = (ILibWrapper_WebRTC_ConnectionFactory)duk_get_pointer(ctx, -1);
|
||||
|
||||
printf("WebRTC Factory Finalizer: %p\n", factory);
|
||||
//printf("WebRTC Factory Finalizer: %p\n", factory);
|
||||
|
||||
if (factory != NULL && ILibIsChainBeingDestroyed(chain) == 0)
|
||||
{
|
||||
@@ -299,7 +299,9 @@ void ILibDuktape_WebRTC_Connection_Debug(void* dtlsSession, char* debugField, in
|
||||
#endif
|
||||
void ILibDuktape_WebRTC_OnConnection(ILibWrapper_WebRTC_Connection connection, int connected)
|
||||
{
|
||||
ILibWebRTC_Duktape_Handlers *ptrs = (ILibWebRTC_Duktape_Handlers*)ILibMemory_GetExtraMemory(connection, ILibMemory_WebRTC_Connection_CONTAINERSIZE);
|
||||
ILibWebRTC_Duktape_Handlers *ptrs = (ILibWebRTC_Duktape_Handlers*)ILibMemory_Extra(connection);
|
||||
if (!ILibMemory_CanaryOK(ptrs->emitter)) { return; }
|
||||
|
||||
if (connected == 0)
|
||||
{
|
||||
ILibDuktape_EventEmitter_SetupEmit(ptrs->ctx, ptrs->ConnectionObject, "disconnected"); // [emit][this][disconnected]
|
||||
@@ -348,25 +350,30 @@ void ILibDuktape_WebRTC_OnConnection(ILibWrapper_WebRTC_Connection connection, i
|
||||
|
||||
void ILibDuktape_WebRTC_OnDataChannel(ILibWrapper_WebRTC_Connection connection, ILibWrapper_WebRTC_DataChannel *dataChannel)
|
||||
{
|
||||
ILibWebRTC_Duktape_Handlers *ptrs = (ILibWebRTC_Duktape_Handlers*)ILibMemory_GetExtraMemory(connection, ILibMemory_WebRTC_Connection_CONTAINERSIZE);
|
||||
|
||||
ILibWebRTC_Duktape_Handlers *ptrs = (ILibWebRTC_Duktape_Handlers*)ILibMemory_Extra(connection);
|
||||
if (ILibMemory_CanaryOK(ptrs->emitter))
|
||||
{
|
||||
ILibDuktape_EventEmitter_SetupEmit(ptrs->ctx, ptrs->ConnectionObject, "dataChannel"); // [emit][this][dataChannel]
|
||||
ILibDuktape_WebRTC_DataChannel_PUSH(ptrs->ctx, dataChannel); // [emit][this][dataChannel][dc]
|
||||
if (duk_pcall_method(ptrs->ctx, 2) != 0) { ILibDuktape_Process_UncaughtExceptionEx(ptrs->ctx, "webrtc.connection.onDataChannel(): "); }
|
||||
duk_pop(ptrs->ctx); // ...
|
||||
}
|
||||
}
|
||||
|
||||
void ILibDuktape_WebRTC_offer_onCandidate(ILibWrapper_WebRTC_Connection connection, struct sockaddr_in6* candidate)
|
||||
{
|
||||
if (candidate != NULL)
|
||||
{
|
||||
ILibWebRTC_Duktape_Handlers *ptrs = (ILibWebRTC_Duktape_Handlers*)ILibMemory_GetExtraMemory(connection, ILibMemory_WebRTC_Connection_CONTAINERSIZE);
|
||||
ILibWebRTC_Duktape_Handlers *ptrs = (ILibWebRTC_Duktape_Handlers*)ILibMemory_Extra(connection);
|
||||
if (ILibMemory_CanaryOK(ptrs->emitter))
|
||||
{
|
||||
ILibDuktape_EventEmitter_SetupEmit(ptrs->ctx, ptrs->ConnectionObject, "candidate"); // [emit][this][candidate]
|
||||
ILibDuktape_SockAddrToOptions(ptrs->ctx, candidate); // [emit][this][candidate][options]
|
||||
if (duk_pcall_method(ptrs->ctx, 2) != 0) { ILibDuktape_Process_UncaughtExceptionEx(ptrs->ctx, "webrtc.connection.onCandidate(): "); }
|
||||
duk_pop(ptrs->ctx); // ...
|
||||
}
|
||||
}
|
||||
}
|
||||
duk_ret_t ILibDuktape_WebRTC_generateOffer(duk_context *ctx)
|
||||
{
|
||||
ILibWrapper_WebRTC_Connection connection = ILibDuktape_WebRTC_Native_GetConnection(ctx);
|
||||
@@ -468,7 +475,7 @@ duk_ret_t ILibDuktape_WebRTC_Connection_Finalizer(duk_context *ctx)
|
||||
ILibWrapper_WebRTC_Connection connection;
|
||||
duk_get_prop_string(ctx, 0, ILibDuktape_WebRTC_ConnectionPtr);
|
||||
connection = (ILibWrapper_WebRTC_Connection)duk_get_pointer(ctx, -1);
|
||||
printf("WebRTCConnection Finalizer on %p\n", (void*)connection);
|
||||
//printf("WebRTCConnection Finalizer on %p\n", (void*)connection);
|
||||
if (connection == NULL) { return 0; }
|
||||
|
||||
#ifdef _WEBRTCDEBUG
|
||||
@@ -495,7 +502,7 @@ duk_ret_t ILibDuktape_WebRTC_CreateConnection(duk_context *ctx)
|
||||
duk_push_object(ctx); // [factory][connection]
|
||||
ILibDuktape_WriteID(ctx, "webRTC.peerConnection");
|
||||
connection = ILibWrapper_WebRTC_ConnectionFactory_CreateConnection2(factory, ILibDuktape_WebRTC_OnConnection, ILibDuktape_WebRTC_OnDataChannel, NULL, sizeof(ILibWebRTC_Duktape_Handlers));
|
||||
ptrs = (ILibWebRTC_Duktape_Handlers*)ILibMemory_GetExtraMemory(connection, ILibMemory_WebRTC_Connection_CONTAINERSIZE);
|
||||
ptrs = (ILibWebRTC_Duktape_Handlers*)ILibMemory_Extra(connection);
|
||||
ptrs->ctx = ctx;
|
||||
ptrs->ConnectionObject = duk_get_heapptr(ctx, -1);
|
||||
ptrs->emitter = ILibDuktape_EventEmitter_Create(ctx);
|
||||
|
||||
@@ -304,11 +304,7 @@ ILibDuktape_WritableStream* ILibDuktape_WritableStream_Init(duk_context *ctx, IL
|
||||
ILibDuktape_WritableStream *retVal;
|
||||
ILibDuktape_EventEmitter *emitter;
|
||||
|
||||
ILibDuktape_PointerValidation_Init(ctx);
|
||||
duk_push_fixed_buffer(ctx, sizeof(ILibDuktape_WritableStream)); // [obj][buffer]
|
||||
retVal = (ILibDuktape_WritableStream*)Duktape_GetBuffer(ctx, -1, NULL); // [obj][buffer]
|
||||
memset(retVal, 0, sizeof(ILibDuktape_WritableStream));
|
||||
|
||||
retVal = (ILibDuktape_WritableStream*)Duktape_PushBuffer(ctx, sizeof(ILibDuktape_WritableStream)); // [obj][buffer]
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_WritableStream_WSPTRS); // [obj]
|
||||
|
||||
retVal->ctx = ctx;
|
||||
|
||||
@@ -55,5 +55,4 @@ typedef struct ILibDuktape_WritableStream
|
||||
ILibDuktape_WritableStream* ILibDuktape_WritableStream_Init(duk_context *ctx, ILibDuktape_WritableStream_WriteHandler WriteHandler, ILibDuktape_WritableStream_EndHandler EndHandler, void *user);
|
||||
void ILibDuktape_WritableStream_Ready(ILibDuktape_WritableStream *stream);
|
||||
|
||||
|
||||
#endif
|
||||
@@ -20,6 +20,7 @@ limitations under the License.
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
#include <direct.h>
|
||||
#include <wchar.h>
|
||||
#endif
|
||||
|
||||
#include "microstack/ILibParsers.h"
|
||||
@@ -88,6 +89,7 @@ typedef struct ILibDuktape_fs_readStreamData
|
||||
int bytesRead;
|
||||
int bytesLeft;
|
||||
int readLoopActive;
|
||||
int unshiftedBytes;
|
||||
char buffer[FS_READSTREAM_BUFFERSIZE];
|
||||
}ILibDuktape_fs_readStreamData;
|
||||
|
||||
@@ -194,7 +196,7 @@ int ILibDuktape_fs_openSyncEx(duk_context *ctx, char *path, char *flags, char *m
|
||||
|
||||
sprintf_s(ILibScratchPad, sizeof(ILibScratchPad), "%d", retVal);
|
||||
#ifdef WIN32
|
||||
fopen_s(&f, path, flags);
|
||||
_wfopen_s(&f, (const wchar_t*)ILibDuktape_String_UTF8ToWide(ctx, path), (const wchar_t*)ILibDuktape_String_UTF8ToWide(ctx, flags));
|
||||
#else
|
||||
f = fopen(path, flags);
|
||||
#endif
|
||||
@@ -439,6 +441,8 @@ void ILibDuktape_fs_readStream_Pause(struct ILibDuktape_readableStream *sender,
|
||||
}
|
||||
void ILibDuktape_fs_readStream_Resume(struct ILibDuktape_readableStream *sender, void *user)
|
||||
{
|
||||
if (!ILibMemory_CanaryOK(user)) { return; }
|
||||
|
||||
ILibDuktape_fs_readStreamData *data = (ILibDuktape_fs_readStreamData*)user;
|
||||
int bytesToRead;
|
||||
|
||||
@@ -447,14 +451,22 @@ void ILibDuktape_fs_readStream_Resume(struct ILibDuktape_readableStream *sender,
|
||||
sender->paused = 0;
|
||||
|
||||
if (data->bytesRead == -1) { data->bytesRead = 1; }
|
||||
data->unshiftedBytes = 0;
|
||||
while (sender->paused == 0 && data->bytesRead > 0 && (data->bytesLeft < 0 || data->bytesLeft > 0))
|
||||
{
|
||||
bytesToRead = data->bytesLeft < 0 ? sizeof(data->buffer) : (data->bytesLeft > sizeof(data->buffer) ? sizeof(data->buffer) : data->bytesLeft);
|
||||
data->bytesRead = (int)fread(data->buffer, 1, bytesToRead, data->fPtr);
|
||||
bytesToRead = data->bytesLeft < 0 ? (int)sizeof(data->buffer) : (data->bytesLeft > ((int)sizeof(data->buffer) - data->unshiftedBytes) ? (int)sizeof(data->buffer) - data->unshiftedBytes : data->bytesLeft);
|
||||
data->bytesRead = (int)fread(data->buffer + data->unshiftedBytes, 1, bytesToRead, data->fPtr);
|
||||
if (data->bytesRead > 0)
|
||||
{
|
||||
if (data->bytesLeft > 0) { data->bytesLeft -= data->bytesRead; }
|
||||
ILibDuktape_readableStream_WriteData(sender, data->buffer, data->bytesRead);
|
||||
data->bytesRead += data->unshiftedBytes; data->unshiftedBytes = 0;
|
||||
do
|
||||
{
|
||||
int preshift = data->unshiftedBytes == 0 ? data->bytesRead : data->unshiftedBytes;
|
||||
ILibDuktape_readableStream_WriteData(sender, data->buffer, data->unshiftedBytes>0 ? data->unshiftedBytes : data->bytesRead);
|
||||
if (data->unshiftedBytes > 0 && data->unshiftedBytes != preshift) { memmove(data->buffer, data->buffer + (preshift - data->unshiftedBytes), data->unshiftedBytes); }
|
||||
} while (data->unshiftedBytes != 0 && data->unshiftedBytes != data->bytesRead);
|
||||
data->unshiftedBytes = 0;
|
||||
if (data->bytesLeft == 0) { data->bytesRead = 0; }
|
||||
}
|
||||
}
|
||||
@@ -502,6 +514,13 @@ duk_ret_t ILibDuktape_fs_readStream_finalizer(duk_context *ctx)
|
||||
|
||||
return 0;
|
||||
}
|
||||
int ILibDuktape_fs_readStream_unshift(struct ILibDuktape_readableStream *sender, int unshiftBytes, void *user)
|
||||
{
|
||||
if (!ILibMemory_CanaryOK(user)) { return(unshiftBytes); }
|
||||
ILibDuktape_fs_readStreamData *data = (ILibDuktape_fs_readStreamData*)user;
|
||||
data->unshiftedBytes = unshiftBytes;
|
||||
return(unshiftBytes);
|
||||
}
|
||||
duk_ret_t ILibDuktape_fs_createReadStream(duk_context *ctx)
|
||||
{
|
||||
int nargs = duk_get_top(ctx);
|
||||
@@ -545,9 +564,7 @@ duk_ret_t ILibDuktape_fs_createReadStream(duk_context *ctx)
|
||||
|
||||
duk_push_object(ctx); // [readStream]
|
||||
ILibDuktape_WriteID(ctx, "fs.readStream");
|
||||
duk_push_fixed_buffer(ctx, sizeof(ILibDuktape_fs_readStreamData)); // [readStream][buffer]
|
||||
data = (ILibDuktape_fs_readStreamData*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
memset(data, 0, sizeof(ILibDuktape_fs_readStreamData));
|
||||
data = (ILibDuktape_fs_readStreamData*)Duktape_PushBuffer(ctx, sizeof(ILibDuktape_fs_readStreamData));
|
||||
duk_put_prop_string(ctx, -2, FS_READSTREAM); // [readStream]
|
||||
duk_push_this(ctx); // [readStream][fs]
|
||||
data->fsObject = duk_get_heapptr(ctx, -1);
|
||||
@@ -560,7 +577,8 @@ duk_ret_t ILibDuktape_fs_createReadStream(duk_context *ctx)
|
||||
data->ReadStreamObject = duk_get_heapptr(ctx, -1);
|
||||
data->bytesLeft = end < 0 ? end : (end - start + 1);
|
||||
data->bytesRead = -1;
|
||||
data->stream = ILibDuktape_ReadableStream_Init(ctx, ILibDuktape_fs_readStream_Pause, ILibDuktape_fs_readStream_Resume, data);
|
||||
//data->stream = ILibDuktape_ReadableStream_Init(ctx, ILibDuktape_fs_readStream_Pause, ILibDuktape_fs_readStream_Resume, data);
|
||||
data->stream = ILibDuktape_ReadableStream_InitEx(ctx, ILibDuktape_fs_readStream_Pause, ILibDuktape_fs_readStream_Resume, ILibDuktape_fs_readStream_unshift, data);
|
||||
data->stream->paused = 1;
|
||||
|
||||
//printf("readStream [start: %d, end: %d\n", start, end);
|
||||
@@ -591,8 +609,11 @@ duk_ret_t ILibDuktape_fs_readdirSync(duk_context *ctx)
|
||||
int i = 0;
|
||||
#ifdef WIN32
|
||||
HANDLE h;
|
||||
WIN32_FIND_DATA data;
|
||||
char *path = (char*)duk_require_string(ctx, 0);
|
||||
WIN32_FIND_DATAW data;
|
||||
duk_size_t pathLen;
|
||||
char *path = (char*)ILibDuktape_String_AsWide(ctx, 0, &pathLen);
|
||||
//char *path = (char*)duk_require_string(ctx, 0);
|
||||
|
||||
#else
|
||||
char *path = ILibDuktape_fs_fixLinuxPath((char*)duk_require_string(ctx, 0));
|
||||
struct dirent *dir;
|
||||
@@ -602,19 +623,21 @@ duk_ret_t ILibDuktape_fs_readdirSync(duk_context *ctx)
|
||||
duk_push_array(ctx); // [retVal]
|
||||
|
||||
#ifdef WIN32
|
||||
h = FindFirstFile(path, &data);
|
||||
h = FindFirstFileW((LPCWSTR)path, &data);
|
||||
if (h != INVALID_HANDLE_VALUE)
|
||||
{
|
||||
if (strcmp(data.cFileName, ".") != 0)
|
||||
if (wcscmp(data.cFileName, L".") != 0)
|
||||
{
|
||||
duk_push_string(ctx, data.cFileName); // [retVal][val]
|
||||
ILibDuktape_String_PushWideString(ctx, (char*)data.cFileName, 0); // [retVal][val]
|
||||
//duk_push_string(ctx, data.cFileName); // [retVal][val]
|
||||
duk_put_prop_index(ctx, -2, i++); // [retVal]
|
||||
}
|
||||
while (FindNextFile(h, &data))
|
||||
while (FindNextFileW(h, &data))
|
||||
{
|
||||
if (strcmp(data.cFileName, "..") != 0)
|
||||
if (wcscmp(data.cFileName, L"..") != 0)
|
||||
{
|
||||
duk_push_string(ctx, data.cFileName); // [retVal][val]
|
||||
ILibDuktape_String_PushWideString(ctx, (char*)data.cFileName, 0); // [retVal][val]
|
||||
//duk_push_string(ctx, data.cFileName); // [retVal][val]
|
||||
duk_put_prop_index(ctx, -2, i++); // [retVal]
|
||||
}
|
||||
}
|
||||
@@ -626,10 +649,13 @@ duk_ret_t ILibDuktape_fs_readdirSync(duk_context *ctx)
|
||||
if (d != NULL)
|
||||
{
|
||||
while ((dir = readdir(d)) != NULL)
|
||||
{
|
||||
if (strcmp(dir->d_name, ".") != 0 && strcmp(dir->d_name, "..") != 0)
|
||||
{
|
||||
duk_push_string(ctx, dir->d_name);
|
||||
duk_put_prop_index(ctx, -2, i++);
|
||||
}
|
||||
}
|
||||
closedir(d);
|
||||
}
|
||||
#endif
|
||||
@@ -672,12 +698,12 @@ char *ILibDuktape_fs_convertTime(uint64_t st, char *dest, int destLen)
|
||||
duk_ret_t ILibDuktape_fs_statSync(duk_context *ctx)
|
||||
{
|
||||
#ifdef WIN32
|
||||
char *path = (char*)duk_require_string(ctx, 0);
|
||||
char *path = ILibDuktape_String_AsWide(ctx, 0, NULL);
|
||||
char data[4096];
|
||||
WIN32_FILE_ATTRIBUTE_DATA *attr = (WIN32_FILE_ATTRIBUTE_DATA*)data;
|
||||
SYSTEMTIME stime;
|
||||
|
||||
if(GetFileAttributesEx(path, GetFileExInfoStandard, (void*)data) == 0)
|
||||
if(GetFileAttributesExW((LPCWSTR)path, GetFileExInfoStandard, (void*)data) == 0)
|
||||
{
|
||||
duk_push_string(ctx, "fs.statSync(): Invalid path");
|
||||
duk_throw(ctx);
|
||||
@@ -726,6 +752,9 @@ duk_ret_t ILibDuktape_fs_statSync(duk_context *ctx)
|
||||
duk_push_string(ctx, ILibDuktape_fs_convertTime(result.st_atime, ILibScratchPad, sizeof(ILibScratchPad)));
|
||||
duk_put_prop_string(ctx, -2, "atime");
|
||||
|
||||
duk_push_int(ctx, result.st_mode);
|
||||
ILibDuktape_CreateReadonlyProperty(ctx, "mode");
|
||||
|
||||
ILibDuktape_CreateInstanceMethodWithBooleanProperty(ctx, FS_STAT_METHOD_RETVAL, S_ISDIR(result.st_mode) || S_ISBLK(result.st_mode) ? 1 : 0, "isDirectory", ILibDuktape_fs_statSyncEx, 0);
|
||||
ILibDuktape_CreateInstanceMethodWithBooleanProperty(ctx, FS_STAT_METHOD_RETVAL, S_ISREG(result.st_mode) ? 1 : 0, "isFile", ILibDuktape_fs_statSyncEx, 0);
|
||||
|
||||
@@ -1093,10 +1122,8 @@ duk_ret_t ILibDuktape_fs_watch(duk_context *ctx)
|
||||
|
||||
duk_push_object(ctx); // [FSWatcher]
|
||||
ILibDuktape_WriteID(ctx, "fs.fsWatcher");
|
||||
duk_push_fixed_buffer(ctx, sizeof(ILibDuktape_fs_watcherData)); // [FSWatcher][data]
|
||||
data = (ILibDuktape_fs_watcherData*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
data = (ILibDuktape_fs_watcherData*)Duktape_PushBuffer(ctx, sizeof(ILibDuktape_fs_watcherData));
|
||||
duk_put_prop_string(ctx, -2, FS_WATCHER_DATA_PTR); // [FSWatcher]
|
||||
memset(data, 0, sizeof(ILibDuktape_fs_watcherData));
|
||||
|
||||
data->emitter = ILibDuktape_EventEmitter_Create(ctx);
|
||||
data->ctx = ctx;
|
||||
@@ -1156,7 +1183,11 @@ duk_ret_t ILibDuktape_fs_rename(duk_context *ctx)
|
||||
char *oldPath = (char*)duk_require_string(ctx, 0);
|
||||
char *newPath = (char*)duk_require_string(ctx, 1);
|
||||
|
||||
#ifdef WIN32
|
||||
if (_wrename((LPCWSTR)ILibDuktape_String_UTF8ToWide(ctx, oldPath), (LPCWSTR)ILibDuktape_String_UTF8ToWide(ctx, newPath)) != 0)
|
||||
#else
|
||||
if (rename(oldPath, newPath) != 0)
|
||||
#endif
|
||||
{
|
||||
sprintf_s(ILibScratchPad, sizeof(ILibScratchPad), "fs.renameSync(): Error renaming %s to %s", oldPath, newPath);
|
||||
duk_push_string(ctx, ILibScratchPad);
|
||||
@@ -1168,16 +1199,21 @@ duk_ret_t ILibDuktape_fs_rename(duk_context *ctx)
|
||||
duk_ret_t ILibDuktape_fs_unlink(duk_context *ctx)
|
||||
{
|
||||
#ifdef WIN32
|
||||
char *path = (char*)duk_require_string(ctx, 0);
|
||||
char *path = ILibDuktape_String_AsWide(ctx, 0, NULL);
|
||||
#else
|
||||
char *path = ILibDuktape_fs_fixLinuxPath((char*)duk_require_string(ctx, 0));
|
||||
#endif
|
||||
|
||||
#ifdef WIN32
|
||||
if(_wremove((const wchar_t*)path) != 0)
|
||||
#else
|
||||
if (remove(path) != 0)
|
||||
#endif
|
||||
{
|
||||
#ifdef WIN32
|
||||
if (RemoveDirectory(path) != 0) { return 0; }
|
||||
if (RemoveDirectoryW((LPCWSTR)path) != 0) { return 0; }
|
||||
#endif
|
||||
sprintf_s(ILibScratchPad, sizeof(ILibScratchPad), "fs.unlinkSync(): Error trying to unlink: %s", path);
|
||||
sprintf_s(ILibScratchPad, sizeof(ILibScratchPad), "fs.unlinkSync(): Error trying to unlink: %s", ILibDuktape_String_WideToUTF8(ctx, path));
|
||||
duk_push_string(ctx, ILibScratchPad);
|
||||
duk_throw(ctx);
|
||||
return(DUK_RET_ERROR);
|
||||
@@ -1189,16 +1225,15 @@ duk_ret_t ILibDuktape_fs_mkdirSync(duk_context *ctx)
|
||||
//int nargs = duk_get_top(ctx);
|
||||
|
||||
#ifdef WIN32
|
||||
char *path = (char*)duk_require_string(ctx, 0);
|
||||
if (_mkdir(path) != 0)
|
||||
char *path = ILibDuktape_String_AsWide(ctx, 0, NULL);
|
||||
ILibDuktape_String_WideToUTF8(ctx, path);
|
||||
if (_wmkdir((const wchar_t*)path) != 0)
|
||||
#else
|
||||
char *path = ILibDuktape_fs_fixLinuxPath((char*)duk_require_string(ctx, 0));
|
||||
if (mkdir(path, 0777) != 0)
|
||||
#endif
|
||||
{
|
||||
sprintf_s(ILibScratchPad, sizeof(ILibScratchPad), "fs.mkdirSync(): Unable to create dir: %s", path);
|
||||
duk_throw(ctx);
|
||||
return(DUK_RET_ERROR);
|
||||
return(ILibDuktape_Error(ctx, "fs.mkdirSync(): Unable to create dir: %s", ILibDuktape_String_WideToUTF8(ctx, path)));
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -1209,9 +1244,20 @@ duk_ret_t ILibDuktape_fs_readFileSync(duk_context *ctx)
|
||||
long fileLen;
|
||||
|
||||
#ifdef WIN32
|
||||
fopen_s(&f, filePath, "rbN");
|
||||
char *flags = "rbN";
|
||||
#else
|
||||
f = fopen(filePath, "rb");
|
||||
char *flags = "rb";
|
||||
#endif
|
||||
|
||||
if (duk_is_object(ctx, 1))
|
||||
{
|
||||
flags = Duktape_GetStringPropertyValue(ctx, 1, "flags", flags);
|
||||
}
|
||||
|
||||
#ifdef WIN32
|
||||
_wfopen_s(&f, (const wchar_t*)ILibDuktape_String_UTF8ToWide(ctx, filePath), (const wchar_t*)ILibDuktape_String_UTF8ToWide(ctx, flags));
|
||||
#else
|
||||
f = fopen(filePath, flags);
|
||||
#endif
|
||||
|
||||
if (f == NULL) { return(ILibDuktape_Error(ctx, "fs.readFileSync(): File [%s] not found", filePath)); }
|
||||
@@ -1219,11 +1265,31 @@ duk_ret_t ILibDuktape_fs_readFileSync(duk_context *ctx)
|
||||
fseek(f, 0, SEEK_END);
|
||||
fileLen = ftell(f);
|
||||
fseek(f, 0, SEEK_SET);
|
||||
|
||||
if(fileLen > 0)
|
||||
{
|
||||
duk_push_fixed_buffer(ctx, (duk_size_t)fileLen);
|
||||
ignore_result(fread(Duktape_GetBuffer(ctx, -1, NULL), 1, (size_t)fileLen, f));
|
||||
fclose(f);
|
||||
duk_push_buffer_object(ctx, -1, 0, (duk_size_t)fileLen, DUK_BUFOBJ_NODEJS_BUFFER);
|
||||
}
|
||||
else
|
||||
{
|
||||
duk_size_t bufferSize = 1024;
|
||||
char *buffer = (char*)duk_push_dynamic_buffer(ctx, bufferSize); // [dynamicBuffer]
|
||||
size_t bytesRead = 0;
|
||||
size_t len = 0;
|
||||
while ((bytesRead = fread(buffer + len, 1, 1024, f)) > 0)
|
||||
{
|
||||
len += bytesRead;
|
||||
if (bytesRead == 1024)
|
||||
{
|
||||
buffer = duk_resize_buffer(ctx, -1, bufferSize + 1024);
|
||||
bufferSize += 1024;
|
||||
}
|
||||
}
|
||||
fclose(f);
|
||||
duk_push_buffer_object(ctx, -1, 0, (duk_size_t)len, DUK_BUFOBJ_NODEJS_BUFFER);
|
||||
}
|
||||
|
||||
return(1);
|
||||
}
|
||||
@@ -1243,6 +1309,19 @@ duk_ret_t ILibDuktape_fs_existsSync(duk_context *ctx)
|
||||
}
|
||||
return(1);
|
||||
}
|
||||
#ifdef _POSIX
|
||||
duk_ret_t ILibduktape_fs_chmodSync(duk_context *ctx)
|
||||
{
|
||||
if(chmod((char*)duk_require_string(ctx, 0), (mode_t)duk_require_int(ctx, 1)) != 0)
|
||||
{
|
||||
return(ILibDuktape_Error(ctx, "Error calling chmod()"));
|
||||
}
|
||||
else
|
||||
{
|
||||
return(0);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
void ILibDuktape_fs_PUSH(duk_context *ctx, void *chain)
|
||||
{
|
||||
duk_push_object(ctx); // [fs]
|
||||
@@ -1267,6 +1346,9 @@ void ILibDuktape_fs_PUSH(duk_context *ctx, void *chain)
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "readDrivesSync", ILibDuktape_fs_readDrivesSync, 0);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "readFileSync", ILibDuktape_fs_readFileSync, DUK_VARARGS);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "existsSync", ILibDuktape_fs_existsSync, 1);
|
||||
#ifdef _POSIX
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "chmodSync", ILibduktape_fs_chmodSync, 2);
|
||||
#endif
|
||||
#ifndef _NOFSWATCHER
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "watch", ILibDuktape_fs_watch, DUK_VARARGS);
|
||||
#endif
|
||||
@@ -1275,6 +1357,41 @@ void ILibDuktape_fs_PUSH(duk_context *ctx, void *chain)
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "mkdirSync", ILibDuktape_fs_mkdirSync, DUK_VARARGS);
|
||||
|
||||
ILibDuktape_CreateFinalizer(ctx, ILibDuktape_fs_Finalizer);
|
||||
|
||||
char copyFile[] = "exports.copyFile = function copyFile(src, dest)\
|
||||
{\
|
||||
var ss = this.createReadStream(src, {flags: 'rb'});\
|
||||
var ds = this.createWriteStream(dest, {flags: 'wb'});\
|
||||
ss.fs = this;\
|
||||
ss.pipe(ds);\
|
||||
ds.ss = ss;\
|
||||
if(!this._copyStreams){this._copyStreams = {};this._copyStreamID = 0;}\
|
||||
ss.id = this._copyStreamID++;\
|
||||
this._copyStreams[ss.id] = ss;\
|
||||
if(arguments.length == 3 && typeof arguments[2] === 'function')\
|
||||
{\
|
||||
ds.on('close', arguments[2]);\
|
||||
}\
|
||||
else if(arguments.length == 4 && typeof arguments[3] === 'function')\
|
||||
{\
|
||||
ds.on('close', arguments[3]);\
|
||||
}\
|
||||
ds.on('close', function onCopyFileDone(){delete this.ss.fs._copyStreams[this.ss.id];});\
|
||||
};\
|
||||
exports.copyFileSync = function copyFileSync(src, dest)\
|
||||
{\
|
||||
var buffer = this.readFileSync(src, {flags: 'rb'});\
|
||||
this.writeFileSync(dest, buffer, {flags: 'wb'});\
|
||||
};\
|
||||
exports.writeFileSync = function writeFileSync(dest, data, options)\
|
||||
{\
|
||||
var fd = this.openSync(dest, options?options.flags:'wb');\
|
||||
this.writeSync(fd, data);\
|
||||
this.closeSync(fd);\
|
||||
};\
|
||||
exports.CHMOD_MODES = {S_IRUSR: 0o400, S_IWUSR: 0o200, S_IXUSR: 0o100, S_IRGRP: 0o40, S_IWGRP: 0o20, S_IXGRP: 0o10, S_IROTH: 0o4, S_IWOTH: 0o2, S_IXOTH: 0o1};\
|
||||
";
|
||||
ILibDuktape_ModSearch_AddHandler_AlsoIncludeJS(ctx, copyFile, sizeof(copyFile) - 1);
|
||||
}
|
||||
|
||||
void ILibDuktape_fs_init(duk_context * ctx)
|
||||
|
||||
@@ -24,6 +24,7 @@ limitations under the License.
|
||||
|
||||
#define DIGEST_USERNAME "\xFF_DigestUsername"
|
||||
#define DIGEST_PASSWORD "\xFF_DigestPassword"
|
||||
#define DIGEST_AUTHTOKEN "\xFF_DigestAuthToken"
|
||||
#define HTTP_DIGEST "\xFF_HTTP_DIGEST"
|
||||
#define DIGEST_CLIENT_REQUEST "\xFF_DIGEST_CLIENT_REQUEST"
|
||||
#define HTTP_CLIENTREQUEST_DATAPTR "\xFF_CLIENTREQUEST_DATAPTR"
|
||||
@@ -158,8 +159,10 @@ char *ILibDuktape_httpDigest_generateAuthenticationHeader(duk_context *ctx, void
|
||||
wwwauth = (char*)Duktape_GetStringPropertyValueEx(ctx, -1, DIGEST2WWWAUTH, NULL, &wwwauthLen);
|
||||
username = (char*)Duktape_GetStringPropertyValue(ctx, -1, DIGEST_USERNAME, NULL);
|
||||
password = (char*)Duktape_GetStringPropertyValue(ctx, -1, DIGEST_PASSWORD, NULL);
|
||||
if (!duk_has_prop_string(ctx, -1, DIGEST_AUTHTOKEN))
|
||||
{
|
||||
if (wwwauth == NULL || username == NULL || password == NULL) { duk_pop(ctx); return(NULL); }
|
||||
|
||||
}
|
||||
duk_push_heapptr(ctx, optionsObj); // [digest][options]
|
||||
method = (char*)Duktape_GetStringPropertyValue(ctx, -1, "method", NULL);
|
||||
path = (char*)Duktape_GetStringPropertyValue(ctx, -1, "path", NULL);
|
||||
@@ -174,9 +177,24 @@ char *ILibDuktape_httpDigest_generateAuthenticationHeader(duk_context *ctx, void
|
||||
ILibGetEntryEx(table, "opaque", 6, (void**)&opaque, &opaqueLen); if (opaqueLen > 0) { opaque[opaqueLen] = 0; }
|
||||
ILibGetEntryEx(table, "qop", 3, (void**)&qop, &qopLen); if (qopLen > 0) { qop[qopLen] = 0; }
|
||||
|
||||
if (duk_has_prop_string(ctx, -1, DIGEST_AUTHTOKEN))
|
||||
{
|
||||
duk_size_t authTokenLen;
|
||||
char *authToken = Duktape_GetStringPropertyValueEx(ctx, -1, DIGEST_AUTHTOKEN, NULL, &authTokenLen);
|
||||
|
||||
if (authTokenLen < sizeof(result1))
|
||||
{
|
||||
memcpy_s(result1, sizeof(result1), authToken, authTokenLen);
|
||||
result1[32] = 0;
|
||||
username = "admin";
|
||||
tmpLen = (int)authTokenLen;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
tmpLen = sprintf_s(ILibScratchPad2, sizeof(ILibScratchPad2), "%s:%s:%s", username, realm, password);
|
||||
util_md5hex(ILibScratchPad2, tmpLen, result1);
|
||||
|
||||
}
|
||||
tmpLen = sprintf_s(ILibScratchPad2, sizeof(ILibScratchPad2), "%s:%s", method, path);
|
||||
util_md5hex(ILibScratchPad2, tmpLen, result2);
|
||||
|
||||
@@ -325,6 +343,11 @@ duk_ret_t ILibDuktape_httpDigest_clientRequest_response(duk_context *ctx)
|
||||
else
|
||||
{
|
||||
duk_push_heapptr(ctx, digestClientPtr); // [digestClientRequest]
|
||||
duk_del_prop_string(ctx, -1, DIGEST_CLIENT_REQUEST);
|
||||
duk_push_this(ctx);
|
||||
duk_del_prop_string(ctx, -1, DIGEST_CLIENT_REQUEST);
|
||||
duk_pop(ctx);
|
||||
|
||||
duk_get_prop_string(ctx, -1, "emit"); // [digestClientRequest][emit]
|
||||
duk_swap_top(ctx, -2); // [emit][this]
|
||||
duk_push_string(ctx, "response"); // [emit][this][response]
|
||||
@@ -579,9 +602,18 @@ duk_ret_t ILibDuktape_httpDigest_http_request(duk_context *ctx)
|
||||
}
|
||||
duk_ret_t ILibduktape_httpDigest_create(duk_context *ctx)
|
||||
{
|
||||
duk_size_t usernameLen, passwordLen;
|
||||
char *username = (char*)duk_require_lstring(ctx, 0, &usernameLen), *password = (char*)duk_require_lstring(ctx, 1, &passwordLen);
|
||||
duk_size_t usernameLen, passwordLen, authTokenLen;
|
||||
ILibDuktape_EventEmitter *emitter;
|
||||
char *username = NULL, *password = NULL, *authToken = NULL;
|
||||
|
||||
if (duk_get_top(ctx) == 1 && duk_is_object(ctx, 0))
|
||||
{
|
||||
if ((authToken = Duktape_GetStringPropertyValueEx(ctx, 0, "authToken", NULL, &authTokenLen)) == NULL) { return(ILibDuktape_Error(ctx, "authToken Required")); }
|
||||
}
|
||||
else
|
||||
{
|
||||
username = (char*)duk_require_lstring(ctx, 0, &usernameLen), password = (char*)duk_require_lstring(ctx, 1, &passwordLen);
|
||||
}
|
||||
|
||||
duk_push_object(ctx); // [obj]
|
||||
ILibDuktape_WriteID(ctx, "httpDigest");
|
||||
@@ -593,10 +625,19 @@ duk_ret_t ILibduktape_httpDigest_create(duk_context *ctx)
|
||||
ILibDuktape_EventEmitter_CreateEventEx(emitter, "upgrade");
|
||||
ILibDuktape_CreateInstanceMethodWithIntProperty(ctx, "isGet", 1, "get", ILibDuktape_httpDigest_http_request, DUK_VARARGS);
|
||||
ILibDuktape_CreateInstanceMethodWithIntProperty(ctx, "isGet", 0, "request", ILibDuktape_httpDigest_http_request, DUK_VARARGS);
|
||||
|
||||
if (authToken == NULL)
|
||||
{
|
||||
duk_push_string(ctx, username);
|
||||
duk_put_prop_string(ctx, -2, DIGEST_USERNAME);
|
||||
duk_push_string(ctx, password);
|
||||
duk_put_prop_string(ctx, -2, DIGEST_PASSWORD);
|
||||
}
|
||||
else
|
||||
{
|
||||
duk_push_lstring(ctx, authToken, authTokenLen);
|
||||
duk_put_prop_string(ctx, -2, DIGEST_AUTHTOKEN);
|
||||
}
|
||||
duk_push_fixed_buffer(ctx, 16);
|
||||
util_randomtext(16, (char*)Duktape_GetBuffer(ctx, -1, NULL));
|
||||
((char*)Duktape_GetBuffer(ctx, -1, NULL))[15] = 0;
|
||||
@@ -610,7 +651,7 @@ duk_ret_t ILibduktape_httpDigest_create(duk_context *ctx)
|
||||
void ILibDuktape_httpDigest_PUSH(duk_context *ctx, void *chain)
|
||||
{
|
||||
duk_push_object(ctx);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "create", ILibduktape_httpDigest_create, 2);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "create", ILibduktape_httpDigest_create, DUK_VARARGS);
|
||||
}
|
||||
duk_ret_t ILibDuktape_httpHeaders(duk_context *ctx)
|
||||
{
|
||||
|
||||
@@ -22,4 +22,3 @@ limitations under the License.
|
||||
void ILibDuktape_http_init(duk_context *ctx, void *chain);
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
@@ -100,6 +100,7 @@ void ILibDuktape_net_socket_OnConnect(ILibAsyncSocket_SocketModule socketModule,
|
||||
{
|
||||
ILibDuktape_net_socket *ptrs = (ILibDuktape_net_socket*)((ILibChain_Link*)socketModule)->ExtraMemoryPtr;
|
||||
struct sockaddr_in6 local;
|
||||
if (ptrs->ctx == NULL) { return; }
|
||||
|
||||
duk_push_heapptr(ptrs->ctx, ptrs->object); // [sockat]
|
||||
duk_push_false(ptrs->ctx); // [socket][connecting]
|
||||
@@ -164,14 +165,13 @@ void ILibDuktape_net_socket_OnConnect(ILibAsyncSocket_SocketModule socketModule,
|
||||
#endif
|
||||
duk_put_prop_string(ptrs->ctx, -2, "message"); // [emit][this][error][errorObj]
|
||||
if (duk_pcall_method(ptrs->ctx, 2) != 0) { ILibDuktape_Process_UncaughtException(ptrs->ctx); }
|
||||
duk_pop(ptrs->ctx); // ...
|
||||
if (ptrs->ctx != NULL) { duk_pop(ptrs->ctx); } // ...
|
||||
}
|
||||
}
|
||||
void ILibDuktape_net_socket_OnDisconnect(ILibAsyncSocket_SocketModule socketModule, void *user)
|
||||
{
|
||||
ILibDuktape_net_socket *ptrs = (ILibDuktape_net_socket*)((ILibChain_Link*)socketModule)->ExtraMemoryPtr;
|
||||
|
||||
if (ILibDuktape_IsPointerValid(ptrs->chain, ptrs->object))
|
||||
if (ILibMemory_CanaryOK(ptrs->emitter))
|
||||
{
|
||||
duk_push_heapptr(ptrs->ctx, ptrs->object); // [sock]
|
||||
duk_push_string(ptrs->ctx, "0.0.0.0"); // [sock][localAddr]
|
||||
@@ -379,7 +379,7 @@ duk_ret_t ILibDuktape_net_socket_finalizer(duk_context *ctx)
|
||||
if (ILibAsyncSocket_IsConnected(ptrs->socketModule) != 0) { ILibAsyncSocket_Disconnect(ptrs->socketModule); }
|
||||
ILibChain_SafeRemove(chain, ptrs->socketModule);
|
||||
}
|
||||
|
||||
ptrs->ctx = NULL;
|
||||
return 0;
|
||||
}
|
||||
int ILibDuktape_net_socket_unshift(ILibDuktape_DuplexStream *sender, int unshiftBytes, void *user)
|
||||
@@ -399,7 +399,6 @@ void ILibDuktape_net_socket_PUSH(duk_context *ctx, ILibAsyncSocket_SocketModule
|
||||
|
||||
duk_push_object(ctx); // [obj]
|
||||
ILibDuktape_WriteID(ctx, "net.socket");
|
||||
ILibDuktape_PointerValidation_Init(ctx);
|
||||
ptrs->ctx = ctx;
|
||||
ptrs->chain = ((ILibChain_Link*)module)->ParentChain;
|
||||
ptrs->object = duk_get_heapptr(ctx, -1);
|
||||
@@ -493,21 +492,29 @@ duk_ret_t ILibDuktape_net_createConnection(duk_context *ctx)
|
||||
ILibTransport_DoneState ILibDuktape_net_server_WriteSink(ILibDuktape_DuplexStream *stream, char *buffer, int bufferLen, void *user)
|
||||
{
|
||||
ILibDuktape_net_server_session *session = (ILibDuktape_net_server_session*)user;
|
||||
if (!ILibMemory_CanaryOK(session)) { return(ILibTransport_DoneState_ERROR); }
|
||||
|
||||
return((ILibTransport_DoneState)ILibAsyncServerSocket_Send(NULL, session->connection, buffer, bufferLen, ILibAsyncSocket_MemoryOwnership_USER));
|
||||
}
|
||||
void ILibDuktape_net_server_EndSink(ILibDuktape_DuplexStream *stream, void *user)
|
||||
{
|
||||
ILibDuktape_net_server_session *session = (ILibDuktape_net_server_session*)user;
|
||||
ILibAsyncServerSocket_Disconnect(NULL, session->connection);
|
||||
if (!ILibMemory_CanaryOK(session)) { return; }
|
||||
|
||||
if (session->connection != NULL) { ILibAsyncServerSocket_Disconnect(NULL, session->connection); }
|
||||
}
|
||||
void ILibDuktape_net_server_PauseSink(ILibDuktape_DuplexStream *sender, void *user)
|
||||
{
|
||||
ILibDuktape_net_server_session *session = (ILibDuktape_net_server_session*)user;
|
||||
if (!ILibMemory_CanaryOK(session)) { return; }
|
||||
|
||||
ILibAsyncSocket_Pause(session->connection);
|
||||
}
|
||||
void ILibDuktape_net_server_ResumeSink(ILibDuktape_DuplexStream *sender, void *user)
|
||||
{
|
||||
ILibDuktape_net_server_session *session = (ILibDuktape_net_server_session*)user;
|
||||
if (!ILibMemory_CanaryOK(session)) { return; }
|
||||
|
||||
ILibAsyncSocket_Resume(session->connection);
|
||||
}
|
||||
duk_ret_t ILibDuktape_net_server_socket_Finalizer(duk_context *ctx)
|
||||
@@ -527,6 +534,8 @@ duk_ret_t ILibDuktape_net_server_socket_Finalizer(duk_context *ctx)
|
||||
int ILibDuktape_net_server_unshiftSink(ILibDuktape_DuplexStream *sender, int unshiftBytes, void *user)
|
||||
{
|
||||
ILibDuktape_net_server_session *session = (ILibDuktape_net_server_session*)user;
|
||||
if (!ILibMemory_CanaryOK(session)) { return(unshiftBytes); }
|
||||
|
||||
session->unshiftBytes = unshiftBytes;
|
||||
return(unshiftBytes);
|
||||
}
|
||||
@@ -534,7 +543,12 @@ void ILibDuktape_net_server_OnConnect(ILibAsyncServerSocket_ServerModule AsyncSe
|
||||
{
|
||||
ILibDuktape_net_server *ptr = (ILibDuktape_net_server*)((void**)ILibMemory_GetExtraMemory(AsyncServerSocketModule, ILibMemory_ASYNCSERVERSOCKET_CONTAINERSIZE))[0];
|
||||
ILibDuktape_net_server_session *session;
|
||||
#ifndef MICROSTACK_NOTLS
|
||||
int isTLS = ILibAsyncSocket_IsUsingTls(ConnectionToken);
|
||||
#else
|
||||
int isTLS = 0;
|
||||
#endif
|
||||
if (!ILibMemory_CanaryOK(ptr)) { return; }
|
||||
|
||||
duk_push_heapptr(ptr->ctx, ptr->self); // [server]
|
||||
|
||||
@@ -545,9 +559,7 @@ void ILibDuktape_net_server_OnConnect(ILibAsyncServerSocket_ServerModule AsyncSe
|
||||
duk_push_object(ptr->ctx); // [emit][this][connection][socket]
|
||||
ILibDuktape_WriteID(ptr->ctx, isTLS ? "tls.serverSocketConnection" : "net.serverSocketConnection");
|
||||
ILibDuktape_CreateFinalizer(ptr->ctx, ILibDuktape_net_server_socket_Finalizer);
|
||||
duk_push_fixed_buffer(ptr->ctx, sizeof(ILibDuktape_net_server_session)); // [emit][this][connection][socket][buffer]
|
||||
session = (ILibDuktape_net_server_session*)Duktape_GetBuffer(ptr->ctx, -1, NULL);
|
||||
memset(session, 0, sizeof(ILibDuktape_net_server_session));
|
||||
session = Duktape_PushBuffer(ptr->ctx, sizeof(ILibDuktape_net_server_session)); // [emit][this][connection][socket][buffer]
|
||||
duk_put_prop_string(ptr->ctx, -2, ILibDuktape_net_Server_Session_buffer); // [emit][this][connection][socket]
|
||||
|
||||
struct sockaddr_in6 local;
|
||||
@@ -583,11 +595,18 @@ void ILibDuktape_net_server_OnConnect(ILibAsyncServerSocket_ServerModule AsyncSe
|
||||
void ILibDuktape_net_server_OnDisconnect(ILibAsyncServerSocket_ServerModule AsyncServerSocketModule, ILibAsyncServerSocket_ConnectionToken ConnectionToken, void *user)
|
||||
{
|
||||
ILibDuktape_net_server_session *session = (ILibDuktape_net_server_session*)user;
|
||||
if (!ILibMemory_CanaryOK(session)) { return; }
|
||||
|
||||
if (session->connection != NULL)
|
||||
{
|
||||
ILibDuktape_DuplexStream_Closed(session->stream);
|
||||
session->connection = NULL;
|
||||
}
|
||||
}
|
||||
void ILibDuktape_net_server_OnReceive(ILibAsyncServerSocket_ServerModule AsyncServerSocketModule, ILibAsyncServerSocket_ConnectionToken ConnectionToken, char* buffer, int *p_beginPointer, int endPointer, ILibAsyncServerSocket_OnInterrupt *OnInterrupt, void **user, int *PAUSE)
|
||||
{
|
||||
ILibDuktape_net_server_session *session = (ILibDuktape_net_server_session*)*user;
|
||||
if (!ILibMemory_CanaryOK(session)) { *p_beginPointer = endPointer; return; }
|
||||
|
||||
session->unshiftBytes = 0;
|
||||
ILibDuktape_DuplexStream_WriteData(session->stream, buffer + *p_beginPointer, endPointer);
|
||||
@@ -599,6 +618,8 @@ void ILibDuktape_net_server_OnInterrupt(ILibAsyncServerSocket_ServerModule Async
|
||||
void ILibDuktape_net_server_OnSendOK(ILibAsyncServerSocket_ServerModule AsyncServerSocketModule, ILibAsyncServerSocket_ConnectionToken ConnectionToken, void *user)
|
||||
{
|
||||
ILibDuktape_net_server_session *session = (ILibDuktape_net_server_session*)user;
|
||||
if (!ILibMemory_CanaryOK(session)) { return; }
|
||||
|
||||
ILibDuktape_DuplexStream_Ready(session->stream);
|
||||
}
|
||||
duk_ret_t ILibDuktape_net_server_listen(duk_context *ctx)
|
||||
@@ -777,10 +798,7 @@ duk_ret_t ILibDuktape_net_createServer(duk_context *ctx)
|
||||
duk_dup(ctx, 0); // [server][Options]
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_SERVER2OPTIONS); // [server]
|
||||
}
|
||||
|
||||
duk_push_fixed_buffer(ctx, sizeof(ILibDuktape_net_server)); // [server][fbuffer]
|
||||
server = (ILibDuktape_net_server*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
memset(server, 0, sizeof(ILibDuktape_net_server));
|
||||
server = Duktape_PushBuffer(ctx, sizeof(ILibDuktape_net_server)); // [server][fbuffer]
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_net_Server_buffer); // [server]
|
||||
|
||||
server->isTLS = isTLS;
|
||||
@@ -828,6 +846,20 @@ duk_ret_t ILibDuktape_net_createServer(duk_context *ctx)
|
||||
|
||||
return 1;
|
||||
}
|
||||
duk_ret_t ILibDuktape_net_addr2int(duk_context *ctx)
|
||||
{
|
||||
struct sockaddr_in6 addr6;
|
||||
ILibResolveEx((char*)duk_require_string(ctx, 0), 0, &addr6);
|
||||
if (addr6.sin6_family == AF_INET)
|
||||
{
|
||||
duk_push_int(ctx, ((struct sockaddr_in*)&addr6)->sin_addr.s_addr);
|
||||
return(1);
|
||||
}
|
||||
else
|
||||
{
|
||||
return(ILibDuktape_Error(ctx, "Error converting address"));
|
||||
}
|
||||
}
|
||||
void ILibDuktape_net_PUSH_net(duk_context *ctx, void *chain)
|
||||
{
|
||||
duk_push_object(ctx); // [net]
|
||||
@@ -843,6 +875,7 @@ void ILibDuktape_net_PUSH_net(duk_context *ctx, void *chain)
|
||||
ILibDuktape_CreateInstanceMethodWithIntProperty(ctx, "tls", 0, "createServer", ILibDuktape_net_createServer, DUK_VARARGS);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "createConnection", ILibDuktape_net_createConnection, DUK_VARARGS);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "connect", ILibDuktape_net_createConnection, DUK_VARARGS);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "addr2int", ILibDuktape_net_addr2int, 1);
|
||||
}
|
||||
duk_ret_t ILibDuktape_globalTunnel_end(duk_context *ctx)
|
||||
{
|
||||
@@ -1003,6 +1036,8 @@ int ILibDuktape_TLS_server_verify(int preverify_ok, X509_STORE_CTX *storectx)
|
||||
|
||||
int i;
|
||||
int retVal = 0;
|
||||
if (!ILibMemory_CanaryOK(data)) { return(0); }
|
||||
|
||||
|
||||
duk_push_heapptr(data->ctx, data->self); // [Server]
|
||||
duk_get_prop_string(data->ctx, -1, ILibDuktape_SERVER2OPTIONS); // [Server][Options]
|
||||
@@ -1026,6 +1061,7 @@ int ILibDuktape_TLS_server_verify(int preverify_ok, X509_STORE_CTX *storectx)
|
||||
void ILibDuktape_tls_server_OnSSL(ILibAsyncServerSocket_ServerModule AsyncServerSocketModule, void *ConnectionToken, SSL* ctx, void **user)
|
||||
{
|
||||
ILibDuktape_net_server *server = (ILibDuktape_net_server*)ILibAsyncServerSocket_GetTag(AsyncServerSocketModule);
|
||||
if (!ILibMemory_CanaryOK(server)) { return; }
|
||||
|
||||
if (ctx != NULL && ILibDuktape_TLS_ctx2server)
|
||||
{
|
||||
@@ -1036,6 +1072,7 @@ static int ILibDuktape_tls_server_sniCallback(SSL *s, int *ad, void *arg)
|
||||
{
|
||||
const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
|
||||
ILibDuktape_net_server *data = (ILibDuktape_net_server*)SSL_get_ex_data(s, ILibDuktape_TLS_ctx2server);
|
||||
if (!ILibMemory_CanaryOK(data)) { return(SSL_TLSEXT_ERR_OK); }
|
||||
|
||||
duk_push_heapptr(data->ctx, data->self); // [server]
|
||||
duk_get_prop_string(data->ctx, -1, ILibDuktape_SERVER2ContextTable); // [server][table]
|
||||
|
||||
@@ -27,12 +27,18 @@ limitations under the License.
|
||||
|
||||
#define ILibDuktape_EventEmitter_MaxEventNameLen 255
|
||||
#define ILibDuktape_EventEmitter_Data "\xFF_EventEmitter_Data"
|
||||
#define ILibDuktape_EventEmitter_RetVal "\xFF_EventEmitter_RetVal"
|
||||
#define ILibDuktape_EventEmitter_TempObject "\xFF_EventEmitter_TempObject"
|
||||
#define ILibDuktape_EventEmitter_DispatcherFunc "\xFF_EventEmitter_DispatcherFunc"
|
||||
#define ILibDuktape_EventEmitter_SetterFunc ((void*)0xFFFF)
|
||||
#define ILibDuktape_EventEmitter_HPTR_LIST "\xFF_EventEmitter_HPTR_LIST"
|
||||
#define ILibDuktape_EventEmitter_Hook ((void*)0xEEEE)
|
||||
#define ILibDuktape_EventEmitter_LastRetValueTable "\xFF_EventEmitter_LastRetValueTable"
|
||||
#define ILibDuktape_EventEmitter_GlobalListenerCount "\xFF_EventEmitter_GlobalListenerCount"
|
||||
#define ILibDuktape_EventEmitter_Forward_SourceName "\xFF_EventEmitter_SourceName"
|
||||
#define ILibDuktape_EventEmitter_Forward_TargetName "\xFF_EventEmitter_TargetName"
|
||||
#define ILibDuktape_EventEmitter_Forward_SourceObject "\xFF_EventEmitter_SourceObject"
|
||||
#define ILibDuktape_EventEmitter_ForwardTable "\xFF_EventEmitter_ForwardTable"
|
||||
|
||||
#ifdef __DOXY__
|
||||
|
||||
@@ -148,7 +154,7 @@ void ILibDuktape_EventEmitter_FinalizerEx(ILibHashtable sender, void *Key1, char
|
||||
int ILibDuktape_EventEmitter_HasListeners(ILibDuktape_EventEmitter *emitter, char *eventName)
|
||||
{
|
||||
int retVal = 0;
|
||||
if (emitter->eventTable != NULL)
|
||||
if(emitter!=NULL && emitter->eventTable != NULL)
|
||||
{
|
||||
ILibLinkedList eventList = ILibHashtable_Get(emitter->eventTable, NULL, eventName, (int)strnlen_s(eventName, 255));
|
||||
if (eventList != NULL)
|
||||
@@ -171,6 +177,9 @@ duk_ret_t ILibDuktape_EventEmitter_emit(duk_context *ctx)
|
||||
int i, j;
|
||||
void **emitList;
|
||||
char *objid;
|
||||
int wasReturnSpecified = 0;
|
||||
|
||||
duk_require_stack(ctx, 3); // This will make sure we have enough stack space to get the emitter object
|
||||
|
||||
duk_push_this(ctx); // [this]
|
||||
objid = Duktape_GetStringPropertyValue(ctx, -1, ILibDuktape_OBJID, "unknown");
|
||||
@@ -184,7 +193,17 @@ duk_ret_t ILibDuktape_EventEmitter_emit(duk_context *ctx)
|
||||
if (data->eventTable == NULL) { duk_push_false(ctx); return(1); } // This probably means the finalizer was already run on the eventEmitter
|
||||
|
||||
eventList = ILibHashtable_Get(data->eventTable, NULL, name, (int)nameLen);
|
||||
if (eventList == NULL) { return ILibDuktape_Error(ctx, "EventEmitter.emit(): Event '%s' not found on object '%s'", name, objid); }
|
||||
if (eventList == NULL)
|
||||
{
|
||||
if (data->eventType == ILibDuktape_EventEmitter_Type_IMPLICIT)
|
||||
{
|
||||
duk_push_false(ctx); return(1);
|
||||
}
|
||||
else
|
||||
{
|
||||
return ILibDuktape_Error(ctx, "EventEmitter.emit(): Event '%s' not found on object '%s'", name, objid);
|
||||
}
|
||||
}
|
||||
|
||||
// Copy the list, so we can enumerate with local memory, so the list can be manipulated while we are dispatching
|
||||
#ifdef WIN32
|
||||
@@ -209,10 +228,18 @@ duk_ret_t ILibDuktape_EventEmitter_emit(duk_context *ctx)
|
||||
}
|
||||
emitList[i] = NULL;
|
||||
|
||||
|
||||
// Before we dispatch, lets clear our last return values for this event
|
||||
duk_push_heapptr(ctx, data->retValTable); // [table]
|
||||
duk_del_prop_lstring(ctx, -1, name, nameLen);
|
||||
duk_pop(ctx); // ...
|
||||
|
||||
// Now that we have all the housekeeping stuff out of the way, we can actually dispatch our events
|
||||
i = 0;
|
||||
while ((func = emitList[i++]) != NULL)
|
||||
{
|
||||
duk_require_stack(ctx, nargs + 1); // This will make sure that we have enough stack space to make the method call
|
||||
|
||||
duk_push_heapptr(ctx, func); // [func]
|
||||
duk_push_heapptr(ctx, self); // [func][this]
|
||||
for (j = 1; j < nargs; ++j)
|
||||
@@ -221,10 +248,39 @@ duk_ret_t ILibDuktape_EventEmitter_emit(duk_context *ctx)
|
||||
}
|
||||
if (duk_pcall_method(ctx, nargs - 1) != 0)
|
||||
{
|
||||
return(ILibDuktape_Error(ctx, "EventEmitter.emit(): Event dispatch for '%s' on '%s' threw an exception: %s", name, objid, duk_safe_to_string(ctx, -1)));
|
||||
duk_push_heapptr(ctx, func); // [func]
|
||||
return(ILibDuktape_Error(ctx, "EventEmitter.emit(): Event dispatch for '%s' on '%s' threw an exception: %s in method '%s()'", name, objid, duk_safe_to_string(ctx, -2), Duktape_GetStringPropertyValue(ctx, -1, "name", "unknown_method")));
|
||||
}
|
||||
|
||||
// Check for return value
|
||||
if (!duk_is_undefined(ctx, -1))
|
||||
{
|
||||
duk_push_heapptr(ctx, data->retValTable); // [retVal][table]
|
||||
duk_dup(ctx, -2); // [retVal][table][retVal]
|
||||
duk_put_prop_lstring(ctx, -2, name, nameLen); // [retVal][table]
|
||||
duk_pop(ctx); // [retVal]
|
||||
|
||||
duk_push_heapptr(ctx, self); // [retVal][this]
|
||||
duk_swap_top(ctx, -2); // [this][retVal]
|
||||
data->lastReturnValue = duk_get_heapptr(ctx, -1);
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_EventEmitter_RetVal); // [this]
|
||||
duk_pop(ctx); // ...
|
||||
wasReturnSpecified = 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (wasReturnSpecified == 0)
|
||||
{
|
||||
data->lastReturnValue = NULL;
|
||||
duk_push_heapptr(ctx, self); // [this]
|
||||
duk_del_prop_string(ctx, -1, ILibDuktape_EventEmitter_RetVal); // [this]
|
||||
duk_pop(ctx); // ...
|
||||
|
||||
duk_push_heapptr(ctx, data->retValTable); // [table]
|
||||
duk_del_prop_lstring(ctx, -1, name, nameLen);
|
||||
duk_pop(ctx); // ...
|
||||
}
|
||||
|
||||
duk_push_boolean(ctx, i > 1 ? 1 : 0);
|
||||
return(1);
|
||||
}
|
||||
@@ -325,9 +381,17 @@ duk_ret_t ILibDuktape_EventEmitter_on(duk_context *ctx)
|
||||
|
||||
eventList = ILibHashtable_Get(data->eventTable, NULL, propName, (int)propNameLen);
|
||||
if (eventList == NULL)
|
||||
{
|
||||
if (data->eventType == ILibDuktape_EventEmitter_Type_IMPLICIT)
|
||||
{
|
||||
ILibDuktape_EventEmitter_CreateEventEx(data, propName);
|
||||
eventList = ILibHashtable_Get(data->eventTable, NULL, propName, (int)propNameLen);
|
||||
}
|
||||
else
|
||||
{
|
||||
return(ILibDuktape_Error(ctx, "EventEmitter.on(): Event '%s' not found", propName));
|
||||
}
|
||||
}
|
||||
hookHandler = ILibHashtable_Get(data->eventTable, ILibDuktape_EventEmitter_Hook, propName, (int)propNameLen);
|
||||
|
||||
node = prepend ? ILibLinkedList_AddHead(eventList, callback) : ILibLinkedList_AddTail(eventList, callback);
|
||||
@@ -339,6 +403,14 @@ duk_ret_t ILibDuktape_EventEmitter_on(duk_context *ctx)
|
||||
duk_put_prop_string(ctx, -2, Duktape_GetStashKey(callback)); // Save the callback to the tmp object, so it won't get GC'ed
|
||||
|
||||
if (hookHandler != NULL) { hookHandler(data, propName, callback); }
|
||||
if (!(propNameLen == 10 && strncmp(propName, "_eventHook", 10) == 0))
|
||||
{
|
||||
// Only emit '_eventHook' when the event itself isn't '_eventHook'
|
||||
ILibDuktape_EventEmitter_SetupEmit(ctx, data->object, "_eventHook"); // [emit][this][_eventHook]
|
||||
duk_push_lstring(ctx, propName, propNameLen); // [emit][this][_eventHook][propName]
|
||||
duk_push_heapptr(ctx, callback); // [emit][this][_eventHook][propName][callback]
|
||||
duk_call_method(ctx, 3); duk_pop(ctx); // ...
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
ILibDuktape_EventEmitter* ILibDuktape_EventEmitter_GetEmitter_fromThis(duk_context *ctx)
|
||||
@@ -453,6 +525,38 @@ duk_ret_t ILibDuktape_EventEmitter_EmbeddedFinalizer(duk_context *ctx)
|
||||
memset(data, 0, sizeof(ILibDuktape_EventEmitter));
|
||||
return(0);
|
||||
}
|
||||
duk_ret_t ILibDuktape_EventEmitter_emitReturnValue(duk_context *ctx)
|
||||
{
|
||||
int retVal = 1;
|
||||
int nargs = duk_get_top(ctx);
|
||||
duk_push_this(ctx); // [this]
|
||||
|
||||
switch (nargs)
|
||||
{
|
||||
case 0:
|
||||
duk_get_prop_string(ctx, -1, ILibDuktape_EventEmitter_RetVal); // [this][retVal]
|
||||
break;
|
||||
case 1:
|
||||
duk_get_prop_string(ctx, -1, ILibDuktape_EventEmitter_TempObject); // [this][tmp]
|
||||
duk_get_prop_string(ctx, -1, ILibDuktape_EventEmitter_LastRetValueTable); // [this][tmp][table]
|
||||
duk_dup(ctx, 0); // [this][tmp][table][key]
|
||||
duk_get_prop(ctx, -2); // [this][tmp][table][val]
|
||||
break;
|
||||
case 2:
|
||||
duk_get_prop_string(ctx, -1, ILibDuktape_EventEmitter_TempObject); // [this][tmp]
|
||||
duk_get_prop_string(ctx, -1, ILibDuktape_EventEmitter_LastRetValueTable); // [this][tmp][table]
|
||||
duk_dup(ctx, 0); // [this][tmp][table][key]
|
||||
duk_dup(ctx, 1); // [this][tmp][table][key][value]
|
||||
duk_put_prop(ctx, -3);
|
||||
retVal = 0;
|
||||
break;
|
||||
default:
|
||||
retVal = ILibDuktape_Error(ctx, "INVALID Parameter Count");
|
||||
break;
|
||||
}
|
||||
|
||||
return(retVal);
|
||||
}
|
||||
ILibDuktape_EventEmitter* ILibDuktape_EventEmitter_Create(duk_context *ctx)
|
||||
{
|
||||
ILibDuktape_EventEmitter *retVal;
|
||||
@@ -467,12 +571,13 @@ ILibDuktape_EventEmitter* ILibDuktape_EventEmitter_Create(duk_context *ctx)
|
||||
}
|
||||
|
||||
duk_push_object(ctx); // [emitterTmp]
|
||||
duk_push_fixed_buffer(ctx, sizeof(ILibDuktape_EventEmitter)); // [emitterTmp][data]
|
||||
retVal = (ILibDuktape_EventEmitter*)Duktape_GetBuffer(ctx, -1, NULL);
|
||||
memset(retVal, 0, sizeof(ILibDuktape_EventEmitter));
|
||||
retVal = (ILibDuktape_EventEmitter*)Duktape_PushBuffer(ctx, sizeof(ILibDuktape_EventEmitter)); // [emitterTmp][data]
|
||||
retVal->tmpObject = duk_get_heapptr(ctx, -2);
|
||||
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_EventEmitter_Data); // [emitterTmp]
|
||||
duk_push_object(ctx); // [emitterTmp][retValTable]
|
||||
retVal->retValTable = duk_get_heapptr(ctx, -1);
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_EventEmitter_LastRetValueTable); // [emitterTmp]
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_EventEmitter_TempObject); // [...parent...]
|
||||
|
||||
retVal->ctx = ctx;
|
||||
@@ -487,6 +592,7 @@ ILibDuktape_EventEmitter* ILibDuktape_EventEmitter_Create(duk_context *ctx)
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "removeListener", ILibDuktape_EventEmitter_removeListener, 2);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "removeAllListeners", ILibDuktape_EventEmitter_removeAllListeners, DUK_VARARGS);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "emit", ILibDuktape_EventEmitter_emit, DUK_VARARGS);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "emit_returnValue", ILibDuktape_EventEmitter_emitReturnValue, DUK_VARARGS);
|
||||
|
||||
duk_push_heap_stash(ctx);
|
||||
if (duk_has_prop_string(ctx, -1, ILibDuktape_EventEmitter_GlobalListenerCount))
|
||||
@@ -508,6 +614,8 @@ ILibDuktape_EventEmitter* ILibDuktape_EventEmitter_Create(duk_context *ctx)
|
||||
duk_push_c_function(ctx, ILibDuktape_EventEmitter_EmbeddedFinalizer, 1);
|
||||
duk_set_finalizer(ctx, -2);
|
||||
|
||||
ILibDuktape_EventEmitter_CreateEventEx(retVal, "_eventHook");
|
||||
|
||||
return retVal;
|
||||
}
|
||||
|
||||
@@ -518,6 +626,10 @@ void ILibDuktape_EventEmitter_AddHook(ILibDuktape_EventEmitter *emitter, char *e
|
||||
ILibHashtable_Put(emitter->eventTable, ILibDuktape_EventEmitter_Hook, eventName, (int)strnlen_s(eventName, 255), handler);
|
||||
}
|
||||
}
|
||||
void ILibDuktape_EventEmitter_ClearHook(ILibDuktape_EventEmitter *emitter, char *eventName)
|
||||
{
|
||||
ILibHashtable_Remove(emitter->eventTable, ILibDuktape_EventEmitter_Hook, eventName, (int)strnlen_s(eventName, 255));
|
||||
}
|
||||
duk_ret_t ILibDuktape_EventEmitter_SetEvent(duk_context *ctx)
|
||||
{
|
||||
char *propName;
|
||||
@@ -617,7 +729,7 @@ duk_ret_t ILibDuktape_EventEmitter_Inherits_createEvent(duk_context *ctx)
|
||||
duk_pop(ctx); // [emitterUtils]
|
||||
|
||||
ILibDuktape_EventEmitter_CreateEventEx(emitter, name);
|
||||
return 0;
|
||||
return(1);
|
||||
}
|
||||
duk_ret_t ILibDuktape_EventEmitter_Inherits_addMethod(duk_context *ctx)
|
||||
{
|
||||
@@ -658,10 +770,45 @@ duk_ret_t ILibDuktape_EventEmitter_Inherits(duk_context *ctx)
|
||||
ILibDuktape_EventEmitter_CreateEventEx(emitter, "~");
|
||||
return 1;
|
||||
}
|
||||
duk_ret_t ILibDuktape_EventEmitter_EventEmitter(duk_context *ctx)
|
||||
{
|
||||
ILibDuktape_EventEmitter *emitter;
|
||||
int nargs = duk_get_top(ctx);
|
||||
int retVal = 0;
|
||||
|
||||
duk_push_this(ctx); // [target]
|
||||
emitter = ILibDuktape_EventEmitter_Create(ctx);
|
||||
duk_push_object(ctx); // [target][emitterUtils]
|
||||
duk_dup(ctx, -2); // [target][emitterUtils][target]
|
||||
duk_put_prop_string(ctx, -2, "\xFF_MainObject"); // [target][emitterUtils]
|
||||
duk_dup(ctx, -1); // [target][emitterUtils][dup]
|
||||
duk_put_prop_string(ctx, -3, "\xFF_emitterUtils"); // [target][emitterUtils]
|
||||
duk_push_pointer(ctx, emitter); // [target][emitterUtils][ptr]
|
||||
duk_put_prop_string(ctx, -2, "emitter"); // [target][emitterUtils]
|
||||
ILibDuktape_CreateFinalizer(ctx, ILibDuktape_EventEmitter_EmitterUtils_Finalizer);
|
||||
|
||||
if (nargs == 1 && duk_require_boolean(ctx, 0))
|
||||
{
|
||||
// Explicit Events
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "createEvent", ILibDuktape_EventEmitter_Inherits_createEvent, 1);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "addMethod", ILibDuktape_EventEmitter_Inherits_addMethod, 2);
|
||||
retVal = 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Implicit Events
|
||||
emitter->eventType = ILibDuktape_EventEmitter_Type_IMPLICIT;
|
||||
}
|
||||
|
||||
ILibDuktape_EventEmitter_CreateEventEx(emitter, "~");
|
||||
|
||||
return(retVal);
|
||||
}
|
||||
void ILibDuktape_EventEmitter_PUSH(duk_context *ctx, void *chain)
|
||||
{
|
||||
duk_push_object(ctx); // [emitter]
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "inherits", ILibDuktape_EventEmitter_Inherits, 1);
|
||||
ILibDuktape_CreateInstanceMethod(ctx, "EventEmitter", ILibDuktape_EventEmitter_EventEmitter, DUK_VARARGS);
|
||||
}
|
||||
void ILibDuktape_EventEmitter_Init(duk_context *ctx)
|
||||
{
|
||||
@@ -690,49 +837,196 @@ duk_ret_t ILibDuktape_EventEmitter_ForwardEvent_Sink(duk_context *ctx)
|
||||
|
||||
duk_ret_t ILibDuktape_EventEmitter_ForwardEvent_Finalizer(duk_context *ctx)
|
||||
{
|
||||
void *src = NULL;
|
||||
char *srcName = NULL;
|
||||
|
||||
if (g_displayFinalizerMessages)
|
||||
{
|
||||
duk_push_this(ctx);
|
||||
src = duk_get_heapptr(ctx, -1);
|
||||
srcName = Duktape_GetStringPropertyValue(ctx, -1, ILibDuktape_OBJID, "UNKNOWN");
|
||||
duk_pop(ctx);
|
||||
}
|
||||
duk_push_current_function(ctx); // [func]
|
||||
if (duk_has_prop_string(ctx, -1, "fptr"))
|
||||
{
|
||||
duk_get_prop_string(ctx, -1, "fptr"); // [func][fptr]
|
||||
if (duk_has_prop_string(ctx, -1, "targetObject"))
|
||||
{
|
||||
duk_get_prop_string(ctx, -1, "targetObject"); // [func][fptr][target]
|
||||
duk_del_prop_string(ctx, -2, "targetObject");
|
||||
if (g_displayFinalizerMessages) { printf("EventEmitter.Forwarder[%s]: Deleted reference to [%s] RC=%d\n", Duktape_GetStringPropertyValue(ctx, -3, "targetName", "UNKNOWN"), Duktape_GetStringPropertyValue(ctx, -1, ILibDuktape_OBJID, "UNKNOWN"), ILibDuktape_GetReferenceCount(ctx, -1) - 1); }
|
||||
if (g_displayFinalizerMessages) { printf("EventEmitter.Forwarder[%s]: Deleted reference to [%s/%p] RC=%d from [%s/%p]\n", Duktape_GetStringPropertyValue(ctx, -3, "targetName", "UNKNOWN"), Duktape_GetStringPropertyValue(ctx, -1, ILibDuktape_OBJID, "UNKNOWN"), duk_get_heapptr(ctx, -1), ILibDuktape_GetReferenceCount(ctx, -1) - 1, srcName, src); }
|
||||
duk_pop_n(ctx, 3);
|
||||
|
||||
}
|
||||
}
|
||||
if (g_displayFinalizerMessages) { duk_eval_string(ctx, "_debugGC();"); duk_pop(ctx); }
|
||||
return(0);
|
||||
}
|
||||
duk_ret_t ILibDuktape_EventEmitter_ForwardEvent_HookSink(duk_context *ctx)
|
||||
{
|
||||
duk_push_current_function(ctx);
|
||||
duk_size_t sourceLen, targetLen, hookLen;
|
||||
char *source, *target, *hook;
|
||||
void *sourceObject, *fptr;
|
||||
|
||||
source = Duktape_GetStringPropertyValueEx(ctx, -1, ILibDuktape_EventEmitter_Forward_SourceName, NULL, &sourceLen);
|
||||
target = Duktape_GetStringPropertyValueEx(ctx, -1, ILibDuktape_EventEmitter_Forward_TargetName, NULL, &targetLen);
|
||||
sourceObject = Duktape_GetHeapptrProperty(ctx, -1, ILibDuktape_EventEmitter_Forward_SourceObject);
|
||||
|
||||
if (source != NULL && target != NULL && sourceObject != NULL)
|
||||
{
|
||||
hook = (char*)duk_get_lstring(ctx, 0, &hookLen);
|
||||
if (!(hookLen == targetLen && strncmp(target, hook, hookLen) == 0))
|
||||
{
|
||||
// This hooked event wasn't for us, so let's rehook this logic up for next time
|
||||
duk_push_this(ctx); // [this]
|
||||
duk_get_prop_string(ctx, -1, "once"); // [this][once]
|
||||
duk_swap_top(ctx, -2); // [once][this]
|
||||
duk_push_string(ctx, "_eventHook"); // [once][this][_eventHook]
|
||||
duk_push_c_function(ctx, ILibDuktape_EventEmitter_ForwardEvent_HookSink, DUK_VARARGS); // [once][this][_eventHook][func]
|
||||
duk_push_lstring(ctx, source, sourceLen); duk_put_prop_string(ctx, -2, ILibDuktape_EventEmitter_Forward_SourceName);
|
||||
duk_push_lstring(ctx, target, targetLen); duk_put_prop_string(ctx, -2, ILibDuktape_EventEmitter_Forward_TargetName);
|
||||
duk_push_heapptr(ctx, sourceObject); duk_put_prop_string(ctx, -2, ILibDuktape_EventEmitter_Forward_SourceObject);
|
||||
duk_call_method(ctx, 2); duk_pop(ctx); // ...
|
||||
}
|
||||
else
|
||||
{
|
||||
// This hooked event is for us
|
||||
ILibDuktape_EventEmitter_SetupOn(ctx, sourceObject, source); // [on][this][source]
|
||||
duk_push_c_function(ctx, ILibDuktape_EventEmitter_ForwardEvent_Sink, DUK_VARARGS); // [on][this][source][sink]
|
||||
fptr = duk_get_heapptr(ctx, -1);
|
||||
duk_push_this(ctx); duk_put_prop_string(ctx, -2, "targetObject");
|
||||
duk_push_lstring(ctx, target, targetLen); duk_put_prop_string(ctx, -2, "targetName");
|
||||
if (duk_pcall_method(ctx, 2) != 0) { ILibDuktape_Process_UncaughtExceptionEx(ctx, "EventEmitter_ForwardEvent(): "); }
|
||||
duk_pop(ctx); // ...
|
||||
|
||||
ILibDuktape_EventEmitter_SetupPrependOnce(ctx, sourceObject, "~"); // [prependOnce][this][~]
|
||||
duk_push_c_function(ctx, ILibDuktape_EventEmitter_ForwardEvent_Finalizer, DUK_VARARGS); // [prependOnce][this]['~'][func]
|
||||
duk_push_heapptr(ctx, fptr); duk_put_prop_string(ctx, -2, "fptr");
|
||||
duk_push_lstring(ctx, target, targetLen); duk_put_prop_string(ctx, -2, "targetName");
|
||||
if (duk_pcall_method(ctx, 2) != 0) { ILibDuktape_Process_UncaughtExceptionEx(ctx, "EventEmitter_ForwardEvent_SetFinalizer(): "); }
|
||||
duk_pop(ctx); // ...
|
||||
}
|
||||
}
|
||||
|
||||
return(0);
|
||||
}
|
||||
void ILibDuktape_EventEmitter_DeleteForwardEvent(duk_context *ctx, duk_idx_t eventSourceIndex, char *sourceEventName)
|
||||
{
|
||||
duk_dup(ctx, eventSourceIndex); // [source]
|
||||
if (duk_has_prop_string(ctx, -1, ILibDuktape_EventEmitter_ForwardTable))
|
||||
{
|
||||
duk_get_prop_string(ctx, -1, ILibDuktape_EventEmitter_ForwardTable); // [source][table]
|
||||
if (duk_has_prop_string(ctx, -1, sourceEventName))
|
||||
{
|
||||
duk_get_prop_string(ctx, -1, sourceEventName); // [source][table][sink]
|
||||
duk_del_prop_string(ctx, -1, "targetObject");
|
||||
duk_get_prop_string(ctx, -3, "removeListener"); // [source][table][sink][removeListener]
|
||||
duk_dup(ctx, -4); // [source][table][sink][removeListener][this]
|
||||
duk_push_string(ctx, sourceEventName); // [source][table][sink][removeListener][this][name]
|
||||
duk_dup(ctx, -4); // [source][table][sink][removeListener][this][name][sink]
|
||||
duk_call_method(ctx, 2); duk_pop_2(ctx); // [source][table]
|
||||
if (duk_has_prop_string(ctx, -1, "~"))
|
||||
{
|
||||
duk_get_prop_string(ctx, -1, "~"); // [source][table][sink]
|
||||
duk_del_prop_string(ctx, -1, "fptr");
|
||||
duk_get_prop_string(ctx, -3, "removeListener"); // [source][table][sink][removeListener]
|
||||
duk_dup(ctx, -4); // [source][table][sink][removeListener][this]
|
||||
duk_push_string(ctx, "~"); // [source][table][sink][removeListener][this][name]
|
||||
duk_dup(ctx, -4); // [source][table][sink][removeListener][this][name][sink]
|
||||
duk_call_method(ctx, 2); duk_pop_2(ctx); // [source][table]
|
||||
}
|
||||
if (duk_has_prop_string(ctx, -1, "_eventHook"))
|
||||
{
|
||||
duk_get_prop_string(ctx, -1, "_eventHook"); // [source][table][sink]
|
||||
duk_get_prop_string(ctx, -3, "removeListener"); // [source][table][sink][removeListener]
|
||||
duk_dup(ctx, -4); // [source][table][sink][removeListener][this]
|
||||
duk_push_string(ctx, "_eventHook"); // [source][table][sink][removeListener][this][name]
|
||||
duk_dup(ctx, -4); // [source][table][sink][removeListener][this][name][sink]
|
||||
duk_call_method(ctx, 2); duk_pop_2(ctx); // [source][table]
|
||||
}
|
||||
}
|
||||
duk_pop(ctx); // [source]
|
||||
}
|
||||
duk_pop(ctx); // ...
|
||||
}
|
||||
void ILibDuktape_EventEmitter_ForwardEvent(duk_context *ctx, duk_idx_t eventSourceIndex, char *sourceEventName, duk_idx_t eventTargetIndex, char *targetEventName)
|
||||
{
|
||||
void *fptr;
|
||||
void *source;
|
||||
void *target;
|
||||
void *table = NULL;
|
||||
duk_dup(ctx, eventTargetIndex); // [targetObject]
|
||||
target = duk_get_heapptr(ctx, -1);
|
||||
duk_pop(ctx); // ...
|
||||
duk_dup(ctx, eventSourceIndex); // [sourceObject]
|
||||
duk_get_prop_string(ctx, -1, "on"); // [sourceObject][on]
|
||||
duk_swap_top(ctx, -2); // [on][this]
|
||||
duk_push_string(ctx, sourceEventName); // [on][this][name]
|
||||
duk_push_c_function(ctx, ILibDuktape_EventEmitter_ForwardEvent_Sink, DUK_VARARGS); // [on][this][name][sink]
|
||||
source = duk_get_heapptr(ctx, -1);
|
||||
duk_pop(ctx); // ...
|
||||
|
||||
|
||||
duk_push_heapptr(ctx, source); // [source]
|
||||
ILibDuktape_EventEmitter_DeleteForwardEvent(ctx, -1, sourceEventName);
|
||||
if (duk_has_prop_string(ctx, -1, ILibDuktape_EventEmitter_ForwardTable))
|
||||
{
|
||||
duk_get_prop_string(ctx, -1, ILibDuktape_EventEmitter_ForwardTable); // [source][table]
|
||||
table = duk_get_heapptr(ctx, -1);
|
||||
duk_pop(ctx); // [source]
|
||||
}
|
||||
else
|
||||
{
|
||||
duk_push_object(ctx); // [source][table]
|
||||
table = duk_get_heapptr(ctx, -1);
|
||||
duk_put_prop_string(ctx, -2, ILibDuktape_EventEmitter_ForwardTable); // [source]
|
||||
}
|
||||
duk_pop(ctx); // ...
|
||||
|
||||
|
||||
duk_push_heapptr(ctx, target); // [target]
|
||||
if (ILibDuktape_EventEmitter_HasListeners(ILibDuktape_EventEmitter_GetEmitter(ctx, -1), targetEventName) > 0)
|
||||
{
|
||||
// Target already has listeners, so we can go ahead and forward events
|
||||
duk_pop(ctx); // ...
|
||||
|
||||
ILibDuktape_EventEmitter_SetupOn(ctx, source, sourceEventName); // [on][this][source]
|
||||
duk_push_c_function(ctx, ILibDuktape_EventEmitter_ForwardEvent_Sink, DUK_VARARGS); // [on][this][source][sink]
|
||||
fptr = duk_get_heapptr(ctx, -1);
|
||||
duk_push_heapptr(ctx, target); // [on][this][name][sink][targetObject]
|
||||
duk_put_prop_string(ctx, -2, "targetObject"); // [on][this][name][sink]
|
||||
duk_push_string(ctx, targetEventName); // [on][this][name][sink][targetName]
|
||||
duk_put_prop_string(ctx, -2, "targetName"); // [on][this][name][sink]
|
||||
duk_push_heapptr(ctx, target); duk_put_prop_string(ctx, -2, "targetObject");
|
||||
duk_push_string(ctx, targetEventName); duk_put_prop_string(ctx, -2, "targetName");
|
||||
if (duk_pcall_method(ctx, 2) != 0) { ILibDuktape_Process_UncaughtExceptionEx(ctx, "EventEmitter_ForwardEvent(): "); }
|
||||
duk_pop(ctx); // ...
|
||||
|
||||
duk_dup(ctx, eventSourceIndex); // [sourceObject]
|
||||
duk_get_prop_string(ctx, -1, "prependOnceListener"); // [sourceObject][prependOnce]
|
||||
duk_swap_top(ctx, -2); // [prependOnce][this]
|
||||
duk_push_string(ctx, "~"); // [prependOnce][this]['~']
|
||||
duk_push_c_function(ctx, ILibDuktape_EventEmitter_ForwardEvent_Finalizer, DUK_VARARGS); // [prependOnce][this]['~'][func]
|
||||
duk_push_heapptr(ctx, fptr); // [prependOnce][this]['~'][func][fptr]
|
||||
duk_put_prop_string(ctx, -2, "fptr"); // [prependOnce][this]['~'][func]
|
||||
duk_push_string(ctx, targetEventName); // [prependOnce][this]['~'][func][name]
|
||||
duk_put_prop_string(ctx, -2, "targetName"); // [prependOnce][this]['~'][func]
|
||||
duk_push_heapptr(ctx, table); // [table]
|
||||
duk_push_heapptr(ctx, fptr); // [table][func]
|
||||
duk_put_prop_string(ctx, -2, sourceEventName); // [table]
|
||||
duk_pop(ctx); // ...
|
||||
|
||||
ILibDuktape_EventEmitter_SetupPrependOnce(ctx, source, "~"); // [prependOnce][this][~]
|
||||
duk_push_c_function(ctx, ILibDuktape_EventEmitter_ForwardEvent_Finalizer, DUK_VARARGS); // [prependOnce][this]['~'][func]
|
||||
|
||||
duk_push_heapptr(ctx, table); // [prependOnce][this]['~'][func][table]
|
||||
duk_dup(ctx, -2); // [prependOnce][this]['~'][func][table][func]
|
||||
duk_put_prop_string(ctx, -2, "~"); // [prependOnce][this]['~'][func][table]
|
||||
duk_pop(ctx); // [prependOnce][this]['~'][func]
|
||||
|
||||
duk_push_heapptr(ctx, fptr); duk_put_prop_string(ctx, -2, "fptr");
|
||||
duk_push_string(ctx, targetEventName); duk_put_prop_string(ctx, -2, "targetName");
|
||||
if (duk_pcall_method(ctx, 2) != 0) { ILibDuktape_Process_UncaughtExceptionEx(ctx, "EventEmitter_ForwardEvent_SetFinalizer(): "); }
|
||||
duk_pop(ctx); // ...
|
||||
}
|
||||
else
|
||||
{
|
||||
// Target has no listeners, so only forward events if someone adds a listener
|
||||
duk_get_prop_string(ctx, -1, "once"); // [target][once]
|
||||
duk_swap_top(ctx, -2); // [once][this]
|
||||
duk_push_string(ctx, "_eventHook"); // [once][this][_eventHook]
|
||||
duk_push_c_function(ctx, ILibDuktape_EventEmitter_ForwardEvent_HookSink, DUK_VARARGS); // [once][this][_eventHook][func]
|
||||
duk_push_string(ctx, sourceEventName); duk_put_prop_string(ctx, -2, ILibDuktape_EventEmitter_Forward_SourceName);
|
||||
duk_push_string(ctx, targetEventName); duk_put_prop_string(ctx, -2, ILibDuktape_EventEmitter_Forward_TargetName);
|
||||
duk_push_heapptr(ctx, source); duk_put_prop_string(ctx, -2, ILibDuktape_EventEmitter_Forward_SourceObject);
|
||||
if (duk_pcall_method(ctx, 2) != 0) { ILibDuktape_Process_UncaughtExceptionEx(ctx, "Error hooking event: %s ", targetEventName); }
|
||||
duk_pop(ctx); // ...
|
||||
}
|
||||
}
|
||||
int ILibDuktape_EventEmitter_AddOnEx(duk_context *ctx, duk_idx_t idx, char *eventName, duk_c_function func)
|
||||
{
|
||||
int retVal = 1;
|
||||
|
||||
@@ -2845,16 +2845,16 @@ typedef struct duk_hthread duk_context;
|
||||
#undef DUK_USE_DATE_GET_NOW
|
||||
#undef DUK_USE_DATE_PARSE_STRING
|
||||
#undef DUK_USE_DATE_PRS_GETDATE
|
||||
#undef DUK_USE_DEBUG
|
||||
#undef DUK_USE_DEBUGGER_DUMPHEAP
|
||||
#undef DUK_USE_DEBUGGER_INSPECT
|
||||
#undef DUK_USE_DEBUGGER_PAUSE_UNCAUGHT
|
||||
#undef DUK_USE_DEBUGGER_SUPPORT
|
||||
//#undef DUK_USE_DEBUG
|
||||
//#undef DUK_USE_DEBUGGER_DUMPHEAP
|
||||
//#undef DUK_USE_DEBUGGER_INSPECT
|
||||
//#undef DUK_USE_DEBUGGER_PAUSE_UNCAUGHT
|
||||
//#undef DUK_USE_DEBUGGER_SUPPORT
|
||||
#define DUK_USE_DEBUGGER_THROW_NOTIFY
|
||||
#undef DUK_USE_DEBUGGER_TRANSPORT_TORTURE
|
||||
#define DUK_USE_DEBUG_BUFSIZE 65536L
|
||||
#define DUK_USE_DEBUG_LEVEL 0
|
||||
#undef DUK_USE_DEBUG_WRITE
|
||||
//#undef DUK_USE_DEBUG_WRITE
|
||||
#define DUK_USE_DOUBLE_LINKED_HEAP
|
||||
#define DUK_USE_DUKTAPE_BUILTIN
|
||||
#define DUK_USE_ENCODING_BUILTINS
|
||||
@@ -2917,8 +2917,8 @@ typedef struct duk_hthread duk_context;
|
||||
#define DUK_USE_HTML_COMMENTS
|
||||
#define DUK_USE_IDCHAR_FASTPATH
|
||||
#undef DUK_USE_INJECT_HEAP_ALLOC_ERROR
|
||||
#undef DUK_USE_INTERRUPT_COUNTER
|
||||
#undef DUK_USE_INTERRUPT_DEBUG_FIXUP
|
||||
//#undef DUK_USE_INTERRUPT_COUNTER
|
||||
//#undef DUK_USE_INTERRUPT_DEBUG_FIXUP
|
||||
#define DUK_USE_JC
|
||||
#define DUK_USE_JSON_BUILTIN
|
||||
#define DUK_USE_JSON_DECNUMBER_FASTPATH
|
||||
|
||||
27
microscript/s.h
Normal file
27
microscript/s.h
Normal file
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
Copyright 2006 - 2018 Intel Corporation
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef __DUKTAPE_SIMPLEDATASTORE__
|
||||
#define __DUKTAPE_SIMPLEDATASTORE__
|
||||
|
||||
|
||||
#include "duktape.h"
|
||||
#include "microstack/ILibSimpleDataStore.h"
|
||||
|
||||
void ILibDuktape_SimpleDataStore_init(duk_context *ctx, ILibSimpleDataStore sharedDb);
|
||||
|
||||
|
||||
#endif
|
||||
@@ -686,12 +686,11 @@ ILibAsyncServerSocket_ServerModule ILibCreateAsyncServerSocketModuleWithMemoryEx
|
||||
//
|
||||
// Set the socket to non-block mode, so we can play nice and share the thread
|
||||
//
|
||||
int flags = 1;
|
||||
#ifdef _WIN32_WCE
|
||||
ioctlsocket(RetVal->ListenSocket, FIONBIO, &flags);
|
||||
#elif WIN32
|
||||
#ifdef WIN32
|
||||
u_long flags = 1;
|
||||
ioctlsocket(RetVal->ListenSocket, FIONBIO, (u_long *)(&flags));
|
||||
#elif _POSIX
|
||||
int flags = 1;
|
||||
flags = fcntl(RetVal->ListenSocket, F_GETFL, 0);
|
||||
fcntl(RetVal->ListenSocket, F_SETFL, O_NONBLOCK | flags);
|
||||
#endif
|
||||
|
||||
@@ -177,4 +177,3 @@ void ILibAsyncServerSocket_GetLocal(ILibAsyncServerSocket_ServerModule ServerSoc
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
@@ -46,7 +46,6 @@ limitations under the License.
|
||||
#include "ILibParsers.h"
|
||||
#include "ILibAsyncSocket.h"
|
||||
#include "ILibRemoteLogging.h"
|
||||
#include "ILibAsyncSocket.h"
|
||||
|
||||
#ifndef MICROSTACK_NOTLS
|
||||
#include <openssl/err.h>
|
||||
@@ -742,6 +741,7 @@ void ILibAsyncSocket_Disconnect(ILibAsyncSocket_SocketModule socketModule)
|
||||
#endif
|
||||
|
||||
struct ILibAsyncSocketModule *module = (struct ILibAsyncSocketModule*)socketModule;
|
||||
if (module == NULL) { return; }
|
||||
|
||||
ILibRemoteLogging_printf(ILibChainGetLogger(module->Transport.ChainLink.ParentChain), ILibRemoteLogging_Modules_Microstack_AsyncSocket, ILibRemoteLogging_Flags_VerbosityLevel_1, "AsyncSocket[%p] << DISCONNECT", (void*)module);
|
||||
|
||||
@@ -942,6 +942,12 @@ void ILibAsyncSocket_ConnectTo(void* socketModule, struct sockaddr *localInterfa
|
||||
}
|
||||
|
||||
#ifdef MICROSTACK_PROXY
|
||||
void ILibAsyncSocket_ClearProxySettings(void *socketModule)
|
||||
{
|
||||
struct ILibAsyncSocketModule *module = (struct ILibAsyncSocketModule*)socketModule;
|
||||
memset(&(module->ProxyAddress), 0, sizeof(struct sockaddr_in6));
|
||||
}
|
||||
|
||||
//! Connect using an HTTPS proxy. If "proxyAddress" is set to NULL, this call acts just to a normal connect call without a proxy.
|
||||
/*!
|
||||
\param socketModule ILibAsyncSocket Client to initiate the connection
|
||||
@@ -1401,7 +1407,11 @@ void ILibAsyncSocket_PreSelect(void* socketModule,fd_set *readset, fd_set *write
|
||||
sem_post(&(module->SendLock));
|
||||
h(module, module->user);
|
||||
sem_wait(&(module->SendLock));
|
||||
if (module->timeout_milliSeconds != 0) { *blocktime = module->timeout_milliSeconds; }
|
||||
if (module->timeout_milliSeconds != 0)
|
||||
{
|
||||
*blocktime = module->timeout_milliSeconds;
|
||||
module->timeout_lastActivity = ILibGetUptime();
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -2329,4 +2339,3 @@ STACK_OF(X509) *ILibAsyncSocket_SslGetCerts(ILibAsyncSocket_SocketModule socketM
|
||||
return SSL_get_peer_cert_chain(sm->ssl);
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
@@ -174,6 +174,7 @@ void ILibAsyncSocket_ResetTotalBytesSent(ILibAsyncSocket_SocketModule socketModu
|
||||
void ILibAsyncSocket_ConnectTo(void* socketModule, struct sockaddr *localInterface, struct sockaddr *remoteAddress, ILibAsyncSocket_OnInterrupt InterruptPtr, void *user);
|
||||
|
||||
#ifdef MICROSTACK_PROXY
|
||||
void ILibAsyncSocket_ClearProxySettings(void *socketModule);
|
||||
void ILibAsyncSocket_ConnectToProxy(void* socketModule, struct sockaddr *localInterface, struct sockaddr *remoteAddress, struct sockaddr *proxyAddress, char* proxyUser, char* proxyPass, ILibAsyncSocket_OnInterrupt InterruptPtr, void *user);
|
||||
#endif
|
||||
|
||||
|
||||
@@ -117,9 +117,7 @@ ILibAsyncUDPSocket_SocketModule ILibAsyncUDPSocket_CreateEx(void *Chain, int Buf
|
||||
#endif
|
||||
|
||||
// Initialize the UDP socket data structure
|
||||
data = (struct ILibAsyncUDPSocket_Data*)malloc(sizeof(struct ILibAsyncUDPSocket_Data));
|
||||
if (data == NULL) return NULL;
|
||||
memset(data, 0, sizeof(struct ILibAsyncUDPSocket_Data));
|
||||
data = (struct ILibAsyncUDPSocket_Data*)ILibMemory_Allocate(sizeof(struct ILibAsyncUDPSocket_Data), 0, NULL, NULL);
|
||||
data->OnData = OnData;
|
||||
data->OnSendOK = OnSendOK;
|
||||
data->user1 = user;
|
||||
|
||||
@@ -155,4 +155,3 @@ SOCKET ILibAsyncUDPSocket_GetSocket(ILibAsyncUDPSocket_SocketModule module);
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
@@ -35,15 +35,39 @@ limitations under the License.
|
||||
#include <openssl/err.h>
|
||||
#include <openssl/hmac.h>
|
||||
#else
|
||||
#include "md5.h"
|
||||
#include "sha1.h"
|
||||
#include "microstack/sha.h"
|
||||
#ifdef WIN32
|
||||
void BCRYPT_INIT(BCRYPT_CTX* ctx, void* alg)
|
||||
{
|
||||
memset(ctx, 0, sizeof(BCRYPT_CTX));
|
||||
BCryptOpenAlgorithmProvider(&(ctx->hAlg), (LPCWSTR)alg, NULL, 0);
|
||||
BCryptGetProperty(ctx->hAlg, BCRYPT_OBJECT_LENGTH, (PBYTE)&(ctx->cbHashObject), sizeof(DWORD), &(ctx->cbData), 0);
|
||||
ctx->pbHashObject = (PBYTE)HeapAlloc(GetProcessHeap(), 0, ctx->cbHashObject);
|
||||
BCryptGetProperty(ctx->hAlg, BCRYPT_HASH_LENGTH, (PBYTE)&(ctx->cbHash), sizeof(DWORD), &(ctx->cbData), 0);
|
||||
BCryptCreateHash(ctx->hAlg, &(ctx->hHash), ctx->pbHashObject, ctx->cbHashObject, NULL, 0, 0);
|
||||
}
|
||||
void BCRYPT_UPDATE(BCRYPT_CTX* ctx, void* data, size_t dataLen)
|
||||
{
|
||||
BCryptHashData(ctx->hHash, (PBYTE)data, (ULONG)dataLen, 0);
|
||||
}
|
||||
void BCRYPT_FINAL(char *h, BCRYPT_CTX* ctx)
|
||||
{
|
||||
BCryptFinishHash(ctx->hHash, (PUCHAR)h, ctx->cbHash, 0);
|
||||
BCryptCloseAlgorithmProvider(ctx->hAlg, 0);
|
||||
BCryptDestroyHash(ctx->hHash);
|
||||
HeapFree(GetProcessHeap(), 0, ctx->pbHashObject);
|
||||
}
|
||||
#else
|
||||
#include "microstack/nossl/md5.h"
|
||||
#include "microstack/nossl/sha1.h"
|
||||
#include "microstack/nossl/sha.h"
|
||||
#include <time.h>
|
||||
#endif
|
||||
#endif
|
||||
|
||||
char utils_HexTable[16] = { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' };
|
||||
char utils_HexTable2[16] = { '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f' };
|
||||
|
||||
|
||||
void __fastcall util_md5(char* data, int datalen, char* result)
|
||||
{
|
||||
MD5_CTX c;
|
||||
|
||||
@@ -58,9 +58,47 @@ void __fastcall util_randomtext(int length, char* result);
|
||||
#define UTIL_SHA512_HASHSIZE 64
|
||||
|
||||
#ifdef MICROSTACK_NOTLS
|
||||
#include "md5.h"
|
||||
#include "sha1.h"
|
||||
#include "microstack/SHA.h"
|
||||
#ifdef WIN32
|
||||
#include <bcrypt.h>
|
||||
|
||||
typedef struct BCRYPT_CTX
|
||||
{
|
||||
BCRYPT_ALG_HANDLE hAlg;
|
||||
BCRYPT_HASH_HANDLE hHash;
|
||||
DWORD cbData;
|
||||
DWORD cbHash;
|
||||
DWORD cbHashObject;
|
||||
PBYTE pbHashObject;
|
||||
}BCRYPT_CTX;
|
||||
#define SHA512_CTX BCRYPT_CTX
|
||||
#define SHA384_CTX BCRYPT_CTX
|
||||
#define SHA256_CTX BCRYPT_CTX
|
||||
#define SHA_CTX BCRYPT_CTX
|
||||
#define MD5_CTX BCRYPT_CTX
|
||||
|
||||
void BCRYPT_INIT(BCRYPT_CTX* ctx, void* alg);
|
||||
void BCRYPT_UPDATE(BCRYPT_CTX* ctx, void* data, size_t dataLen);
|
||||
void BCRYPT_FINAL(char *h, BCRYPT_CTX* ctx);
|
||||
#define SHA512_Init(ctx) BCRYPT_INIT(ctx, BCRYPT_SHA512_ALGORITHM)
|
||||
#define SHA384_Init(ctx) BCRYPT_INIT(ctx, BCRYPT_SHA384_ALGORITHM)
|
||||
#define SHA256_Init(ctx) BCRYPT_INIT(ctx, BCRYPT_SHA256_ALGORITHM)
|
||||
#define SHA1_Init(ctx) BCRYPT_INIT(ctx, BCRYPT_SHA1_ALGORITHM)
|
||||
#define MD5_Init(ctx) BCRYPT_INIT(ctx, BCRYPT_MD5_ALGORITHM)
|
||||
#define SHA512_Update(ctx, data, len) BCRYPT_UPDATE(ctx, data, len)
|
||||
#define SHA384_Update(ctx, data, len) BCRYPT_UPDATE(ctx, data, len)
|
||||
#define SHA256_Update(ctx, data, len) BCRYPT_UPDATE(ctx, data, len)
|
||||
#define SHA1_Update(ctx, data, len) BCRYPT_UPDATE(ctx, data, len)
|
||||
#define MD5_Update(ctx, data, len) BCRYPT_UPDATE(ctx, data, len)
|
||||
#define SHA512_Final(md, ctx) BCRYPT_FINAL(md, ctx)
|
||||
#define SHA384_Final(md, ctx) BCRYPT_FINAL(md, ctx)
|
||||
#define SHA256_Final(md, ctx) BCRYPT_FINAL(md, ctx)
|
||||
#define SHA1_Final(md, ctx) BCRYPT_FINAL(md, ctx)
|
||||
#define MD5_Final(md, ctx) BCRYPT_FINAL(md, ctx)
|
||||
|
||||
#else
|
||||
#include "microstack/nossl/md5.h"
|
||||
#include "microstack/nossl/SHA.h"
|
||||
#include "microstack/nossl/sha1.h"
|
||||
|
||||
#define SHA256_CTX SHA256Context
|
||||
#define SHA512_CTX SHA512Context
|
||||
@@ -77,6 +115,7 @@ void __fastcall util_randomtext(int length, char* result);
|
||||
#define SHA512_Update(ctx, data, len) SHA512Input(ctx, (uint8_t*)data, len)
|
||||
#define SHA512_Final(md, ctx) SHA512Result (ctx, md)
|
||||
#endif
|
||||
#endif
|
||||
|
||||
|
||||
#ifndef MICROSTACK_NOTLS
|
||||
|
||||
@@ -20,6 +20,12 @@ limitations under the License.
|
||||
#include <iphlpapi.h>
|
||||
#include <Dbghelp.h>
|
||||
#endif
|
||||
|
||||
#if defined(WIN32) && !defined(_WIN32_WCE)
|
||||
#define _CRTDBG_MAP_ALLOC
|
||||
#include <crtdbg.h>
|
||||
#endif
|
||||
|
||||
#include "ILibParsers.h"
|
||||
|
||||
#ifdef _POSIX
|
||||
@@ -56,6 +62,8 @@ void CALLBACK ILibIPAddressMonitor_dispatch(
|
||||
IN LPWSAOVERLAPPED lpOverlapped,
|
||||
IN DWORD dwFlags
|
||||
)
|
||||
{
|
||||
if (ILibMemory_CanaryOK(lpOverlapped))
|
||||
{
|
||||
if (dwError == 0 && lpOverlapped->hEvent != NULL)
|
||||
{
|
||||
@@ -64,14 +72,15 @@ void CALLBACK ILibIPAddressMonitor_dispatch(
|
||||
}
|
||||
else if (lpOverlapped->hEvent == NULL)
|
||||
{
|
||||
free(lpOverlapped);
|
||||
ILibMemory_Free(lpOverlapped);
|
||||
}
|
||||
}
|
||||
}
|
||||
void ILibIPAddressMonitor_MicrostackThreadDispatch(void *chain, void *user)
|
||||
{
|
||||
_ILibIPAddressMonitor *obj = (_ILibIPAddressMonitor*)user;
|
||||
if (obj->onUpdate != NULL) { obj->onUpdate(obj, obj->user); }
|
||||
WSAIoctl(obj->mSocket, SIO_ADDRESS_LIST_CHANGE, NULL, 0, NULL, 0, &(obj->bytesReturned), (LPWSAOVERLAPPED)&(obj->reserved), ILibIPAddressMonitor_dispatch);
|
||||
WSAIoctl(obj->mSocket, SIO_ADDRESS_LIST_CHANGE, NULL, 0, NULL, 0, &(obj->bytesReturned), obj->reserved, ILibIPAddressMonitor_dispatch);
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -128,7 +137,7 @@ ILibIPAddressMonitor ILibIPAddressMonitor_Create(void *chain, ILibIPAddressMonit
|
||||
obj->onUpdate = handler;
|
||||
obj->user = user;
|
||||
#ifdef WIN32
|
||||
obj->reserved = ILibMemory_Allocate(sizeof(OVERLAPPED), 0, NULL, NULL);
|
||||
obj->reserved = (OVERLAPPED*)ILibMemory_SmartAllocate(sizeof(OVERLAPPED)); // This leaks due to a bug in Windows, where the WSAIoctl frequently doesn't event on shutdown. If we free try to free it manually, it will cause a crash, because windows will have an invalid overlapped object.
|
||||
obj->reserved->hEvent = (HANDLE)obj;
|
||||
obj->mSocket = socket(AF_INET, SOCK_DGRAM, 0);
|
||||
WSAIoctl(obj->mSocket, SIO_ADDRESS_LIST_CHANGE, NULL, 0, NULL, 0, &(obj->bytesReturned), obj->reserved, ILibIPAddressMonitor_dispatch);
|
||||
|
||||
@@ -393,4 +393,3 @@ void ILibMulticastSocket_WakeOnLan(void *module, char* mac)
|
||||
ILibMulticastSocket_Broadcast((struct ILibMulticastSocket_StateModule*)module, ILibScratchPad, 102, 1);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -39,4 +39,3 @@ void ILibSetTTL(void *module, int ttl);
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
@@ -1047,6 +1047,7 @@ typedef struct ILibBaseChain
|
||||
|
||||
void *Timer;
|
||||
void *Reserved;
|
||||
ILibLinkedList OnDestroyEventSinks;
|
||||
ILibLinkedList Links;
|
||||
ILibLinkedList LinksPendingDelete;
|
||||
ILibHashtable ChainStash;
|
||||
@@ -1063,7 +1064,73 @@ typedef struct ILibBaseChain
|
||||
void *node;
|
||||
}ILibBaseChain;
|
||||
|
||||
void* ILibMemory_AllocateA_Init(void *buffer)
|
||||
{
|
||||
((void**)buffer)[0] = (char*)buffer + sizeof(void*);
|
||||
return(buffer);
|
||||
}
|
||||
void* ILibMemory_Init(void *ptr, size_t primarySize, size_t extraSize, ILibMemory_Types memType)
|
||||
{
|
||||
if (ptr == NULL) { ILIBCRITICALEXIT(254); }
|
||||
memset(ptr, 0, primarySize + extraSize + sizeof(ILibMemory_Header) + (extraSize > 0 ? sizeof(ILibMemory_Header) : 0));
|
||||
|
||||
void *primary = ILibMemory_FromRaw(ptr);
|
||||
|
||||
((ILibMemory_Header*)ptr)->size = primarySize;
|
||||
((ILibMemory_Header*)ptr)->extraSize = extraSize;
|
||||
((ILibMemory_Header*)ptr)->CANARY = ILibMemory_Canary;
|
||||
((ILibMemory_Header*)ptr)->memoryType = memType;
|
||||
|
||||
if (extraSize > 0)
|
||||
{
|
||||
ILibMemory_Header *extra = (ILibMemory_Header*)ILibMemory_RawPtr(ILibMemory_Extra(primary));
|
||||
extra->size = extraSize;
|
||||
extra->extraSize = 0;
|
||||
extra->CANARY = ILibMemory_Canary;
|
||||
extra->memoryType = ILibMemory_Types_OTHER;
|
||||
}
|
||||
|
||||
return(primary);
|
||||
}
|
||||
void ILibMemory_Free(void *ptr)
|
||||
{
|
||||
if (ILibMemory_CanaryOK(ptr) && ILibMemory_MemType(ptr) == ILibMemory_Types_HEAP)
|
||||
{
|
||||
if (ILibMemory_ExtraSize(ptr) > 0)
|
||||
{
|
||||
memset(ILibMemory_RawPtr(ILibMemory_Extra(ptr)), 0, sizeof(ILibMemory_Header));
|
||||
}
|
||||
memset(ILibMemory_RawPtr(ptr), 0, sizeof(ILibMemory_Header));
|
||||
free(ILibMemory_RawPtr(ptr));
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef WIN32
|
||||
int ILibMemory_CanaryOK(void *ptr)
|
||||
{
|
||||
__try
|
||||
{
|
||||
return(ILibMemory_Ex_CanaryOK(ptr));
|
||||
}
|
||||
__except (EXCEPTION_EXECUTE_HANDLER)
|
||||
{
|
||||
return(0);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
const int ILibMemory_CHAIN_CONTAINERSIZE = sizeof(ILibBaseChain);
|
||||
void ILibMemory_AllocateTemp_Sink(void *obj)
|
||||
{
|
||||
ILibMemory_Free(obj);
|
||||
}
|
||||
void* ILibMemory_AllocateTemp(void* chain, size_t sz)
|
||||
{
|
||||
char *ret = ILibMemory_SmartAllocate(sz);
|
||||
ILibLifeTime_AddEx(ILibGetBaseTimer(chain), ret, 0, ILibMemory_AllocateTemp_Sink, ILibMemory_AllocateTemp_Sink);
|
||||
return(ret);
|
||||
}
|
||||
|
||||
void* ILibMemory_AllocateA_InitMem(void *buffer, size_t bufferLen)
|
||||
{
|
||||
char *retVal = ((char*)buffer + 8 + sizeof(void*));
|
||||
@@ -1079,11 +1146,11 @@ void* ILibMemory_AllocateA_Get(void *buffer, size_t sz)
|
||||
{
|
||||
char *retVal = NULL;
|
||||
|
||||
if (ILibMemory_AllocateA_Size(buffer) > (int)sz)
|
||||
if (ILibMemory_AllocateA_Size(buffer) > sz)
|
||||
{
|
||||
retVal = ILibMemory_AllocateA_Next(buffer);
|
||||
ILibMemory_AllocateA_Size(buffer) -= (int)sz;
|
||||
ILibMemory_AllocateA_Next(buffer) = (char*)ILibMemory_AllocateA_Next(buffer) + (int)sz;
|
||||
ILibMemory_AllocateA_Size(buffer) -= sz;
|
||||
ILibMemory_AllocateA_Next(buffer) = (char*)ILibMemory_AllocateA_Next(buffer) + sz;
|
||||
}
|
||||
|
||||
return(retVal);
|
||||
@@ -1141,16 +1208,6 @@ ILibHashtable ILibChain_GetBaseHashtable(void* chain)
|
||||
return(b->ChainStash);
|
||||
}
|
||||
|
||||
void ILibChain_OnDestroyEvent_Sink(void *object)
|
||||
{
|
||||
ILibChain_Link *link = (ILibChain_Link*)object;
|
||||
ILibChain_DestroyEvent e = (ILibChain_DestroyEvent)((void**)link->ExtraMemoryPtr)[0];
|
||||
|
||||
if (e != NULL)
|
||||
{
|
||||
e(link->ParentChain, ((void**)link->ExtraMemoryPtr)[1]);
|
||||
}
|
||||
}
|
||||
//! Add an event handler to be dispatched when the Microstack Chain is shutdown
|
||||
/*!
|
||||
\param chain Microstack Chain to add an event handler to
|
||||
@@ -1159,20 +1216,16 @@ void ILibChain_OnDestroyEvent_Sink(void *object)
|
||||
*/
|
||||
void ILibChain_OnDestroyEvent_AddHandler(void *chain, ILibChain_DestroyEvent sink, void *user)
|
||||
{
|
||||
ILibChain_Link *link = ILibChain_Link_Allocate(sizeof(ILibChain_Link), 2 * sizeof(void*));
|
||||
link->ParentChain = chain;
|
||||
link->DestroyHandler = (ILibChain_Destroy)&ILibChain_OnDestroyEvent_Sink;
|
||||
((void**)link->ExtraMemoryPtr)[0] = sink;
|
||||
((void**)link->ExtraMemoryPtr)[1] = user;
|
||||
ILibBaseChain *bchain = (ILibBaseChain*)chain;
|
||||
void **data = (void**)ILibMemory_Allocate(sizeof(void*) * 2, 0, NULL, NULL);
|
||||
data[0] = sink;
|
||||
data[1] = user;
|
||||
|
||||
if (ILibIsChainRunning(chain) == 0)
|
||||
if (bchain->OnDestroyEventSinks == NULL)
|
||||
{
|
||||
ILibAddToChain(chain, link);
|
||||
}
|
||||
else
|
||||
{
|
||||
ILibChain_SafeAdd(chain, link);
|
||||
bchain->OnDestroyEventSinks = ILibLinkedList_Create();
|
||||
}
|
||||
ILibLinkedList_AddTail(bchain->OnDestroyEventSinks, data);
|
||||
}
|
||||
void ILibChain_OnStartEvent_Sink(void* object, fd_set *readset, fd_set *writeset, fd_set *errorset, int* blocktime)
|
||||
{
|
||||
@@ -1530,12 +1583,17 @@ void ILibChain_RunOnMicrostackThreadSink(void *obj)
|
||||
void* chain = ((void**)obj)[0];
|
||||
ILibChain_StartEvent handler = (ILibChain_StartEvent)((void**)obj)[1];
|
||||
void* user = ((void**)obj)[2];
|
||||
void* freeOnShutdown = ((void**)obj)[3];
|
||||
|
||||
if (ILibIsChainBeingDestroyed(chain) == 0)
|
||||
{
|
||||
// Only Dispatch if the chain is still running
|
||||
if (handler != NULL) { handler(chain, user); }
|
||||
}
|
||||
else if (freeOnShutdown != NULL)
|
||||
{
|
||||
free(user);
|
||||
}
|
||||
free(obj);
|
||||
}
|
||||
//! Dispatch an operation to the Microstack Chain thread
|
||||
@@ -1544,15 +1602,16 @@ void ILibChain_RunOnMicrostackThreadSink(void *obj)
|
||||
\param handler Event to dispatch on the microstack thread
|
||||
\param user Custom user data to dispatch to the microstack thread
|
||||
*/
|
||||
void ILibChain_RunOnMicrostackThreadEx(void *chain, ILibChain_StartEvent handler, void *user)
|
||||
void ILibChain_RunOnMicrostackThreadEx2(void *chain, ILibChain_StartEvent handler, void *user, int freeOnShutdown)
|
||||
{
|
||||
void** value = NULL;
|
||||
|
||||
value = (void**)ILibMemory_Allocate(3 * sizeof(void*), 0, NULL, NULL);
|
||||
value = (void**)ILibMemory_Allocate(4 * sizeof(void*), 0, NULL, NULL);
|
||||
|
||||
value[0] = chain;
|
||||
value[1] = handler;
|
||||
value[2] = user;
|
||||
value[3] = (void*)(uint64_t)freeOnShutdown;
|
||||
ILibLifeTime_AddEx(ILibGetBaseTimer(chain), value, 0, &ILibChain_RunOnMicrostackThreadSink, &ILibChain_RunOnMicrostackThreadSink);
|
||||
}
|
||||
#ifdef WIN32
|
||||
@@ -1990,6 +2049,11 @@ void ILib_WindowsExceptionDebug(CONTEXT *exceptionContext)
|
||||
pimg->SizeOfStruct = sizeof(IMAGEHLP_LINE64);
|
||||
|
||||
len = sprintf_s(buffer, sizeof(buffer), "FATAL EXCEPTION [%s] @ ", (g_ILibCrashID != NULL ? g_ILibCrashID : ""));
|
||||
#ifdef WIN64
|
||||
len += sprintf_s(buffer + len, sizeof(buffer) - len, "[FuncAddr: 0x%016llx / BaseAddr: 0x%016llx / Delta: %lld]\n", (unsigned __int64)StackFrame.AddrPC.Offset, (unsigned __int64)&ILibCreateChain, (unsigned __int64)&ILibCreateChain - (unsigned __int64)StackFrame.AddrPC.Offset);
|
||||
#else
|
||||
len += sprintf_s(buffer + len, sizeof(buffer) - len, "[FuncAddr: 0x%08x / BaseAddr: 0x%08x / Delta: %d]\n", (unsigned __int32)StackFrame.AddrPC.Offset, (unsigned __int32)&ILibCreateChain, (unsigned __int32)&ILibCreateChain - (unsigned __int32)StackFrame.AddrPC.Offset);
|
||||
#endif
|
||||
|
||||
if (SymFromAddr(GetCurrentProcess(), StackFrame.AddrPC.Offset, &tmp, psym))
|
||||
{
|
||||
@@ -2003,11 +2067,6 @@ void ILib_WindowsExceptionDebug(CONTEXT *exceptionContext)
|
||||
len += sprintf_s(buffer + len, sizeof(buffer) - len, "]\n");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
util_tohex((char*)&(StackFrame.AddrPC.Offset), sizeof(DWORD64), imgBuffer);
|
||||
len += sprintf_s(buffer + len, sizeof(buffer) - len, "[FuncAddr: 0x%s]\n", imgBuffer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2078,6 +2137,7 @@ void ILib_POSIX_CrashHandler(int code)
|
||||
if ((strings[i])[c] == ']') { (strings[i])[c] = 0; }
|
||||
if ((strings[i])[c] == 0) { break; }
|
||||
}
|
||||
|
||||
if (pipe(fd) == 0)
|
||||
{
|
||||
pid = vfork();
|
||||
@@ -2126,8 +2186,15 @@ char* ILib_POSIX_InstallCrashHandler(char *exename)
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
|
||||
void ILibChain_DebugDelta(char *buffer, int bufferLen, uint64_t delta)
|
||||
{
|
||||
ILibChain_DebugOffset(buffer, bufferLen, (uint64_t)&ILibCreateChain - delta);
|
||||
}
|
||||
|
||||
void ILibChain_DebugOffset(char *buffer, int bufferLen, uint64_t addrOffset)
|
||||
{
|
||||
#ifndef _NOILIBSTACKDEBUG
|
||||
#ifdef WIN32
|
||||
int len = 0;
|
||||
char symBuffer[4096];
|
||||
@@ -2141,11 +2208,19 @@ void ILibChain_DebugOffset(char *buffer, int bufferLen, uint64_t addrOffset)
|
||||
pimg->SizeOfStruct = sizeof(IMAGEHLP_LINE64);
|
||||
SymInitialize(GetCurrentProcess(), NULL, TRUE);
|
||||
|
||||
sprintf_s(buffer, bufferLen, "[Unable to decode function address]");
|
||||
#ifdef WIN64
|
||||
sprintf_s(buffer, bufferLen, "[Unable to decode function address, BaseAddr: 0x%016llx]", (unsigned __int64)&ILibCreateChain);
|
||||
#else
|
||||
sprintf_s(buffer, bufferLen, "[Unable to decode function address, BaseAddr: 0x%08x]", (unsigned __int32)&ILibCreateChain);
|
||||
#endif
|
||||
|
||||
if (SymFromAddr(GetCurrentProcess(), (DWORD64)addrOffset, &tmp, psym))
|
||||
{
|
||||
len += sprintf_s(buffer + len, bufferLen - len, "[%s", (char*)(psym->Name));
|
||||
#ifdef WIN64
|
||||
len += sprintf_s(buffer + len, bufferLen - len, "[BaseAddr: 0x%016llx, %s", (unsigned __int64)&ILibCreateChain, (char*)(psym->Name));
|
||||
#else
|
||||
len += sprintf_s(buffer + len, bufferLen - len, "[BaseAddr: 0x%08x, %s", (unsigned __int32)&ILibCreateChain, (char*)(psym->Name));
|
||||
#endif
|
||||
if (SymGetLineFromAddr64(GetCurrentProcess(), (DWORD64)addrOffset, &tmp2, pimg))
|
||||
{
|
||||
len += sprintf_s(buffer + len, bufferLen - len, " => %s:%d]\n", (char*)(pimg->FileName), pimg->LineNumber);
|
||||
@@ -2155,8 +2230,54 @@ void ILibChain_DebugOffset(char *buffer, int bufferLen, uint64_t addrOffset)
|
||||
len += sprintf_s(buffer + len, bufferLen - len, "]\n");
|
||||
}
|
||||
}
|
||||
#else
|
||||
char addrtmp[255];
|
||||
int len = 0;
|
||||
pid_t pid;
|
||||
int fd[2];
|
||||
|
||||
sprintf_s(addrtmp, sizeof(addrtmp), "0x%016"PRIx64, addrOffset);
|
||||
((char**)ILib_POSIX_CrashParamBuffer)[1] = addrtmp;
|
||||
|
||||
if (pipe(fd) == 0)
|
||||
{
|
||||
pid = vfork();
|
||||
if (pid == 0)
|
||||
{
|
||||
dup2(fd[1], STDOUT_FILENO);
|
||||
close(fd[1]);
|
||||
|
||||
execv("/usr/bin/addr2line", (char**)ILib_POSIX_CrashParamBuffer);
|
||||
if (write(STDOUT_FILENO, "??:0", 4)) {}
|
||||
exit(0);
|
||||
}
|
||||
if (pid > 0)
|
||||
{
|
||||
char tmp[8192];
|
||||
int rlen;
|
||||
|
||||
rlen = read(fd[0], tmp, 8192);
|
||||
if (rlen > 0 && tmp[0] != '?')
|
||||
{
|
||||
memcpy_s(buffer + len, bufferLen - len, "=> ", 3);
|
||||
len += 3;
|
||||
memcpy_s(buffer + len, bufferLen - len, tmp, rlen);
|
||||
len += rlen;
|
||||
}
|
||||
else
|
||||
{
|
||||
memcpy_s(buffer + len, bufferLen - len, "=> NOT FOUND", 12);
|
||||
len += 12;
|
||||
}
|
||||
close(fd[0]);
|
||||
}
|
||||
|
||||
buffer[len] = 0;
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
char* ILibChain_Debug(void *chain, char* buffer, int bufferLen)
|
||||
{
|
||||
char *retVal = NULL;
|
||||
@@ -2584,6 +2705,25 @@ ILibExportMethod void ILibStartChain(void *Chain)
|
||||
#endif
|
||||
}
|
||||
|
||||
// Before we start, lets signal that the chain is stopping
|
||||
if (chain->OnDestroyEventSinks != NULL)
|
||||
{
|
||||
void *n = ILibLinkedList_GetNode_Head(chain->OnDestroyEventSinks);
|
||||
while (n != NULL)
|
||||
{
|
||||
void **edata = (void**)ILibLinkedList_GetDataFromNode(n);
|
||||
if (edata != NULL)
|
||||
{
|
||||
((ILibChain_DestroyEvent)edata[0])(chain, edata[1]);
|
||||
free(edata);
|
||||
}
|
||||
n = ILibLinkedList_GetNextNode(n);
|
||||
}
|
||||
ILibLinkedList_Destroy(chain->OnDestroyEventSinks);
|
||||
chain->OnDestroyEventSinks = NULL;
|
||||
}
|
||||
|
||||
|
||||
// Because many modules in the chain are using the base chain timer which is the first node
|
||||
// in the chain in the base timer), these modules may start cleaning up their timers. So, we
|
||||
// are going to make an exception and Destroy the base timer last, something that would usualy
|
||||
@@ -4681,7 +4821,7 @@ struct packetheader* ILibParsePacketHeader(char* buffer, int offset, int length)
|
||||
RetVal->StatusCode = (int)atoi(tempbuffer);
|
||||
free(tempbuffer);
|
||||
RetVal->StatusData = StartLine->FirstResult->NextResult->NextResult->data;
|
||||
RetVal->StatusDataLength = StartLine->FirstResult->NextResult->NextResult->datalength;
|
||||
RetVal->StatusDataLength = (int)((f->data + f->datalength) - RetVal->StatusData);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -5218,7 +5358,7 @@ ILibParseUriResult ILibParseUriEx (const char* URI, size_t URILen, char** Addr,
|
||||
}
|
||||
AddrStruct->sin6_port = (unsigned short)htons(lport);
|
||||
}
|
||||
else
|
||||
else if(laddr!=NULL)
|
||||
{
|
||||
// IPv4
|
||||
AddrStruct->sin6_family = AF_INET;
|
||||
@@ -5557,7 +5697,7 @@ void ILibencodeblock( unsigned char in[3], unsigned char out[4], int len )
|
||||
{
|
||||
out[0] = cb64[ in[0] >> 2 ];
|
||||
out[1] = cb64[ ((in[0] & 0x03) << 4) | ((in[1] & 0xf0) >> 4) ];
|
||||
out[2] = (unsigned char) (len > 1 ? cb64[ ((in[1] & 0x0f) << 2) | ((in[2] & 0xc0) >> 6) ] : '=');
|
||||
out[2] = (unsigned char) (len > 1 ? cb64[ ((in[1] & 0x0f) << 2) | (len>2?((in[2] & 0xc0) >> 6):0) ] : '=');
|
||||
out[3] = (unsigned char) (len > 2 ? cb64[ in[2] & 0x3f ] : '=');
|
||||
}
|
||||
|
||||
@@ -5590,10 +5730,26 @@ int ILibBase64Encode(unsigned char* input, const int inputlen, unsigned char** o
|
||||
out = *output;
|
||||
in = input;
|
||||
|
||||
if (input == NULL || inputlen == 0) { *output = NULL; return 0; }
|
||||
while ((in+3) <= (input+inputlen)) { ILibencodeblock(in, out, 3); in += 3; out += 4; }
|
||||
if ((input+inputlen)-in == 1) { ILibencodeblock(in, out, 1); out += 4; }
|
||||
else if ((input+inputlen)-in == 2) { ILibencodeblock(in, out, 2); out += 4; }
|
||||
if (input == NULL || inputlen == 0)
|
||||
{
|
||||
*output = NULL; return 0;
|
||||
}
|
||||
while ((in+3) <= (input+inputlen))
|
||||
{
|
||||
ILibencodeblock(in, out, 3);
|
||||
in += 3;
|
||||
out += 4;
|
||||
}
|
||||
if ((input+inputlen)-in == 1)
|
||||
{
|
||||
ILibencodeblock(in, out, 1);
|
||||
out += 4;
|
||||
}
|
||||
else if ((input+inputlen)-in == 2)
|
||||
{
|
||||
ILibencodeblock(in, out, 2);
|
||||
out += 4;
|
||||
}
|
||||
*out = 0;
|
||||
|
||||
return (int)(out-*output);
|
||||
@@ -6056,6 +6212,7 @@ void ILibLifeTime_Remove(void *LifeTimeToken, void *data)
|
||||
node = ILibLinkedList_GetNextNode(node);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (removed == 0)
|
||||
{
|
||||
//
|
||||
@@ -6065,7 +6222,6 @@ void ILibLifeTime_Remove(void *LifeTimeToken, void *data)
|
||||
ILibLinkedList_AddTail(UPnPLifeTime->Reserved, data);
|
||||
ILibLinkedList_UnLock(UPnPLifeTime->Reserved);
|
||||
}
|
||||
}
|
||||
ILibLinkedList_UnLock(UPnPLifeTime->ObjectList);
|
||||
|
||||
//
|
||||
@@ -7040,7 +7196,7 @@ void* ILibSparseArray_Add(ILibSparseArray sarray, int index, void *data)
|
||||
else if(root->bucket[i].index < 0)
|
||||
{
|
||||
// Need to use Linked List
|
||||
ILibSparseArray_Node* n = (ILibSparseArray_Node*)malloc(sizeof(ILibSparseArray_Node));
|
||||
ILibSparseArray_Node* n = (ILibSparseArray_Node*)ILibMemory_Allocate(sizeof(ILibSparseArray_Node), 0, NULL, NULL);
|
||||
n->index = index;
|
||||
n->ptr = data;
|
||||
n = (ILibSparseArray_Node*)ILibLinkedList_SortedInsert(root->bucket[i].ptr, &ILibSparseArray_Comparer, n);
|
||||
@@ -7063,7 +7219,7 @@ void* ILibSparseArray_Add(ILibSparseArray sarray, int index, void *data)
|
||||
else
|
||||
{
|
||||
// We need to create a linked list, add the old value, then insert our new value (No return value)
|
||||
ILibSparseArray_Node* n = (ILibSparseArray_Node*)malloc(sizeof(ILibSparseArray_Node));
|
||||
ILibSparseArray_Node* n = (ILibSparseArray_Node*)ILibMemory_Allocate(sizeof(ILibSparseArray_Node), 0, NULL, NULL);
|
||||
n->index = root->bucket[i].index;
|
||||
n->ptr = root->bucket[i].ptr;
|
||||
|
||||
@@ -7071,7 +7227,7 @@ void* ILibSparseArray_Add(ILibSparseArray sarray, int index, void *data)
|
||||
root->bucket[i].ptr = ILibLinkedList_Create();
|
||||
ILibLinkedList_AddHead(root->bucket[i].ptr, n);
|
||||
|
||||
n = (ILibSparseArray_Node*)malloc(sizeof(ILibSparseArray_Node));
|
||||
n = (ILibSparseArray_Node*)(ILibSparseArray_Node*)ILibMemory_Allocate(sizeof(ILibSparseArray_Node), 0, NULL, NULL);
|
||||
n->index = index;
|
||||
n->ptr = data;
|
||||
ILibLinkedList_SortedInsert(root->bucket[i].ptr, &ILibSparseArray_Comparer, n);
|
||||
@@ -7852,6 +8008,7 @@ long long ILibGetUptime()
|
||||
if (hlib == NULL) return 0;
|
||||
pILibGetUptimeGetTickCount64 = (ULONGLONG(*)())GetProcAddress(hlib, "GetTickCount64");
|
||||
ILibGetUptimeFirst = 0;
|
||||
FreeLibrary(hlib);
|
||||
}
|
||||
if (pILibGetUptimeGetTickCount64 != NULL) return pILibGetUptimeGetTickCount64();
|
||||
|
||||
@@ -8810,8 +8967,14 @@ int ILibInetCompare(struct sockaddr* addr1, struct sockaddr* addr2, int compare)
|
||||
int ILibResolveEx3(char* hostname, char *service, struct sockaddr_in6* addr6, int addr6Count)
|
||||
{
|
||||
int r, i = 0;
|
||||
#ifdef WIN32
|
||||
ADDRINFOW *result = NULL, *current = NULL;
|
||||
ADDRINFOW hints;
|
||||
#else
|
||||
struct addrinfo *result = NULL, *current = NULL;
|
||||
struct addrinfo hints;
|
||||
#endif
|
||||
|
||||
int len = 0;
|
||||
|
||||
if (addr6 != NULL && addr6Count > 0)
|
||||
@@ -8823,19 +8986,29 @@ int ILibResolveEx3(char* hostname, char *service, struct sockaddr_in6* addr6, in
|
||||
hints.ai_socktype = SOCK_STREAM;
|
||||
hints.ai_protocol = IPPROTO_TCP;
|
||||
|
||||
#ifndef WIN32
|
||||
#ifdef WIN32
|
||||
if (hostname[0] == '[')
|
||||
{
|
||||
int hostnameLen = strnlen_s(hostname, 4096);
|
||||
char *newHost = alloca(hostnameLen);
|
||||
int hostnameLen = (int)strnlen_s(hostname, 4096);
|
||||
char *newHost = _alloca((size_t)hostnameLen);
|
||||
memcpy_s(newHost, hostnameLen, hostname + 1, hostnameLen - 2);
|
||||
newHost[hostnameLen - 2] = 0;
|
||||
hostname = newHost;
|
||||
}
|
||||
#endif
|
||||
|
||||
size_t hnameLen = hostname == NULL ? 0 : (2 + (2 * MultiByteToWideChar(CP_UTF8, 0, (LPCCH)hostname, -1, NULL, 0)));
|
||||
size_t svcLen = service == NULL ? 0 : (2 + (2 * MultiByteToWideChar(CP_UTF8, 0, (LPCCH)service, -1, NULL, 0)));
|
||||
PCWSTR hname = hnameLen == 0 ? NULL : _alloca(hnameLen);
|
||||
PCWSTR svc = svcLen == 0 ? NULL : _alloca(svcLen);
|
||||
if (hname != NULL) { MultiByteToWideChar(CP_UTF8, 0, (LPCCH)hostname, -1, (LPWSTR)hname, (int)hnameLen); }
|
||||
if (svc != NULL) { MultiByteToWideChar(CP_UTF8, 0, (LPCCH)service, -1, (LPWSTR)svc, (int)svcLen); }
|
||||
r = GetAddrInfoW(hname, svc, &hints, &result);
|
||||
if (r != 0) { if (result != NULL) { FreeAddrInfoW(result); } return r; }
|
||||
#else
|
||||
r = getaddrinfo(hostname, service, &hints, &result);
|
||||
if (r != 0) { if (result != NULL) { freeaddrinfo(result); } return r; }
|
||||
#endif
|
||||
|
||||
if (result == NULL) return -1;
|
||||
|
||||
// Determine Number of results
|
||||
@@ -8865,7 +9038,11 @@ int ILibResolveEx3(char* hostname, char *service, struct sockaddr_in6* addr6, in
|
||||
current = current->ai_next;
|
||||
}
|
||||
|
||||
#ifdef WIN32
|
||||
FreeAddrInfoW(result);
|
||||
#else
|
||||
freeaddrinfo(result);
|
||||
#endif
|
||||
return i;
|
||||
}
|
||||
int ILibResolveEx2(char* hostname, unsigned short port, struct sockaddr_in6* addr6, int count)
|
||||
|
||||
@@ -160,7 +160,7 @@ long ILibGetTimeStamp();
|
||||
#endif
|
||||
void ILibGetTimeOfDay(struct timeval *tp);
|
||||
|
||||
/*
|
||||
|
||||
// Implemented in Windows using events.
|
||||
#define sem_t HANDLE
|
||||
#define sem_init(x,pShared,InitValue) *x=CreateSemaphore(NULL,InitValue,SEM_MAX_COUNT,NULL)
|
||||
@@ -168,15 +168,15 @@ long ILibGetTimeStamp();
|
||||
#define sem_wait(x) WaitForSingleObject(*x,INFINITE)
|
||||
#define sem_trywait(x) ((WaitForSingleObject(*x,0)==WAIT_OBJECT_0)?0:1)
|
||||
#define sem_post(x) ReleaseSemaphore(*x,1,NULL)
|
||||
*/
|
||||
|
||||
// Implemented in Windows using critical section.
|
||||
#define sem_t CRITICAL_SECTION
|
||||
#define sem_init(x,pShared,InitValue) InitializeCriticalSection(x);
|
||||
#define sem_destroy(x) (DeleteCriticalSection(x))
|
||||
#define sem_wait(x) EnterCriticalSection(x)
|
||||
#define sem_trywait(x) TryEnterCriticalSection(x)
|
||||
#define sem_post(x) LeaveCriticalSection(x)
|
||||
|
||||
//// Implemented in Windows using critical section.
|
||||
//#define sem_t CRITICAL_SECTION
|
||||
//#define sem_init(x,pShared,InitValue) InitializeCriticalSection(x);
|
||||
//#define sem_destroy(x) (DeleteCriticalSection(x))
|
||||
//#define sem_wait(x) EnterCriticalSection(x)
|
||||
//#define sem_trywait(x) TryEnterCriticalSection(x)
|
||||
//#define sem_post(x) LeaveCriticalSection(x)
|
||||
|
||||
#define strncasecmp(x,y,z) _strnicmp(x,y,z)
|
||||
#define strcasecmp(x,y) _stricmp(x,y)
|
||||
@@ -301,18 +301,56 @@ int ILibIsRunningOnChainThread(void* chain);
|
||||
ILibChain_Link* ILibChain_Link_Allocate(int structSize, int extraMemorySize);
|
||||
int ILibChain_Link_GetExtraMemorySize(ILibChain_Link* link);
|
||||
|
||||
typedef enum ILibMemory_Types
|
||||
{
|
||||
ILibMemory_Types_HEAP = 0,
|
||||
ILibMemory_Types_STACK = 1,
|
||||
ILibMemory_Types_OTHER = 2
|
||||
}ILibMemory_Types;
|
||||
|
||||
typedef struct ILibMemory_Header
|
||||
{
|
||||
size_t size;
|
||||
size_t extraSize;
|
||||
int CANARY;
|
||||
ILibMemory_Types memoryType;
|
||||
}ILibMemory_Header;
|
||||
|
||||
#define ILibMemory_Canary (((int*)((char*)(const char*)"broe"))[0])
|
||||
#define ILibMemory_RawPtr(ptr) ((char*)(ptr) - sizeof(ILibMemory_Header))
|
||||
#define ILibMemory_RawSize(ptr) (ILibMemory_Size((ptr)) + ILibMemory_ExtraSize((ptr)) + sizeof(ILibMemory_Header))
|
||||
#define ILibMemory_MemType(ptr) (((ILibMemory_Header*)ILibMemory_RawPtr((ptr)))->memoryType)
|
||||
#define ILibMemory_Size(ptr) (((ILibMemory_Header*)ILibMemory_RawPtr((ptr)))->size)
|
||||
#define ILibMemory_ExtraSize(ptr) (((ILibMemory_Header*)ILibMemory_RawPtr((ptr)))->extraSize)
|
||||
#define ILibMemory_Ex_CanaryOK(ptr) ((((ILibMemory_Header*)ILibMemory_RawPtr((ptr)))->CANARY) == ILibMemory_Canary)
|
||||
#ifdef WIN32
|
||||
#define ILibMemory_AllocateA(bufferLen) ILibMemory_AllocateA_InitMem(_alloca(8+bufferLen+sizeof(void*)), (size_t)(8+bufferLen+sizeof(void*)))
|
||||
int ILibMemory_CanaryOK(void *ptr);
|
||||
#else
|
||||
#define ILibMemory_AllocateA(bufferLen) ILibMemory_AllocateA_InitMem(alloca(8+bufferLen+sizeof(void*)), (size_t)(8+bufferLen+sizeof(void*)))
|
||||
#define ILibMemory_CanaryOK(ptr) ILibMemory_Ex_CanaryOK(ptr)
|
||||
#endif
|
||||
#define ILibMemory_AllocateA_Size(buffer) (((unsigned int*)((char*)(buffer)-4))[0])
|
||||
#define ILibMemory_AllocateA_Next(buffer) (((void**)((char*)(buffer)-4-sizeof(void*)))[0])
|
||||
#define ILibMemory_AllocateA_Raw(buffer) ((void*)((char*)(buffer)-4-sizeof(void*)-4))
|
||||
#define ILibMemory_AllocateA_RawSize(buffer) (((unsigned int*)((char*)(buffer)-4-sizeof(void*)-4))[0])
|
||||
|
||||
#define ILibMemory_Extra(ptr) (ILibMemory_ExtraSize(ptr)>0?((char*)(ptr) + ILibMemory_Size((ptr)) + sizeof(ILibMemory_Header)):NULL)
|
||||
#define ILibMemory_FromRaw(ptr) ((char*)(ptr) + sizeof(ILibMemory_Header))
|
||||
|
||||
void* ILibMemory_Init(void *ptr, size_t primarySize, size_t extraSize, ILibMemory_Types memType);
|
||||
#define ILibMemory_SmartAllocate(len) ILibMemory_Init(malloc(len+sizeof(ILibMemory_Header)), (int)len, 0, ILibMemory_Types_HEAP)
|
||||
#define ILibMemory_SmartAllocateEx(primaryLen, extraLen) ILibMemory_Init(malloc(primaryLen + extraLen + sizeof(ILibMemory_Header) + (extraLen>0?sizeof(ILibMemory_Header):0)), (int)primaryLen, (int)extraLen, ILibMemory_Types_HEAP)
|
||||
void ILibMemory_Free(void *ptr);
|
||||
void* ILibMemory_AllocateTemp(void* chain, size_t sz);
|
||||
|
||||
#ifdef WIN32
|
||||
#define ILibMemory_AllocateA(bufferLen) ILibMemory_AllocateA_Init(ILibMemory_Init(_alloca(bufferLen + sizeof(void*) + (2*sizeof(ILibMemory_Header))), bufferLen, sizeof(void*), ILibMemory_Types_STACK))
|
||||
#else
|
||||
#define ILibMemory_AllocateA(bufferLen) ILibMemory_AllocateA_Init(ILibMemory_Init(alloca(bufferLen + sizeof(void*) + (2*sizeof(ILibMemory_Header))), bufferLen, sizeof(void*), ILibMemory_Types_STACK))
|
||||
#endif
|
||||
#define ILibMemory_AllocateA_Size(buffer) ILibMemory_Size(buffer)
|
||||
#define ILibMemory_AllocateA_Next(buffer) (((void**)buffer)[0])
|
||||
#define ILibMemory_AllocateA_Raw(buffer) ILibMemory_RawPtr(buffer)
|
||||
#define ILibMemory_AllocateA_RawSize(buffer) ILibMemory_RawSize(buffer);
|
||||
|
||||
void* ILibMemory_AllocateA_Get(void *buffer, size_t sz);
|
||||
void* ILibMemory_AllocateA_InitMem(void *buffer, size_t bufferLen);
|
||||
void* ILibMemory_AllocateA_Init(void *buffer);
|
||||
|
||||
void* ILibMemory_Allocate(int containerSize, int extraMemorySize, void** allocatedContainer, void **extraMemory);
|
||||
int ILibMemory_GetExtraMemorySize(void* extraMemory);
|
||||
ILibExportMethod void* ILibMemory_GetExtraMemory(void *container, int containerSize);
|
||||
@@ -857,8 +895,10 @@ int ILibIsRunningOnChainThread(void* chain);
|
||||
ILibExportMethod void ILibChain_EndContinue(void *chain);
|
||||
|
||||
void ILibForceUnBlockChain(void *Chain);
|
||||
void ILibChain_RunOnMicrostackThreadEx(void *chain, ILibChain_StartEvent handler, void *user);
|
||||
void ILibChain_RunOnMicrostackThreadEx2(void *chain, ILibChain_StartEvent handler, void *user, int freeOnShutdown);
|
||||
#define ILibChain_RunOnMicrostackThreadEx(chain, handler, user) ILibChain_RunOnMicrostackThreadEx2(chain, handler, user, 0)
|
||||
#define ILibChain_RunOnMicrostackThread(chain, handler, user) if(ILibIsRunningOnChainThread(chain)==0){ILibChain_RunOnMicrostackThreadEx(chain, handler, user);}else{handler(chain,user);}
|
||||
#define ILibChain_RunOnMicrostackThread2(chain, handler, user, freeOnShutdown) if(ILibIsRunningOnChainThread(chain)==0){ILibChain_RunOnMicrostackThreadEx2(chain, handler, user, freeOnShutdown);}else{handler(chain,user);}
|
||||
#ifdef WIN32
|
||||
HANDLE ILibChain_GetMicrostackThreadHandle(void *chain);
|
||||
#endif
|
||||
@@ -1280,6 +1320,7 @@ int ILibIsRunningOnChainThread(void* chain);
|
||||
//
|
||||
// Used to log critical problems
|
||||
//
|
||||
void ILibChain_DebugDelta(char *buffer, int bufferLen, uint64_t addrOffset);
|
||||
void ILibChain_DebugOffset(char *buffer, int bufferLen, uint64_t addrOffset);
|
||||
char* ILibChain_Debug(void *chain, char* buffer, int bufferLen);
|
||||
extern char* g_ILibCrashID;
|
||||
|
||||
@@ -14,8 +14,8 @@ See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
#ifdef MEMORY_CHECK
|
||||
#include <assert.h>
|
||||
#ifdef MEMORY_CHECK
|
||||
#define MEMCHECK(x) x
|
||||
#else
|
||||
#define MEMCHECK(x)
|
||||
@@ -30,7 +30,6 @@ limitations under the License.
|
||||
#include "ILibParsers.h"
|
||||
#include "ILibRemoteLogging.h"
|
||||
#include "ILibProcessPipe.h"
|
||||
#include <assert.h>
|
||||
#ifndef WIN32
|
||||
#include <fcntl.h> /* Obtain O_* constant definitions */
|
||||
#include <unistd.h>
|
||||
@@ -67,7 +66,7 @@ typedef struct ILibProcessPipe_PipeObject
|
||||
char* buffer;
|
||||
int bufferSize;
|
||||
|
||||
int readOffset;
|
||||
int readOffset, readNewOffset;
|
||||
int totalRead;
|
||||
int processingLoop;
|
||||
|
||||
@@ -276,7 +275,20 @@ void ILibProcessPipe_Manager_WindowsRunLoopEx(void *arg)
|
||||
if (x == WAIT_FAILED || (x-WAIT_OBJECT_0) == 0) { break; }
|
||||
data = (ILibProcessPipe_WaitHandle*)hList[x + FD_SETSIZE];
|
||||
manager->activeWaitHandle = data;
|
||||
if (data != NULL && data->callback != NULL) { data->callback(data->event, data->user); }
|
||||
if (data != NULL && data->callback != NULL)
|
||||
{
|
||||
if (data->callback(data->event, data->user) == FALSE)
|
||||
{
|
||||
// FALSE means to remove the WaitHandle
|
||||
void *node = ILibLinkedList_GetNode_Search(manager->ActivePipes, ILibProcessPipe_Manager_WindowsWaitHandles_Remove_Comparer, data->event);
|
||||
if (node != NULL)
|
||||
{
|
||||
free(ILibLinkedList_GetDataFromNode(node));
|
||||
ILibLinkedList_Remove(node);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ResetEvent(manager->updateEvent);
|
||||
}
|
||||
@@ -503,21 +515,40 @@ ILibProcessPipe_PipeObject* ILibProcessPipe_CreatePipe(ILibProcessPipe_Manager m
|
||||
}
|
||||
|
||||
#ifdef WIN32
|
||||
|
||||
typedef struct ILibProcessPipe_Process_Destroy_WinRunThread_Data
|
||||
{
|
||||
ILibProcessPipe_Process_Object *pj;
|
||||
HANDLE h;
|
||||
}ILibProcessPipe_Process_Destroy_WinRunThread_Data;
|
||||
void __stdcall ILibProcessPipe_Process_Destroy_WinRunThread(ULONG_PTR obj)
|
||||
{
|
||||
ILibProcessPipe_Process_Object *p = (ILibProcessPipe_Process_Object*)obj;
|
||||
if (p->exiting != 0) { return; }
|
||||
if (p->stdIn != NULL) { ILibProcessPipe_FreePipe(p->stdIn); }
|
||||
if (p->stdOut != NULL) { ILibProcessPipe_FreePipe(p->stdOut); }
|
||||
if (p->stdErr != NULL) { ILibProcessPipe_FreePipe(p->stdErr); }
|
||||
free(p);
|
||||
ILibProcessPipe_Process_Destroy_WinRunThread_Data *data = (ILibProcessPipe_Process_Destroy_WinRunThread_Data*)obj;
|
||||
if (ILibMemory_CanaryOK(data) && ILibMemory_CanaryOK(data->pj))
|
||||
{
|
||||
if (data->pj->exiting == 0)
|
||||
{
|
||||
if (ILibMemory_CanaryOK(data) && ILibMemory_CanaryOK(data->pj) && data->pj->stdIn != NULL) { ILibProcessPipe_FreePipe(data->pj->stdIn); }
|
||||
if (ILibMemory_CanaryOK(data) && ILibMemory_CanaryOK(data->pj) && data->pj->stdOut != NULL) { ILibProcessPipe_FreePipe(data->pj->stdOut); }
|
||||
if (ILibMemory_CanaryOK(data) && ILibMemory_CanaryOK(data->pj) && data->pj->stdErr != NULL) { ILibProcessPipe_FreePipe(data->pj->stdErr); }
|
||||
if (ILibMemory_CanaryOK(data) && ILibMemory_CanaryOK(data->pj)) { ILibMemory_Free(data->pj); }
|
||||
}
|
||||
}
|
||||
SetEvent(data->h);
|
||||
}
|
||||
#endif
|
||||
void ILibProcessPipe_Process_Destroy(ILibProcessPipe_Process_Object *p)
|
||||
{
|
||||
if (!ILibMemory_CanaryOK(p)) { return; }
|
||||
|
||||
#ifdef WIN32
|
||||
ILibProcessPipe_Process_Destroy_WinRunThread_Data *data = ILibMemory_AllocateA(sizeof(ILibProcessPipe_Process_Destroy_WinRunThread_Data));
|
||||
data->pj = p;
|
||||
data->h = CreateEvent(NULL, TRUE, FALSE, NULL);
|
||||
// We can't destroy this now, because we're on the MicrostackThread. We must destroy this on the WindowsRunLoop Thread.
|
||||
QueueUserAPC((PAPCFUNC)ILibProcessPipe_Process_Destroy_WinRunThread, p->parent->workerThread, (ULONG_PTR)p);
|
||||
QueueUserAPC((PAPCFUNC)ILibProcessPipe_Process_Destroy_WinRunThread, p->parent->workerThread, (ULONG_PTR)data);
|
||||
WaitForSingleObjectEx(data->h, 3000, TRUE);
|
||||
CloseHandle(data->h);
|
||||
#else
|
||||
if (p->exiting != 0) { return; }
|
||||
if (p->stdIn != NULL) { ILibProcessPipe_FreePipe(p->stdIn); }
|
||||
@@ -542,15 +573,12 @@ void ILibProcessPipe_Process_BrokenPipeSink(ILibProcessPipe_Pipe sender)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
void* ILibProcessPipe_Process_KillEx(ILibProcessPipe_Process p)
|
||||
{
|
||||
void *retVal = ILibProcessPipe_Process_Kill(p);
|
||||
ILibProcessPipe_Process_Destroy((ILibProcessPipe_Process_Object*)p);
|
||||
return retVal;
|
||||
}
|
||||
|
||||
void ILibProcessPipe_Process_SoftKill(ILibProcessPipe_Process p)
|
||||
{
|
||||
ILibProcessPipe_Process_Object* j = (ILibProcessPipe_Process_Object*)p;
|
||||
if (!ILibMemory_CanaryOK(p)) { return; }
|
||||
|
||||
#ifdef WIN32
|
||||
TerminateProcess(j->hProcess, 1067);
|
||||
#else
|
||||
@@ -559,36 +587,8 @@ void ILibProcessPipe_Process_SoftKill(ILibProcessPipe_Process p)
|
||||
waitpid((pid_t)j->PID, &code, 0);
|
||||
#endif
|
||||
}
|
||||
void* ILibProcessPipe_Process_Kill(ILibProcessPipe_Process p)
|
||||
{
|
||||
ILibProcessPipe_Process_Object* j = (ILibProcessPipe_Process_Object*)p;
|
||||
|
||||
#ifdef WIN32
|
||||
// First things first, unhook all the pipes from the Windows Run Loop
|
||||
if (ILibIsChainBeingDestroyed(j->chain) == 0)
|
||||
{
|
||||
if (j->stdIn != NULL && j->stdIn->mOverlapped != NULL) { ILibProcessPipe_WaitHandle_Remove(j->parent, j->stdIn->mOverlapped->hEvent); }
|
||||
if (j->stdOut != NULL && j->stdOut->mOverlapped != NULL) { ILibProcessPipe_WaitHandle_Remove(j->parent, j->stdOut->mOverlapped->hEvent); }
|
||||
if (j->stdErr != NULL && j->stdErr->mOverlapped != NULL) { ILibProcessPipe_WaitHandle_Remove(j->parent, j->stdErr->mOverlapped->hEvent); }
|
||||
if (j->hProcess != NULL) { ILibProcessPipe_WaitHandle_Remove(j->parent, j->hProcess); TerminateProcess(j->hProcess, 1067); }
|
||||
}
|
||||
else
|
||||
{
|
||||
TerminateProcess(j->hProcess, 1067);
|
||||
}
|
||||
#else
|
||||
int code;
|
||||
if (j->stdIn != NULL) { j->stdIn->brokenPipeHandler = NULL; }
|
||||
if (j->stdOut != NULL) { j->stdOut->brokenPipeHandler = NULL; }
|
||||
if (j->stdErr != NULL) { j->stdErr->brokenPipeHandler = NULL; }
|
||||
|
||||
kill((pid_t)j->PID, SIGKILL);
|
||||
waitpid((pid_t)j->PID, &code, 0);
|
||||
#endif
|
||||
return(j->userObject);
|
||||
}
|
||||
|
||||
ILibProcessPipe_Process ILibProcessPipe_Manager_SpawnProcessEx2(ILibProcessPipe_Manager pipeManager, char* target, char* const* parameters, ILibProcessPipe_SpawnTypes spawnType, int extraMemorySize)
|
||||
ILibProcessPipe_Process ILibProcessPipe_Manager_SpawnProcessEx3(ILibProcessPipe_Manager pipeManager, char* target, char* const* parameters, ILibProcessPipe_SpawnTypes spawnType, void *sid, int extraMemorySize)
|
||||
{
|
||||
ILibProcessPipe_Process_Object* retVal = NULL;
|
||||
|
||||
@@ -604,12 +604,13 @@ ILibProcessPipe_Process ILibProcessPipe_Manager_SpawnProcessEx2(ILibProcessPipe_
|
||||
ZeroMemory(&processInfo, sizeof(PROCESS_INFORMATION));
|
||||
ZeroMemory(&info, sizeof(STARTUPINFOA));
|
||||
|
||||
if (spawnType != ILibProcessPipe_SpawnTypes_DEFAULT && (sessionId = WTSGetActiveConsoleSessionId()) == 0xFFFFFFFF) { return(NULL); } // No session attached to console, but requested to execute as logged in user
|
||||
if (spawnType != ILibProcessPipe_SpawnTypes_SPECIFIED_USER && spawnType != ILibProcessPipe_SpawnTypes_DEFAULT && (sessionId = WTSGetActiveConsoleSessionId()) == 0xFFFFFFFF) { return(NULL); } // No session attached to console, but requested to execute as logged in user
|
||||
if (spawnType != ILibProcessPipe_SpawnTypes_DEFAULT)
|
||||
{
|
||||
procHandle = GetCurrentProcess();
|
||||
if (OpenProcessToken(procHandle, TOKEN_DUPLICATE, &token) == 0) { ILIBMARKPOSITION(2); return(NULL); }
|
||||
if (DuplicateTokenEx(token, MAXIMUM_ALLOWED, 0, SecurityImpersonation, TokenPrimary, &userToken) == 0) { CloseHandle(token); ILIBMARKPOSITION(2); return(NULL); }
|
||||
if (spawnType == ILibProcessPipe_SpawnTypes_SPECIFIED_USER) { sessionId = (DWORD)(uint64_t)sid; }
|
||||
if (SetTokenInformation(userToken, (TOKEN_INFORMATION_CLASS)TokenSessionId, &sessionId, sizeof(sessionId)) == 0) { CloseHandle(token); CloseHandle(userToken); ILIBMARKPOSITION(2); return(NULL); }
|
||||
if (spawnType == ILibProcessPipe_SpawnTypes_WINLOGON) { info.lpDesktop = "Winsta0\\Winlogon"; }
|
||||
}
|
||||
@@ -646,14 +647,19 @@ ILibProcessPipe_Process ILibProcessPipe_Manager_SpawnProcessEx2(ILibProcessPipe_
|
||||
pid_t pid;
|
||||
#endif
|
||||
|
||||
if ((retVal = (ILibProcessPipe_Process_Object*)malloc(sizeof(ILibProcessPipe_Process_Object))) == NULL) { ILIBCRITICALEXIT(254); }
|
||||
memset(retVal, 0, sizeof(ILibProcessPipe_Process_Object));
|
||||
|
||||
retVal = (ILibProcessPipe_Process_Object*)ILibMemory_SmartAllocate(sizeof(ILibProcessPipe_Process_Object));
|
||||
if (spawnType != ILibProcessPipe_SpawnTypes_DETACHED)
|
||||
{
|
||||
retVal->stdErr = ILibProcessPipe_CreatePipe(pipeManager, 4096, NULL, extraMemorySize);
|
||||
retVal->stdErr->mProcess = retVal;
|
||||
}
|
||||
retVal->parent = (ILibProcessPipe_Manager_Object*)pipeManager;
|
||||
retVal->chain = retVal->parent->ChainLink.ParentChain;
|
||||
#ifdef WIN32
|
||||
|
||||
info.cb = sizeof(STARTUPINFOA);
|
||||
if (spawnType != ILibProcessPipe_SpawnTypes_DETACHED)
|
||||
{
|
||||
retVal->stdIn = ILibProcessPipe_CreatePipe(pipeManager, 4096, NULL, extraMemorySize);
|
||||
retVal->stdIn->mProcess = retVal;
|
||||
retVal->stdOut = ILibProcessPipe_CreatePipe(pipeManager, 4096, NULL, extraMemorySize);
|
||||
@@ -663,20 +669,23 @@ ILibProcessPipe_Process ILibProcessPipe_Manager_SpawnProcessEx2(ILibProcessPipe_
|
||||
ILibProcessPipe_PipeObject_DisableInherit(&(retVal->stdOut->mPipe_ReadEnd));
|
||||
ILibProcessPipe_PipeObject_DisableInherit(&(retVal->stdErr->mPipe_ReadEnd));
|
||||
|
||||
info.cb = sizeof(STARTUPINFOA);
|
||||
info.hStdError = retVal->stdErr->mPipe_WriteEnd;
|
||||
info.hStdInput = retVal->stdIn->mPipe_ReadEnd;
|
||||
info.hStdOutput = retVal->stdOut->mPipe_WriteEnd;
|
||||
info.dwFlags |= STARTF_USESTDHANDLES;
|
||||
}
|
||||
|
||||
if ((spawnType == ILibProcessPipe_SpawnTypes_DEFAULT && !CreateProcessA(target, parms, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &info, &processInfo)) ||
|
||||
(spawnType != ILibProcessPipe_SpawnTypes_DEFAULT && !CreateProcessAsUserA(userToken, target, parms, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &info, &processInfo)))
|
||||
{
|
||||
if (spawnType != ILibProcessPipe_SpawnTypes_DETACHED)
|
||||
{
|
||||
ILibProcessPipe_FreePipe(retVal->stdErr);
|
||||
ILibProcessPipe_FreePipe(retVal->stdOut);
|
||||
ILibProcessPipe_FreePipe(retVal->stdIn);
|
||||
}
|
||||
if (allocParms != 0) { free(parms); }
|
||||
free(retVal);
|
||||
ILibMemory_Free(retVal);
|
||||
if (token != NULL) { CloseHandle(token); }
|
||||
if (userToken != NULL) { CloseHandle(userToken); }
|
||||
return(NULL);
|
||||
@@ -684,14 +693,21 @@ ILibProcessPipe_Process ILibProcessPipe_Manager_SpawnProcessEx2(ILibProcessPipe_
|
||||
|
||||
|
||||
if (allocParms != 0) { free(parms); }
|
||||
if (spawnType != ILibProcessPipe_SpawnTypes_DETACHED)
|
||||
{
|
||||
CloseHandle(retVal->stdOut->mPipe_WriteEnd); retVal->stdOut->mPipe_WriteEnd = NULL;
|
||||
CloseHandle(retVal->stdErr->mPipe_WriteEnd); retVal->stdErr->mPipe_WriteEnd = NULL;
|
||||
CloseHandle(retVal->stdIn->mPipe_ReadEnd); retVal->stdIn->mPipe_ReadEnd = NULL;
|
||||
}
|
||||
|
||||
retVal->hProcess = processInfo.hProcess;
|
||||
if (processInfo.hThread != NULL) CloseHandle(processInfo.hThread);
|
||||
retVal->PID = processInfo.dwProcessId;
|
||||
|
||||
if (token != NULL) { CloseHandle(token); token = NULL; }
|
||||
if (userToken != NULL) { CloseHandle(userToken); userToken = NULL; }
|
||||
#else
|
||||
int UID = (int)(uint64_t)sid;
|
||||
if (spawnType == ILibProcessPipe_SpawnTypes_TERM)
|
||||
{
|
||||
int pipe;
|
||||
@@ -709,32 +725,42 @@ ILibProcessPipe_Process ILibProcessPipe_Manager_SpawnProcessEx2(ILibProcessPipe_
|
||||
retVal->stdOut->mProcess = retVal;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (spawnType != ILibProcessPipe_SpawnTypes_DETACHED)
|
||||
{
|
||||
retVal->stdIn = ILibProcessPipe_CreatePipe(pipeManager, 4096, NULL, extraMemorySize);
|
||||
retVal->stdIn->mProcess = retVal;
|
||||
retVal->stdOut = ILibProcessPipe_CreatePipe(pipeManager, 4096, (ILibProcessPipe_GenericBrokenPipeHandler)ILibProcessPipe_Process_BrokenPipeSink, extraMemorySize);
|
||||
retVal->stdOut->mProcess = retVal;
|
||||
}
|
||||
pid = vfork();
|
||||
}
|
||||
if (pid < 0)
|
||||
{
|
||||
if (spawnType != ILibProcessPipe_SpawnTypes_DETACHED)
|
||||
{
|
||||
ILibProcessPipe_FreePipe(retVal->stdErr);
|
||||
ILibProcessPipe_FreePipe(retVal->stdOut);
|
||||
ILibProcessPipe_FreePipe(retVal->stdIn);
|
||||
free(retVal);
|
||||
}
|
||||
ILibMemory_Free(retVal);
|
||||
return(NULL);
|
||||
}
|
||||
if (pid == 0)
|
||||
{
|
||||
if (spawnType != ILibProcessPipe_SpawnTypes_DETACHED)
|
||||
{
|
||||
close(retVal->stdErr->mPipe_ReadEnd); //close read end of stderr pipe
|
||||
dup2(retVal->stdErr->mPipe_WriteEnd, STDERR_FILENO);
|
||||
close(retVal->stdErr->mPipe_WriteEnd);
|
||||
|
||||
}
|
||||
if (spawnType == ILibProcessPipe_SpawnTypes_TERM)
|
||||
{
|
||||
putenv("TERM=xterm");
|
||||
}
|
||||
else
|
||||
{
|
||||
if (spawnType != ILibProcessPipe_SpawnTypes_DETACHED)
|
||||
{
|
||||
close(retVal->stdIn->mPipe_WriteEnd); //close write end of stdin pipe
|
||||
close(retVal->stdOut->mPipe_ReadEnd); //close read end of stdout pipe
|
||||
@@ -745,19 +771,31 @@ ILibProcessPipe_Process ILibProcessPipe_Manager_SpawnProcessEx2(ILibProcessPipe_
|
||||
close(retVal->stdIn->mPipe_ReadEnd);
|
||||
close(retVal->stdOut->mPipe_WriteEnd);
|
||||
}
|
||||
}
|
||||
if (UID != -1)
|
||||
{
|
||||
setuid((uid_t)UID);
|
||||
}
|
||||
execv(target, parameters);
|
||||
exit(1);
|
||||
}
|
||||
if (spawnType != ILibProcessPipe_SpawnTypes_TERM)
|
||||
if (spawnType != ILibProcessPipe_SpawnTypes_TERM && spawnType != ILibProcessPipe_SpawnTypes_DETACHED)
|
||||
{
|
||||
close(retVal->stdIn->mPipe_ReadEnd);
|
||||
close(retVal->stdOut->mPipe_WriteEnd);
|
||||
}
|
||||
if (spawnType != ILibProcessPipe_SpawnTypes_DETACHED)
|
||||
{
|
||||
close(retVal->stdErr->mPipe_WriteEnd);
|
||||
}
|
||||
retVal->PID = pid;
|
||||
#endif
|
||||
return retVal;
|
||||
}
|
||||
int ILibProcessPipe_Process_IsDetached(ILibProcessPipe_Process p)
|
||||
{
|
||||
return(((ILibProcessPipe_Process_Object*)p)->stdErr == NULL && ((ILibProcessPipe_Process_Object*)p)->stdIn == NULL && ((ILibProcessPipe_Process_Object*)p)->stdOut == NULL);
|
||||
}
|
||||
void ILibProcessPipe_Pipe_SwapBuffers(ILibProcessPipe_Pipe obj, char* newBuffer, int newBufferLen, int newBufferReadOffset, int newBufferTotalBytesRead, char **oldBuffer, int *oldBufferLen, int *oldBufferReadOffset, int *oldBufferTotalBytesRead)
|
||||
{
|
||||
ILibProcessPipe_PipeObject *pipeObject = (ILibProcessPipe_PipeObject*)obj;
|
||||
@@ -1167,20 +1205,20 @@ DWORD ILibProcessPipe_Pipe_BackgroundReader(void *arg)
|
||||
{
|
||||
ILibProcessPipe_PipeObject *pipeObject = (ILibProcessPipe_PipeObject*)arg;
|
||||
DWORD bytesRead = 0;
|
||||
int consumed;
|
||||
int consumed = 0;
|
||||
|
||||
while (pipeObject->PAUSED == 0 || WaitForSingleObject(pipeObject->mPipe_Reader_ResumeEvent, INFINITE) == WAIT_OBJECT_0)
|
||||
{
|
||||
// Pipe is in ACTIVE state
|
||||
consumed = 0;
|
||||
pipeObject->PAUSED = 0;
|
||||
|
||||
while (pipeObject->readOffset != 0 && pipeObject->PAUSED == 0)
|
||||
while(consumed != 0 && pipeObject->PAUSED == 0 && (pipeObject->totalRead - pipeObject->readOffset)>0)
|
||||
{
|
||||
((ILibProcessPipe_GenericReadHandler)pipeObject->handler)(pipeObject->buffer + pipeObject->readOffset, pipeObject->totalRead - pipeObject->readOffset, &consumed, pipeObject->user1, pipeObject->user2);
|
||||
if (consumed == 0)
|
||||
{
|
||||
memmove_s(pipeObject->buffer, pipeObject->bufferSize, pipeObject->buffer + pipeObject->readOffset, pipeObject->totalRead - pipeObject->readOffset);
|
||||
pipeObject->readNewOffset = pipeObject->totalRead - pipeObject->readOffset;
|
||||
pipeObject->totalRead -= pipeObject->readOffset;
|
||||
pipeObject->readOffset = 0;
|
||||
}
|
||||
@@ -1189,6 +1227,7 @@ DWORD ILibProcessPipe_Pipe_BackgroundReader(void *arg)
|
||||
// Entire buffer consumed
|
||||
pipeObject->readOffset = 0;
|
||||
pipeObject->totalRead = 0;
|
||||
pipeObject->readNewOffset = 0;
|
||||
consumed = 0;
|
||||
}
|
||||
else
|
||||
@@ -1199,12 +1238,16 @@ DWORD ILibProcessPipe_Pipe_BackgroundReader(void *arg)
|
||||
}
|
||||
|
||||
if (pipeObject->PAUSED == 1) { continue; }
|
||||
if (!ReadFile(pipeObject->mPipe_ReadEnd, pipeObject->buffer + pipeObject->readOffset, pipeObject->bufferSize - pipeObject->readOffset, &bytesRead, NULL)) { break; }
|
||||
if (!ReadFile(pipeObject->mPipe_ReadEnd, pipeObject->buffer + pipeObject->readOffset + pipeObject->readNewOffset, pipeObject->bufferSize - pipeObject->readOffset - pipeObject->readNewOffset, &bytesRead, NULL)) { break; }
|
||||
|
||||
consumed = 0;
|
||||
pipeObject->totalRead += bytesRead;
|
||||
((ILibProcessPipe_GenericReadHandler)pipeObject->handler)(pipeObject->buffer + pipeObject->readOffset, pipeObject->totalRead - pipeObject->readOffset, &consumed, pipeObject->user1, pipeObject->user2);
|
||||
pipeObject->readOffset += consumed;
|
||||
if (consumed == 0)
|
||||
{
|
||||
pipeObject->readNewOffset = pipeObject->totalRead - pipeObject->readOffset;
|
||||
}
|
||||
}
|
||||
|
||||
if (pipeObject->brokenPipeHandler != NULL) { pipeObject->brokenPipeHandler(pipeObject); }
|
||||
@@ -1311,6 +1354,8 @@ void ILibProcessPipe_Process_UpdateUserObject(ILibProcessPipe_Process module, vo
|
||||
void ILibProcessPipe_Process_AddHandlers(ILibProcessPipe_Process module, int bufferSize, ILibProcessPipe_Process_ExitHandler exitHandler, ILibProcessPipe_Process_OutputHandler stdOut, ILibProcessPipe_Process_OutputHandler stdErr, ILibProcessPipe_Process_SendOKHandler sendOk, void *user)
|
||||
{
|
||||
ILibProcessPipe_Process_Object* j = (ILibProcessPipe_Process_Object*)module;
|
||||
if (j != NULL && ILibMemory_CanaryOK(j))
|
||||
{
|
||||
j->userObject = user;
|
||||
j->exitHandler = exitHandler;
|
||||
|
||||
@@ -1322,12 +1367,18 @@ void ILibProcessPipe_Process_AddHandlers(ILibProcessPipe_Process module, int buf
|
||||
ILibProcessPipe_WaitHandle_Add(j->parent, j->hProcess, j, &ILibProcessPipe_Process_OnExit);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
ILibTransport_DoneState ILibProcessPipe_Pipe_Write(ILibProcessPipe_Pipe po, char* buffer, int bufferLen, ILibTransport_MemoryOwnership ownership)
|
||||
{
|
||||
ILibProcessPipe_PipeObject* pipeObject = (ILibProcessPipe_PipeObject*)po;
|
||||
ILibTransport_DoneState retVal = ILibTransport_DoneState_ERROR;
|
||||
|
||||
if (pipeObject == NULL)
|
||||
{
|
||||
return(ILibTransport_DoneState_ERROR);
|
||||
}
|
||||
|
||||
if (pipeObject->WriteBuffer == NULL)
|
||||
{
|
||||
pipeObject->WriteBuffer = ILibQueue_Create();
|
||||
@@ -1391,9 +1442,15 @@ ILibTransport_DoneState ILibProcessPipe_Pipe_Write(ILibProcessPipe_Pipe po, char
|
||||
ILibTransport_DoneState ILibProcessPipe_Process_WriteStdIn(ILibProcessPipe_Process p, char* buffer, int bufferLen, ILibTransport_MemoryOwnership ownership)
|
||||
{
|
||||
ILibProcessPipe_Process_Object *j = (ILibProcessPipe_Process_Object*)p;
|
||||
|
||||
if (ILibMemory_CanaryOK(j))
|
||||
{
|
||||
return(ILibProcessPipe_Pipe_Write(j->stdIn, buffer, bufferLen, ownership));
|
||||
}
|
||||
else
|
||||
{
|
||||
return(ILibTransport_DoneState_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
void ILibProcessPipe_Pipe_ReadSink(char *buffer, int bufferLen, int* bytesConsumed, void* user1, void* user2)
|
||||
{
|
||||
@@ -1410,4 +1467,3 @@ DWORD ILibProcessPipe_Process_GetPID(ILibProcessPipe_Process p) { return(p != NU
|
||||
#else
|
||||
pid_t ILibProcessPipe_Process_GetPID(ILibProcessPipe_Process p) { return(p != NULL ? (pid_t)((ILibProcessPipe_Process_Object*)p)->PID : 0); }
|
||||
#endif
|
||||
|
||||
|
||||
@@ -39,6 +39,8 @@ typedef enum ILibProcessPipe_SpawnTypes
|
||||
ILibProcessPipe_SpawnTypes_USER = 1,
|
||||
ILibProcessPipe_SpawnTypes_WINLOGON = 2,
|
||||
ILibProcessPipe_SpawnTypes_TERM = 3,
|
||||
ILibProcessPipe_SpawnTypes_DETACHED = 4,
|
||||
ILibProcessPipe_SpawnTypes_SPECIFIED_USER = 5
|
||||
}ILibProcessPipe_SpawnTypes;
|
||||
|
||||
|
||||
@@ -66,12 +68,12 @@ void ILibProcessPipe_Pipe_AddPipeReadHandler(ILibProcessPipe_Pipe targetPipe, in
|
||||
void ILibProcessPipe_Pipe_SetBrokenPipeHandler(ILibProcessPipe_Pipe targetPipe, ILibProcessPipe_Pipe_BrokenPipeHandler handler);
|
||||
|
||||
ILibProcessPipe_Manager ILibProcessPipe_Manager_Create(void *chain);
|
||||
ILibProcessPipe_Process ILibProcessPipe_Manager_SpawnProcessEx2(ILibProcessPipe_Manager pipeManager, char* target, char* const * parameters, ILibProcessPipe_SpawnTypes spawnType, int extraMemorySize);
|
||||
int ILibProcessPipe_Process_IsDetached(ILibProcessPipe_Process p);
|
||||
ILibProcessPipe_Process ILibProcessPipe_Manager_SpawnProcessEx3(ILibProcessPipe_Manager pipeManager, char* target, char* const* parameters, ILibProcessPipe_SpawnTypes spawnType, void *sessionId, int extraMemorySize);
|
||||
#define ILibProcessPipe_Manager_SpawnProcess(pipeManager, target, parameters) ILibProcessPipe_Manager_SpawnProcessEx2(pipeManager, target, parameters, ILibProcessPipe_SpawnTypes_DEFAULT, 0)
|
||||
#define ILibProcessPipe_Manager_SpawnProcessEx(pipeManager, target, parameters, spawnType) ILibProcessPipe_Manager_SpawnProcessEx2(pipeManager, target, parameters, spawnType, 0)
|
||||
#define ILibProcessPipe_Manager_SpawnProcessEx2(pipeManager, target, parameters, spawnType, extraMemorySize) ILibProcessPipe_Manager_SpawnProcessEx3(pipeManager, target, parameters, spawnType, NULL, extraMemorySize)
|
||||
#define ILibProcessPipe_Manager_SpawnProcessWithExtraPipeMemory(pipeManager, target, parameters, memorySize) ILibProcessPipe_Manager_SpawnProcessEx2(pipeManager, target, parameters, ILibProcessPipe_SpawnTypes_DEFAULT, memorySize)
|
||||
void* ILibProcessPipe_Process_Kill(ILibProcessPipe_Process p);
|
||||
void* ILibProcessPipe_Process_KillEx(ILibProcessPipe_Process p);
|
||||
void ILibProcessPipe_Process_SoftKill(ILibProcessPipe_Process p);
|
||||
void ILibProcessPipe_Process_AddHandlers(ILibProcessPipe_Process module, int bufferSize, ILibProcessPipe_Process_ExitHandler exitHandler, ILibProcessPipe_Process_OutputHandler stdOut, ILibProcessPipe_Process_OutputHandler stdErr, ILibProcessPipe_Process_SendOKHandler sendOk, void *user);
|
||||
void ILibProcessPipe_Process_UpdateUserObject(ILibProcessPipe_Process module, void *userObj);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user