Commit 086ef006 authored by Max Lv's avatar Max Lv

remove spdylay

parent 0c6eeae0
......@@ -57,71 +57,6 @@ include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
SPDYLAY_SOURCES := spdylay_buffer.c \
spdylay_client_cert_vector.c \
spdylay_frame.c \
spdylay_gzip.c \
spdylay_helper.c \
spdylay_map.c \
spdylay_npn.c \
spdylay_outbound_item.c \
spdylay_pq.c \
spdylay_queue.c \
spdylay_session.c \
spdylay_stream.c \
spdylay_submit.c \
spdylay_zlib.c
LOCAL_STATIC_LIBRARIES := libevent libcrypto
LOCAL_MODULE := spdylay
LOCAL_SRC_FILES := $(addprefix spdylay/, $(SPDYLAY_SOURCES))
LOCAL_CFLAGS := -O2 -g -I$(LOCAL_PATH)/spdylay \
-I$(LOCAL_PATH)/spdylay/includes \
-I$(LOCAL_PATH)/libevent/include \
-I$(LOCAL_PATH)/libevent \
-I$(LOCAL_PATH)/openssl/include
include $(BUILD_STATIC_LIBRARY)
include $(CLEAR_VARS)
SHRPX_SOURCES := util.cc spdylay_ssl.cc \
spdylay_config.h shrpx_config.cc \
shrpx_listen_handler.cc \
shrpx_client_handler.cc \
shrpx_upstream.h shrpx_spdy_upstream.cc \
shrpx_https_upstream.cc \
shrpx_downstream_queue.cc \
shrpx_downstream.cc \
shrpx_downstream_connection.cc \
shrpx_http_downstream_connection.cc \
shrpx_spdy_downstream_connection.cc \
shrpx_spdy_session.cc \
shrpx_log.cc shrpx_http.cc \
shrpx_io_control.cc \
shrpx_ssl.cc shrpx_thread_event_receiver.cc \
shrpx_worker.cc \
shrpx_accesslog.cc http-parser/http_parser.c \
shrpx.cc
LOCAL_STATIC_LIBRARIES := libevent libssl libcrypto libspdylay
LOCAL_LDLIBS := -lz
LOCAL_MODULE := shrpx
LOCAL_SRC_FILES := $(addprefix shrpx/, $(SHRPX_SOURCES))
LOCAL_CFLAGS := -O2 -g -I$(LOCAL_PATH)/spdylay \
-I$(LOCAL_PATH)/spdylay/includes \
-I$(LOCAL_PATH)/shrpx \
-I$(LOCAL_PATH)/libevent/include \
-I$(LOCAL_PATH)/libevent \
-I$(LOCAL_PATH)/openssl/include
include $(BUILD_EXECUTABLE)
include $(CLEAR_VARS)
OBFSPROXY_SOURCES := container.c crypt.c external.c \
main.c managed.c network.c \
obfs_main.c protocol.c sha256.c \
......
/*
* Spdylay - SPDY Library
*
* Copyright (c) 2012 Tatsuhiro Tsujikawa
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef EVENT_POLL_H
#define EVENT_POLL_H
#include "spdylay_config.h"
#ifdef HAVE_EPOLL
# include "EventPoll_epoll.h"
#elif HAVE_KQUEUE
# include "EventPoll_kqueue.h"
#endif // HAVE_KQUEUE
#endif // EVENT_POLL_H
/*
* Spdylay - SPDY Library
*
* Copyright (c) 2012 Tatsuhiro Tsujikawa
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef EVENT_POLL_EVENT_H
#define EVENT_POLL_EVENT_H
#include "spdylay_config.h"
namespace spdylay {
enum EventPollEvent {
EP_POLLIN = 1,
EP_POLLOUT = 1 << 1,
EP_POLLHUP = 1 << 2,
EP_POLLERR = 1 << 3
};
enum EventPollOp {
EP_ADD,
EP_MOD
};
} // namespace spdylay
#endif // EVENT_POLL_EVENT_H
/*
* Spdylay - SPDY Library
*
* Copyright (c) 2012 Tatsuhiro Tsujikawa
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "EventPoll_epoll.h"
#include <unistd.h>
#include <cassert>
namespace spdylay {
EventPoll::EventPoll(size_t max_events)
: max_events_(max_events), num_events_(0)
{
epfd_ = epoll_create(1);
assert(epfd_ != -1);
evlist_ = new epoll_event[max_events_];
}
EventPoll::~EventPoll()
{
if(epfd_ != -1) {
close(epfd_);
}
delete [] evlist_;
}
int EventPoll::poll(int timeout)
{
num_events_ = 0;
int n = epoll_wait(epfd_, evlist_, max_events_, timeout);
if(n > 0) {
num_events_ = n;
}
return n;
}
int EventPoll::get_num_events()
{
return num_events_;
}
void* EventPoll::get_user_data(size_t p)
{
return evlist_[p].data.ptr;
}
int EventPoll::get_events(size_t p)
{
int events = 0;
int revents = evlist_[p].events;
if(revents & EPOLLIN) {
events |= EP_POLLIN;
}
if(revents & EPOLLOUT) {
events |= EP_POLLOUT;
}
if(revents & EPOLLHUP) {
events |= EP_POLLHUP;
}
if(revents & EPOLLERR) {
events |= EP_POLLERR;
}
return events;
}
namespace {
int update_event(int epfd, int op, int fd, int events, void *user_data)
{
epoll_event ev;
ev.events = 0;
if(events & EP_POLLIN) {
ev.events |= EPOLLIN;
}
if(events & EP_POLLOUT) {
ev.events |= EPOLLOUT;
}
ev.data.ptr = user_data;
return epoll_ctl(epfd, op, fd, &ev);
}
} // namespace
int EventPoll::ctl_event(int op, int fd, int events, void *user_data)
{
if(op == EP_ADD) {
op = EPOLL_CTL_ADD;
} else if(op == EP_MOD) {
op = EPOLL_CTL_MOD;
} else {
return -1;
}
return update_event(epfd_, op, fd, events, user_data);
}
} // namespace spdylay
/*
* Spdylay - SPDY Library
*
* Copyright (c) 2012 Tatsuhiro Tsujikawa
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef EVENT_POLL_EPOLL_H
#define EVENT_POLL_EPOLL_H
#include "spdylay_config.h"
#include <cstdlib>
#include <sys/epoll.h>
#include "EventPollEvent.h"
namespace spdylay {
class EventPoll {
public:
EventPoll(size_t max_events);
~EventPoll();
// Returns 0 if this function succeeds, or -1.
// On success
int poll(int timeout);
// Returns number of events detected in previous call of poll().
int get_num_events();
// Returns events of p-eth event.
int get_events(size_t p);
// Returns user data of p-th event.
void* get_user_data(size_t p);
// Adds/Modifies event to watch.
int ctl_event(int op, int fd, int events, void *user_data);
private:
int epfd_;
size_t max_events_;
epoll_event *evlist_;
size_t num_events_;
};
} // namespace spdylay
#endif // EVENT_POLL_EPOLL_H
/*
* Spdylay - SPDY Library
*
* Copyright (c) 2012 Tatsuhiro Tsujikawa
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "EventPoll_kqueue.h"
#include <unistd.h>
#include <cerrno>
#include <cassert>
#ifdef KEVENT_UDATA_INTPTR_T
# define PTR_TO_UDATA(X) (reinterpret_cast<intptr_t>(X))
#else // !KEVENT_UDATA_INTPTR_T
# define PTR_TO_UDATA(X) (X)
#endif // !KEVENT_UDATA_INTPTR_T
namespace spdylay {
EventPoll::EventPoll(size_t max_events)
: max_events_(max_events), num_events_(0)
{
kq_ = kqueue();
assert(kq_ != -1);
evlist_ = new struct kevent[max_events_];
}
EventPoll::~EventPoll()
{
if(kq_ != -1) {
close(kq_);
}
delete [] evlist_;
}
int EventPoll::poll(int timeout)
{
timespec ts, *ts_ptr;
if(timeout == -1) {
ts_ptr = 0;
} else {
ts.tv_sec = timeout/1000;
ts.tv_nsec = (timeout%1000)*1000000;
ts_ptr = &ts;
}
num_events_ = 0;
int n;
while((n = kevent(kq_, evlist_, 0, evlist_, max_events_, ts_ptr)) == -1 &&
errno == EINTR);
if(n > 0) {
num_events_ = n;
}
return n;
}
int EventPoll::get_num_events()
{
return num_events_;
}
void* EventPoll::get_user_data(size_t p)
{
return reinterpret_cast<void*>(evlist_[p].udata);
}
int EventPoll::get_events(size_t p)
{
int events = 0;
short filter = evlist_[p].filter;
if(filter == EVFILT_READ) {
events |= EP_POLLIN;
}
if(filter == EVFILT_WRITE) {
events |= EP_POLLOUT;
}
return events;
}
namespace {
int update_event(int kq, int fd, int events, void *user_data)
{
struct kevent changelist[2];
EV_SET(&changelist[0], fd, EVFILT_READ,
EV_ADD | ((events & EP_POLLIN) ? EV_ENABLE : EV_DISABLE),
0, 0, PTR_TO_UDATA(user_data));
EV_SET(&changelist[1], fd, EVFILT_WRITE,
EV_ADD | ((events & EP_POLLOUT) ? EV_ENABLE : EV_DISABLE),
0, 0, PTR_TO_UDATA(user_data));
timespec ts = { 0, 0 };
return kevent(kq, changelist, 2, changelist, 0, &ts);
}
} // namespace
int EventPoll::ctl_event(int op, int fd, int events, void *user_data)
{
return update_event(kq_, fd, events, user_data);
}
} // namespace spdylay
/*
* Spdylay - SPDY Library
*
* Copyright (c) 2012 Tatsuhiro Tsujikawa
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef EVENT_POLL_KQUEUE_H
#define EVENT_POLL_KQUEUE_H
#include "spdylay_config.h"
#include <cstdlib>
#include <sys/types.h>
#include <sys/event.h>
#include <sys/time.h>
#include "EventPollEvent.h"
namespace spdylay {
class EventPoll {
public:
EventPoll(size_t max_events);
~EventPoll();
// Returns 0 if this function succeeds, or -1.
// On success
int poll(int timeout);
// Returns number of events detected in previous call of poll().
int get_num_events();
// Returns events of p-eth event.
int get_events(size_t p);
// Returns user data of p-th event.
void* get_user_data(size_t p);
// Adds/Modifies event to watch.
int ctl_event(int op, int fd, int events, void *user_data);
private:
int kq_;
size_t max_events_;
struct kevent *evlist_;
size_t num_events_;
};
} // namespace spdylay
#endif // EVENT_POLL_KQUEUE_H
/*
* Spdylay - SPDY Library
*
* Copyright (c) 2012 Tatsuhiro Tsujikawa
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "HtmlParser.h"
#include <libxml/uri.h>
#include "util.h"
namespace spdylay {
ParserData::ParserData(const std::string& base_uri)
: base_uri(base_uri)
{}
HtmlParser::HtmlParser(const std::string& base_uri)
: base_uri_(base_uri),
parser_ctx_(0),
parser_data_(base_uri)
{}
HtmlParser::~HtmlParser()
{
htmlFreeParserCtxt(parser_ctx_);
}
namespace {
const char* get_attr(const xmlChar **attrs, const char *name)
{
for(; *attrs; attrs += 2) {
if(util::strieq(reinterpret_cast<const char*>(attrs[0]), name)) {
return reinterpret_cast<const char*>(attrs[1]);
}
}
return 0;
}
} // namespace
namespace {
void start_element_func
(void* user_data,
const xmlChar *name,
const xmlChar **attrs)
{
ParserData *parser_data = reinterpret_cast<ParserData*>(user_data);
if(util::strieq(reinterpret_cast<const char*>(name), "link")) {
const char *rel_attr = get_attr(attrs, "rel");
const char *href_attr = get_attr(attrs, "href");
if((util::strieq(rel_attr, "shortcut icon") ||
util::strieq(rel_attr, "stylesheet")) &&
href_attr) {
xmlChar *u = xmlBuildURI(reinterpret_cast<const xmlChar*>(href_attr),
reinterpret_cast<const xmlChar*>
(parser_data->base_uri.c_str()));
if(u) {
parser_data->links.push_back(reinterpret_cast<char*>(u));
free(u);
}
}
} else if(util::strieq(reinterpret_cast<const char*>(name), "img")) {
const char *src_attr = get_attr(attrs, "src");
if(src_attr) {
xmlChar *u = xmlBuildURI(reinterpret_cast<const xmlChar*>(src_attr),
reinterpret_cast<const xmlChar*>
(parser_data->base_uri.c_str()));
if(u) {
parser_data->links.push_back(reinterpret_cast<char*>(u));
free(u);
}
}
}
}
} // namespace
namespace {
xmlSAXHandler saxHandler =
{
0, // internalSubsetSAXFunc
0, // isStandaloneSAXFunc
0, // hasInternalSubsetSAXFunc
0, // hasExternalSubsetSAXFunc
0, // resolveEntitySAXFunc
0, // getEntitySAXFunc
0, // entityDeclSAXFunc
0, // notationDeclSAXFunc
0, // attributeDeclSAXFunc
0, // elementDeclSAXFunc
0, // unparsedEntityDeclSAXFunc
0, // setDocumentLocatorSAXFunc
0, // startDocumentSAXFunc
0, // endDocumentSAXFunc
&start_element_func, // startElementSAXFunc
0, // endElementSAXFunc
0, // referenceSAXFunc
0, // charactersSAXFunc
0, // ignorableWhitespaceSAXFunc
0, // processingInstructionSAXFunc
0, // commentSAXFunc
0, // warningSAXFunc
0, // errorSAXFunc
0, // fatalErrorSAXFunc
0, // getParameterEntitySAXFunc
0, // cdataBlockSAXFunc
0, // externalSubsetSAXFunc
0, // unsigned int initialized
0, // void * _private
0, // startElementNsSAX2Func
0, // endElementNsSAX2Func
0, // xmlStructuredErrorFunc
};
} // namespace
int HtmlParser::parse_chunk(const char *chunk, size_t size, int fin)
{
if(!parser_ctx_) {
parser_ctx_ = htmlCreatePushParserCtxt(&saxHandler,
&parser_data_,
chunk, size,
base_uri_.c_str(),
XML_CHAR_ENCODING_NONE);
if(!parser_ctx_) {
return -1;
} else {
if(fin) {
return parse_chunk_internal(0, 0, fin);
} else {
return 0;
}
}
} else {
return parse_chunk_internal(chunk, size, fin);
}
}
int HtmlParser::parse_chunk_internal(const char *chunk, size_t size,
int fin)
{
int rv = htmlParseChunk(parser_ctx_, chunk, size, fin);
if(rv == 0) {
return 0;
} else {
return -1;
}
}
const std::vector<std::string>& HtmlParser::get_links() const
{
return parser_data_.links;
}
void HtmlParser::clear_links()
{
parser_data_.links.clear();
}
} // namespace spdylay
/*
* Spdylay - SPDY Library
*
* Copyright (c) 2012 Tatsuhiro Tsujikawa
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef HTML_PARSER_H
#define HTML_PARSER_H
#include "spdylay_config.h"
#include <vector>
#include <string>
#ifdef HAVE_LIBXML2
#include <libxml/HTMLparser.h>
namespace spdylay {
struct ParserData {
std::string base_uri;
std::vector<std::string> links;
ParserData(const std::string& base_uri);
};
class HtmlParser {
public:
HtmlParser(const std::string& base_uri);
~HtmlParser();
int parse_chunk(const char *chunk, size_t size, int fin);
const std::vector<std::string>& get_links() const;
void clear_links();
private:
int parse_chunk_internal(const char *chunk, size_t size, int fin);
std::string base_uri_;
htmlParserCtxtPtr parser_ctx_;
ParserData parser_data_;
};
} // namespace spdylay
#else // !HAVE_LIBXML2
namespace spdylay {
class HtmlParser {
public:
HtmlParser(const std::string& base_uri) {}
~HtmlParser() {}
int parse_chunk(const char *chunk, size_t size, int fin) { return 0; }
const std::vector<std::string>& get_links() const { return links_; }
void clear_links() {}
private:
std::vector<std::string> links_;
};
} // namespace spdylay
#endif // !HAVE_LIBXML2
#endif // HTML_PARSER_H
This diff is collapsed.
/*
* Spdylay - SPDY Library
*
* Copyright (c) 2012 Tatsuhiro Tsujikawa
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef SPDY_SERVER_H
#define SPDY_SERVER_H
#include "spdylay_config.h"
#include <stdint.h>
#include <sys/types.h>
#include <cstdlib>
#include <string>
#include <vector>
#include <map>
#include <openssl/ssl.h>
#include <spdylay/spdylay.h>
namespace spdylay {
struct Config {
std::string htdocs;
bool verbose;
bool daemon;
std::string host;
uint16_t port;
std::string private_key_file;
std::string cert_file;
spdylay_on_request_recv_callback on_request_recv_callback;
void *data_ptr;
uint16_t version;
bool verify_client;
bool no_tls;
Config();
};
class Sessions;
class EventHandler {
public:
EventHandler(const Config *config);
virtual ~EventHandler() {}
virtual int execute(Sessions *sessions) = 0;
virtual bool want_read() = 0;
virtual bool want_write() = 0;
virtual int fd() const = 0;
virtual bool finish() = 0;
const Config* config() const
{
return config_;
}
bool mark_del()
{
return mark_del_;
}
void mark_del(bool d)
{
mark_del_ = d;
}
private:
const Config *config_;
bool mark_del_;
};
struct Request {
int32_t stream_id;
std::vector<std::pair<std::string, std::string> > headers;
int file;
std::pair<std::string, size_t> response_body;
Request(int32_t stream_id);
~Request();
};
class SpdyEventHandler : public EventHandler {
public:
SpdyEventHandler(const Config* config,
int fd, SSL *ssl, uint16_t version,
const spdylay_session_callbacks *callbacks,
int64_t session_id);
virtual ~SpdyEventHandler();
virtual int execute(Sessions *sessions);
virtual bool want_read();
virtual bool want_write();
virtual int fd() const;
virtual bool finish();
uint16_t version() const;
ssize_t send_data(const uint8_t *data, size_t len, int flags);
ssize_t recv_data(uint8_t *data, size_t len, int flags);
bool would_block() const;
int submit_file_response(const std::string& status,
int32_t stream_id,
time_t last_modified,
off_t file_length,
spdylay_data_provider *data_prd);
int submit_response(const std::string& status,
int32_t stream_id,
spdylay_data_provider *data_prd);
int submit_response
(const std::string& status,
int32_t stream_id,
const std::vector<std::pair<std::string, std::string> >& headers,
spdylay_data_provider *data_prd);
void add_stream(int32_t stream_id, Request *req);
void remove_stream(int32_t stream_id);
Request* get_stream(int32_t stream_id);
int64_t session_id() const;
private:
spdylay_session *session_;
int fd_;
SSL* ssl_;
uint16_t version_;
int64_t session_id_;
uint8_t io_flags_;
std::map<int32_t, Request*> id2req_;
};
class SpdyServer {
public:
SpdyServer(const Config* config);
~SpdyServer();
int listen();
int run();
private:
const Config *config_;
int sfd_[2];
};
void htdocs_on_request_recv_callback
(spdylay_session *session, int32_t stream_id, void *user_data);
ssize_t file_read_callback
(spdylay_session *session, int32_t stream_id,
uint8_t *buf, size_t length, int *eof,
spdylay_data_source *source, void *user_data);
} // namespace spdylay
#endif // SPDY_SERVER_H
/*
* Spdylay - SPDY Library
*
* Copyright (c) 2013 Tatsuhiro Tsujikawa
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef BASE64_H
#define BASE64_H
#include <string>
namespace spdylay {
namespace base64 {
template<typename InputIterator>
std::string encode(InputIterator first, InputIterator last)
{
static const char CHAR_TABLE[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/',
};
std::string res;
size_t len = last-first;
if(len == 0) {
return res;
}
size_t r = len%3;
InputIterator j = last-r;
char temp[4];
while(first != j) {
int n = static_cast<unsigned char>(*first++) << 16;
n += static_cast<unsigned char>(*first++) << 8;
n += static_cast<unsigned char>(*first++);
temp[0] = CHAR_TABLE[n >> 18];
temp[1] = CHAR_TABLE[(n >> 12) & 0x3fu];
temp[2] = CHAR_TABLE[(n >> 6) & 0x3fu];
temp[3] = CHAR_TABLE[n & 0x3fu];
res.append(temp, sizeof(temp));
}
if(r == 2) {
int n = static_cast<unsigned char>(*first++) << 16;
n += static_cast<unsigned char>(*first++) << 8;
temp[0] = CHAR_TABLE[n >> 18];
temp[1] = CHAR_TABLE[(n >> 12) & 0x3fu];
temp[2] = CHAR_TABLE[(n >> 6) & 0x3fu];
temp[3] = '=';
res.append(temp, sizeof(temp));
} else if(r == 1) {
int n = static_cast<unsigned char>(*first++) << 16;
temp[0] = CHAR_TABLE[n >> 18];
temp[1] = CHAR_TABLE[(n >> 12) & 0x3fu];
temp[2] = '=';
temp[3] = '=';
res.append(temp, sizeof(temp));
}
return res;
}
template<typename InputIterator>
InputIterator getNext
(InputIterator first,
InputIterator last,
const int* tbl)
{
for(; first != last; ++first) {
if(tbl[static_cast<size_t>(*first)] != -1 || *first == '=') {
break;
}
}
return first;
}
template<typename InputIterator>
std::string decode(InputIterator first, InputIterator last)
{
static const int INDEX_TABLE[] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
};
std::string res;
InputIterator k[4];
int eq = 0;
for(; first != last;) {
for(int i = 1; i <= 4; ++i) {
k[i-1] = getNext(first, last, INDEX_TABLE);
if(k[i-1] == last) {
// If i == 1, input may look like this: "TWFu\n" (i.e.,
// garbage at the end)
if(i != 1) {
res.clear();
}
return res;
} else if(*k[i-1] == '=' && eq == 0) {
eq = i;
}
first = k[i-1]+1;
}
if(eq) {
break;
}
int n = (INDEX_TABLE[static_cast<unsigned char>(*k[0])] << 18)+
(INDEX_TABLE[static_cast<unsigned char>(*k[1])] << 12)+
(INDEX_TABLE[static_cast<unsigned char>(*k[2])] << 6)+
INDEX_TABLE[static_cast<unsigned char>(*k[3])];
res += n >> 16;
res += n >> 8 & 0xffu;
res += n & 0xffu;
}
if(eq) {
if(eq <= 2) {
res.clear();
return res;
} else {
for(int i = eq; i <= 4; ++i) {
if(*k[i-1] != '=') {
res.clear();
return res;
}
}
if(eq == 3) {
int n = (INDEX_TABLE[static_cast<unsigned char>(*k[0])] << 18)+
(INDEX_TABLE[static_cast<unsigned char>(*k[1])] << 12);
res += n >> 16;
} else if(eq == 4) {
int n = (INDEX_TABLE[static_cast<unsigned char>(*k[0])] << 18)+
(INDEX_TABLE[static_cast<unsigned char>(*k[1])] << 12)+
(INDEX_TABLE[static_cast<unsigned char>(*k[2])] << 6);
res += n >> 16;
res += n >> 8 & 0xffu;
}
}
}
return res;
}
} // namespace base64
} // namespace spdylay
#endif // BASE64_H
/* config.h. Generated from config.h.in by configure. */
/* config.h.in. Generated from configure.ac by autoheader. */
/* Define if building universal (internal helper macro) */
/* #undef AC_APPLE_UNIVERSAL_BUILD */
/* Define to 1 if you have the <arpa/inet.h> header file. */
#define HAVE_ARPA_INET_H 1
/* Define to 1 if you have the `clock_gettime`. */
#define HAVE_CLOCK_GETTIME 1
/* Define to 1 if you have the <dlfcn.h> header file. */
#define HAVE_DLFCN_H 1
/* Define to 1 if you have the `epoll`. */
#define HAVE_EPOLL 1
/* Define to 1 if you have the `getpwnam' function. */
#define HAVE_GETPWNAM 1
/* Define to 1 if you have the <inttypes.h> header file. */
#define HAVE_INTTYPES_H 1
/* Define to 1 if you have the `kqueue' function. */
/* #undef HAVE_KQUEUE */
/* Define to 1 if you have `libxml2` library. */
#define HAVE_LIBXML2 1
/* Define to 1 if your system has a GNU libc compatible `malloc' function, and
to 0 otherwise. */
#define HAVE_MALLOC 1
/* Define to 1 if you have the `memmove' function. */
#define HAVE_MEMMOVE 1
/* Define to 1 if you have the <memory.h> header file. */
#define HAVE_MEMORY_H 1
/* Define to 1 if you have the `memset' function. */
#define HAVE_MEMSET 1
/* Define to 1 if you have the <netinet/in.h> header file. */
#define HAVE_NETINET_IN_H 1
/* Define to 1 if the system has the type `ptrdiff_t'. */
#define HAVE_PTRDIFF_T 1
/* Define to 1 if you have the <pwd.h> header file. */
#define HAVE_PWD_H 1
/* Define if g++ supports C++11 features. */
#define HAVE_STDCXX_11 /**/
/* Define to 1 if you have the <stddef.h> header file. */
#define HAVE_STDDEF_H 1
/* Define to 1 if you have the <stdint.h> header file. */
#define HAVE_STDINT_H 1
/* Define to 1 if you have the <stdlib.h> header file. */
#define HAVE_STDLIB_H 1
/* Define to 1 if you have the <strings.h> header file. */
#define HAVE_STRINGS_H 1
/* Define to 1 if you have the <string.h> header file. */
#define HAVE_STRING_H 1
/* Define to 1 if you have the <sys/stat.h> header file. */
#define HAVE_SYS_STAT_H 1
/* Define to 1 if you have the <sys/types.h> header file. */
#define HAVE_SYS_TYPES_H 1
/* Define to 1 if you have the <time.h> header file. */
#define HAVE_TIME_H 1
/* Define to 1 if you have the <unistd.h> header file. */
#define HAVE_UNISTD_H 1
/* Define to 1 if you have the <winsock2.h> header file. */
/* #undef HAVE_WINSOCK2_H */
/* Define to 1 if struct kevent.udata is intptr_t */
/* #undef KEVENT_UDATA_INTPTR_T */
/* Define to the sub-directory in which libtool stores uninstalled libraries.
*/
#define LT_OBJDIR ".libs/"
/* Define to 1 if your C compiler doesn't accept -c and -o together. */
/* #undef NO_MINUS_C_MINUS_O */
/* Name of package */
#define PACKAGE "spdylay"
/* Define to the address where bug reports for this package should be sent. */
#define PACKAGE_BUGREPORT "t-tujikawa@users.sourceforge.net"
/* Define to the full name of this package. */
#define PACKAGE_NAME "spdylay"
/* Define to the full name and version of this package. */
#define PACKAGE_STRING "spdylay 0.3.8-DEV"
/* Define to the one symbol short name of this package. */
#define PACKAGE_TARNAME "spdylay"
/* Define to the home page for this package. */
#define PACKAGE_URL ""
/* Define to the version of this package. */
#define PACKAGE_VERSION "0.3.8-DEV"
/* Define to 1 if you have the ANSI C header files. */
#define STDC_HEADERS 1
/* Version number of package */
#define VERSION "0.3.8-DEV"
/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most
significant byte first (like Motorola and SPARC, unlike Intel). */
#if defined AC_APPLE_UNIVERSAL_BUILD
# if defined __BIG_ENDIAN__
# define WORDS_BIGENDIAN 1
# endif
#else
# ifndef WORDS_BIGENDIAN
/* # undef WORDS_BIGENDIAN */
# endif
#endif
/* Number of bits in a file offset, on hosts where this is settable. */
#define _FILE_OFFSET_BITS 64
/* Define for large files, on AIX-style hosts. */
/* #undef _LARGE_FILES */
/* Define for Solaris 2.5.1 so the uint32_t typedef from <sys/synch.h>,
<pthread.h>, or <semaphore.h> is not used. If the typedef were allowed, the
#define below would cause a syntax error. */
/* #undef _UINT32_T */
/* Define for Solaris 2.5.1 so the uint64_t typedef from <sys/synch.h>,
<pthread.h>, or <semaphore.h> is not used. If the typedef were allowed, the
#define below would cause a syntax error. */
/* #undef _UINT64_T */
/* Define for Solaris 2.5.1 so the uint8_t typedef from <sys/synch.h>,
<pthread.h>, or <semaphore.h> is not used. If the typedef were allowed, the
#define below would cause a syntax error. */
/* #undef _UINT8_T */
/* Define to rpl_malloc if the replacement function should be used. */
/* #undef malloc */
/* Define to `unsigned int' if <sys/types.h> does not define. */
/* #undef size_t */
/* Define to `int' if <sys/types.h> does not define. */
/* #undef ssize_t */
/* Define to the type of an unsigned integer type of width exactly 16 bits if
such a type exists and the standard includes do not define it. */
/* #undef uint16_t */
/* Define to the type of an unsigned integer type of width exactly 32 bits if
such a type exists and the standard includes do not define it. */
/* #undef uint32_t */
/* Define to the type of an unsigned integer type of width exactly 64 bits if
such a type exists and the standard includes do not define it. */
/* #undef uint64_t */
/* Define to the type of an unsigned integer type of width exactly 8 bits if
such a type exists and the standard includes do not define it. */
/* #undef uint8_t */
# Authors ordered by first contribution.
Ryan Dahl <ry@tinyclouds.org>
Jeremy Hinegardner <jeremy@hinegardner.org>
Sergey Shepelev <temotor@gmail.com>
Joe Damato <ice799@gmail.com>
tomika <tomika_nospam@freemail.hu>
Phoenix Sol <phoenix@burninglabs.com>
Cliff Frey <cliff@meraki.com>
Ewen Cheslack-Postava <ewencp@cs.stanford.edu>
Santiago Gala <sgala@apache.org>
Tim Becker <tim.becker@syngenio.de>
Jeff Terrace <jterrace@gmail.com>
Ben Noordhuis <info@bnoordhuis.nl>
Nathan Rajlich <nathan@tootallnate.net>
Mark Nottingham <mnot@mnot.net>
Aman Gupta <aman@tmm1.net>
Tim Becker <tim.becker@kuriositaet.de>
Sean Cunningham <sean.cunningham@mandiant.com>
Peter Griess <pg@std.in>
Salman Haq <salman.haq@asti-usa.com>
Cliff Frey <clifffrey@gmail.com>
Jon Kolb <jon@b0g.us>
Fouad Mardini <f.mardini@gmail.com>
Paul Querna <pquerna@apache.org>
Felix Geisendörfer <felix@debuggable.com>
koichik <koichik@improvement.jp>
Andre Caron <andre.l.caron@gmail.com>
Ivo Raisr <ivosh@ivosh.net>
James McLaughlin <jamie@lacewing-project.org>
David Gwynne <loki@animata.net>
Thomas LE ROUX <thomas@procheo.fr>
Randy Rizun <rrizun@ortivawireless.com>
Andre Louis Caron <andre.louis.caron@usherbrooke.ca>
Simon Zimmermann <simonz05@gmail.com>
Erik Dubbelboer <erik@dubbelboer.com>
Martell Malone <martellmalone@gmail.com>
Bertrand Paquet <bpaquet@octo.com>
BogDan Vatra <bogdan@kde.org>
Peter Faiman <peter@thepicard.org>
Corey Richardson <corey@octayn.net>
Tóth Tamás <tomika_nospam@freemail.hu>
Contributors must agree to the Contributor License Agreement before patches
can be accepted.
http://spreadsheets2.google.com/viewform?hl=en&formkey=dDJXOGUwbzlYaWM4cHN1MERwQS1CSnc6MQ
http_parser.c is based on src/http/ngx_http_parse.c from NGINX copyright
Igor Sysoev.
Additional changes are licensed under the same terms as NGINX and
copyright Joyent, Inc. and other Node contributors. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
HTTP Parser
===========
This is a parser for HTTP messages written in C. It parses both requests and
responses. The parser is designed to be used in performance HTTP
applications. It does not make any syscalls nor allocations, it does not
buffer data, it can be interrupted at anytime. Depending on your
architecture, it only requires about 40 bytes of data per message
stream (in a web server that is per connection).
Features:
* No dependencies
* Handles persistent streams (keep-alive).
* Decodes chunked encoding.
* Upgrade support
* Defends against buffer overflow attacks.
The parser extracts the following information from HTTP messages:
* Header fields and values
* Content-Length
* Request method
* Response status code
* Transfer-Encoding
* HTTP version
* Request URL
* Message body
Usage
-----
One `http_parser` object is used per TCP connection. Initialize the struct
using `http_parser_init()` and set the callbacks. That might look something
like this for a request parser:
http_parser_settings settings;
settings.on_url = my_url_callback;
settings.on_header_field = my_header_field_callback;
/* ... */
http_parser *parser = malloc(sizeof(http_parser));
http_parser_init(parser, HTTP_REQUEST);
parser->data = my_socket;
When data is received on the socket execute the parser and check for errors.
size_t len = 80*1024, nparsed;
char buf[len];
ssize_t recved;
recved = recv(fd, buf, len, 0);
if (recved < 0) {
/* Handle error. */
}
/* Start up / continue the parser.
* Note we pass recved==0 to signal that EOF has been recieved.
*/
nparsed = http_parser_execute(parser, &settings, buf, recved);
if (parser->upgrade) {
/* handle new protocol */
} else if (nparsed != recved) {
/* Handle error. Usually just close the connection. */
}
HTTP needs to know where the end of the stream is. For example, sometimes
servers send responses without Content-Length and expect the client to
consume input (for the body) until EOF. To tell http_parser about EOF, give
`0` as the forth parameter to `http_parser_execute()`. Callbacks and errors
can still be encountered during an EOF, so one must still be prepared
to receive them.
Scalar valued message information such as `status_code`, `method`, and the
HTTP version are stored in the parser structure. This data is only
temporally stored in `http_parser` and gets reset on each new message. If
this information is needed later, copy it out of the structure during the
`headers_complete` callback.
The parser decodes the transfer-encoding for both requests and responses
transparently. That is, a chunked encoding is decoded before being sent to
the on_body callback.
The Special Problem of Upgrade
------------------------------
HTTP supports upgrading the connection to a different protocol. An
increasingly common example of this is the Web Socket protocol which sends
a request like
GET /demo HTTP/1.1
Upgrade: WebSocket
Connection: Upgrade
Host: example.com
Origin: http://example.com
WebSocket-Protocol: sample
followed by non-HTTP data.
(See http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75 for more
information the Web Socket protocol.)
To support this, the parser will treat this as a normal HTTP message without a
body. Issuing both on_headers_complete and on_message_complete callbacks. However
http_parser_execute() will stop parsing at the end of the headers and return.
The user is expected to check if `parser->upgrade` has been set to 1 after
`http_parser_execute()` returns. Non-HTTP data begins at the buffer supplied
offset by the return value of `http_parser_execute()`.
Callbacks
---------
During the `http_parser_execute()` call, the callbacks set in
`http_parser_settings` will be executed. The parser maintains state and
never looks behind, so buffering the data is not necessary. If you need to
save certain data for later usage, you can do that from the callbacks.
There are two types of callbacks:
* notification `typedef int (*http_cb) (http_parser*);`
Callbacks: on_message_begin, on_headers_complete, on_message_complete.
* data `typedef int (*http_data_cb) (http_parser*, const char *at, size_t length);`
Callbacks: (requests only) on_uri,
(common) on_header_field, on_header_value, on_body;
Callbacks must return 0 on success. Returning a non-zero value indicates
error to the parser, making it exit immediately.
In case you parse HTTP message in chunks (i.e. `read()` request line
from socket, parse, read half headers, parse, etc) your data callbacks
may be called more than once. Http-parser guarantees that data pointer is only
valid for the lifetime of callback. You can also `read()` into a heap allocated
buffer to avoid copying memory around if this fits your application.
Reading headers may be a tricky task if you read/parse headers partially.
Basically, you need to remember whether last header callback was field or value
and apply following logic:
(on_header_field and on_header_value shortened to on_h_*)
------------------------ ------------ --------------------------------------------
| State (prev. callback) | Callback | Description/action |
------------------------ ------------ --------------------------------------------
| nothing (first call) | on_h_field | Allocate new buffer and copy callback data |
| | | into it |
------------------------ ------------ --------------------------------------------
| value | on_h_field | New header started. |
| | | Copy current name,value buffers to headers |
| | | list and allocate new buffer for new name |
------------------------ ------------ --------------------------------------------
| field | on_h_field | Previous name continues. Reallocate name |
| | | buffer and append callback data to it |
------------------------ ------------ --------------------------------------------
| field | on_h_value | Value for current header started. Allocate |
| | | new buffer and copy callback data to it |
------------------------ ------------ --------------------------------------------
| value | on_h_value | Value continues. Reallocate value buffer |
| | | and append callback data to it |
------------------------ ------------ --------------------------------------------
Parsing URLs
------------
A simplistic zero-copy URL parser is provided as `http_parser_parse_url()`.
Users of this library may wish to use it to parse URLs constructed from
consecutive `on_url` callbacks.
See examples of reading in headers:
* [partial example](http://gist.github.com/155877) in C
* [from http-parser tests](http://github.com/joyent/http-parser/blob/37a0ff8/test.c#L403) in C
* [from Node library](http://github.com/joyent/node/blob/842eaf4/src/http.js#L284) in Javascript
/* Based on src/http/ngx_http_parse.c from NGINX copyright Igor Sysoev
*
* Additional changes are licensed under the same terms as NGINX and
* copyright Joyent, Inc. and other Node contributors. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
/* Dump what the parser finds to stdout as it happen */
#include "http_parser.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int on_message_begin(http_parser* _) {
(void)_;
printf("\n***MESSAGE BEGIN***\n\n");
return 0;
}
int on_headers_complete(http_parser* _) {
(void)_;
printf("\n***HEADERS COMPLETE***\n\n");
return 0;
}
int on_message_complete(http_parser* _) {
(void)_;
printf("\n***MESSAGE COMPLETE***\n\n");
return 0;
}
int on_url(http_parser* _, const char* at, size_t length) {
(void)_;
printf("Url: %.*s\n", (int)length, at);
return 0;
}
int on_header_field(http_parser* _, const char* at, size_t length) {
(void)_;
printf("Header field: %.*s\n", (int)length, at);
return 0;
}
int on_header_value(http_parser* _, const char* at, size_t length) {
(void)_;
printf("Header value: %.*s\n", (int)length, at);
return 0;
}
int on_body(http_parser* _, const char* at, size_t length) {
(void)_;
printf("Body: %.*s\n", (int)length, at);
return 0;
}
void usage(const char* name) {
fprintf(stderr,
"Usage: %s $type $filename\n"
" type: -x, where x is one of {r,b,q}\n"
" parses file as a Response, reQuest, or Both\n",
name);
exit(EXIT_FAILURE);
}
int main(int argc, char* argv[]) {
enum http_parser_type file_type;
if (argc != 3) {
usage(argv[0]);
}
char* type = argv[1];
if (type[0] != '-') {
usage(argv[0]);
}
switch (type[1]) {
/* in the case of "-", type[1] will be NUL */
case 'r':
file_type = HTTP_RESPONSE;
break;
case 'q':
file_type = HTTP_REQUEST;
break;
case 'b':
file_type = HTTP_BOTH;
break;
default:
usage(argv[0]);
}
char* filename = argv[2];
FILE* file = fopen(filename, "r");
if (file == NULL) {
perror("fopen");
return EXIT_FAILURE;
}
fseek(file, 0, SEEK_END);
long file_length = ftell(file);
if (file_length == -1) {
perror("ftell");
return EXIT_FAILURE;
}
fseek(file, 0, SEEK_SET);
char* data = malloc(file_length);
if (fread(data, 1, file_length, file) != (size_t)file_length) {
fprintf(stderr, "couldn't read entire file\n");
free(data);
return EXIT_FAILURE;
}
http_parser_settings settings;
memset(&settings, 0, sizeof(settings));
settings.on_message_begin = on_message_begin;
settings.on_url = on_url;
settings.on_header_field = on_header_field;
settings.on_header_value = on_header_value;
settings.on_headers_complete = on_headers_complete;
settings.on_body = on_body;
settings.on_message_complete = on_message_complete;
http_parser parser;
http_parser_init(&parser, file_type);
size_t nparsed = http_parser_execute(&parser, &settings, data, file_length);
free(data);
if (nparsed != (size_t)file_length) {
fprintf(stderr,
"Error: %s (%s)\n",
http_errno_description(HTTP_PARSER_ERRNO(&parser)),
http_errno_name(HTTP_PARSER_ERRNO(&parser)));
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
#include "http_parser.h"
#include <stdio.h>
#include <string.h>
void
dump_url (const char *url, const struct http_parser_url *u)
{
unsigned int i;
printf("\tfield_set: 0x%x, port: %u\n", u->field_set, u->port);
for (i = 0; i < UF_MAX; i++) {
if ((u->field_set & (1 << i)) == 0) {
printf("\tfield_data[%u]: unset\n", i);
continue;
}
printf("\tfield_data[%u]: off: %u len: %u part: \"%.*s\n",
i,
u->field_data[i].off,
u->field_data[i].len,
u->field_data[i].len,
url + u->field_data[i].off);
}
}
int main(int argc, char ** argv) {
if (argc != 3) {
printf("Syntax : %s connect|get url\n", argv[0]);
return 1;
}
struct http_parser_url u;
int len = strlen(argv[2]);
int connect = strcmp("connect", argv[1]) == 0 ? 1 : 0;
printf("Parsing %s, connect %d\n", argv[2], connect);
int result = http_parser_parse_url(argv[2], len, connect, &u);
if (result != 0) {
printf("Parse error : %d\n", result);
return result;
}
printf("Parse ok, result : \n");
dump_url(argv[2], &u);
return 0;
}
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment