Fix in parse headers so it wouldn't always store an empty string
[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 license
10 /////////////////////////////////////////////////////////////////////////////
11
12 #ifdef __GNUG__
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_SOCKETS
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 m_headers(wxKEY_STRING)
43 {
44 m_addr = NULL;
45 m_read = FALSE;
46 m_proxy_mode = FALSE;
47
48 SetNotify(GSOCK_LOST_FLAG);
49 }
50
51 wxHTTP::~wxHTTP()
52 {
53 // wxString isn't a wxObject
54 wxNode *node = m_headers.First();
55 wxString *string;
56
57 while (node) {
58 string = (wxString *)node->Data();
59 delete string;
60 node = node->Next();
61 }
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 void wxHTTP::SetHeader(const wxString& header, const wxString& h_data)
75 {
76 if (m_read) {
77 m_headers.Clear();
78 m_read = FALSE;
79 }
80
81 wxNode *node = m_headers.Find(header);
82
83 if (!node)
84 m_headers.Append(header, (wxObject *)(new wxString(h_data)));
85 else {
86 wxString *str = (wxString *)node->Data();
87 (*str) = h_data;
88 }
89 }
90
91 wxString wxHTTP::GetHeader(const wxString& header)
92 {
93 wxNode *node;
94 wxString upper_header;
95
96 upper_header = header.Upper();
97
98 node = m_headers.Find(upper_header);
99 if (!node)
100 return wxEmptyString;
101
102 return *((wxString *)node->Data());
103 }
104
105 void wxHTTP::SendHeaders()
106 {
107 wxNode *head = m_headers.First();
108
109 while (head)
110 {
111 wxString *str = (wxString *)head->Data();
112
113 wxString buf;
114 buf.Printf(wxT("%s: %s\n\r"), head->GetKeyString(), str->GetData());
115
116 const wxWX2MBbuf cbuf = buf.mb_str();
117 Write(cbuf, strlen(cbuf));
118
119 head = head->Next();
120 }
121 }
122
123 bool wxHTTP::ParseHeaders()
124 {
125 wxString line;
126 wxStringTokenizer tokenzr;
127
128 m_headers.Clear();
129 m_read = TRUE;
130
131 #if defined(__VISAGECPP__)
132 // VA just can't stand while(1)
133 bool bOs2var = TRUE;
134 while(bOs2var) {
135 #else
136 while (1) {
137 #endif
138 m_perr = GetLine(this, line);
139 if (m_perr != wxPROTO_NOERR)
140 return FALSE;
141
142 if (line.Length() == 0)
143 break;
144
145 wxString left_str = line.BeforeFirst(':');
146 wxString *str = new wxString(line.AfterFirst(':').Strip(wxString::both));
147 left_str.MakeUpper();
148
149 m_headers.Append(left_str, (wxObject *) str);
150 }
151 return TRUE;
152 }
153
154 bool wxHTTP::Connect(const wxString& host)
155 {
156 wxIPV4address *addr;
157
158 if (m_addr) {
159 delete m_addr;
160 m_addr = NULL;
161 Close();
162 }
163
164 m_addr = addr = new wxIPV4address();
165
166 if (!addr->Hostname(host)) {
167 delete m_addr;
168 m_addr = NULL;
169 m_perr = wxPROTO_NETERR;
170 return FALSE;
171 }
172
173 if (!addr->Service(wxT("http")))
174 addr->Service(80);
175
176 return TRUE;
177 }
178
179 bool wxHTTP::Connect(wxSockAddress& addr, bool WXUNUSED(wait))
180 {
181 if (m_addr) {
182 delete m_addr;
183 m_addr = NULL;
184 Close();
185 }
186
187 m_addr = (wxSockAddress *) addr.Clone();
188 return TRUE;
189 }
190
191 bool wxHTTP::BuildRequest(const wxString& path, wxHTTP_Req req)
192 {
193 wxChar *tmp_buf;
194 wxChar buf[200]; // 200 is arbitrary.
195 wxString tmp_str = path;
196
197 // If there is no User-Agent defined, define it.
198 if (GetHeader(wxT("User-Agent")).IsNull())
199 SetHeader(wxT("User-Agent"), wxT("wxWindows 2.x"));
200
201 switch (req) {
202 case wxHTTP_GET:
203 tmp_buf = wxT("GET");
204 break;
205 default:
206 return FALSE;
207 }
208
209 SaveState();
210 SetFlags(NONE);
211 Notify(FALSE);
212
213 wxSprintf(buf, wxT("%s %s HTTP/1.0\n\r"), tmp_buf, tmp_str.GetData());
214 const wxWX2MBbuf pathbuf = wxConvLibc.cWX2MB(buf);
215 Write(pathbuf, strlen(wxMBSTRINGCAST pathbuf));
216 SendHeaders();
217 Write("\n\r", 2);
218
219 m_perr = GetLine(this, tmp_str);
220 if (m_perr != wxPROTO_NOERR) {
221 RestoreState();
222 return FALSE;
223 }
224
225 if (!tmp_str.Contains(wxT("HTTP/"))) {
226 // TODO: support HTTP v0.9 which can have no header.
227 // FIXME: tmp_str is not put back in the in-queue of the socket.
228 SetHeader(wxT("Content-Length"), wxT("-1"));
229 SetHeader(wxT("Content-Type"), wxT("none/none"));
230 RestoreState();
231 return TRUE;
232 }
233
234 wxStringTokenizer token(tmp_str,wxT(' '));
235 wxString tmp_str2;
236 bool ret_value;
237
238 token.NextToken();
239 tmp_str2 = token.NextToken();
240
241 switch (tmp_str2[(unsigned int) 0]) {
242 case wxT('1'):
243 /* INFORMATION / SUCCESS */
244 break;
245 case wxT('2'):
246 /* SUCCESS */
247 break;
248 case wxT('3'):
249 /* REDIRECTION */
250 break;
251 default:
252 m_perr = wxPROTO_NOFILE;
253 RestoreState();
254 return FALSE;
255 }
256
257 ret_value = ParseHeaders();
258 RestoreState();
259 return ret_value;
260 }
261
262 class wxHTTPStream : public wxSocketInputStream {
263 public:
264 wxHTTP *m_http;
265 size_t m_httpsize;
266 unsigned long m_read_bytes;
267
268 wxHTTPStream(wxHTTP *http) : wxSocketInputStream(*http), m_http(http) {}
269 size_t GetSize() const { return m_httpsize; }
270 virtual ~wxHTTPStream(void) { m_http->Abort(); }
271
272 protected:
273 size_t OnSysRead(void *buffer, size_t bufsize);
274 };
275
276 size_t wxHTTPStream::OnSysRead(void *buffer, size_t bufsize)
277 {
278 size_t ret;
279
280 if (m_httpsize > 0 && m_read_bytes >= m_httpsize)
281 return 0;
282
283 ret = wxSocketInputStream::OnSysRead(buffer, bufsize);
284 m_read_bytes += ret;
285
286 return ret;
287 }
288
289 bool wxHTTP::Abort(void)
290 {
291 bool ret;
292
293 ret = wxSocketClient::Close();
294
295 return ret;
296 }
297
298 wxInputStream *wxHTTP::GetInputStream(const wxString& path)
299 {
300 wxHTTPStream *inp_stream = new wxHTTPStream(this);
301 wxString new_path;
302
303 m_perr = wxPROTO_CONNERR;
304 if (!m_addr)
305 return NULL;
306
307 // We set m_connected back to FALSE so wxSocketBase will know what to do.
308 if (!wxProtocol::Connect(*m_addr))
309 return NULL;
310
311 if (!BuildRequest(path, wxHTTP_GET))
312 return NULL;
313
314 if (!GetHeader(wxT("Content-Length")).IsEmpty())
315 inp_stream->m_httpsize = wxAtoi(WXSTRINGCAST GetHeader(wxT("Content-Length")));
316 else
317 inp_stream->m_httpsize = (size_t)-1;
318
319 inp_stream->m_read_bytes = 0;
320
321 Notify(FALSE);
322 SetFlags(SPEED | WAITALL);
323
324 return inp_stream;
325 }
326
327 #endif
328 // wxUSE_SOCKETS