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
8 // Copyright: (c) 1997, 1998 Guilhem Lavaux
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // For compilers that support precompilation, includes "wx.h".
13 #include "wx/wxprec.h"
19 #if wxUSE_PROTOCOL_HTTP
25 #include "wx/string.h"
29 #include "wx/tokenzr.h"
30 #include "wx/socket.h"
31 #include "wx/protocol/protocol.h"
33 #include "wx/protocol/http.h"
34 #include "wx/sckstrm.h"
35 #include "wx/thread.h"
38 // ----------------------------------------------------------------------------
40 // ----------------------------------------------------------------------------
42 IMPLEMENT_DYNAMIC_CLASS(wxHTTP
, wxProtocol
)
43 IMPLEMENT_PROTOCOL(wxHTTP
, wxT("http"), wxT("80"), true)
53 SetNotify(wxSOCKET_LOST_FLAG
);
63 void wxHTTP::ClearHeaders()
68 void wxHTTP::ClearCookies()
73 wxString
wxHTTP::GetContentType() const
75 return GetHeader(wxT("Content-Type"));
78 void wxHTTP::SetProxyMode(bool on
)
83 wxHTTP::wxHeaderIterator
wxHTTP::FindHeader(const wxString
& header
)
85 wxHeaderIterator it
= m_headers
.begin();
86 for ( wxHeaderIterator en
= m_headers
.end(); it
!= en
; ++it
)
88 if ( header
.CmpNoCase(it
->first
) == 0 )
95 wxHTTP::wxHeaderConstIterator
wxHTTP::FindHeader(const wxString
& header
) const
97 wxHeaderConstIterator it
= m_headers
.begin();
98 for ( wxHeaderConstIterator en
= m_headers
.end(); it
!= en
; ++it
)
100 if ( header
.CmpNoCase(it
->first
) == 0 )
107 wxHTTP::wxCookieIterator
wxHTTP::FindCookie(const wxString
& cookie
)
109 wxCookieIterator it
= m_cookies
.begin();
110 for ( wxCookieIterator en
= m_cookies
.end(); it
!= en
; ++it
)
112 if ( cookie
.CmpNoCase(it
->first
) == 0 )
119 wxHTTP::wxCookieConstIterator
wxHTTP::FindCookie(const wxString
& cookie
) const
121 wxCookieConstIterator it
= m_cookies
.begin();
122 for ( wxCookieConstIterator en
= m_cookies
.end(); it
!= en
; ++it
)
124 if ( cookie
.CmpNoCase(it
->first
) == 0 )
131 void wxHTTP::SetHeader(const wxString
& header
, const wxString
& h_data
)
138 wxHeaderIterator it
= FindHeader(header
);
139 if (it
!= m_headers
.end())
142 m_headers
[header
] = h_data
;
145 wxString
wxHTTP::GetHeader(const wxString
& header
) const
147 wxHeaderConstIterator it
= FindHeader(header
);
149 return it
== m_headers
.end() ? wxGetEmptyString() : it
->second
;
152 wxString
wxHTTP::GetCookie(const wxString
& cookie
) const
154 wxCookieConstIterator it
= FindCookie(cookie
);
156 return it
== m_cookies
.end() ? wxGetEmptyString() : it
->second
;
159 wxString
wxHTTP::GenerateAuthString(const wxString
& user
, const wxString
& pass
) const
161 // TODO: Use wxBase64Encode() now that we have it instead of reproducing it
163 static const char *base64
= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
168 buf
.Printf(wxT("Basic "));
170 toencode
.Printf(wxT("%s:%s"),user
.c_str(),pass
.c_str());
172 size_t len
= toencode
.length();
173 const wxChar
*from
= toencode
.c_str();
174 while (len
>= 3) { // encode full blocks first
175 buf
<< wxString::Format(wxT("%c%c"), base64
[(from
[0] >> 2) & 0x3f], base64
[((from
[0] << 4) & 0x30) | ((from
[1] >> 4) & 0xf)]);
176 buf
<< wxString::Format(wxT("%c%c"), base64
[((from
[1] << 2) & 0x3c) | ((from
[2] >> 6) & 0x3)], base64
[from
[2] & 0x3f]);
180 if (len
> 0) { // pad the remaining characters
181 buf
<< wxString::Format(wxT("%c"), base64
[(from
[0] >> 2) & 0x3f]);
183 buf
<< wxString::Format(wxT("%c="), base64
[(from
[0] << 4) & 0x30]);
185 buf
<< wxString::Format(wxT("%c%c"), base64
[((from
[0] << 4) & 0x30) | ((from
[1] >> 4) & 0xf)], base64
[(from
[1] << 2) & 0x3c]);
193 void wxHTTP::SetPostBuffer(const wxString
& post_buf
)
195 // Use To8BitData() for backwards compatibility in this deprecated method.
196 // The new code should use the other overload or SetPostText() and specify
197 // the encoding to use for the text explicitly.
198 wxScopedCharBuffer scb
= post_buf
.To8BitData();
201 m_postBuffer
.Clear();
202 m_postBuffer
.AppendData(scb
.data(), scb
.length());
207 wxHTTP::SetPostBuffer(const wxString
& contentType
,
208 const wxMemoryBuffer
& data
)
211 m_contentType
= contentType
;
213 return !m_postBuffer
.IsEmpty();
217 wxHTTP::SetPostText(const wxString
& contentType
,
218 const wxString
& data
,
219 const wxMBConv
& conv
)
222 wxScopedCharBuffer scb
= data
.mb_str(conv
);
223 const size_t len
= scb
.length();
224 const char* const buf
= scb
.data();
225 #else // !wxUSE_UNICODE
226 const size_t len
= data
.length();
227 const char* const buf
= data
.mb_str(conv
);
228 #endif // wxUSE_UNICODE/!wxUSE_UNICODE
233 m_postBuffer
.Clear();
234 m_postBuffer
.AppendData(buf
, len
);
235 m_contentType
= contentType
;
240 void wxHTTP::SendHeaders()
242 typedef wxStringToStringHashMap::iterator iterator
;
245 for (iterator it
= m_headers
.begin(), en
= m_headers
.end(); it
!= en
; ++it
)
247 buf
.Printf(wxT("%s: %s\r\n"), it
->first
.c_str(), it
->second
.c_str());
249 const wxWX2MBbuf cbuf
= buf
.mb_str();
250 Write(cbuf
, strlen(cbuf
));
254 bool wxHTTP::ParseHeaders()
257 wxStringTokenizer tokenzr
;
265 m_lastError
= ReadLine(this, line
);
266 if (m_lastError
!= wxPROTO_NOERR
)
272 wxString left_str
= line
.BeforeFirst(':');
273 if(!left_str
.CmpNoCase("Set-Cookie"))
275 wxString cookieName
= line
.AfterFirst(':').Strip(wxString::both
).BeforeFirst('=');
276 wxString cookieValue
= line
.AfterFirst(':').Strip(wxString::both
).AfterFirst('=').BeforeFirst(';');
277 m_cookies
[cookieName
] = cookieValue
;
280 m_headers
[left_str
] = line
.AfterFirst(':').Strip(wxString::both
);
284 m_headers
[left_str
] = line
.AfterFirst(':').Strip(wxString::both
);
290 bool wxHTTP::Connect(const wxString
& host
, unsigned short port
)
299 m_addr
= addr
= new wxIPV4address();
301 if (!addr
->Hostname(host
)) {
303 m_lastError
= wxPROTO_NETERR
;
309 else if (!addr
->Service(wxT("http")))
312 wxString hostHdr
= host
;
313 if ( port
&& port
!= 80 )
314 hostHdr
<< wxT(":") << port
;
315 SetHeader(wxT("Host"), hostHdr
);
317 m_lastError
= wxPROTO_NOERR
;
321 bool wxHTTP::Connect(const wxSockAddress
& addr
, bool WXUNUSED(wait
))
328 m_addr
= addr
.Clone();
330 wxIPV4address
*ipv4addr
= wxDynamicCast(&addr
, wxIPV4address
);
333 wxString hostHdr
= ipv4addr
->OrigHostname();
334 unsigned short port
= ipv4addr
->Service();
335 if ( port
&& port
!= 80 )
336 hostHdr
<< wxT(":") << port
;
337 SetHeader(wxT("Host"), hostHdr
);
340 m_lastError
= wxPROTO_NOERR
;
344 bool wxHTTP::BuildRequest(const wxString
& path
, const wxString
& method
)
346 // Use the data in the post buffer, if any.
347 if ( !m_postBuffer
.IsEmpty() )
350 len
<< m_postBuffer
.GetDataLen();
352 // Content length must be correct, so always set, possibly
353 // overriding the value set explicitly by a previous call to
354 // SetHeader("Content-Length").
355 SetHeader(wxS("Content-Length"), len
);
357 // However if the user had explicitly set the content type, don't
358 // override it with the content type passed to SetPostText().
359 if ( !m_contentType
.empty() && GetContentType().empty() )
360 SetHeader(wxS("Content-Type"), m_contentType
);
365 // If there is no User-Agent defined, define it.
366 if ( GetHeader(wxT("User-Agent")).empty() )
367 SetHeader(wxT("User-Agent"), wxT("wxWidgets 2.x"));
369 // Send authentication information
370 if (!m_username
.empty() || !m_password
.empty()) {
371 SetHeader(wxT("Authorization"), GenerateAuthString(m_username
, m_password
));
376 // we may use non blocking sockets only if we can dispatch events from them
377 int flags
= wxIsMainThread() && wxApp::IsMainLoopRunning() ? wxSOCKET_NONE
379 // and we must use wxSOCKET_WAITALL to ensure that all data is sent
380 flags
|= wxSOCKET_WAITALL
;
385 buf
.Printf(wxT("%s %s HTTP/1.0\r\n"), method
, path
);
386 const wxWX2MBbuf pathbuf
= buf
.mb_str();
387 Write(pathbuf
, strlen(pathbuf
));
391 if ( !m_postBuffer
.IsEmpty() ) {
392 Write(m_postBuffer
.GetData(), m_postBuffer
.GetDataLen());
394 m_postBuffer
.Clear();
398 m_lastError
= ReadLine(this, tmp_str
);
399 if (m_lastError
!= wxPROTO_NOERR
) {
404 if (!tmp_str
.Contains(wxT("HTTP/"))) {
405 // TODO: support HTTP v0.9 which can have no header.
406 // FIXME: tmp_str is not put back in the in-queue of the socket.
407 m_lastError
= wxPROTO_NOERR
;
408 SetHeader(wxT("Content-Length"), wxT("-1"));
409 SetHeader(wxT("Content-Type"), wxT("none/none"));
414 wxStringTokenizer
token(tmp_str
,wxT(' '));
419 tmp_str2
= token
.NextToken();
421 m_http_response
= wxAtoi(tmp_str2
);
423 switch ( tmp_str2
[0u].GetValue() )
426 /* INFORMATION / SUCCESS */
438 m_lastError
= wxPROTO_NOFILE
;
443 m_lastError
= wxPROTO_NOERR
;
444 ret_value
= ParseHeaders();
449 bool wxHTTP::Abort(void)
451 return wxSocketClient::Close();
454 // ----------------------------------------------------------------------------
455 // wxHTTPStream and wxHTTP::GetInputStream
456 // ----------------------------------------------------------------------------
458 class wxHTTPStream
: public wxSocketInputStream
463 unsigned long m_read_bytes
;
465 wxHTTPStream(wxHTTP
*http
) : wxSocketInputStream(*http
)
472 size_t GetSize() const { return m_httpsize
; }
473 virtual ~wxHTTPStream(void) { m_http
->Abort(); }
476 size_t OnSysRead(void *buffer
, size_t bufsize
);
478 wxDECLARE_NO_COPY_CLASS(wxHTTPStream
);
481 size_t wxHTTPStream::OnSysRead(void *buffer
, size_t bufsize
)
483 if (m_read_bytes
>= m_httpsize
)
485 m_lasterror
= wxSTREAM_EOF
;
489 size_t ret
= wxSocketInputStream::OnSysRead(buffer
, bufsize
);
492 if (m_httpsize
==(size_t)-1 && m_lasterror
== wxSTREAM_READ_ERROR
)
494 // if m_httpsize is (size_t) -1 this means read until connection closed
495 // which is equivalent to getting a READ_ERROR, for clients however this
496 // must be translated into EOF, as it is the expected way of signalling
497 // end end of the content
498 m_lasterror
= wxSTREAM_EOF
;
504 wxInputStream
*wxHTTP::GetInputStream(const wxString
& path
)
506 wxHTTPStream
*inp_stream
;
510 m_lastError
= wxPROTO_CONNERR
; // all following returns share this type of error
514 // We set m_connected back to false so wxSocketBase will know what to do.
516 wxSocketClient::Connect(*m_addr
, false );
517 wxSocketClient::WaitOnConnect(10);
519 if (!wxSocketClient::IsConnected())
522 if (!wxProtocol::Connect(*m_addr
))
526 // Use the user-specified method if any or determine the method to use
527 // automatically depending on whether we have anything to post or not.
528 wxString method
= m_method
;
530 method
= m_postBuffer
.IsEmpty() ? wxS("GET"): wxS("POST");
532 if (!BuildRequest(path
, method
))
535 inp_stream
= new wxHTTPStream(this);
537 if (!GetHeader(wxT("Content-Length")).empty())
538 inp_stream
->m_httpsize
= wxAtoi(GetHeader(wxT("Content-Length")));
540 inp_stream
->m_httpsize
= (size_t)-1;
542 inp_stream
->m_read_bytes
= 0;
545 SetFlags(wxSOCKET_BLOCK
| wxSOCKET_WAITALL
);
547 // no error; reset m_lastError
548 m_lastError
= wxPROTO_NOERR
;
552 #endif // wxUSE_PROTOCOL_HTTP