]> git.saurik.com Git - wxWidgets.git/blame - src/common/http.cpp
Implemented the same simple API for creating customized
[wxWidgets.git] / src / common / http.cpp
CommitLineData
f4ada568 1/////////////////////////////////////////////////////////////////////////////
670f9935 2// Name: src/common/http.cpp
f4ada568
GL
3// Purpose: HTTP protocol
4// Author: Guilhem Lavaux
dbccd1c2 5// Modified by: Simo Virokannas (authentication, Dec 2005)
f4ada568
GL
6// Created: August 1997
7// RCS-ID: $Id$
8// Copyright: (c) 1997, 1998 Guilhem Lavaux
65571936 9// Licence: wxWindows licence
f4ada568
GL
10/////////////////////////////////////////////////////////////////////////////
11
fcc6dddd
JS
12// For compilers that support precompilation, includes "wx.h".
13#include "wx/wxprec.h"
14
15#ifdef __BORLANDC__
670f9935 16 #pragma hdrstop
fcc6dddd
JS
17#endif
18
a5d46b73 19#if wxUSE_PROTOCOL_HTTP
ce4169a4 20
f4ada568
GL
21#include <stdio.h>
22#include <stdlib.h>
a8d628fc
DS
23
24#ifndef WX_PRECOMP
670f9935
WS
25 #include "wx/string.h"
26 #include "wx/app.h"
a8d628fc
DS
27#endif
28
f4ada568
GL
29#include "wx/tokenzr.h"
30#include "wx/socket.h"
31#include "wx/protocol/protocol.h"
fae05df5 32#include "wx/url.h"
f4ada568
GL
33#include "wx/protocol/http.h"
34#include "wx/sckstrm.h"
35
f4ada568 36IMPLEMENT_DYNAMIC_CLASS(wxHTTP, wxProtocol)
5d3e7b52 37IMPLEMENT_PROTOCOL(wxHTTP, wxT("http"), wxT("80"), true)
f4ada568 38
f4ada568 39wxHTTP::wxHTTP()
df5168c4 40 : wxProtocol()
f4ada568 41{
48f7ffbe
WS
42 m_addr = NULL;
43 m_read = false;
44 m_proxy_mode = false;
45 m_post_buf = wxEmptyString;
46 m_http_response = 0;
f4ada568 47
48f7ffbe 48 SetNotify(wxSOCKET_LOST_FLAG);
f4ada568
GL
49}
50
51wxHTTP::~wxHTTP()
2fb203e6
VZ
52{
53 ClearHeaders();
54
55 delete m_addr;
56}
57
58void wxHTTP::ClearHeaders()
f4ada568 59{
df5168c4 60 m_headers.clear();
f4ada568
GL
61}
62
63wxString wxHTTP::GetContentType()
64{
48f7ffbe 65 return GetHeader(wxT("Content-Type"));
f4ada568
GL
66}
67
f61815af
GL
68void wxHTTP::SetProxyMode(bool on)
69{
48f7ffbe 70 m_proxy_mode = on;
f61815af
GL
71}
72
bdcade0a 73wxHTTP::wxHeaderIterator wxHTTP::FindHeader(const wxString& header)
71414756 74{
bdcade0a
MB
75 wxHeaderIterator it = m_headers.begin();
76 for ( wxHeaderIterator en = m_headers.end(); it != en; ++it )
77 {
78 if ( wxStricmp(it->first, header) == 0 )
79 break;
80 }
71414756 81
bdcade0a
MB
82 return it;
83}
84
85wxHTTP::wxHeaderConstIterator wxHTTP::FindHeader(const wxString& header) const
86{
87 wxHeaderConstIterator it = m_headers.begin();
88 for ( wxHeaderConstIterator en = m_headers.end(); it != en; ++it )
71414756
VZ
89 {
90 if ( wxStricmp(it->first, header) == 0 )
91 break;
92 }
93
94 return it;
95}
96
f4ada568
GL
97void wxHTTP::SetHeader(const wxString& header, const wxString& h_data)
98{
48f7ffbe
WS
99 if (m_read) {
100 ClearHeaders();
101 m_read = false;
102 }
f4ada568 103
48f7ffbe
WS
104 wxHeaderIterator it = FindHeader(header);
105 if (it != m_headers.end())
106 it->second = h_data;
107 else
108 m_headers[header] = h_data;
f4ada568
GL
109}
110
71414756 111wxString wxHTTP::GetHeader(const wxString& header) const
f4ada568 112{
bdcade0a 113 wxHeaderConstIterator it = FindHeader(header);
f4ada568 114
01482482 115 return it == m_headers.end() ? wxGetEmptyString() : it->second;
f4ada568
GL
116}
117
dbccd1c2
JS
118wxString wxHTTP::GenerateAuthString(const wxString& user, const wxString& pass) const
119{
120 static const char *base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
121
122 wxString buf;
123 wxString toencode;
124
125 buf.Printf(wxT("Basic "));
126
127 toencode.Printf(wxT("%s:%s"),user.c_str(),pass.c_str());
128
670f9935 129 size_t len = toencode.length();
dbccd1c2
JS
130 const wxChar *from = toencode.c_str();
131 while (len >= 3) { // encode full blocks first
132 buf << wxString::Format(wxT("%c%c"), base64[(from[0] >> 2) & 0x3f], base64[((from[0] << 4) & 0x30) | ((from[1] >> 4) & 0xf)]);
133 buf << wxString::Format(wxT("%c%c"), base64[((from[1] << 2) & 0x3c) | ((from[2] >> 6) & 0x3)], base64[from[2] & 0x3f]);
134 from += 3;
135 len -= 3;
136 }
137 if (len > 0) { // pad the remaining characters
138 buf << wxString::Format(wxT("%c"), base64[(from[0] >> 2) & 0x3f]);
139 if (len == 1) {
140 buf << wxString::Format(wxT("%c="), base64[(from[0] << 4) & 0x30]);
141 } else {
886f61ca 142 buf << wxString::Format(wxT("%c%c"), base64[((from[0] << 4) & 0x30) | ((from[1] >> 4) & 0xf)], base64[(from[1] << 2) & 0x3c]);
dbccd1c2
JS
143 }
144 buf << wxString::Format(wxT("="));
145 }
146
147 return buf;
148}
149
f9133b32
VZ
150void wxHTTP::SetPostBuffer(const wxString& post_buf)
151{
71414756 152 m_post_buf = post_buf;
f9133b32
VZ
153}
154
f4ada568
GL
155void wxHTTP::SendHeaders()
156{
48f7ffbe
WS
157 typedef wxStringToStringHashMap::iterator iterator;
158 wxString buf;
f4ada568 159
48f7ffbe
WS
160 for (iterator it = m_headers.begin(), en = m_headers.end(); it != en; ++it )
161 {
162 buf.Printf(wxT("%s: %s\r\n"), it->first.c_str(), it->second.c_str());
53c6e7cc 163
48f7ffbe
WS
164 const wxWX2MBbuf cbuf = buf.mb_str();
165 Write(cbuf, strlen(cbuf));
166 }
f4ada568
GL
167}
168
169bool wxHTTP::ParseHeaders()
170{
48f7ffbe
WS
171 wxString line;
172 wxStringTokenizer tokenzr;
f4ada568 173
48f7ffbe
WS
174 ClearHeaders();
175 m_read = true;
f4ada568 176
a09f8377 177 for ( ;; )
48f7ffbe 178 {
f3d0213e 179 m_perr = ReadLine(this, line);
48f7ffbe
WS
180 if (m_perr != wxPROTO_NOERR)
181 return false;
182
670f9935 183 if (line.length() == 0)
48f7ffbe
WS
184 break;
185
186 wxString left_str = line.BeforeFirst(':');
187 m_headers[left_str] = line.AfterFirst(':').Strip(wxString::both);
188 }
189 return true;
f4ada568
GL
190}
191
f9133b32 192bool wxHTTP::Connect(const wxString& host, unsigned short port)
f4ada568 193{
48f7ffbe 194 wxIPV4address *addr;
f4ada568 195
48f7ffbe
WS
196 if (m_addr) {
197 delete m_addr;
198 m_addr = NULL;
199 Close();
200 }
f4ada568 201
48f7ffbe 202 m_addr = addr = new wxIPV4address();
f4ada568 203
48f7ffbe
WS
204 if (!addr->Hostname(host)) {
205 delete m_addr;
206 m_addr = NULL;
207 m_perr = wxPROTO_NETERR;
208 return false;
209 }
f4ada568 210
48f7ffbe
WS
211 if ( port )
212 addr->Service(port);
213 else if (!addr->Service(wxT("http")))
214 addr->Service(80);
ce22d615 215
48f7ffbe 216 SetHeader(wxT("Host"), host);
f4ada568 217
48f7ffbe 218 return true;
f4ada568
GL
219}
220
8a2c6ef8 221bool wxHTTP::Connect(wxSockAddress& addr, bool WXUNUSED(wait))
f4ada568 222{
48f7ffbe
WS
223 if (m_addr) {
224 delete m_addr;
225 Close();
226 }
f4ada568 227
48f7ffbe 228 m_addr = addr.Clone();
acd15a3f 229
48f7ffbe
WS
230 wxIPV4address *ipv4addr = wxDynamicCast(&addr, wxIPV4address);
231 if (ipv4addr)
232 SetHeader(wxT("Host"), ipv4addr->OrigHostname());
5b96a71a 233
48f7ffbe 234 return true;
f4ada568
GL
235}
236
237bool wxHTTP::BuildRequest(const wxString& path, wxHTTP_Req req)
238{
48f7ffbe 239 const wxChar *request;
f9133b32 240
48f7ffbe
WS
241 switch (req)
242 {
243 case wxHTTP_GET:
244 request = wxT("GET");
245 break;
246
247 case wxHTTP_POST:
248 request = wxT("POST");
249 if ( GetHeader( wxT("Content-Length") ).IsNull() )
250 SetHeader( wxT("Content-Length"), wxString::Format( wxT("%lu"), (unsigned long)m_post_buf.Len() ) );
251 break;
252
253 default:
254 return false;
255 }
256
257 m_http_response = 0;
258
259 // If there is no User-Agent defined, define it.
260 if (GetHeader(wxT("User-Agent")).IsNull())
261 SetHeader(wxT("User-Agent"), wxT("wxWidgets 2.x"));
262
dbccd1c2 263 // Send authentication information
670f9935 264 if (!m_username.empty() || !m_password.empty()) {
dbccd1c2
JS
265 SetHeader(wxT("Authorization"), GenerateAuthString(m_username, m_password));
266 }
267
48f7ffbe
WS
268 SaveState();
269
270 // we may use non blocking sockets only if we can dispatch events from them
271 SetFlags( wxIsMainThread() && wxApp::IsMainLoopRunning() ? wxSOCKET_NONE
272 : wxSOCKET_BLOCK );
273 Notify(false);
274
275 wxString buf;
276 buf.Printf(wxT("%s %s HTTP/1.0\r\n"), request, path.c_str());
277 const wxWX2MBbuf pathbuf = wxConvLocal.cWX2MB(buf);
278 Write(pathbuf, strlen(wxMBSTRINGCAST pathbuf));
279 SendHeaders();
280 Write("\r\n", 2);
281
282 if ( req == wxHTTP_POST ) {
283 Write(m_post_buf.mbc_str(), m_post_buf.Len());
284 m_post_buf = wxEmptyString;
285 }
286
287 wxString tmp_str;
f3d0213e 288 m_perr = ReadLine(this, tmp_str);
48f7ffbe
WS
289 if (m_perr != wxPROTO_NOERR) {
290 RestoreState();
291 return false;
292 }
293
294 if (!tmp_str.Contains(wxT("HTTP/"))) {
295 // TODO: support HTTP v0.9 which can have no header.
296 // FIXME: tmp_str is not put back in the in-queue of the socket.
297 SetHeader(wxT("Content-Length"), wxT("-1"));
298 SetHeader(wxT("Content-Type"), wxT("none/none"));
299 RestoreState();
300 return true;
301 }
f4ada568 302
48f7ffbe
WS
303 wxStringTokenizer token(tmp_str,wxT(' '));
304 wxString tmp_str2;
305 bool ret_value;
306
307 token.NextToken();
308 tmp_str2 = token.NextToken();
309
310 m_http_response = wxAtoi(tmp_str2);
311
c9f78968 312 switch ( tmp_str2[0u].GetValue() )
48f7ffbe
WS
313 {
314 case wxT('1'):
315 /* INFORMATION / SUCCESS */
316 break;
317
318 case wxT('2'):
319 /* SUCCESS */
320 break;
321
322 case wxT('3'):
323 /* REDIRECTION */
324 break;
325
326 default:
327 m_perr = wxPROTO_NOFILE;
328 RestoreState();
329 return false;
330 }
331
332 ret_value = ParseHeaders();
333 RestoreState();
334 return ret_value;
f4ada568
GL
335}
336
fc4b32c2
GRG
337class wxHTTPStream : public wxSocketInputStream
338{
f4ada568 339public:
48f7ffbe
WS
340 wxHTTP *m_http;
341 size_t m_httpsize;
342 unsigned long m_read_bytes;
9a1b2c28 343
48f7ffbe
WS
344 wxHTTPStream(wxHTTP *http) : wxSocketInputStream(*http), m_http(http) {}
345 size_t GetSize() const { return m_httpsize; }
346 virtual ~wxHTTPStream(void) { m_http->Abort(); }
a324a7bc
GL
347
348protected:
48f7ffbe 349 size_t OnSysRead(void *buffer, size_t bufsize);
22f3361e
VZ
350
351 DECLARE_NO_COPY_CLASS(wxHTTPStream)
f4ada568
GL
352};
353
a324a7bc
GL
354size_t wxHTTPStream::OnSysRead(void *buffer, size_t bufsize)
355{
32013d27
VZ
356 if (m_httpsize > 0 && m_read_bytes >= m_httpsize)
357 {
358 m_lasterror = wxSTREAM_EOF;
359 return 0;
360 }
a324a7bc 361
32013d27
VZ
362 size_t ret = wxSocketInputStream::OnSysRead(buffer, bufsize);
363 m_read_bytes += ret;
a324a7bc 364
8b6b8e21
SC
365 if (m_httpsize==(size_t)-1 && m_lasterror == wxSTREAM_READ_ERROR )
366 {
367 // if m_httpsize is (size_t) -1 this means read until connection closed
368 // which is equivalent to getting a READ_ERROR, for clients however this
369 // must be translated into EOF, as it is the expected way of signalling
370 // end end of the content
371 m_lasterror = wxSTREAM_EOF ;
372 }
373
32013d27 374 return ret;
a324a7bc
GL
375}
376
f4ada568
GL
377bool wxHTTP::Abort(void)
378{
48f7ffbe 379 return wxSocketClient::Close();
f4ada568
GL
380}
381
382wxInputStream *wxHTTP::GetInputStream(const wxString& path)
383{
48f7ffbe 384 wxHTTPStream *inp_stream;
8f5bda17 385
48f7ffbe 386 wxString new_path;
f4ada568 387
48f7ffbe
WS
388 m_perr = wxPROTO_CONNERR;
389 if (!m_addr)
390 return NULL;
f4ada568 391
48f7ffbe 392 // We set m_connected back to false so wxSocketBase will know what to do.
ad8b8498 393#ifdef __WXMAC__
48f7ffbe
WS
394 wxSocketClient::Connect(*m_addr , false );
395 wxSocketClient::WaitOnConnect(10);
ad8b8498
SC
396
397 if (!wxSocketClient::IsConnected())
398 return NULL;
399#else
48f7ffbe
WS
400 if (!wxProtocol::Connect(*m_addr))
401 return NULL;
ad8b8498 402#endif
f4ada568 403
48f7ffbe
WS
404 if (!BuildRequest(path, m_post_buf.empty() ? wxHTTP_GET : wxHTTP_POST))
405 return NULL;
f4ada568 406
48f7ffbe 407 inp_stream = new wxHTTPStream(this);
8f5bda17 408
48f7ffbe
WS
409 if (!GetHeader(wxT("Content-Length")).empty())
410 inp_stream->m_httpsize = wxAtoi(WXSTRINGCAST GetHeader(wxT("Content-Length")));
411 else
412 inp_stream->m_httpsize = (size_t)-1;
a324a7bc 413
48f7ffbe 414 inp_stream->m_read_bytes = 0;
a324a7bc 415
48f7ffbe
WS
416 Notify(false);
417 SetFlags(wxSOCKET_BLOCK | wxSOCKET_WAITALL);
9a1b2c28 418
48f7ffbe 419 return inp_stream;
f4ada568 420}
35a4dab7 421
a5d46b73 422#endif // wxUSE_PROTOCOL_HTTP