Autogenerate Stub code in C++ to access a webservice? - c++

I'm chancing my arm with this question.
I'm looking for a tool which will avoid doing a lot of coding by autogenerating much of the code to access a webservice.
I'm trying to help out someone who uses a 4GL system which doesn't support webservices. However they can access a win32 dll - which looks like being the easiest solution. All they need to do is occasionally call a function on a web service and get a result back.
Its been a loooong time since I wrote any C++ and my attempts at doing this have just exposed how rusty I am.
I've played around with the gsoap2 toolkit and MS's svcutil.exe tool for auto generating code.
They do what they are supposed to do but, unlike the add reference tool in visual studio with vb.net or c#.net, these toolkits don't generate a stub access class that I managed to find.
Instead they generate individual function calls for each method and you have to pass them httpcontexts and a whole load of other stuff - something I don't really want to have to learn how to do for a one off.
What I want to do is mechanical:
Take the wsdl definition
AutoGenerate the Webservice access code (done - gsoap2)
Write/generate a small stub to open the webservice and authenticate using basic authentication and to return an instance of the webservice instance class.
publish as a dll
The idea being to have a single dll with a single function like
getws(username, password, url)
which will return an object which exposes the methods of the webservices - a stub, nothing clever.
I know I'm clutching at straws here but does anyone know of a tool/way to avoid all the mechanical work and to end up with a simple class which I can modify to add authentication.
The webservice has around 30 methods - and I have to expose them all, each has a collection of parameters. Writing a stub class to call the functions generated by gsoap2 would be a lot of typing and a nightmare to get to work/debug. Theres got to be a better way.
What I want to do is the equivalent of the .net code below - VS autogenerates the WS code. All I have to do is expose it in my class.
Private Shared oWs As WS.publicws = Nothing
Public Shared Function GetWS(ByVal Username As String, ByVal password As String, ByVal URL As String) As WS.publicws
Dim oBinding As New ServiceModel.BasicHttpBinding
If Not oWs Is Nothing Then Return oWs
Dim oEndPoint As New ServiceModel.EndpointAddress(URL)
oBinding.Security.Mode = ServiceModel.BasicHttpSecurityMode.TransportCredentialOnly
oBinding.Security.Transport.Realm = ServiceModel.HttpClientCredentialType.Basic
oWS = New WS.publicws (oBinding, oEndPoint)
oWS.ClientCredentials.UserName.UserName = username
oWS.ClientCredentials.UserName.Password = password
Using scope = New ServiceModel.OperationContextScope(oWs.InnerChannel)
ServiceModel.OperationContext.Current.OutgoingMessageProperties(System.ServiceModel.Channels.HttpRequestMessageProperty.Name) = httpRequestProperty
End Using
Return oWs
End Function

Related

Access method's parameter with dll injection

I have a 64bit process, I figured out one of its statically linked library methods.
Source of this method:
int SSL_connect(SSL *s)
{
if (s->handshake_func == 0)
/* Not properly initialized yet */
SSL_set_connect_state(s);
return (s->method->ssl_connect(s));
}
Actual assembly image: click here.
What I want to do is using dll injection in order to access SSL parameter. I'm using x64dbg + ScyllaHide plugin to inject dlls, so any custom injection tools shouldn't be needed. I successfully injected a simple dll into this process, so I think it's enough for this case.
Is there any chance to access the variable from here without any modification of assembly?
Could anyone throw me some bone, please? (I don't ask for code, I just need some hint as I'm rather a newbie to C++ and dll injection world than an expert).
If you can find out the address of the SSL_connect function you can detour it. This means that you can write a JMP instruction at the begin of the method to your patched-method.
If your jumped-to method has the same calling convention and signature you can simply access SSL* and do what you want with it afterwards you can jump back...
To let the jump back work you would need to restore the org code or create a copy of the org method...
Another way would be a Hardware-Break-Point: read for example here.

How can I create a JSON webservice to store and retrieve data from a simple properties file?

How can I create a Java or Javascript JSON webservice to retrieve data from a simple properties file? My intention is to uses this as a global property storage for a Jenkins instance that runs many Unit tests. The master property file also needs to be capable of being manually edited and stored in source control.
I am just wondering what method people would recommend that would be the easiest for a junior level programmer like me. I need read capability at miniumum but, and if its not too hard, write capability also. Therefore, that means it is not required to be REST.
If something like this already exists in Java or Groovy, a link to that resource would be appreciated. I am a SoapUI expert but I am unsure if a mock service could do this sort of thing.
I found something like this in Ruby but I could not get it to work as I am not a Ruby programmer at all.
There are a multitude of Java REST frameworks, but I'm most familiar with Jersey so here's a Groovy script that gives a simple read capability to a properties file.
#Grapes([
#Grab(group='org.glassfish.jersey.containers', module='jersey-container-grizzly2-http', version='2.0'),
#Grab(group='org.glassfish.jersey.core', module='jersey-server', version='2.0'),
#Grab(group='org.glassfish.jersey.media', module='jersey-media-json-jackson', version='2.0')
])
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory
import org.glassfish.jersey.jackson.JacksonFeature
import javax.ws.rs.GET
import javax.ws.rs.Path
import javax.ws.rs.Produces
#Path("properties")
class PropertiesResource {
#GET
#Produces("application/json")
Properties get() {
new File("test.properties").withReader { Reader reader ->
Properties p = new Properties()
p.load(reader)
return p
}
}
}
def rc = new org.glassfish.jersey.server.ResourceConfig(PropertiesResource, JacksonFeature);
GrizzlyHttpServerFactory.createHttpServer('http://localhost:8080/'.toURI(), rc).start()
System.console().readLine("Press any key to exit...")
Unfortunately, since Jersey uses the 3.1 version of the asm library, there are conflicts with Groovy's 4.0 version of asm unless you run the script using the groovy-all embeddable jar (it won't work by just calling groovy on the command-line and passing the script). I also had to supply an Apache Ivy dependency. (Hopefully the Groovy team will resolve these in the next release--the asm one in particular has caused me grief in the past.) So you can call it like this (supply the full paths to the classpath jars):
java -cp ivy-2.2.0.jar:groovy-all-2.1.6.jar groovy.lang.GroovyShell restProperties.groovy
All you have to do is create a properties file named test.properties, then copy the above script into a file named restProperties.groovy, then run via the above command line. Then you can run the following in Unix to try it out.
curl http://localhost:8080/properties
And it will return a JSON map of your properties file.

Getting ColdFusion-Called Web Service to Work with JavaLoader-Loaded Objects

Is it possible to use JavaLoader to get objects returned by CF-called web services, and JavaLoader-loaded objects to be the same classpath context? I mean, without a lot of difficulty?
// get a web service
ws = createObject("webservice", local.lms.wsurl);
// user created by coldfusion
user = ws.GenerateUserObject();
/* user status created by java loader.
** this api provider requires that you move the stubs
** (generated when hitting the wsdl from CF for the first time)
** to the classpath.
** this is one of the stubs/classes that gets called from that.
*/
UserStatus = javaLoader.create("com.geolearning.geonext.webservices.Status");
// set user status: classpath context clash
user.setStatus(UserStatus.Active);
Error:
Detail: Either there are no methods with the specified method name and
argument types or the setStatus method is overloaded with argument
types that ColdFusion cannot decipher reliably. ColdFusion found 0
methods that match the provided arguments. If this is a Java object
and you verified that the method exists, use the javacast function to
reduce ambiguity.
Message: The setStatus method was not found.
MethodName setStatus
Even though the call, on the surface, matches a method signature on user--setStatus(com.geolearning.geonext.webservices.Status)--the class is on a different classpath context. That's why I get the error above.
Jamie and I worked on this off-line and came up with a creative solution :)
(Apologies for the long answer, but I thought a bit of an explanation was warranted for those who find class loaders as confusing as I do. If you are not interested in the "why" aspect, feel free to jump to the end).
Issue:
The problem is definitely due to multiple class loaders/paths. Apparently CF web services use a dynamic URLClassLoader (just like the JavaLoader). That is how it can load the generated web service classes on-the-fly, even though those classes are not in the core CF "class path".
(Based on my limited understanding...) Class loaders follow a hierarchy. When multiple class loaders are involved, they must observe certain rules or they will not play well together. One of the rules is that child class loaders can only "see" objects loaded by an ancestor (parent, grandparent, etcetera). They cannot see classes loaded by a sibling.
If you examine the object created by the JavaLoader, and the other by createObject, they are indeed siblings ie both children of the CF bootstrap class loader. So the one will not recognize objects loaded by the other, which would explain why the setStatus call failed.
Given that a child can see objects loaded by a parent, the obvious solution is to change how the objects are constructed. Structure the calls so that one of the class loaders ends up as a parent of the other. Curiously that turned out to be trickier than it sounded. I could not find a way to make that happen, despite trying a number of combinations (including using the switchThreadContextClassLoader method).
Solution:
Finally I had a crazy thought: do not load any jars. Just use the web service's loader as the parentClassLoader. It already has everything it needs in its own individual "class path":
// display class path of web service class loader
dynamicLoader = webService.getClass().getClassLoader();
dynamicClassPath = dynamicLoader.getURLS();
WriteDump("CLASS PATH: "& dynamicClassPath[1].toString() );
The JavaLoader will automatically delegate calls for classes it cannot find to parentClassLoader - and bingo - everything works. No more more class loader conflict.
webService = createObject("webservice", webserviceURL, webserviceArgs);
javaLoader = createObject("component", "javaloader.JavaLoader").init(
loadPaths = [] // nothing
, parentClassLoader=webService.getClass().getClassLoader()
);
user = webService.GenerateUserObject();
userStatus = javaLoader.create("com.geolearning.geonext.webservices.Status");
user.setStatus(userStatus.Active);
WriteDump(var=user.getStatus(), label="SUCCESS: user.getStatus()");

WinRT and missing Web API models for Amazon API access

I was working with porting the sample from the link below to a Windows 8 Metro styled app
http://aws.amazon.com/code/Product-Advertising-API/2480
Looks like many features from the web model are removed (or moved) in WinRT:
HttpUtility.UrlEncode
HttpUtility.UrlDecode
HMAC / HMACSHA256
to name a few. Are there alternatives to these on WInRT? I looked online and there's very little insight.
Theres source code for URLDecode here, and looks like Uri.EscapeDataString can be used for Encode.
http://www.koders.com/csharp/fid1A50096D8FA38302680B0EEDAC5B1CE1AEA855D0.aspx?s=%22Lawrence+Pit%22
copy the source code over, change the GetChars function to this
static char [] GetChars (MemoryStream b, Encoding e)
{
return e.GetChars (b.ToArray(), 0, (int) b.Length);
}
I had to use the code snippet from here to properly hash encrypt the string
http://channel9.msdn.com/Forums/TechOff/Porting-to-WinRT/4df7586e1ef5400682eda00f0143b610
Use methods from the WebUtility class instead:
System.Net.WebUtility.UrlEncode(string);
System.Net.WebUtility.UrlDecode(string);

C++\IronPython integration example code?

I'm looking for a simple example code for C++\IronPython integration, i.e. embedding python code inside a C++, or better yet, Visual C++ program.
The example code should include: how to share objects between the languages, how to call functions\methods back and forth etc...
Also, an explicit setup procedure would help too. (How to include the Python runtime dll in Visual Studio etc...)
I've found a nice example for C#\IronPython here, but couldn't find C++\IronPython example code.
UPDATE - I've written a more generic example (plus a link to a zip file containing the entire VS2008 project) as entry on my blog here.
Sorry, I am so late to the game, but here is how I have integrated IronPython into a C++/cli app in Visual Studio 2008 - .net 3.5. (actually mixed mode app with C/C++)
I write add-ons for a map making applicaiton written in Assembly. The API is exposed so that C/C++ add-ons can be written. I mix C/C++ with C++/cli. Some of the elements from this example are from the API (such as XPCALL and CmdEnd() - please just ignore them)
///////////////////////////////////////////////////////////////////////
void XPCALL PythonCmd2(int Result, int Result1, int Result2)
{
if(Result==X_OK)
{
try
{
String^ filename = gcnew String(txtFileName);
String^ path = Assembly::GetExecutingAssembly()->Location;
ScriptEngine^ engine = Python::CreateEngine();
ScriptScope^ scope = engine->CreateScope();
ScriptSource^ source = engine->CreateScriptSourceFromFile(String::Concat(Path::GetDirectoryName(path), "\\scripts\\", filename + ".py"));
scope->SetVariable("DrawingList", DynamicHelpers::GetPythonTypeFromType(AddIn::DrawingList::typeid));
scope->SetVariable("DrawingElement", DynamicHelpers::GetPythonTypeFromType(AddIn::DrawingElement::typeid));
scope->SetVariable("DrawingPath", DynamicHelpers::GetPythonTypeFromType(AddIn::DrawingPath::typeid));
scope->SetVariable("Node", DynamicHelpers::GetPythonTypeFromType(AddIn::Node::typeid));
source->Execute(scope);
}
catch(Exception ^e)
{
Console::WriteLine(e->ToString());
CmdEnd();
}
}
else
{
CmdEnd();
}
}
///////////////////////////////////////////////////////////////////////////////
As you can see, I expose to IronPython some objects (DrawingList, DrawingElement, DrawingPath & Node). These objects are C++/cli objects that I created to expose "things" to IronPython.
When the C++/cli source->Execute(scope) line is called, the only python line
to run is the DrawingList.RequestData.
RequestData takes a delegate and a data type.
When the C++/cli code is done, it calls the delegate pointing to the
function "diamond"
In the function diamond it retrieves the requested data with the call to
DrawingList.RequestedValue() The call to DrawingList.AddElement(dp) adds the
new element to the Applications visual Database.
And lastly the call to DrawingList.EndCommand() tells the FastCAD engine to
clean up and end the running of the plugin.
import clr
def diamond(Result1, Result2, Result3):
if(Result1 == 0):
dp = DrawingPath()
dp.drawingStuff.EntityColor = 2
dp.drawingStuff.SecondEntityColor = 2
n = DrawingList.RequestedValue()
dp.Nodes.Add(Node(n.X-50,n.Y+25))
dp.Nodes.Add(Node(n.X-25,n.Y+50))
dp.Nodes.Add(Node(n.X+25,n.Y+50))
dp.Nodes.Add(Node(n.X+50,n.Y+25))
dp.Nodes.Add(Node(n.X,n.Y-40))
DrawingList.AddElement(dp)
DrawingList.EndCommand()
DrawingList.RequestData(diamond, DrawingList.RequestType.PointType)
I hope this is what you were looking for.
If you don't need .NET functionality, you could rely on embedding Python instead of IronPython. See Python's documentation on Embedding Python in Another Application for more info and an example. If you don't mind being dependent on BOOST, you could try out its Python integration library.