46#include "EST_socket.h"
50#include "EST_String.h"
56EST_Regex RxURL(
"\\([a-z]+\\)://?\\([^/:]+\\)\\(:\\([0-9]+\\)\\)?\\(.*\\)");
58static EST_Regex ipnum(
"[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+");
60const int default_http_port = 80;
63#define MAX_LINE_LENGTH (256)
65static int port_to_int(
const char *port)
69 if (!port || *port ==
'\0')
93 path = url.
after(
"file:");
112static int connect_to_server(
const char *
host,
int port)
119 memset(&address, 0,
sizeof(address));
121 if (
shost.matches(ipnum))
127 err(
"can't find host",
host);
130 memset(&(address.sin_addr),0,
sizeof(
struct in_addr));
131 address.sin_family=
hostentp->h_addrtype;
136 address.sin_port=
htons(port);
139 err(
"can't create socket", NIL);
141 if (connect(s, (
struct sockaddr *)&address,
sizeof(address)) < 0)
144 err(
"can't connect to host",
151static void server_send(
int s,
const char *text)
157 if ((
sent = write(s, text, n))<0)
158 err(
"error talking to server", NIL);
163static const char *server_get_line(
int s)
165 static char buffer[MAX_LINE_LENGTH+1];
172 if ((n=read(s, p, 1)) == 0)
175 err(
"error while reading from server", NIL);
176 else if (*(p++) ==
'\n')
189int fd_open_stdinout(
const char *
r_or_w)
195 else if (
r_or_w[0] ==
'w')
198 err(
"mode not understood for -",
r_or_w);
207int fd_open_file(
const char *name,
const char *
r_or_w)
214 return fd_open_stdinout(
r_or_w);
221 else if (
r_or_w[0] ==
'w')
226 else if (
r_or_w[0] ==
'a')
232 err(
"mode not understood",
r_or_w);
237 fd= open(name,
mode, 0666);
240 lseek(fd, 0, SEEK_END);
245int fd_open_http(
const char *
host,
253 port=default_http_port;
255 if ((s=connect_to_server(
host, port)) < 0)
263 char location[1024] =
"";
265 server_send(s,
"GET ");
266 server_send(s, path);
267 server_send(s,
" HTTP/1.0\n\n");
270 line= server_get_line(s);
275 err(
"HTTP error", line);
279 while((line = server_get_line(s)))
281 if (*line==
'\r' || *line ==
'\n' || *line ==
'\0')
283 else if (
sscanf(line,
"Location: %s", location) == 1)
285 cout <<
"redirect to '" << location <<
"'\n";
289 if (code == 301 || code == 302)
293 if (*location ==
'\0')
294 err(
"Redirection to no loction", NIL);
300 err(
"redirection to bad URL", location);
307 err(
"Write to HTTP url not yet implemented", NIL);
312int fd_open_ftp(
const char *
host,
325int fd_open_tcp(
const char *
host,
335 if ((s=connect_to_server(
host, port)) < 0)
338 server_send(s, text);
352int fd_open_url(
const char *
protocol,
361 && (!port || *port ==
'\0'))
362 return fd_open_file(path,
r_or_w);
364 return fd_open_ftp(
host, port_to_int(port), path,
r_or_w);
366 return fd_open_http(
host, port_to_int(port), path,
r_or_w);
368 return fd_open_tcp(
host, port_to_int(port), path,
r_or_w);
EST_String after(int pos, int len=1) const
Part after pos+len.
int matches(const char *e, int pos=0) const
Exactly match this string?
EST_String at(int from, int len=0) const
Return part at position.