corrected error code for http responses with no content-length indicated (from READ_E...
[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 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
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
28 #ifndef WX_PRECOMP
29 #include "wx/string.h"
30 #include "wx/app.h"
31 #endif
32
33 #include "wx/tokenzr.h"
34 #include "wx/socket.h"
35 #include "wx/protocol/protocol.h"
36 #include "wx/url.h"
37 #include "wx/protocol/http.h"
38 #include "wx/sckstrm.h"
39
40 IMPLEMENT_DYNAMIC_CLASS(wxHTTP, wxProtocol)
41 IMPLEMENT_PROTOCOL(wxHTTP, wxT("http"), wxT("80"), true)
42
43 wxHTTP::wxHTTP()
44 : wxProtocol()
45 {
46 m_addr = NULL;
47 m_read = false;
48 m_proxy_mode = false;
49 m_post_buf = wxEmptyString;
50 m_http_response = 0;
51
52 SetNotify(wxSOCKET_LOST_FLAG);
53 }
54
55 wxHTTP::~wxHTTP()
56 {
57 ClearHeaders();
58
59 delete m_addr;
60 }
61
62 void wxHTTP::ClearHeaders()
63 {
64 m_headers.clear();
65 }
66
67 wxString wxHTTP::GetContentType()
68 {
69 return GetHeader(wxT("Content-Type"));
70 }
71
72 void wxHTTP::SetProxyMode(bool on)
73 {
74 m_proxy_mode = on;
75 }
76
77 wxHTTP::wxHeaderIterator wxHTTP::FindHeader(const wxString& header)
78 {
79 wxHeaderIterator it = m_headers.begin();
80 for ( wxHeaderIterator en = m_headers.end(); it != en; ++it )
81 {
82 if ( wxStricmp(it->first, header) == 0 )
83 break;
84 }
85
86 return it;
87 }
88
89 wxHTTP::wxHeaderConstIterator wxHTTP::FindHeader(const wxString& header) const
90 {
91 wxHeaderConstIterator it = m_headers.begin();
92 for ( wxHeaderConstIterator en = m_headers.end(); it != en; ++it )
93 {
94 if ( wxStricmp(it->first, header) == 0 )
95 break;
96 }
97
98 return it;
99 }
100
101 void wxHTTP::SetHeader(const wxString& header, const wxString& h_data)
102 {
103 if (m_read) {
104 ClearHeaders();
105 m_read = false;
106 }
107
108 wxHeaderIterator it = FindHeader(header);
109 if (it != m_headers.end())
110 it->second = h_data;
111 else
112 m_headers[header] = h_data;
113 }
114
115 wxString wxHTTP::GetHeader(const wxString& header) const
116 {
117 wxHeaderConstIterator it = FindHeader(header);
118
119 return it == m_headers.end() ? wxGetEmptyString() : it->second;
120 }
121
122 void wxHTTP::SetPostBuffer(const wxString& post_buf)
123 {
124 m_post_buf = post_buf;
125 }
126
127 void wxHTTP::SendHeaders()
128 {
129 typedef wxStringToStringHashMap::iterator iterator;
130 wxString buf;
131
132 for (iterator it = m_headers.begin(), en = m_headers.end(); it != en; ++it )
133 {
134 buf.Printf(wxT("%s: %s\r\n"), it->first.c_str(), it->second.c_str());
135
136 const wxWX2MBbuf cbuf = buf.mb_str();
137 Write(cbuf, strlen(cbuf));
138 }
139 }
140
141 bool wxHTTP::ParseHeaders()
142 {
143 wxString line;
144 wxStringTokenizer tokenzr;
145
146 ClearHeaders();
147 m_read = true;
148
149 #if defined(__VISAGECPP__)
150 // VA just can't stand while(1)
151 bool bOs2var = true;
152 while(bOs2var)
153 #else
154 while (1)
155 #endif
156 {
157 m_perr = ReadLine(this, line);
158 if (m_perr != wxPROTO_NOERR)
159 return false;
160
161 if (line.Length() == 0)
162 break;
163
164 wxString left_str = line.BeforeFirst(':');
165 m_headers[left_str] = line.AfterFirst(':').Strip(wxString::both);
166 }
167 return true;
168 }
169
170 bool wxHTTP::Connect(const wxString& host, unsigned short port)
171 {
172 wxIPV4address *addr;
173
174 if (m_addr) {
175 delete m_addr;
176 m_addr = NULL;
177 Close();
178 }
179
180 m_addr = addr = new wxIPV4address();
181
182 if (!addr->Hostname(host)) {
183 delete m_addr;
184 m_addr = NULL;
185 m_perr = wxPROTO_NETERR;
186 return false;
187 }
188
189 if ( port )
190 addr->Service(port);
191 else if (!addr->Service(wxT("http")))
192 addr->Service(80);
193
194 SetHeader(wxT("Host"), host);
195
196 return true;
197 }
198
199 bool wxHTTP::Connect(wxSockAddress& addr, bool WXUNUSED(wait))
200 {
201 if (m_addr) {
202 delete m_addr;
203 Close();
204 }
205
206 m_addr = addr.Clone();
207
208 wxIPV4address *ipv4addr = wxDynamicCast(&addr, wxIPV4address);
209 if (ipv4addr)
210 SetHeader(wxT("Host"), ipv4addr->OrigHostname());
211
212 return true;
213 }
214
215 bool wxHTTP::BuildRequest(const wxString& path, wxHTTP_Req req)
216 {
217 const wxChar *request;
218
219 switch (req)
220 {
221 case wxHTTP_GET:
222 request = wxT("GET");
223 break;
224
225 case wxHTTP_POST:
226 request = wxT("POST");
227 if ( GetHeader( wxT("Content-Length") ).IsNull() )
228 SetHeader( wxT("Content-Length"), wxString::Format( wxT("%lu"), (unsigned long)m_post_buf.Len() ) );
229 break;
230
231 default:
232 return false;
233 }
234
235 m_http_response = 0;
236
237 // If there is no User-Agent defined, define it.
238 if (GetHeader(wxT("User-Agent")).IsNull())
239 SetHeader(wxT("User-Agent"), wxT("wxWidgets 2.x"));
240
241 SaveState();
242
243 // we may use non blocking sockets only if we can dispatch events from them
244 SetFlags( wxIsMainThread() && wxApp::IsMainLoopRunning() ? wxSOCKET_NONE
245 : wxSOCKET_BLOCK );
246 Notify(false);
247
248 wxString buf;
249 buf.Printf(wxT("%s %s HTTP/1.0\r\n"), request, path.c_str());
250 const wxWX2MBbuf pathbuf = wxConvLocal.cWX2MB(buf);
251 Write(pathbuf, strlen(wxMBSTRINGCAST pathbuf));
252 SendHeaders();
253 Write("\r\n", 2);
254
255 if ( req == wxHTTP_POST ) {
256 Write(m_post_buf.mbc_str(), m_post_buf.Len());
257 m_post_buf = wxEmptyString;
258 }
259
260 wxString tmp_str;
261 m_perr = ReadLine(this, tmp_str);
262 if (m_perr != wxPROTO_NOERR) {
263 RestoreState();
264 return false;
265 }
266
267 if (!tmp_str.Contains(wxT("HTTP/"))) {
268 // TODO: support HTTP v0.9 which can have no header.
269 // FIXME: tmp_str is not put back in the in-queue of the socket.
270 SetHeader(wxT("Content-Length"), wxT("-1"));
271 SetHeader(wxT("Content-Type"), wxT("none/none"));
272 RestoreState();
273 return true;
274 }
275
276 wxStringTokenizer token(tmp_str,wxT(' '));
277 wxString tmp_str2;
278 bool ret_value;
279
280 token.NextToken();
281 tmp_str2 = token.NextToken();
282
283 m_http_response = wxAtoi(tmp_str2);
284
285 switch (tmp_str2[0u])
286 {
287 case wxT('1'):
288 /* INFORMATION / SUCCESS */
289 break;
290
291 case wxT('2'):
292 /* SUCCESS */
293 break;
294
295 case wxT('3'):
296 /* REDIRECTION */
297 break;
298
299 default:
300 m_perr = wxPROTO_NOFILE;
301 RestoreState();
302 return false;
303 }
304
305 ret_value = ParseHeaders();
306 RestoreState();
307 return ret_value;
308 }
309
310 class wxHTTPStream : public wxSocketInputStream
311 {
312 public:
313 wxHTTP *m_http;
314 size_t m_httpsize;
315 unsigned long m_read_bytes;
316
317 wxHTTPStream(wxHTTP *http) : wxSocketInputStream(*http), m_http(http) {}
318 size_t GetSize() const { return m_httpsize; }
319 virtual ~wxHTTPStream(void) { m_http->Abort(); }
320
321 protected:
322 size_t OnSysRead(void *buffer, size_t bufsize);
323
324 DECLARE_NO_COPY_CLASS(wxHTTPStream)
325 };
326
327 size_t wxHTTPStream::OnSysRead(void *buffer, size_t bufsize)
328 {
329 if (m_httpsize > 0 && m_read_bytes >= m_httpsize)
330 {
331 m_lasterror = wxSTREAM_EOF;
332 return 0;
333 }
334
335 size_t ret = wxSocketInputStream::OnSysRead(buffer, bufsize);
336 m_read_bytes += ret;
337
338 if (m_httpsize==(size_t)-1 && m_lasterror == wxSTREAM_READ_ERROR )
339 {
340 // if m_httpsize is (size_t) -1 this means read until connection closed
341 // which is equivalent to getting a READ_ERROR, for clients however this
342 // must be translated into EOF, as it is the expected way of signalling
343 // end end of the content
344 m_lasterror = wxSTREAM_EOF ;
345 }
346
347 return ret;
348 }
349
350 bool wxHTTP::Abort(void)
351 {
352 return wxSocketClient::Close();
353 }
354
355 wxInputStream *wxHTTP::GetInputStream(const wxString& path)
356 {
357 wxHTTPStream *inp_stream;
358
359 wxString new_path;
360
361 m_perr = wxPROTO_CONNERR;
362 if (!m_addr)
363 return NULL;
364
365 // We set m_connected back to false so wxSocketBase will know what to do.
366 #ifdef __WXMAC__
367 wxSocketClient::Connect(*m_addr , false );
368 wxSocketClient::WaitOnConnect(10);
369
370 if (!wxSocketClient::IsConnected())
371 return NULL;
372 #else
373 if (!wxProtocol::Connect(*m_addr))
374 return NULL;
375 #endif
376
377 if (!BuildRequest(path, m_post_buf.empty() ? wxHTTP_GET : wxHTTP_POST))
378 return NULL;
379
380 inp_stream = new wxHTTPStream(this);
381
382 if (!GetHeader(wxT("Content-Length")).empty())
383 inp_stream->m_httpsize = wxAtoi(WXSTRINGCAST GetHeader(wxT("Content-Length")));
384 else
385 inp_stream->m_httpsize = (size_t)-1;
386
387 inp_stream->m_read_bytes = 0;
388
389 Notify(false);
390 SetFlags(wxSOCKET_BLOCK | wxSOCKET_WAITALL);
391
392 return inp_stream;
393 }
394
395 #endif // wxUSE_PROTOCOL_HTTP
396