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