added support for POST method and alternate ports (part of patch 649438)
[wxWidgets.git] / src / common / http.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: http.cpp
3 // Purpose: HTTP protocol
4 // Author: Guilhem Lavaux
5 // Modified by:
6 // Created: August 1997
7 // RCS-ID: $Id$
8 // Copyright: (c) 1997, 1998 Guilhem Lavaux
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 #ifdef __GNUG__
13 #pragma implementation "http.h"
14 #endif
15
16 // For compilers that support precompilation, includes "wx.h".
17 #include "wx/wxprec.h"
18
19 #ifdef __BORLANDC__
20 #pragma hdrstop
21 #endif
22
23 #if wxUSE_PROTOCOL_HTTP
24
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include "wx/string.h"
28 #include "wx/tokenzr.h"
29 #include "wx/socket.h"
30 #include "wx/protocol/protocol.h"
31 #include "wx/url.h"
32 #include "wx/protocol/http.h"
33 #include "wx/sckstrm.h"
34
35 IMPLEMENT_DYNAMIC_CLASS(wxHTTP, wxProtocol)
36 IMPLEMENT_PROTOCOL(wxHTTP, wxT("http"), wxT("80"), TRUE)
37
38 #define HTTP_BSIZE 2048
39
40 wxHTTP::wxHTTP()
41 : wxProtocol()
42 {
43 m_addr = NULL;
44 m_read = FALSE;
45 m_proxy_mode = FALSE;
46 m_post_buf = wxEmptyString;
47
48 SetNotify(wxSOCKET_LOST_FLAG);
49 }
50
51 wxHTTP::~wxHTTP()
52 {
53 ClearHeaders();
54
55 delete m_addr;
56 }
57
58 void wxHTTP::ClearHeaders()
59 {
60 m_headers.clear();
61 }
62
63 wxString wxHTTP::GetContentType()
64 {
65 return GetHeader(wxT("Content-Type"));
66 }
67
68 void wxHTTP::SetProxyMode(bool on)
69 {
70 m_proxy_mode = on;
71 }
72
73 void wxHTTP::SetHeader(const wxString& header, const wxString& h_data)
74 {
75 if (m_read) {
76 ClearHeaders();
77 m_read = FALSE;
78 }
79
80 wxStringToStringHashMap::iterator it = m_headers.find(header);
81 if (it != m_headers.end())
82 it->second = h_data;
83 else
84 m_headers[header.Upper()] = h_data;
85 }
86
87 wxString wxHTTP::GetHeader(const wxString& header)
88 {
89 wxStringToStringHashMap::iterator it = m_headers.find(header.Upper());
90
91 if (it == m_headers.end())
92 return wxEmptyString;
93
94 return it->second;
95 }
96
97 void wxHTTP::SetPostBuffer(const wxString& post_buf)
98 {
99 m_post_buf = post_buf;
100 }
101
102 void wxHTTP::SendHeaders()
103 {
104 typedef wxStringToStringHashMap::iterator iterator;
105 wxString buf;
106
107 for (iterator it = m_headers.begin(), en = m_headers.end(); it != en; ++it )
108 {
109 buf.Printf(wxT("%s: %s\r\n"), it->first.c_str(), it->second.c_str());
110
111 const wxWX2MBbuf cbuf = buf.mb_str();
112 Write(cbuf, strlen(cbuf));
113 }
114 }
115
116 bool wxHTTP::ParseHeaders()
117 {
118 wxString line;
119 wxStringTokenizer tokenzr;
120
121 ClearHeaders();
122 m_read = TRUE;
123
124 #if defined(__VISAGECPP__)
125 // VA just can't stand while(1)
126 bool bOs2var = TRUE;
127 while(bOs2var) {
128 #else
129 while (1) {
130 #endif
131 m_perr = GetLine(this, line);
132 if (m_perr != wxPROTO_NOERR)
133 return FALSE;
134
135 if (line.Length() == 0)
136 break;
137
138 wxString left_str = line.BeforeFirst(':');
139 left_str.MakeUpper();
140
141 m_headers[left_str] = line.AfterFirst(':').Strip(wxString::both);
142 }
143 return TRUE;
144 }
145
146 bool wxHTTP::Connect(const wxString& host, unsigned short port)
147 {
148 wxIPV4address *addr;
149
150 if (m_addr) {
151 delete m_addr;
152 m_addr = NULL;
153 Close();
154 }
155
156 m_addr = addr = new wxIPV4address();
157
158 if (!addr->Hostname(host)) {
159 delete m_addr;
160 m_addr = NULL;
161 m_perr = wxPROTO_NETERR;
162 return FALSE;
163 }
164
165 if ( port ) addr->Service(port);
166 else if (!addr->Service(wxT("http")))
167 addr->Service(80);
168
169 SetHeader(wxT("Host"), host);
170
171 return TRUE;
172 }
173
174 bool wxHTTP::Connect(wxSockAddress& addr, bool WXUNUSED(wait))
175 {
176 if (m_addr) {
177 delete m_addr;
178 Close();
179 }
180
181 m_addr = addr.Clone();
182
183 wxIPV4address *ipv4addr = wxDynamicCast(&addr, wxIPV4address);
184 if (ipv4addr)
185 SetHeader(wxT("Host"), ipv4addr->OrigHostname());
186
187 return TRUE;
188 }
189
190 bool wxHTTP::BuildRequest(const wxString& path, wxHTTP_Req req)
191 {
192 const wxChar *request;
193
194 switch (req) {
195 case wxHTTP_GET:
196 request = wxT("GET");
197 break;
198 case wxHTTP_POST:
199 tmp_buf = wxT("POST");
200 break;
201 default:
202 return FALSE;
203 }
204
205 // If there is no User-Agent defined, define it.
206 if (GetHeader(wxT("User-Agent")).IsNull())
207 SetHeader(wxT("User-Agent"), wxT("wxWindows 2.x"));
208
209 SaveState();
210 SetFlags(wxSOCKET_NONE);
211 Notify(FALSE);
212
213 wxString buf;
214 buf.Printf(wxT("%s %s HTTP/1.0\r\n"), request, path.c_str());
215 const wxWX2MBbuf pathbuf = wxConvLocal.cWX2MB(buf);
216 Write(pathbuf, strlen(wxMBSTRINGCAST pathbuf));
217 SendHeaders();
218 Write("\r\n", 2);
219
220 if ( req == wxHTTP_POST ) {
221 Write(m_post_buf, m_post_buf.Len());
222 m_post_buf = wxEmptyString;
223 }
224
225 wxString tmp_str;
226 m_perr = GetLine(this, tmp_str);
227 if (m_perr != wxPROTO_NOERR) {
228 RestoreState();
229 return FALSE;
230 }
231
232 if (!tmp_str.Contains(wxT("HTTP/"))) {
233 // TODO: support HTTP v0.9 which can have no header.
234 // FIXME: tmp_str is not put back in the in-queue of the socket.
235 SetHeader(wxT("Content-Length"), wxT("-1"));
236 SetHeader(wxT("Content-Type"), wxT("none/none"));
237 RestoreState();
238 return TRUE;
239 }
240
241 wxStringTokenizer token(tmp_str,wxT(' '));
242 wxString tmp_str2;
243 bool ret_value;
244
245 token.NextToken();
246 tmp_str2 = token.NextToken();
247
248 switch (tmp_str2[0u]) {
249 case wxT('1'):
250 /* INFORMATION / SUCCESS */
251 break;
252 case wxT('2'):
253 /* SUCCESS */
254 break;
255 case wxT('3'):
256 /* REDIRECTION */
257 break;
258 default:
259 m_perr = wxPROTO_NOFILE;
260 RestoreState();
261 return FALSE;
262 }
263
264 ret_value = ParseHeaders();
265 RestoreState();
266 return ret_value;
267 }
268
269 class wxHTTPStream : public wxSocketInputStream
270 {
271 public:
272 wxHTTP *m_http;
273 size_t m_httpsize;
274 unsigned long m_read_bytes;
275
276 wxHTTPStream(wxHTTP *http) : wxSocketInputStream(*http), m_http(http) {}
277 size_t GetSize() const { return m_httpsize; }
278 virtual ~wxHTTPStream(void) { m_http->Abort(); }
279
280 protected:
281 size_t OnSysRead(void *buffer, size_t bufsize);
282
283 DECLARE_NO_COPY_CLASS(wxHTTPStream)
284 };
285
286 size_t wxHTTPStream::OnSysRead(void *buffer, size_t bufsize)
287 {
288 if (m_httpsize > 0 && m_read_bytes >= m_httpsize)
289 {
290 m_lasterror = wxSTREAM_EOF;
291 return 0;
292 }
293
294 size_t ret = wxSocketInputStream::OnSysRead(buffer, bufsize);
295 m_read_bytes += ret;
296
297 return ret;
298 }
299
300 bool wxHTTP::Abort(void)
301 {
302 return wxSocketClient::Close();
303 }
304
305 wxInputStream *wxHTTP::GetInputStream(const wxString& path)
306 {
307 wxHTTPStream *inp_stream;
308
309 wxString new_path;
310
311 m_perr = wxPROTO_CONNERR;
312 if (!m_addr)
313 return NULL;
314
315 // We set m_connected back to FALSE so wxSocketBase will know what to do.
316 #ifdef __WXMAC__
317 wxSocketClient::Connect(*m_addr , FALSE );
318 wxSocketClient::WaitOnConnect(10);
319
320 if (!wxSocketClient::IsConnected())
321 return NULL;
322 #else
323 if (!wxProtocol::Connect(*m_addr))
324 return NULL;
325 #endif
326
327 if (!BuildRequest(path, m_post_buf.IsEmpty() ? wxHTTP_GET : wxHTTP_POST))
328 return NULL;
329
330 inp_stream = new wxHTTPStream(this);
331
332 if (!GetHeader(wxT("Content-Length")).IsEmpty())
333 inp_stream->m_httpsize = wxAtoi(WXSTRINGCAST GetHeader(wxT("Content-Length")));
334 else
335 inp_stream->m_httpsize = (size_t)-1;
336
337 inp_stream->m_read_bytes = 0;
338
339 Notify(FALSE);
340 SetFlags(wxSOCKET_BLOCK | wxSOCKET_WAITALL);
341
342 return inp_stream;
343 }
344
345 #endif // wxUSE_PROTOCOL_HTTP
346