]> git.saurik.com Git - wxWidgets.git/blame - src/common/http.cpp
Fix wxListCtrl::EndEditLabel() which simply didn't work.
[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"
204abcd4 35#include "wx/thread.h"
f4ada568 36
730b772b
FM
37
38// ----------------------------------------------------------------------------
39// wxHTTP
40// ----------------------------------------------------------------------------
41
f4ada568 42IMPLEMENT_DYNAMIC_CLASS(wxHTTP, wxProtocol)
5d3e7b52 43IMPLEMENT_PROTOCOL(wxHTTP, wxT("http"), wxT("80"), true)
f4ada568 44
f4ada568 45wxHTTP::wxHTTP()
df5168c4 46 : wxProtocol()
f4ada568 47{
48f7ffbe
WS
48 m_addr = NULL;
49 m_read = false;
50 m_proxy_mode = false;
51 m_post_buf = wxEmptyString;
52 m_http_response = 0;
f4ada568 53
48f7ffbe 54 SetNotify(wxSOCKET_LOST_FLAG);
f4ada568
GL
55}
56
57wxHTTP::~wxHTTP()
2fb203e6
VZ
58{
59 ClearHeaders();
60
61 delete m_addr;
62}
63
64void wxHTTP::ClearHeaders()
f4ada568 65{
730b772b 66 m_headers.clear();
f4ada568
GL
67}
68
906cb3f1
JS
69void wxHTTP::ClearCookies()
70{
71 m_cookies.clear();
72}
73
730b772b 74wxString wxHTTP::GetContentType() const
f4ada568 75{
48f7ffbe 76 return GetHeader(wxT("Content-Type"));
f4ada568
GL
77}
78
f61815af
GL
79void wxHTTP::SetProxyMode(bool on)
80{
48f7ffbe 81 m_proxy_mode = on;
f61815af
GL
82}
83
bdcade0a 84wxHTTP::wxHeaderIterator wxHTTP::FindHeader(const wxString& header)
71414756 85{
bdcade0a
MB
86 wxHeaderIterator it = m_headers.begin();
87 for ( wxHeaderIterator en = m_headers.end(); it != en; ++it )
88 {
86501081 89 if ( header.CmpNoCase(it->first) == 0 )
bdcade0a
MB
90 break;
91 }
71414756 92
bdcade0a
MB
93 return it;
94}
95
96wxHTTP::wxHeaderConstIterator wxHTTP::FindHeader(const wxString& header) const
97{
98 wxHeaderConstIterator it = m_headers.begin();
99 for ( wxHeaderConstIterator en = m_headers.end(); it != en; ++it )
71414756 100 {
86501081 101 if ( header.CmpNoCase(it->first) == 0 )
71414756
VZ
102 break;
103 }
104
105 return it;
106}
107
906cb3f1
JS
108wxHTTP::wxCookieIterator wxHTTP::FindCookie(const wxString& cookie)
109{
110 wxCookieIterator it = m_cookies.begin();
111 for ( wxCookieIterator en = m_cookies.end(); it != en; ++it )
112 {
113 if ( cookie.CmpNoCase(it->first) == 0 )
114 break;
115 }
116
117 return it;
118}
119
120wxHTTP::wxCookieConstIterator wxHTTP::FindCookie(const wxString& cookie) const
121{
122 wxCookieConstIterator it = m_cookies.begin();
123 for ( wxCookieConstIterator en = m_cookies.end(); it != en; ++it )
124 {
125 if ( cookie.CmpNoCase(it->first) == 0 )
126 break;
127 }
128
129 return it;
130}
131
f4ada568
GL
132void wxHTTP::SetHeader(const wxString& header, const wxString& h_data)
133{
48f7ffbe
WS
134 if (m_read) {
135 ClearHeaders();
136 m_read = false;
137 }
f4ada568 138
48f7ffbe
WS
139 wxHeaderIterator it = FindHeader(header);
140 if (it != m_headers.end())
141 it->second = h_data;
142 else
143 m_headers[header] = h_data;
f4ada568
GL
144}
145
71414756 146wxString wxHTTP::GetHeader(const wxString& header) const
f4ada568 147{
bdcade0a 148 wxHeaderConstIterator it = FindHeader(header);
f4ada568 149
01482482 150 return it == m_headers.end() ? wxGetEmptyString() : it->second;
f4ada568
GL
151}
152
906cb3f1
JS
153wxString wxHTTP::GetCookie(const wxString& cookie) const
154{
155 wxCookieConstIterator it = FindCookie(cookie);
156
157 return it == m_cookies.end() ? wxGetEmptyString() : it->second;
158}
159
dbccd1c2
JS
160wxString wxHTTP::GenerateAuthString(const wxString& user, const wxString& pass) const
161{
e97cbf83
VZ
162 // TODO: Use wxBase64Encode() now that we have it instead of reproducing it
163
dbccd1c2
JS
164 static const char *base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
165
166 wxString buf;
167 wxString toencode;
168
169 buf.Printf(wxT("Basic "));
170
171 toencode.Printf(wxT("%s:%s"),user.c_str(),pass.c_str());
172
670f9935 173 size_t len = toencode.length();
dbccd1c2
JS
174 const wxChar *from = toencode.c_str();
175 while (len >= 3) { // encode full blocks first
176 buf << wxString::Format(wxT("%c%c"), base64[(from[0] >> 2) & 0x3f], base64[((from[0] << 4) & 0x30) | ((from[1] >> 4) & 0xf)]);
177 buf << wxString::Format(wxT("%c%c"), base64[((from[1] << 2) & 0x3c) | ((from[2] >> 6) & 0x3)], base64[from[2] & 0x3f]);
178 from += 3;
179 len -= 3;
180 }
181 if (len > 0) { // pad the remaining characters
182 buf << wxString::Format(wxT("%c"), base64[(from[0] >> 2) & 0x3f]);
183 if (len == 1) {
184 buf << wxString::Format(wxT("%c="), base64[(from[0] << 4) & 0x30]);
185 } else {
886f61ca 186 buf << wxString::Format(wxT("%c%c"), base64[((from[0] << 4) & 0x30) | ((from[1] >> 4) & 0xf)], base64[(from[1] << 2) & 0x3c]);
dbccd1c2 187 }
2523e9b7 188 buf << wxT("=");
dbccd1c2
JS
189 }
190
191 return buf;
192}
193
f9133b32
VZ
194void wxHTTP::SetPostBuffer(const wxString& post_buf)
195{
71414756 196 m_post_buf = post_buf;
f9133b32
VZ
197}
198
f4ada568
GL
199void wxHTTP::SendHeaders()
200{
48f7ffbe
WS
201 typedef wxStringToStringHashMap::iterator iterator;
202 wxString buf;
f4ada568 203
48f7ffbe
WS
204 for (iterator it = m_headers.begin(), en = m_headers.end(); it != en; ++it )
205 {
206 buf.Printf(wxT("%s: %s\r\n"), it->first.c_str(), it->second.c_str());
53c6e7cc 207
48f7ffbe
WS
208 const wxWX2MBbuf cbuf = buf.mb_str();
209 Write(cbuf, strlen(cbuf));
210 }
f4ada568
GL
211}
212
213bool wxHTTP::ParseHeaders()
214{
48f7ffbe
WS
215 wxString line;
216 wxStringTokenizer tokenzr;
f4ada568 217
48f7ffbe 218 ClearHeaders();
906cb3f1 219 ClearCookies();
48f7ffbe 220 m_read = true;
f4ada568 221
a09f8377 222 for ( ;; )
48f7ffbe 223 {
730b772b
FM
224 m_lastError = ReadLine(this, line);
225 if (m_lastError != wxPROTO_NOERR)
48f7ffbe
WS
226 return false;
227
670f9935 228 if (line.length() == 0)
48f7ffbe
WS
229 break;
230
231 wxString left_str = line.BeforeFirst(':');
906cb3f1
JS
232 if(!left_str.CmpNoCase("Set-Cookie"))
233 {
234 wxString cookieName = line.AfterFirst(':').Strip(wxString::both).BeforeFirst('=');
235 wxString cookieValue = line.AfterFirst(':').Strip(wxString::both).AfterFirst('=').BeforeFirst(';');
236 m_cookies[cookieName] = cookieValue;
237
238 // For compatibility
239 m_headers[left_str] = line.AfterFirst(':').Strip(wxString::both);
240 }
241 else
242 {
243 m_headers[left_str] = line.AfterFirst(':').Strip(wxString::both);
244 }
48f7ffbe
WS
245 }
246 return true;
f4ada568
GL
247}
248
f9133b32 249bool wxHTTP::Connect(const wxString& host, unsigned short port)
f4ada568 250{
48f7ffbe 251 wxIPV4address *addr;
f4ada568 252
48f7ffbe
WS
253 if (m_addr) {
254 delete m_addr;
255 m_addr = NULL;
256 Close();
257 }
f4ada568 258
48f7ffbe 259 m_addr = addr = new wxIPV4address();
f4ada568 260
48f7ffbe
WS
261 if (!addr->Hostname(host)) {
262 delete m_addr;
263 m_addr = NULL;
730b772b 264 m_lastError = wxPROTO_NETERR;
48f7ffbe
WS
265 return false;
266 }
f4ada568 267
48f7ffbe
WS
268 if ( port )
269 addr->Service(port);
270 else if (!addr->Service(wxT("http")))
271 addr->Service(80);
ce22d615 272
1c7a6772
VZ
273 wxString hostHdr = host;
274 if ( port && port != 80 )
275 hostHdr << wxT(":") << port;
276 SetHeader(wxT("Host"), hostHdr);
f4ada568 277
730b772b 278 m_lastError = wxPROTO_NOERR;
48f7ffbe 279 return true;
f4ada568
GL
280}
281
ddc7f0c9 282bool wxHTTP::Connect(const wxSockAddress& addr, bool WXUNUSED(wait))
f4ada568 283{
48f7ffbe
WS
284 if (m_addr) {
285 delete m_addr;
286 Close();
287 }
f4ada568 288
48f7ffbe 289 m_addr = addr.Clone();
acd15a3f 290
48f7ffbe 291 wxIPV4address *ipv4addr = wxDynamicCast(&addr, wxIPV4address);
1c7a6772
VZ
292 if ( ipv4addr )
293 {
294 wxString hostHdr = ipv4addr->OrigHostname();
295 unsigned short port = ipv4addr->Service();
296 if ( port && port != 80 )
297 hostHdr << wxT(":") << port;
298 SetHeader(wxT("Host"), hostHdr);
299 }
5b96a71a 300
730b772b 301 m_lastError = wxPROTO_NOERR;
48f7ffbe 302 return true;
f4ada568
GL
303}
304
305bool wxHTTP::BuildRequest(const wxString& path, wxHTTP_Req req)
306{
48f7ffbe 307 const wxChar *request;
f9133b32 308
48f7ffbe
WS
309 switch (req)
310 {
311 case wxHTTP_GET:
312 request = wxT("GET");
313 break;
314
315 case wxHTTP_POST:
316 request = wxT("POST");
317 if ( GetHeader( wxT("Content-Length") ).IsNull() )
318 SetHeader( wxT("Content-Length"), wxString::Format( wxT("%lu"), (unsigned long)m_post_buf.Len() ) );
319 break;
320
321 default:
322 return false;
323 }
324
325 m_http_response = 0;
326
327 // If there is no User-Agent defined, define it.
328 if (GetHeader(wxT("User-Agent")).IsNull())
329 SetHeader(wxT("User-Agent"), wxT("wxWidgets 2.x"));
330
dbccd1c2 331 // Send authentication information
670f9935 332 if (!m_username.empty() || !m_password.empty()) {
dbccd1c2
JS
333 SetHeader(wxT("Authorization"), GenerateAuthString(m_username, m_password));
334 }
335
48f7ffbe
WS
336 SaveState();
337
338 // we may use non blocking sockets only if we can dispatch events from them
339 SetFlags( wxIsMainThread() && wxApp::IsMainLoopRunning() ? wxSOCKET_NONE
340 : wxSOCKET_BLOCK );
341 Notify(false);
342
343 wxString buf;
344 buf.Printf(wxT("%s %s HTTP/1.0\r\n"), request, path.c_str());
86501081
VS
345 const wxWX2MBbuf pathbuf = buf.mb_str();
346 Write(pathbuf, strlen(pathbuf));
48f7ffbe
WS
347 SendHeaders();
348 Write("\r\n", 2);
349
350 if ( req == wxHTTP_POST ) {
351 Write(m_post_buf.mbc_str(), m_post_buf.Len());
352 m_post_buf = wxEmptyString;
353 }
354
355 wxString tmp_str;
730b772b
FM
356 m_lastError = ReadLine(this, tmp_str);
357 if (m_lastError != wxPROTO_NOERR) {
48f7ffbe
WS
358 RestoreState();
359 return false;
360 }
361
362 if (!tmp_str.Contains(wxT("HTTP/"))) {
363 // TODO: support HTTP v0.9 which can have no header.
364 // FIXME: tmp_str is not put back in the in-queue of the socket.
730b772b 365 m_lastError = wxPROTO_NOERR;
48f7ffbe
WS
366 SetHeader(wxT("Content-Length"), wxT("-1"));
367 SetHeader(wxT("Content-Type"), wxT("none/none"));
368 RestoreState();
369 return true;
370 }
f4ada568 371
48f7ffbe
WS
372 wxStringTokenizer token(tmp_str,wxT(' '));
373 wxString tmp_str2;
374 bool ret_value;
375
376 token.NextToken();
377 tmp_str2 = token.NextToken();
378
379 m_http_response = wxAtoi(tmp_str2);
380
c9f78968 381 switch ( tmp_str2[0u].GetValue() )
48f7ffbe
WS
382 {
383 case wxT('1'):
384 /* INFORMATION / SUCCESS */
385 break;
386
387 case wxT('2'):
388 /* SUCCESS */
389 break;
390
391 case wxT('3'):
392 /* REDIRECTION */
393 break;
394
395 default:
730b772b 396 m_lastError = wxPROTO_NOFILE;
48f7ffbe
WS
397 RestoreState();
398 return false;
399 }
400
730b772b 401 m_lastError = wxPROTO_NOERR;
48f7ffbe
WS
402 ret_value = ParseHeaders();
403 RestoreState();
404 return ret_value;
f4ada568
GL
405}
406
730b772b
FM
407bool wxHTTP::Abort(void)
408{
409 return wxSocketClient::Close();
410}
411
412// ----------------------------------------------------------------------------
413// wxHTTPStream and wxHTTP::GetInputStream
414// ----------------------------------------------------------------------------
415
fc4b32c2
GRG
416class wxHTTPStream : public wxSocketInputStream
417{
f4ada568 418public:
48f7ffbe
WS
419 wxHTTP *m_http;
420 size_t m_httpsize;
421 unsigned long m_read_bytes;
9a1b2c28 422
48f7ffbe
WS
423 wxHTTPStream(wxHTTP *http) : wxSocketInputStream(*http), m_http(http) {}
424 size_t GetSize() const { return m_httpsize; }
425 virtual ~wxHTTPStream(void) { m_http->Abort(); }
a324a7bc
GL
426
427protected:
48f7ffbe 428 size_t OnSysRead(void *buffer, size_t bufsize);
22f3361e 429
c0c133e1 430 wxDECLARE_NO_COPY_CLASS(wxHTTPStream);
f4ada568
GL
431};
432
a324a7bc
GL
433size_t wxHTTPStream::OnSysRead(void *buffer, size_t bufsize)
434{
ccc3a25d 435 if (m_read_bytes >= m_httpsize)
32013d27
VZ
436 {
437 m_lasterror = wxSTREAM_EOF;
438 return 0;
439 }
a324a7bc 440
32013d27
VZ
441 size_t ret = wxSocketInputStream::OnSysRead(buffer, bufsize);
442 m_read_bytes += ret;
a324a7bc 443
8b6b8e21
SC
444 if (m_httpsize==(size_t)-1 && m_lasterror == wxSTREAM_READ_ERROR )
445 {
446 // if m_httpsize is (size_t) -1 this means read until connection closed
447 // which is equivalent to getting a READ_ERROR, for clients however this
448 // must be translated into EOF, as it is the expected way of signalling
449 // end end of the content
730b772b 450 m_lasterror = wxSTREAM_EOF;
8b6b8e21
SC
451 }
452
32013d27 453 return ret;
a324a7bc
GL
454}
455
f4ada568
GL
456wxInputStream *wxHTTP::GetInputStream(const wxString& path)
457{
48f7ffbe 458 wxHTTPStream *inp_stream;
8f5bda17 459
48f7ffbe 460 wxString new_path;
f4ada568 461
730b772b 462 m_lastError = wxPROTO_CONNERR; // all following returns share this type of error
48f7ffbe
WS
463 if (!m_addr)
464 return NULL;
f4ada568 465
48f7ffbe 466 // We set m_connected back to false so wxSocketBase will know what to do.
ad8b8498 467#ifdef __WXMAC__
48f7ffbe
WS
468 wxSocketClient::Connect(*m_addr , false );
469 wxSocketClient::WaitOnConnect(10);
ad8b8498
SC
470
471 if (!wxSocketClient::IsConnected())
472 return NULL;
473#else
48f7ffbe
WS
474 if (!wxProtocol::Connect(*m_addr))
475 return NULL;
ad8b8498 476#endif
f4ada568 477
48f7ffbe
WS
478 if (!BuildRequest(path, m_post_buf.empty() ? wxHTTP_GET : wxHTTP_POST))
479 return NULL;
f4ada568 480
48f7ffbe 481 inp_stream = new wxHTTPStream(this);
8f5bda17 482
48f7ffbe 483 if (!GetHeader(wxT("Content-Length")).empty())
86501081 484 inp_stream->m_httpsize = wxAtoi(GetHeader(wxT("Content-Length")));
48f7ffbe
WS
485 else
486 inp_stream->m_httpsize = (size_t)-1;
a324a7bc 487
48f7ffbe 488 inp_stream->m_read_bytes = 0;
a324a7bc 489
48f7ffbe
WS
490 Notify(false);
491 SetFlags(wxSOCKET_BLOCK | wxSOCKET_WAITALL);
9a1b2c28 492
730b772b
FM
493 // no error; reset m_lastError
494 m_lastError = wxPROTO_NOERR;
48f7ffbe 495 return inp_stream;
f4ada568 496}
35a4dab7 497
a5d46b73 498#endif // wxUSE_PROTOCOL_HTTP