1 
2 /** Small helpers for libCURL
3  *
4  * This module contains all the CURL related helpers.
5  */
6 module acme.curl_helpers;
7 
8 import etc.c.curl;
9 
10 import std.conv;
11 import std.net.curl;
12 import std.stdio;
13 import std.string;
14 import std.typecons;
15 
16 /** Compose an error msg from custom and CURL error
17  *
18  * Params:
19  *  msg - custom message
20  */
21 string getCurlError(string s, CURLcode c)
22 {
23 	import std.format;
24 	auto errorstring = curl_easy_strerror(c).to!string;
25 	auto resultstring = format( "%s\nErrorcode: %d (%s)", s, c, errorstring);
26     return resultstring;
27 }
28 
29 /* ---------------------------------------------------------------------------- */
30 
31 /** Get just the http receive headers with a given name from an URL
32 
33 	Params:
34 	  url - Url to query
35 	  headerKey - headerline to query
36 	Returns:
37 	  the value of a given header or null
38  */
39 string getResponseHeader(string url, string headerKey)
40 {
41 	string headerVal;
42 
43 	auto http = HTTP(url);
44 	http.method = HTTP.Method.head;
45 	http.onReceiveHeader =
46 		(in char[] key, in char[] value)
47 			{
48 				writeln( "Response Header : ", key, " = ", value);
49 				if (key.toLower == headerKey.toLower)
50 					headerVal = value.idup;
51 			};
52 	http.perform();
53 	return headerVal;
54 }
55 
56 /* ---------------------------------------------------------------------------- */
57 
58 /** Do some posting, filter for some headerkey
59  *
60  * Params:
61  *  url - url to pst to
62  *  postBody - data to post
63  *  rheaders - responseheader to return
64  *  nonce - pointer to nonce string, so that we can update it.
65  *
66  * Returns:
67  *   the received payload of the POST operation
68  */
69 string doPost(string url, char[] postBody, HTTP.StatusLine* status,
70 	string[string]* rheaders,
71 	string* nonce)
72 {
73 	string response;
74 	string headerVal;
75 
76 	auto http = HTTP(url);
77 	http.verbose = true;
78 	http.method = HTTP.Method.post;
79 	http.addRequestHeader("Content-Type", "application/jose+json");
80 
81 	http.onReceiveHeader =
82 		(in char[] key, in char[] value)
83 			{
84 				if (key.toLower == "replay-nonce") {
85 					*nonce = value.idup;
86 					writeln("Setting new NOnce: ", *nonce);
87 				}
88 			};
89 	http.onReceive =
90 		(ubyte[] data)
91 			{
92 				//writefln( "data: %s", to!string(data));
93 				response ~= data;
94 				return data.length;
95 			};
96 	http.postData = postBody;
97 
98 	http.perform();
99 
100 	if (status !is null) *status = http.statusLine;
101 
102 	if (rheaders !is null)
103 		*rheaders = http.responseHeaders;
104 
105 	return response;
106 }
107 
108 /* ---------------------------------------------------------------------------- */
109