1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
|
/** -*-C-*-ish
Kaya standard library
Copyright (C) 2004, 2005 Edwin Brady
This file is distributed under the terms of the GNU Lesser General
Public Licence. See COPYING for licence.
*/
module HTTP;
import Array;
import Net;
import Regex;
import Tuples;
import Strings;
public data HTTPversion = HTTP10 | HTTP11;
public Exception BadUsername = Exception("Username for basic authentication must not contain a : character.",120);
"A data type for storing URL information. The localpart must include the initial '/'. If secure is true, https will be used."
public data HTTPURL(String server, Int port, String localpart, Bool secure);
"Parse a String containing a URL into a HTTPURL"
public HTTPURL parseURL(String url) {
re = compile("^https?://([^/]+)(/.*)$",createArray(1));
matches = match(re,url);
server = matches.matches[1];
local = matches.matches[2];
secure = quickMatch("^https://",url);
if (quickMatch(":",server)) {
hdata = split(":",server);
server = hdata[0];
port = Int(hdata[1]);
} else {
if (secure) {
port = 443;
} else {
port = 80;
}
}
return HTTPURL(server,port,local,secure);
}
"Retrieve a URL by HTTP.
Give the protocol, server, path and port as a HTTPURL."
public String getURL(HTTPURL url,
[(String,String)] headers = createArray(1),
HTTPversion version = HTTP10)
{
return getURL(url.server,url.localpart,headers,url.port,version,url.secure);
}
"Retrieve a URL by HTTP.
Give the <em>server</em>, <em>path</em> and <em>port</em> separately."
public String getURL(String server, String dir,
[(String,String)] headers = createArray(1),
Int port = 80, HTTPversion version = HTTP10, Bool secure=false)
{
h = connect(TCP, server, port, secure);
case version of {
HTTP10 -> hver = "HTTP/1.0";
| HTTP11 -> hver = "HTTP/1.1";
}
send(h,"GET "+dir+" "+hver+"\nConnection: close\n");
for x in headers {
hd = x.fst;
hv = x.snd;
send(h,hd+": "+hv+"\n");
}
send(h,"Host:"+server+"\n\n");
urldata = recv(h);
closeConnection(h);
return urldata;
}
"Creates an authentication header suitable for HTTP Basic Auth"
public (String,String) basicAuthHeader(String user, String pwd) {
if (quickMatch(":",user)) {
throw(BadUsername);
}
userpass = user+":"+pwd;
upenc = base64Encode(userpass);
return ("Authorization","Basic "+upenc);
}
|