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