1
0

cUrlClient: Exported to Lua API.

This commit is contained in:
Mattes D 2016-08-23 13:20:43 +02:00
parent 74918ce805
commit 5ca371bb9a
7 changed files with 639 additions and 2 deletions

View File

@ -1,7 +1,7 @@
-- Network.lua
-- Defines the documentation for the cNetwork-related classes
-- Defines the documentation for the cNetwork-related classes and cUrlClient
@ -365,6 +365,178 @@ g_Server = nil
Send = { Params = "RawData, RemoteHost, RemotePort", Return = "bool", Notes = "Sends the specified raw data (string) to the specified remote host. The RemoteHost can be either a hostname or an IP address; if it is a hostname, the endpoint will queue a DNS lookup first, if it is an IP address, the send operation is executed immediately. Returns true if there was no immediate error, false on any failure. Note that the return value needn't represent whether the packet was actually sent, only if it was successfully queued." },
},
}, -- cUDPEndpoint
cUrlClient =
{
Desc =
[[
Implements high-level asynchronous access to URLs, such as downloading webpages over HTTP(S).</p>
<p>
Note that unlike other languages' URL access libraries, this class implements asynchronous requests.
This means that the functions only start a request and return immediately. The request is then
fulfilled in the background, while the server continues to run. The response is delivered back to the
plugin using callbacks. This allows the plugin to start requests and not block the server until the
response is received.</p>
<p>
The functions that make network requests are all static and have a dual interface. Either you can use
a single callback function, which gets called once the entire response is received or an error is
encountered. Or you can use a table of callback functions, each function being called whenever the
specific event happens during the request and response lifetime. See the Simple Callback and Callback
Table chapters later on this page for details and examples.</p>
<p>
All the request function also support optional parameters for further customization of the request -
the Headers parameter specifies additional HTTP headers that are to be sent (as a dictionary-table of
key -> value), the RequestBody parameter specifying the optional body of the request (used mainly for
POST and PUT requests), and an Options parameter specifying additional options specific to the protocol
used.
]],
AdditionalInfo =
{
{
Header = "Simple Callback",
Contents =
[[
When you don't need fine control for receiving the requests and are interested only in the result,
you can use the simple callback approach. Pass a single function as the Callback parameter, the
function will get called when the response is fully processed, either with the body of the response,
or with an error message:
<pre class="prettyprint lang-lua">
cUrlClient:Get(url,
function (a_Body, a_Data)
if (a_Body) then
-- Response received correctly, a_Body contains the entire response body,
-- a_Data is a dictionary-table of the response's HTTP headers
else
-- There was an error, a_Data is the error message string
end
end
)
</pre>
]],
},
{
Header = "Callback Table",
Contents =
[[
To provide complete control over the request and response handling, Cuberite allows plugins to pass
a table of callbacks as the Callback parameter. Then the respective functions are called for their
respective events during the lifetime of the request and response. This way it is possible to
process huge downloads that wouldn't fit into memory otherwise, or display detailed progress.</p>
Each callback function receives a "self" as its first parameter, this allows the functions to
access the Callback table and any of its other members, allowing the use of Lua object idiom for
the table. See <a href="https://forum.cuberite.org/thread-2062.html">this forum post</a> for an
example.
<p>
The following callback functions are used by Cuberite. Any callback that is not assigned is
silently ignored. The table may also contain other functions and other values, those are silently
ignored.</p>
<table>
<tr><th>Callback</th><th>Params</th><th>Notes</th></tr>
<tr><td>OnConnected</td><td>self, {{cTCPLink}}, RemoteIP, RemotePort</td><td>Called when the connection to the remote host is established. <i>Note that current implementation doesn't provide the {{cTCPLink}} parameter and passes nil instead.</i></td></tr>
<tr><td>OnCertificateReceived</td><td>self</td><td>Called for HTTPS URLs when the server's certificate is received. If the callback returns anything else than true, the connection is aborted. <i>Note that the current implementation doesn't provide the certificate because there is no representation for the cert in Lua.</i></td></tr>
<tr><td>OnTlsHandshakeCompleted</td><td>self</td><td>Called for HTTPS URLs when the TLS is established on the connection.</td></tr>
<tr><td>OnRequestSent</td><td>self</td><td>Called after the entire request is sent to the server.</td></tr>
<tr><td>OnStatusLine</td><td>self, HttpVersion, StatusCode, Rest</td><td>The initial line of the response has been parsed. HttpVersion is typically "HTTP/1.1", StatusCode is the numerical HTTP status code reported by the server (200 being OK), Rest is the rest of the line, usually a short message in case of an error.</td></tr>
<tr><td>OnHeader</td><td>self, Name, Value</td><td>A new HTTP response header line has been received.</td></tr>
<tr><td>OnHeadersFinished</td><td>self, AllHeaders</td><td>All HTTP response headers have been parsed. AllHeaders is a dictionary-table containing all the headers received.</td></tr>
<tr><td>OnBodyData</td><td>self, Data</td><td>A piece of the response body has been received. This callback is called repeatedly until the entire body is reported through its Data parameter.</td></tr>
<tr><td>OnBodyFinished</td><td>self</td><td>The entire response body has been reported by OnBodyData(), the response has finished.</td></tr>
<tr><td>OnError</td><td>self, ErrorMsg</td><td>Called whenever an error is detected. After this call, no other callback will get called.</td></tr>
<tr><td>OnRedirecting</td><td>self, NewUrl</td><td>Called if the server returned a valid redirection HTTP status code and a Location header, and redirection is allowed by the Options.</td></tr>
</table>
<p>
The following example is adapted from the Debuggers plugin's "download" command, it downloads the
contents of an URL into a file.
<pre class="prettyprint lang-lua">
function HandleConsoleDownload(a_Split) -- Console command handler
-- Read the params from the command:
local url = a_Split[2]
local fnam = a_Split[3]
if (not(url) or not(fnam)) then
return true, "Missing parameters. Usage: download <url> <filename>"
end
-- Define the cUrlClient callbacks
local callbacks =
{
OnStatusLine = function (self, a_HttpVersion, a_Status, a_Rest)
-- Only open the output file if the server reports a success:
if (a_Status ~= 200) then
LOG("Cannot download " .. url .. ", HTTP error code " .. a_Status)
return
end
local f, err = io.open(fnam, "wb")
if not(f) then
LOG("Cannot download " .. url .. ", error opening the file " .. fnam .. ": " .. (err or "<no message>"))
return
end
self.m_File = f
end,
OnBodyData = function (self, a_Data)
-- If the file has been opened, write the data:
if (self.m_File) then
self.m_File:write(a_Data)
end
end,
OnBodyFinished = function (self)
-- If the file has been opened, close it and report success
if (self.m_File) then
self.m_File:close()
LOG("File " .. fnam .. " has been downloaded.")
end
end,
}
-- Start the URL download:
local isSuccess, msg = cUrlClient:Get(url, callbacks)
if not(isSuccess) then
LOG("Cannot start an URL download: " .. (msg or "<no message>"))
return true
end
return true
end
</pre>
]],
},
{
Header = "Options",
Contents =
[[
The requests support the following options, specified in the optional Options table parameter:
<table>
<tr><th>Option name</th><th>Description</th></tr>
<tr><td>MaxRedirects</td><td>Maximum number of HTTP redirects that the cUrlClient will follow. If the server still reports a redirect after reaching this many redirects, the cUrlClient reports an error. May be specified as either a number or a string parsable into a number. Default: 30.</td></tr>
<tr><td>OwnCert</td><td>The client certificate to use, if requested by the server. A string containing a PEM- or DER-encoded cert is expected.</td></tr>
<tr><td>OwnPrivKey</td><td>The private key appropriate for OwnCert. A string containing a PEM- or DER-encoded private key is expected.</td></tr>
<tr><td>OwnPrivKeyPassword</td><td>The password for OwnPrivKey. If not present or empty, no password is assumed.</td></tr>
</table>
<p>
Redirection:
<ul>
<li>If a redirect is received, and redirection is allowed by MaxRedirects, the redirection is
reported via OnRedirecting() callback and the request is restarted at the redirect URL, without
reporting any of the redirect's headers nor body.</li>
<li>If a redirect is received and redirection is not allowed (maximum redirection attempts have
been reached), the OnRedirecting() callback is called with the redirect URL and then the request
terminates with an OnError() callback, without reporting the redirect's headers nor body.</li>
</ul>
]],
},
},
Functions =
{
Delete = { Params = "URL, Callbacks, [Headers], [RequestBody], [Options]", Return = "bool, [ErrMsg]", IsStatic = true, Notes = "Starts a HTTP DELETE request. Alias for Request(\"DELETE\", ...). Returns true on succes, false and error message on immediate failure (unparsable URL etc.)."},
Get = { Params = "URL, Callbacks, [Headers], [RequestBody], [Options]", Return = "bool, [ErrMsg]", IsStatic = true, Notes = "Starts a HTTP GET request. Alias for Request(\"GET\", ...). Returns true on succes, false and error message on immediate failure (unparsable URL etc.)."},
Post = { Params = "URL, Callbacks, [Headers], [RequestBody], [Options]", Return = "bool, [ErrMsg]", IsStatic = true, Notes = "Starts a HTTP POST request. Alias for Request(\"POST\", ...). Returns true on succes, false and error message on immediate failure (unparsable URL etc.)."},
Put = { Params = "URL, Callbacks, [Headers], [RequestBody], [Options]", Return = "bool, [ErrMsg]", IsStatic = true, Notes = "Starts a HTTP PUT request. Alias for Request(\"PUT\", ...). Returns true on succes, false and error message on immediate failure (unparsable URL etc.)."},
Request = { Params = "Method, URL, Callbacks, [Headers], [RequestBody], [Options]", Return = "bool, [ErrMsg]", IsStatic = true, Notes = "Starts a request with the specified Method. Returns true on succes, false and error message on immediate failure (unparsable URL etc.)."},
},
}, -- cUrlClient
}

View File

@ -61,7 +61,7 @@ function Initialize(a_Plugin)
-- TestUUIDFromName()
-- TestRankMgr()
TestFileExt()
TestFileLastMod()
-- TestFileLastMod()
TestPluginInterface()
local LastSelfMod = cFile:GetLastModificationTime(a_Plugin:GetLocalFolder() .. "/Debuggers.lua")
@ -2135,6 +2135,35 @@ end
function HandleConsoleTestUrlClient(a_Split, a_EntireCmd)
local url = a_Split[2] or "https://github.com"
local isSuccess, msg = cUrlClient:Get(url,
function (a_Body, a_SecondParam)
if not(a_Body) then
-- An error has occurred, a_SecondParam is the error message
LOG("Error while retrieving URL \"" .. url .. "\": " .. (a_SecondParam or "<no message>"))
return
end
-- Body received, a_SecondParam is the HTTP headers dictionary-table
assert(type(a_Body) == "string")
assert(type(a_SecondParam) == "table")
LOG("URL body received, length is " .. string.len(a_Body) .. " bytes and there are these headers:")
for k, v in pairs(a_SecondParam) do
LOG(" \"" .. k .. "\": \"" .. v .. "\"")
end
LOG("(headers list finished)")
end
)
if not(isSuccess) then
LOG("cUrlClient request failed: " .. (msg or "<no message>"))
end
return true
end
function HandleConsoleTestUrlParser(a_Split, a_EntireCmd)
LOG("Testing cUrlParser...")
local UrlsToTest =
@ -2262,6 +2291,56 @@ end
function HandleConsoleDownload(a_Split)
-- Check params:
local url = a_Split[2]
local fnam = a_Split[3]
if (not(url) or not(fnam)) then
return true, "Missing parameters. Usage: download <url> <filename>"
end
local callbacks =
{
OnStatusLine = function (self, a_HttpVersion, a_Status, a_Rest)
if (a_Status ~= 200) then
LOG("Cannot download " .. url .. ", HTTP error code " .. a_Status)
return
end
local f, err = io.open(fnam, "wb")
if not(f) then
LOG("Cannot download " .. url .. ", error opening the file " .. fnam .. ": " .. (err or "<no message>"))
return
end
self.m_File = f
end,
OnBodyData = function (self, a_Data)
if (self.m_File) then
self.m_File:write(a_Data)
end
end,
OnBodyFinished = function (self)
if (self.m_File) then
self.m_File:close()
LOG("File " .. fnam .. " has been downloaded.")
end
end,
}
local isSuccess, msg = cUrlClient:Get(url, callbacks)
if not(isSuccess) then
LOG("Cannot start an URL download: " .. (msg or "<no message>"))
return true
end
return true
end
function HandleBlkCmd(a_Split, a_Player)
-- Gets info about the block the player is looking at.
local World = a_Player:GetWorld();

View File

@ -224,6 +224,12 @@ g_PluginInfo =
HelpString = "Performs cBoundingBox API tests",
},
["download"] =
{
Handler = HandleConsoleDownload,
HelpString = "Downloads a file from a specified URL",
},
["hash"] =
{
Handler = HandleConsoleHash,
@ -278,6 +284,12 @@ g_PluginInfo =
HelpString = "Tests the cLineBlockTracer",
},
["testurlclient"] =
{
Handler = HandleConsoleTestUrlClient,
HelpString = "Tests the cUrlClient",
},
["testurlparser"] =
{
Handler = HandleConsoleTestUrlParser,

View File

@ -2139,6 +2139,17 @@ cLuaState * cLuaState::QueryCanonLuaState(void)
void cLuaState::LogApiCallParamFailure(const char * a_FnName, const char * a_ParamNames)
{
LOGWARNING("%s: Cannot read params: %s, bailing out.", a_FnName, a_ParamNames);
LogStackTrace();
LogStackValues("Values on the stack");
}
int cLuaState::ReportFnCallErrors(lua_State * a_LuaState)
{
LOGWARNING("LUA: %s", lua_tostring(a_LuaState, -1));

View File

@ -301,6 +301,26 @@ public:
return cLuaState(m_Ref.GetLuaState()).CallTableFn(m_Ref, a_FnName, std::forward<Args>(args)...);
}
/** Calls the Lua function stored under the specified name in the referenced table, if still available.
A "self" parameter is injected in front of all the given parameters and is set to the callback table.
Returns true if callback has been called.
Returns false if the Lua state isn't valid anymore, or the function doesn't exist. */
template <typename... Args>
bool CallTableFnWithSelf(const char * a_FnName, Args &&... args)
{
auto cs = m_CS;
if (cs == nullptr)
{
return false;
}
cCSLock Lock(*cs);
if (!m_Ref.IsValid())
{
return false;
}
return cLuaState(m_Ref.GetLuaState()).CallTableFn(m_Ref, a_FnName, m_Ref, std::forward<Args>(args)...);
}
/** Set the contained reference to the table in the specified Lua state's stack position.
If another table has been previously contained, it is unreferenced first.
Returns true on success, false on failure (not a table at the specified stack pos). */
@ -741,6 +761,10 @@ public:
Returns nullptr if the canon Lua state cannot be queried. */
cLuaState * QueryCanonLuaState(void);
/** Outputs to log a warning about API call being unable to read its parameters from the stack,
logs the stack trace and stack values. */
void LogApiCallParamFailure(const char * a_FnName, const char * a_ParamNames);
protected:
cCriticalSection m_CS;

View File

@ -2,6 +2,7 @@
// ManualBindings_Network.cpp
// Implements the cNetwork-related API bindings for Lua
// Also implements the cUrlClient bindings
#include "Globals.h"
#include "LuaTCPLink.h"
@ -12,6 +13,7 @@
#include "LuaNameLookup.h"
#include "LuaServerHandle.h"
#include "LuaUDPEndpoint.h"
#include "../HTTP/UrlClient.h"
@ -903,6 +905,329 @@ static int tolua_cUDPEndpoint_Send(lua_State * L)
/** Used when the cUrlClient Lua request wants all the callbacks.
Maps each callback onto a Lua function callback in the callback table. */
class cFullUrlClientCallbacks:
public cUrlClient::cCallbacks
{
public:
/** Creates a new instance bound to the specified table of callbacks. */
cFullUrlClientCallbacks(cLuaState::cTableRefPtr && a_Callbacks):
m_Callbacks(std::move(a_Callbacks))
{
}
// cUrlClient::cCallbacks overrides:
virtual void OnConnected(cTCPLink & a_Link) override
{
// TODO: Cannot push a cTCPLink to Lua, need to translate via cLuaTCPLink
m_Callbacks->CallTableFnWithSelf("OnConnected", cLuaState::Nil, a_Link.GetRemoteIP(), a_Link.GetRemotePort());
}
virtual bool OnCertificateReceived() override
{
// TODO: The received cert needs proper type specification from the underlying cUrlClient framework and in the Lua engine as well
bool res = true;
m_Callbacks->CallTableFnWithSelf("OnCertificateReceived", cLuaState::Return, res);
return res;
}
virtual void OnTlsHandshakeCompleted() override
{
m_Callbacks->CallTableFnWithSelf("OnTlsHandshakeCompleted");
}
virtual void OnRequestSent() override
{
m_Callbacks->CallTableFnWithSelf("OnRequestSent");
}
virtual void OnStatusLine(const AString & a_HttpVersion, int a_StatusCode, const AString & a_Rest) override
{
m_Callbacks->CallTableFnWithSelf("OnStatusLine", a_HttpVersion, a_StatusCode, a_Rest);
}
virtual void OnHeader(const AString & a_Key, const AString & a_Value) override
{
m_Callbacks->CallTableFnWithSelf("OnHeader", a_Key, a_Value);
m_Headers[a_Key] = a_Value;
}
virtual void OnHeadersFinished() override
{
m_Callbacks->CallTableFnWithSelf("OnHeadersFinished", m_Headers);
}
virtual void OnBodyData(const void * a_Data, size_t a_Size) override
{
m_Callbacks->CallTableFnWithSelf("OnBodyData", AString(reinterpret_cast<const char *>(a_Data), a_Size));
}
virtual void OnBodyFinished() override
{
m_Callbacks->CallTableFnWithSelf("OnBodyFinished");
}
virtual void OnError(const AString & a_ErrorMsg) override
{
m_Callbacks->CallTableFnWithSelf("OnError", a_ErrorMsg);
}
virtual void OnRedirecting(const AString & a_NewLocation) override
{
m_Callbacks->CallTableFnWithSelf("OnRedirecting", a_NewLocation);
}
protected:
/** The Lua table containing the callbacks. */
cLuaState::cTableRefPtr m_Callbacks;
/** Accumulator for all the headers to be reported in the OnHeadersFinished() callback. */
AStringMap m_Headers;
};
/** Used when the cUrlClient Lua request has just a single callback.
The callback is used to report the entire body at once, together with the HTTP headers, or to report an error:
callback("BodyContents", {headers})
callback(nil, "ErrorMessage")
Accumulates the body contents into a single string until the body is finished.
Accumulates all HTTP headers into an AStringMap. */
class cSimpleUrlClientCallbacks:
public cUrlClient::cCallbacks
{
public:
/** Creates a new instance that uses the specified callback to report when request finishes. */
cSimpleUrlClientCallbacks(cLuaState::cCallbackPtr && a_Callback):
m_Callback(std::move(a_Callback))
{
}
virtual void OnHeader(const AString & a_Key, const AString & a_Value) override
{
m_Headers[a_Key] = a_Value;
}
virtual void OnBodyData(const void * a_Data, size_t a_Size) override
{
m_ResponseBody.append(reinterpret_cast<const char *>(a_Data), a_Size);
}
virtual void OnBodyFinished() override
{
m_Callback->Call(m_ResponseBody, m_Headers);
}
virtual void OnError(const AString & a_ErrorMsg) override
{
m_Callback->Call(cLuaState::Nil, a_ErrorMsg);
}
protected:
/** The callback to call when the request finishes. */
cLuaState::cCallbackPtr m_Callback;
/** The accumulator for the partial body data, so that OnBodyFinished() can send the entire thing at once. */
AString m_ResponseBody;
/** Accumulator for all the headers to be reported in the combined callback. */
AStringMap m_Headers;
};
/** Common code shared among the cUrlClient request methods.
a_Method is the method name to be used in the request.
a_UrlStackIdx is the position on the Lua stack of the Url parameter. */
static int tolua_cUrlClient_Request_Common(lua_State * a_LuaState, const AString & a_Method, int a_UrlStackIdx)
{
// Check params:
cLuaState L(a_LuaState);
if (!L.CheckParamString(a_UrlStackIdx))
{
return 0;
}
// Read params:
AString url, requestBody;
AStringMap headers, options;
cLuaState::cTableRefPtr callbacks;
cLuaState::cCallbackPtr onCompleteBodyCallback;
if (!L.GetStackValues(a_UrlStackIdx, url))
{
L.LogApiCallParamFailure("cUrlClient:Request()", Printf("URL (%d)", a_UrlStackIdx).c_str());
L.Push(false);
L.Push("Invalid params");
return 2;
}
cUrlClient::cCallbacksPtr urlClientCallbacks;
if (lua_istable(L, a_UrlStackIdx + 1))
{
if (!L.GetStackValue(a_UrlStackIdx + 1, callbacks))
{
L.LogApiCallParamFailure("cUrlClient:Request()", Printf("CallbacksTable (%d)", a_UrlStackIdx + 1).c_str());
L.Push(false);
L.Push("Invalid Callbacks param");
return 2;
}
urlClientCallbacks = cpp14::make_unique<cFullUrlClientCallbacks>(std::move(callbacks));
}
else if (lua_isfunction(L, a_UrlStackIdx + 1))
{
if (!L.GetStackValue(a_UrlStackIdx + 1, onCompleteBodyCallback))
{
L.LogApiCallParamFailure("cUrlClient:Request()", Printf("CallbacksFn (%d)", a_UrlStackIdx + 1).c_str());
L.Push(false);
L.Push("Invalid OnCompleteBodyCallback param");
return 2;
}
urlClientCallbacks = cpp14::make_unique<cSimpleUrlClientCallbacks>(std::move(onCompleteBodyCallback));
}
else
{
L.LogApiCallParamFailure("cUrlClient:Request()", Printf("Callbacks (%d)", a_UrlStackIdx + 1).c_str());
L.Push(false);
L.Push("Invalid OnCompleteBodyCallback param");
return 2;
}
if (!L.GetStackValues(a_UrlStackIdx + 2, cLuaState::cOptionalParam<AStringMap>(headers), cLuaState::cOptionalParam<AString>(requestBody), cLuaState::cOptionalParam<AStringMap>(options)))
{
L.LogApiCallParamFailure("cUrlClient:Request()", Printf("Header, Body or Options (%d, %d, %d)", a_UrlStackIdx + 2, a_UrlStackIdx + 3, a_UrlStackIdx + 4).c_str());
L.Push(false);
L.Push("Invalid params");
return 2;
}
// Make the request:
auto res = cUrlClient::Request(a_Method, url, std::move(urlClientCallbacks), std::move(headers), std::move(requestBody), std::move(options));
if (!res.first)
{
L.Push(false);
L.Push(res.second);
return 2;
}
L.Push(true);
return 1;
}
/** Implements cUrlClient:Get() using cUrlClient::Request(). */
static int tolua_cUrlClient_Delete(lua_State * a_LuaState)
{
/* Function signatures:
cUrlClient:Delete(URL, {CallbacksFnTable}, [{HeadersMapTable}], [RequestBody], [{OptionsMapTable}]) -> true / false + string
cUrlClient:Delete(URL, OnCompleteBodyCallback, [{HeadersMapTable}], [RequestBody], [{OptionsMapTable}]) -> true / false + string
*/
return tolua_cUrlClient_Request_Common(a_LuaState, "DELETE", 2);
}
/** Implements cUrlClient:Get() using cUrlClient::Request(). */
static int tolua_cUrlClient_Get(lua_State * a_LuaState)
{
/* Function signatures:
cUrlClient:Get(URL, {CallbacksFnTable}, [{HeadersMapTable}], [RequestBody], [{OptionsMapTable}]) -> true / false + string
cUrlClient:Get(URL, OnCompleteBodyCallback, [{HeadersMapTable}], [RequestBody], [{OptionsMapTable}]) -> true / false + string
*/
return tolua_cUrlClient_Request_Common(a_LuaState, "GET", 2);
}
/** Implements cUrlClient:Post() using cUrlClient::Request(). */
static int tolua_cUrlClient_Post(lua_State * a_LuaState)
{
/* Function signatures:
cUrlClient:Post(URL, {CallbacksFnTable}, [{HeadersMapTable}], [RequestBody], [{OptionsMapTable}]) -> true / false + string
cUrlClient:Post(URL, OnCompleteBodyCallback, [{HeadersMapTable}], [RequestBody], [{OptionsMapTable}]) -> true / false + string
*/
return tolua_cUrlClient_Request_Common(a_LuaState, "POST", 2);
}
/** Implements cUrlClient:Put() using cUrlClient::Request(). */
static int tolua_cUrlClient_Put(lua_State * a_LuaState)
{
/* Function signatures:
cUrlClient:Put(URL, {CallbacksFnTable}, [{HeadersMapTable}], [RequestBody], [{OptionsMapTable}]) -> true / false + string
cUrlClient:Put(URL, OnCompleteBodyCallback, [{HeadersMapTable}], [RequestBody], [{OptionsMapTable}]) -> true / false + string
*/
return tolua_cUrlClient_Request_Common(a_LuaState, "PUT", 2);
}
/** Binds cUrlClient::Request(). */
static int tolua_cUrlClient_Request(lua_State * a_LuaState)
{
/* Function signatures:
cUrlClient:Request(Method, URL, {CallbacksFnTable}, [{HeadersMapTable}], [RequestBody], [{OptionsMapTable}]) -> true / false + string
cUrlClient:Request(Method, URL, OnCompleteBodyCallback, [{HeadersMapTable}], [RequestBody], [{OptionsMapTable}]) -> true / false + string
*/
// Check that the Method param is a string:
cLuaState L(a_LuaState);
if (!L.CheckParamString(2))
{
return 0;
}
// Redirect the rest to the common code:
AString method;
if (!L.GetStackValue(2, method))
{
L.LogApiCallParamFailure("cUrlClient:Request", "Method (2)");
L.Push(cLuaState::Nil);
L.Push("Invalid params");
return 2;
}
return tolua_cUrlClient_Request_Common(a_LuaState, method, 3);
}
////////////////////////////////////////////////////////////////////////////////
// Register the bindings:
@ -913,10 +1238,12 @@ void cManualBindings::BindNetwork(lua_State * tolua_S)
tolua_usertype(tolua_S, "cServerHandle");
tolua_usertype(tolua_S, "cTCPLink");
tolua_usertype(tolua_S, "cUDPEndpoint");
tolua_usertype(tolua_S, "cUrlClient");
tolua_cclass(tolua_S, "cNetwork", "cNetwork", "", nullptr);
tolua_cclass(tolua_S, "cServerHandle", "cServerHandle", "", tolua_collect_cServerHandle);
tolua_cclass(tolua_S, "cTCPLink", "cTCPLink", "", nullptr);
tolua_cclass(tolua_S, "cUDPEndpoint", "cUDPEndpoint", "", tolua_collect_cUDPEndpoint);
tolua_cclass(tolua_S, "cUrlClient", "cUrlClient", "", nullptr);
// Fill in the functions (alpha-sorted):
tolua_beginmodule(tolua_S, "cNetwork");
@ -953,6 +1280,13 @@ void cManualBindings::BindNetwork(lua_State * tolua_S)
tolua_function(tolua_S, "Send", tolua_cUDPEndpoint_Send);
tolua_endmodule(tolua_S);
tolua_beginmodule(tolua_S, "cUrlClient");
tolua_function(tolua_S, "Delete", tolua_cUrlClient_Delete);
tolua_function(tolua_S, "Get", tolua_cUrlClient_Get);
tolua_function(tolua_S, "Post", tolua_cUrlClient_Post);
tolua_function(tolua_S, "Put", tolua_cUrlClient_Put);
tolua_function(tolua_S, "Request", tolua_cUrlClient_Request);
tolua_endmodule(tolua_S);
}

View File

@ -322,6 +322,11 @@ void cTCPLinkImpl::EventCallback(bufferevent * a_BufferEvent, short a_What, void
{
ASSERT(a_Self != nullptr);
cTCPLinkImplPtr Self = static_cast<cTCPLinkImpl *>(a_Self)->m_Self;
if (Self == nullptr)
{
// The link has already been freed
return;
}
// If an error is reported, call the error callback:
if (a_What & BEV_EVENT_ERROR)