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