You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@trafficserver.apache.org by jp...@apache.org on 2014/07/06 02:46:18 UTC

[1/2] TS-2729: Lay down some initial HTTP/2 infrastructure

Repository: trafficserver
Updated Branches:
  refs/heads/master b3f11f242 -> 9c0458c4b


http://git-wip-us.apache.org/repos/asf/trafficserver/blob/9c0458c4/proxy/http2/Http2SessionAccept.cc
----------------------------------------------------------------------
diff --git a/proxy/http2/Http2SessionAccept.cc b/proxy/http2/Http2SessionAccept.cc
new file mode 100644
index 0000000..b535052
--- /dev/null
+++ b/proxy/http2/Http2SessionAccept.cc
@@ -0,0 +1,81 @@
+/** @file
+
+  A brief file description
+
+  @section license License
+
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements.  See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership.  The ASF licenses this file
+  to you under the Apache License, Version 2.0 (the
+  "License"); you may not use this file except in compliance
+  with the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+ */
+
+#include "Http2SessionAccept.h"
+#include "Http2ClientSession.h"
+#include "I_Machine.h"
+#include "Error.h"
+
+Http2SessionAccept::Http2SessionAccept(const HttpSessionAccept::Options& _o)
+  : SessionAccept(NULL), options(_o)
+{
+  SET_HANDLER(&Http2SessionAccept::mainEvent);
+}
+
+Http2SessionAccept::~Http2SessionAccept()
+{
+}
+
+void
+Http2SessionAccept::accept(NetVConnection * netvc, MIOBuffer * iobuf, IOBufferReader * reader)
+{
+  // XXX we need to refactor the ACL checks from HttpSessionAccept so that we can invoke them here, and also in
+  // the SPDY protocol layer ...
+  Warning("skipping access control checks for HTTP/2 connection");
+
+  netvc->attributes = this->options.transport_type;
+
+  if (is_debug_tag_set("http2_seq")) {
+    const sockaddr * client_ip = netvc->get_remote_addr();
+    ip_port_text_buffer ipb;
+
+    Debug("http2_seq", "[HttpSessionAccept2:mainEvent %p] accepted connection from %s transport type = %d",
+      netvc, ats_ip_nptop(client_ip, ipb, sizeof(ipb)), netvc->attributes);
+  }
+
+  // XXX Allocate a Http2ClientSession
+  Http2ClientSession * new_session = http2ClientSessionAllocator.alloc();
+
+  new_session->new_connection(netvc, iobuf, reader, false /* backdoor */);
+}
+
+int
+Http2SessionAccept::mainEvent(int event, void *data)
+{
+  ink_release_assert(event == NET_EVENT_ACCEPT || event == EVENT_ERROR);
+  ink_release_assert((event == NET_EVENT_ACCEPT) ? (data != 0) : (1));
+
+  if (event == NET_EVENT_ACCEPT) {
+    this->accept(static_cast<NetVConnection *>(data), NULL, NULL);
+    return EVENT_CONT;
+  }
+
+  // XXX We should hoist the error handling so that all the protocols generate the statistics
+  // without code duplication.
+  if (((long) data) == -ECONNABORTED) {
+    HTTP_SUM_DYN_STAT(http_ua_msecs_counts_errors_pre_accept_hangups_stat, 0);
+  }
+
+  MachineFatal("HTTP/2 accept received fatal error: errno = %d", -((int)(intptr_t)data));
+  return EVENT_CONT;
+}

http://git-wip-us.apache.org/repos/asf/trafficserver/blob/9c0458c4/proxy/http2/Http2SessionAccept.h
----------------------------------------------------------------------
diff --git a/proxy/http2/Http2SessionAccept.h b/proxy/http2/Http2SessionAccept.h
new file mode 100644
index 0000000..5976510
--- /dev/null
+++ b/proxy/http2/Http2SessionAccept.h
@@ -0,0 +1,57 @@
+/** @file
+
+  A brief file description
+
+  @section license License
+
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements.  See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership.  The ASF licenses this file
+  to you under the Apache License, Version 2.0 (the
+  "License"); you may not use this file except in compliance
+  with the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+ */
+
+#ifndef __HTTP2_SESSION_ACCEPT_H__
+#define __HTTP2_SESSION_ACCEPT_H__
+
+#include "libts.h"
+#include "I_Net.h"
+
+// XXX HttpSessionAccept::Options needs to be refactored and separated from HttpSessionAccept so that
+// it can generically apply to all protocol implementations.
+#include "http/HttpSessionAccept.h"
+
+// HTTP/2 Session Accept.
+//
+// HTTP/2 needs to be explicitly enabled on a server port. The syntax is different for SSL and raw
+// ports. There's currently no support for the HTTP/1.1 upgrade path. The example below configures
+// HTTP/2 on port 80 and port 443 (with TLS).
+//
+// CONFIG proxy.config.http.server_ports STRING 80:proto=http2 443:ssl:proto=h2-12
+
+struct Http2SessionAccept : public SessionAccept
+{
+  explicit Http2SessionAccept(const HttpSessionAccept::Options&);
+  ~Http2SessionAccept();
+
+  void accept(NetVConnection *, MIOBuffer *, IOBufferReader *);
+  int mainEvent(int event, void * netvc);
+
+private:
+  Http2SessionAccept(const Http2SessionAccept&);
+  Http2SessionAccept& operator =(const Http2SessionAccept&);
+
+  HttpSessionAccept::Options options;
+};
+
+#endif // __HTTP2_SESSION_ACCEPT_H__

http://git-wip-us.apache.org/repos/asf/trafficserver/blob/9c0458c4/proxy/http2/Makefile.am
----------------------------------------------------------------------
diff --git a/proxy/http2/Makefile.am b/proxy/http2/Makefile.am
new file mode 100644
index 0000000..6207bd9
--- /dev/null
+++ b/proxy/http2/Makefile.am
@@ -0,0 +1,40 @@
+# Makefile.am for Http
+#
+#  Licensed to the Apache Software Foundation (ASF) under one
+#  or more contributor license agreements.  See the NOTICE file
+#  distributed with this work for additional information
+#  regarding copyright ownership.  The ASF licenses this file
+#  to you under the Apache License, Version 2.0 (the
+#  "License"); you may not use this file except in compliance
+#  with the License.  You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+#  Unless required by applicable law or agreed to in writing, software
+#  distributed under the License is distributed on an "AS IS" BASIS,
+#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#  See the License for the specific language governing permissions and
+#  limitations under the License.
+
+AM_CPPFLAGS = \
+  $(iocore_include_dirs) \
+  -I$(top_srcdir)/proxy/api/ts \
+  -I$(top_srcdir)/lib \
+  -I$(top_builddir)/lib \
+  -I$(top_srcdir)/lib/records \
+  -I$(top_srcdir)/lib/ts \
+  -I$(top_srcdir)/mgmt \
+  -I$(top_srcdir)/mgmt/utils \
+  -I$(top_srcdir)/proxy \
+  -I$(top_srcdir)/proxy/http \
+  -I$(top_srcdir)/proxy/hdrs \
+  -I$(top_srcdir)/proxy/shared \
+  -I$(top_srcdir)/proxy/http/remap
+
+noinst_LIBRARIES = libhttp2.a
+
+libhttp2_a_SOURCES = \
+  HTTP2.cc \
+  Http2ClientSession.cc \
+  Http2ConnectionState.cc \
+  Http2SessionAccept.cc


[2/2] git commit: TS-2729: Lay down some initial HTTP/2 infrastructure

Posted by jp...@apache.org.
TS-2729: Lay down some initial HTTP/2 infrastructure

Factor out a common client session base class. Add ProxyClientSession
as a base class for user agent session.  This enforces the pattern
of modelling a client session as a VConnection, and gives some basic
common API.  Push session hooks handling down to ProxyClientSession.
This gives us a common implementation for different kinds of sessions.

Add various HTTP/2 constants, types and enumerations.

Add basic HTTP/2 infrastructure. Create a Http2ClientSession class
to manage the session, session hooks and frame input and output.
The Http2ConnectionState class handles the protocol semantics and
knows about how different frames should be handled.


Project: http://git-wip-us.apache.org/repos/asf/trafficserver/repo
Commit: http://git-wip-us.apache.org/repos/asf/trafficserver/commit/9c0458c4
Tree: http://git-wip-us.apache.org/repos/asf/trafficserver/tree/9c0458c4
Diff: http://git-wip-us.apache.org/repos/asf/trafficserver/diff/9c0458c4

Branch: refs/heads/master
Commit: 9c0458c4b05341c46a9ccb5b8323bf277b09804d
Parents: b3f11f2
Author: James Peach <jp...@apache.org>
Authored: Tue May 27 21:07:24 2014 -0700
Committer: James Peach <jp...@apache.org>
Committed: Sat Jul 5 17:45:21 2014 -0700

----------------------------------------------------------------------
 configure.ac                        |   7 +-
 iocore/eventsystem/I_Event.h        |   1 +
 lib/records/RecHttp.cc              |   8 +-
 lib/ts/ink_memory.h                 |  19 ++
 mgmt/FileManager.h                  |   2 -
 mgmt/MultiFile.h                    |  10 +-
 mgmt/web2/WebGlobals.h              |   1 -
 proxy/InkAPI.cc                     |   6 +-
 proxy/InkAPIInternal.h              |  16 +-
 proxy/Makefile.am                   |   8 +-
 proxy/ProtocolProbeSessionAccept.cc |  32 ++-
 proxy/ProxyClientSession.cc         | 177 +++++++++++++++++
 proxy/ProxyClientSession.h          | 113 +++++++++++
 proxy/http/HttpClientSession.cc     | 189 +++---------------
 proxy/http/HttpClientSession.h      |  52 ++---
 proxy/http/HttpConfig.h             |   6 -
 proxy/http/HttpProxyServerMain.cc   |  10 +
 proxy/http/HttpSM.cc                |  12 +-
 proxy/http/HttpSM.h                 |   2 +-
 proxy/http/HttpSessionAccept.cc     |   2 +-
 proxy/http2/HTTP2.cc                | 256 ++++++++++++++++++++++++
 proxy/http2/HTTP2.h                 | 252 ++++++++++++++++++++++++
 proxy/http2/Http2ClientSession.cc   | 321 +++++++++++++++++++++++++++++++
 proxy/http2/Http2ClientSession.h    | 160 +++++++++++++++
 proxy/http2/Http2ConnectionState.cc | 167 ++++++++++++++++
 proxy/http2/Http2ConnectionState.h  |  79 ++++++++
 proxy/http2/Http2SessionAccept.cc   |  81 ++++++++
 proxy/http2/Http2SessionAccept.h    |  57 ++++++
 proxy/http2/Makefile.am             |  40 ++++
 29 files changed, 1858 insertions(+), 228 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/trafficserver/blob/9c0458c4/configure.ac
----------------------------------------------------------------------
diff --git a/configure.ac b/configure.ac
index 5f0e1f1..84a1007 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1431,8 +1431,10 @@ fi
 # -----------------------------------------------------------------------------
 # 5. CHECK FOR HEADER FILES
 
-TS_FLAG_HEADERS([sys/types.h sys/mman.h])
-TS_FLAG_HEADERS([sys/epoll.h \
+TS_FLAG_HEADERS([sys/types.h \
+                  sys/uio.h \
+                  sys/mman.h \
+                  sys/epoll.h \
                   sys/event.h \
                   sys/param.h \
                   sys/pset.h \
@@ -1910,6 +1912,7 @@ AC_CONFIG_FILES([
   proxy/hdrs/Makefile
   proxy/http/Makefile
   proxy/http/remap/Makefile
+  proxy/http2/Makefile
   proxy/logging/Makefile
   proxy/shared/Makefile
   proxy/spdy/Makefile

http://git-wip-us.apache.org/repos/asf/trafficserver/blob/9c0458c4/iocore/eventsystem/I_Event.h
----------------------------------------------------------------------
diff --git a/iocore/eventsystem/I_Event.h b/iocore/eventsystem/I_Event.h
index 797e313..356a691 100644
--- a/iocore/eventsystem/I_Event.h
+++ b/iocore/eventsystem/I_Event.h
@@ -73,6 +73,7 @@
 #define TRANSFORM_EVENTS_START                    2000
 #define STAT_PAGES_EVENTS_START                   2100
 #define HTTP_SESSION_EVENTS_START                 2200
+#define HTTP2_SESSION_EVENTS_START                2250
 #define HTTP_TUNNEL_EVENTS_START                  2300
 #define HTTP_SCH_UPDATE_EVENTS_START              2400
 #define NT_ASYNC_CONNECT_EVENT_EVENTS_START       3000

http://git-wip-us.apache.org/repos/asf/trafficserver/blob/9c0458c4/lib/records/RecHttp.cc
----------------------------------------------------------------------
diff --git a/lib/records/RecHttp.cc b/lib/records/RecHttp.cc
index 753a3c1..5dfd484 100644
--- a/lib/records/RecHttp.cc
+++ b/lib/records/RecHttp.cc
@@ -36,7 +36,7 @@ SessionProtocolNameRegistry globalSessionProtocolNameRegistry;
 const char * const TS_NPN_PROTOCOL_HTTP_0_9 = "http/0.9";
 const char * const TS_NPN_PROTOCOL_HTTP_1_0 = "http/1.0";
 const char * const TS_NPN_PROTOCOL_HTTP_1_1 = "http/1.1";
-const char * const TS_NPN_PROTOCOL_HTTP_2   = "http/2";
+const char * const TS_NPN_PROTOCOL_HTTP_2_0 = "h2-12";    // draft-ietf-httpbis-http2-12
 const char * const TS_NPN_PROTOCOL_SPDY_1   = "spdy/1";   // obsolete
 const char * const TS_NPN_PROTOCOL_SPDY_2   = "spdy/2";
 const char * const TS_NPN_PROTOCOL_SPDY_3   = "spdy/3";
@@ -50,7 +50,7 @@ const char * const TS_NPN_PROTOCOL_GROUP_SPDY = "spdy";
 int TS_NPN_PROTOCOL_INDEX_HTTP_0_9 = SessionProtocolNameRegistry::INVALID;
 int TS_NPN_PROTOCOL_INDEX_HTTP_1_0 = SessionProtocolNameRegistry::INVALID;
 int TS_NPN_PROTOCOL_INDEX_HTTP_1_1 = SessionProtocolNameRegistry::INVALID;
-int TS_NPN_PROTOCOL_INDEX_HTTP_2 = SessionProtocolNameRegistry::INVALID;
+int TS_NPN_PROTOCOL_INDEX_HTTP_2_0 = SessionProtocolNameRegistry::INVALID;
 int TS_NPN_PROTOCOL_INDEX_SPDY_1 = SessionProtocolNameRegistry::INVALID;
 int TS_NPN_PROTOCOL_INDEX_SPDY_2 = SessionProtocolNameRegistry::INVALID;
 int TS_NPN_PROTOCOL_INDEX_SPDY_3 = SessionProtocolNameRegistry::INVALID;
@@ -582,7 +582,7 @@ ts_session_protocol_well_known_name_indices_init()
   TS_NPN_PROTOCOL_INDEX_HTTP_0_9 = globalSessionProtocolNameRegistry.toIndexConst(TS_NPN_PROTOCOL_HTTP_0_9);
   TS_NPN_PROTOCOL_INDEX_HTTP_1_0 = globalSessionProtocolNameRegistry.toIndexConst(TS_NPN_PROTOCOL_HTTP_1_0);
   TS_NPN_PROTOCOL_INDEX_HTTP_1_1 = globalSessionProtocolNameRegistry.toIndexConst(TS_NPN_PROTOCOL_HTTP_1_1);
-  TS_NPN_PROTOCOL_INDEX_HTTP_2 = globalSessionProtocolNameRegistry.toIndexConst(TS_NPN_PROTOCOL_HTTP_2);
+  TS_NPN_PROTOCOL_INDEX_HTTP_2_0 = globalSessionProtocolNameRegistry.toIndexConst(TS_NPN_PROTOCOL_HTTP_2_0);
   TS_NPN_PROTOCOL_INDEX_SPDY_1 = globalSessionProtocolNameRegistry.toIndexConst(TS_NPN_PROTOCOL_SPDY_1);
   TS_NPN_PROTOCOL_INDEX_SPDY_2 = globalSessionProtocolNameRegistry.toIndexConst(TS_NPN_PROTOCOL_SPDY_2);
   TS_NPN_PROTOCOL_INDEX_SPDY_3 = globalSessionProtocolNameRegistry.toIndexConst(TS_NPN_PROTOCOL_SPDY_3);
@@ -592,7 +592,7 @@ ts_session_protocol_well_known_name_indices_init()
   HTTP_PROTOCOL_SET.markIn(TS_NPN_PROTOCOL_INDEX_HTTP_0_9);
   HTTP_PROTOCOL_SET.markIn(TS_NPN_PROTOCOL_INDEX_HTTP_1_0);
   HTTP_PROTOCOL_SET.markIn(TS_NPN_PROTOCOL_INDEX_HTTP_1_1);
-  HTTP2_PROTOCOL_SET.markIn(TS_NPN_PROTOCOL_INDEX_HTTP_2);
+  HTTP2_PROTOCOL_SET.markIn(TS_NPN_PROTOCOL_INDEX_HTTP_2_0);
   SPDY_PROTOCOL_SET.markIn(TS_NPN_PROTOCOL_INDEX_SPDY_3);
   SPDY_PROTOCOL_SET.markIn(TS_NPN_PROTOCOL_INDEX_SPDY_3_1);
 

http://git-wip-us.apache.org/repos/asf/trafficserver/blob/9c0458c4/lib/ts/ink_memory.h
----------------------------------------------------------------------
diff --git a/lib/ts/ink_memory.h b/lib/ts/ink_memory.h
index 5b7601a..908685c 100644
--- a/lib/ts/ink_memory.h
+++ b/lib/ts/ink_memory.h
@@ -37,6 +37,10 @@
 #include <sys/types.h>
 #endif
 
+#if HAVE_SYS_UIO_H
+#include <sys/uio.h>
+#endif
+
 #if HAVE_SYS_MMAN_H
 #include <sys/mman.h>
 #endif
@@ -120,6 +124,21 @@ char *_xstrdup(const char *str, int length, const char *path);
 #endif
 
 #ifdef __cplusplus
+
+template <typename PtrType, typename SizeType>
+static inline IOVec
+make_iovec(PtrType ptr, SizeType sz) {
+  IOVec iov = { ptr, static_cast<size_t>(sz) };
+  return iov;
+}
+
+template <typename PtrType, unsigned N>
+static inline IOVec
+make_iovec(PtrType (&array)[N]) {
+  IOVec iov = { &array[0], static_cast<size_t>(sizeof(array)) };
+  return iov;
+}
+
 /** Set data to zero.
 
     Calls @c memset on @a t with a value of zero and a length of @c

http://git-wip-us.apache.org/repos/asf/trafficserver/blob/9c0458c4/mgmt/FileManager.h
----------------------------------------------------------------------
diff --git a/mgmt/FileManager.h b/mgmt/FileManager.h
index ae35343..41a3f0a 100644
--- a/mgmt/FileManager.h
+++ b/mgmt/FileManager.h
@@ -36,9 +36,7 @@
 #include "ink_hash_table.h"
 #include "List.h"
 #include "Rollback.h"
-#include "WebGlobals.h"
 #include "MultiFile.h"
-#include "WebHttpMessage.h"
 
 class Rollback;
 

http://git-wip-us.apache.org/repos/asf/trafficserver/blob/9c0458c4/mgmt/MultiFile.h
----------------------------------------------------------------------
diff --git a/mgmt/MultiFile.h b/mgmt/MultiFile.h
index d498486..50ca86f 100644
--- a/mgmt/MultiFile.h
+++ b/mgmt/MultiFile.h
@@ -32,14 +32,18 @@
  *
  ****************************************************************************/
 
-//#include "libts.h"
-#include "WebGlobals.h"
-
 class ExpandingArray;
 class textBuffer;
 
+#if defined(NAME_MAX)
+#define FILE_NAME_MAX       NAME_MAX
+#else
+#define FILE_NAME_MAX       255
+#endif
+
 struct fileEntry
 {
+  // XXX Remove this arbitrary filename length limit.
   char name[FILE_NAME_MAX];
   time_t c_time;
 };

http://git-wip-us.apache.org/repos/asf/trafficserver/blob/9c0458c4/mgmt/web2/WebGlobals.h
----------------------------------------------------------------------
diff --git a/mgmt/web2/WebGlobals.h b/mgmt/web2/WebGlobals.h
index 2ff3dc9..220be91 100644
--- a/mgmt/web2/WebGlobals.h
+++ b/mgmt/web2/WebGlobals.h
@@ -108,7 +108,6 @@ extern WebInterFaceGlobals wGlobals;
 extern WebContext autoconfContext;
 
 #define MAX_SERVICE_THREADS 100
-#define FILE_NAME_MAX       255
 
 //-------------------------------------------------------------------------
 // web2 items

http://git-wip-us.apache.org/repos/asf/trafficserver/blob/9c0458c4/proxy/InkAPI.cc
----------------------------------------------------------------------
diff --git a/proxy/InkAPI.cc b/proxy/InkAPI.cc
index 00501b2..23d17cb 100644
--- a/proxy/InkAPI.cc
+++ b/proxy/InkAPI.cc
@@ -1248,7 +1248,7 @@ APIHooks::append(INKContInternal *cont)
 }
 
 APIHook *
-APIHooks::get()
+APIHooks::get() const
 {
   return m_hooks.head;
 }
@@ -5736,17 +5736,19 @@ TSHttpTxnDebugGet(TSHttpTxn txnp)
   sdk_assert(sdk_sanity_check_txn(txnp) == TS_SUCCESS);
   return ((HttpSM *)txnp)->debug_on;
 }
+
 void
 TSHttpSsnDebugSet(TSHttpSsn ssnp, int on)
 {
   sdk_assert(sdk_sanity_check_http_ssn(ssnp) == TS_SUCCESS);
   ((HttpClientSession *)ssnp)->debug_on = on;
 }
+
 int
 TSHttpSsnDebugGet(TSHttpSsn ssnp)
 {
   sdk_assert(sdk_sanity_check_http_ssn(ssnp) == TS_SUCCESS);
-  return ((HttpClientSession *)ssnp)->debug_on;
+  return ((HttpClientSession *)ssnp)->debug();
 }
 
 int

http://git-wip-us.apache.org/repos/asf/trafficserver/blob/9c0458c4/proxy/InkAPIInternal.h
----------------------------------------------------------------------
diff --git a/proxy/InkAPIInternal.h b/proxy/InkAPIInternal.h
index 2d7aaaf..49725b9 100644
--- a/proxy/InkAPIInternal.h
+++ b/proxy/InkAPIInternal.h
@@ -37,6 +37,9 @@
 #include "P_Cache.h"
 #include "I_Tasks.h"
 
+/* Some defines that might be candidates for configurable settings later.
+ */
+#define HTTP_SSN_TXN_MAX_USER_ARG         16   /* max number of user arguments for Transactions and Sessions */
 
 typedef enum
   {
@@ -124,6 +127,13 @@ struct HttpAltInfo
   float m_qvalue;
 };
 
+enum APIHookScope
+{
+  API_HOOK_SCOPE_NONE,
+  API_HOOK_SCOPE_GLOBAL,
+  API_HOOK_SCOPE_LOCAL
+};
+
 /// A single API hook that can be invoked.
 class APIHook
 {
@@ -140,7 +150,7 @@ class APIHooks
 public:
   void prepend(INKContInternal * cont);
   void append(INKContInternal * cont);
-  APIHook *get();
+  APIHook *get() const;
   void clear();
   bool is_empty() const;
   void invoke(int event, void* data);
@@ -187,7 +197,7 @@ public:
   /// Add the hook @a cont to the end of the hooks for @a id.
   void append(ID id, INKContInternal * cont);
   /// Get the list of hooks for @a id.
-  APIHook *get(ID id);
+  APIHook *get(ID id) const;
   /// @return @c true if @a id is a valid id, @c false otherwise.
   static bool is_valid(ID id);
 
@@ -250,7 +260,7 @@ FeatureAPIHooks<ID,N>::append(ID id, INKContInternal *cont)
 
 template < typename ID, ID N >
 APIHook *
-FeatureAPIHooks<ID,N>::get(ID id)
+FeatureAPIHooks<ID,N>::get(ID id) const
 {
   return m_hooks[id].get();
 }

http://git-wip-us.apache.org/repos/asf/trafficserver/blob/9c0458c4/proxy/Makefile.am
----------------------------------------------------------------------
diff --git a/proxy/Makefile.am b/proxy/Makefile.am
index 6a52102..cb6bcad 100644
--- a/proxy/Makefile.am
+++ b/proxy/Makefile.am
@@ -17,7 +17,7 @@
 #  limitations under the License.
 
 # Note that hdrs is targeted from ../Makefile.am
-SUBDIRS = congest http spdy logging config
+SUBDIRS = congest http http2 spdy logging config
 noinst_LIBRARIES =
 bin_PROGRAMS = \
   traffic_server \
@@ -170,6 +170,8 @@ traffic_server_SOURCES = \
   Prefetch.h \
   ProtocolProbeSessionAccept.cc \
   ProtocolProbeSessionAccept.h \
+  ProxyClientSession.cc \
+  ProxyClientSession.h \
   ReverseProxy.cc \
   ReverseProxy.h \
   SocksProxy.cc \
@@ -192,6 +194,7 @@ endif
 traffic_server_LDFLAGS = @EXTRA_CXX_LDFLAGS@ @LIBTOOL_LINK_FLAGS@
 traffic_server_LDADD = \
   http/libhttp.a \
+  http2/libhttp2.a \
   spdy/libspdy.a \
   http/remap/libhttp_remap.a \
   congest/libCongestionControl.a \
@@ -292,6 +295,8 @@ traffic_sac_SOURCES = \
   Prefetch.cc \
   ProtocolProbeSessionAccept.cc \
   ProtocolProbeSessionAccept.h \
+  ProxyClientSession.cc \
+  ProxyClientSession.h \
   Update.cc \
   Plugin.cc \
   InkAPI.cc \
@@ -301,6 +306,7 @@ traffic_sac_SOURCES = \
 traffic_sac_LDFLAGS = @EXTRA_CXX_LDFLAGS@ @LIBTOOL_LINK_FLAGS@
 traffic_sac_LDADD = \
   http/libhttp.a \
+  http2/libhttp2.a \
   spdy/libspdy.a \
   shared/libdiagsconfig.a \
   http/remap/libhttp_remap.a \

http://git-wip-us.apache.org/repos/asf/trafficserver/blob/9c0458c4/proxy/ProtocolProbeSessionAccept.cc
----------------------------------------------------------------------
diff --git a/proxy/ProtocolProbeSessionAccept.cc b/proxy/ProtocolProbeSessionAccept.cc
index 46adb48..255da0c 100644
--- a/proxy/ProtocolProbeSessionAccept.cc
+++ b/proxy/ProtocolProbeSessionAccept.cc
@@ -25,6 +25,34 @@
 #include "I_Machine.h"
 #include "ProtocolProbeSessionAccept.h"
 #include "Error.h"
+#include "http2/HTTP2.h"
+
+static bool
+proto_is_spdy(IOBufferReader * reader)
+{
+  // SPDY clients have to start by sending a control frame (the high bit is set). Let's assume
+  // that no other protocol could possibly ever set this bit!
+  return ((uint8_t)(*reader)[0]) == 0x80u;
+}
+
+static bool
+proto_is_http2(IOBufferReader * reader)
+{
+  char buf[HTTP2_CONNECTION_PREFACE_LEN];
+  char * end;
+  ptrdiff_t nbytes;
+
+  end = reader->memcpy(buf, sizeof(buf), 0 /* offset */);
+  nbytes = end - buf;
+
+  // Client must send at least 4 bytes to get a reasonable match.
+  if (nbytes < 4) {
+    return false;
+  }
+
+  ink_assert(nbytes <= HTTP2_CONNECTION_PREFACE_LEN);
+  return memcmp(HTTP2_CONNECTION_PREFACE, buf, nbytes) == 0;
+}
 
 struct ProtocolProbeTrampoline : public Continuation, public ProtocolProbeSessionAcceptEnums
 {
@@ -75,8 +103,10 @@ struct ProtocolProbeTrampoline : public Continuation, public ProtocolProbeSessio
 
     // SPDY clients have to start by sending a control frame (the high bit is set). Let's assume
     // that no other protocol could possibly ever set this bit!
-    if ((uint8_t)(*reader->start()) == 0x80u) {
+    if (proto_is_spdy(reader)) {
       key = PROTO_SPDY;
+    } else if (proto_is_http2(reader)) {
+      key = PROTO_HTTP2;
     } else {
       key = PROTO_HTTP;
     }

http://git-wip-us.apache.org/repos/asf/trafficserver/blob/9c0458c4/proxy/ProxyClientSession.cc
----------------------------------------------------------------------
diff --git a/proxy/ProxyClientSession.cc b/proxy/ProxyClientSession.cc
new file mode 100644
index 0000000..de88a34
--- /dev/null
+++ b/proxy/ProxyClientSession.cc
@@ -0,0 +1,177 @@
+/** @file
+
+  ProxyClientSession - Base class for protocol client sessions.
+
+  @section license License
+
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements.  See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership.  The ASF licenses this file
+  to you under the Apache License, Version 2.0 (the
+  "License"); you may not use this file except in compliance
+  with the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+ */
+
+#include "HttpConfig.h"
+#include "HttpDebugNames.h"
+#include "ProxyClientSession.h"
+
+static int64_t next_cs_id = 0;
+
+ProxyClientSession::ProxyClientSession()
+    : VConnection(NULL), debug_on(false), hooks_on(true)
+{
+  ink_zero(this->user_args);
+}
+
+int64_t
+ProxyClientSession::next_connection_id()
+{
+  return ink_atomic_increment(&next_cs_id, 1);
+}
+
+static const TSEvent eventmap[TS_HTTP_LAST_HOOK + 1] = {
+  TS_EVENT_HTTP_READ_REQUEST_HDR,       // TS_HTTP_READ_REQUEST_HDR_HOOK
+  TS_EVENT_HTTP_OS_DNS,                 // TS_HTTP_OS_DNS_HOOK
+  TS_EVENT_HTTP_SEND_REQUEST_HDR,       // TS_HTTP_SEND_REQUEST_HDR_HOOK
+  TS_EVENT_HTTP_READ_CACHE_HDR,         // TS_HTTP_READ_CACHE_HDR_HOOK
+  TS_EVENT_HTTP_READ_RESPONSE_HDR,      // TS_HTTP_READ_RESPONSE_HDR_HOOK
+  TS_EVENT_HTTP_SEND_RESPONSE_HDR,      // TS_HTTP_SEND_RESPONSE_HDR_HOOK
+  TS_EVENT_HTTP_REQUEST_TRANSFORM,      // TS_HTTP_REQUEST_TRANSFORM_HOOK
+  TS_EVENT_HTTP_RESPONSE_TRANSFORM,     // TS_HTTP_RESPONSE_TRANSFORM_HOOK
+  TS_EVENT_HTTP_SELECT_ALT,             // TS_HTTP_SELECT_ALT_HOOK
+  TS_EVENT_HTTP_TXN_START,              // TS_HTTP_TXN_START_HOOK
+  TS_EVENT_HTTP_TXN_CLOSE,              // TS_HTTP_TXN_CLOSE_HOOK
+  TS_EVENT_HTTP_SSN_START,              // TS_HTTP_SSN_START_HOOK
+  TS_EVENT_HTTP_SSN_CLOSE,              // TS_HTTP_SSN_CLOSE_HOOK
+  TS_EVENT_HTTP_CACHE_LOOKUP_COMPLETE,  // TS_HTTP_CACHE_LOOKUP_COMPLETE_HOOK
+  TS_EVENT_HTTP_PRE_REMAP,              // TS_HTTP_PRE_REMAP_HOOK
+  TS_EVENT_HTTP_POST_REMAP,             // TS_HTTP_POST_REMAP_HOOK
+  TS_EVENT_NONE,                        // TS_HTTP_RESPONSE_CLIENT_HOOK
+  TS_EVENT_NONE,                        // TS_HTTP_LAST_HOOK
+};
+
+static bool
+is_valid_hook(TSHttpHookID hookid) {
+  return (hookid >= 0) && (hookid < TS_HTTP_LAST_HOOK);
+}
+
+void
+ProxyClientSession::cleanup()
+{
+  this->api_hooks.clear();
+  this->mutex.clear();
+}
+
+int
+ProxyClientSession::state_api_callout(int event, void * /* data ATS_UNUSED */)
+{
+  switch (event) {
+  case EVENT_NONE:
+  case EVENT_INTERVAL:
+  case TS_EVENT_HTTP_CONTINUE:
+    if (likely(is_valid_hook(this->api_hookid))) {
+      if (this->api_current == NULL && this->api_scope == API_HOOK_SCOPE_GLOBAL) {
+        this->api_current = http_global_hooks->get(this->api_hookid);
+        this->api_scope = API_HOOK_SCOPE_LOCAL;
+      }
+
+      if (this->api_current == NULL && this->api_scope == API_HOOK_SCOPE_LOCAL) {
+        this->api_current = ssn_hook_get(this->api_hookid);
+        this->api_scope = API_HOOK_SCOPE_NONE;
+      }
+
+      if (this->api_current) {
+        bool            plugin_lock = false;
+        APIHook *       hook = this->api_current;
+        Ptr<ProxyMutex> plugin_mutex;
+
+        if (hook->m_cont->mutex) {
+          plugin_mutex = hook->m_cont->mutex;
+          plugin_lock = MUTEX_TAKE_TRY_LOCK(hook->m_cont->mutex, mutex->thread_holding);
+          if (!plugin_lock) {
+            SET_HANDLER(&ProxyClientSession::state_api_callout);
+            mutex->thread_holding->schedule_in(this, HRTIME_MSECONDS(10));
+            return 0;
+          }
+        }
+
+        this->api_current = this->api_current->next();
+        hook->invoke(eventmap[this->api_hookid], this);
+
+        if (plugin_lock) {
+          Mutex_unlock(plugin_mutex, this_ethread());
+        }
+
+        return 0;
+      }
+    }
+
+    handle_api_return(event);
+    break;
+
+  case TS_EVENT_HTTP_ERROR:
+    this->handle_api_return(event);
+    break;
+
+  // coverity[unterminated_default]
+  default:
+    ink_assert(false);
+  }
+
+  return 0;
+}
+
+void
+ProxyClientSession::do_api_callout(TSHttpHookID id)
+{
+  ink_assert(id == TS_HTTP_SSN_START_HOOK || id == TS_HTTP_SSN_CLOSE_HOOK);
+
+  this->api_hookid = id;
+  this->api_scope = API_HOOK_SCOPE_GLOBAL;
+  this->api_current = NULL;
+
+  if (this->hooks_on && this->has_hooks()) {
+    SET_HANDLER(&ProxyClientSession::state_api_callout);
+    this->state_api_callout(EVENT_NONE, NULL);
+  } else {
+    this->handle_api_return(TS_EVENT_HTTP_CONTINUE);
+  }
+}
+
+void
+ProxyClientSession::handle_api_return(int event)
+{
+  TSHttpHookID hookid = this->api_hookid;
+
+  SET_HANDLER(&ProxyClientSession::state_api_callout);
+
+  this->api_hookid = TS_HTTP_LAST_HOOK;
+  this->api_scope = API_HOOK_SCOPE_NONE;
+  this->api_current = NULL;
+
+  switch (hookid) {
+  case TS_HTTP_SSN_START_HOOK:
+    if (event == TS_EVENT_HTTP_ERROR) {
+      this->do_io_close();
+    } else {
+      this->start();
+    }
+    break;
+  case TS_HTTP_SSN_CLOSE_HOOK:
+    this->destroy();
+    break;
+  default:
+    Fatal("received invalid session hook %s (%d)", HttpDebugNames::get_api_hook_name(hookid), hookid);
+    break;
+  }
+}

http://git-wip-us.apache.org/repos/asf/trafficserver/blob/9c0458c4/proxy/ProxyClientSession.h
----------------------------------------------------------------------
diff --git a/proxy/ProxyClientSession.h b/proxy/ProxyClientSession.h
new file mode 100644
index 0000000..19fbb24
--- /dev/null
+++ b/proxy/ProxyClientSession.h
@@ -0,0 +1,113 @@
+/** @file
+
+  ProxyClientSession - Base class for protocol client sessions.
+
+  @section license License
+
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements.  See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership.  The ASF licenses this file
+  to you under the Apache License, Version 2.0 (the
+  "License"); you may not use this file except in compliance
+  with the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+ */
+
+#ifndef __PROXY_CLIENT_SESSION_H__
+#define __PROXY_CLIENT_SESSION_H__
+
+#include "libts.h"
+#include "P_Net.h"
+#include "InkAPIInternal.h"
+
+// Emit a debug message conditional on whether this particular client session
+// has debugging enabled. This should only be called from within a client session
+// member function.
+#define DebugSsn(ssn, tag, ...) DebugSpecific((ssn)->debug(), tag, __VA_ARGS__)
+
+class ProxyClientSession : public VConnection
+{
+public:
+  ProxyClientSession();
+
+  virtual void destroy() = 0;
+  virtual void start() = 0;
+
+  virtual void new_connection(NetVConnection * new_vc, MIOBuffer * iobuf, IOBufferReader * reader, bool backdoor) = 0;
+
+  virtual void ssn_hook_append(TSHttpHookID id, INKContInternal * cont) {
+    this->api_hooks.prepend(id, cont);
+  }
+
+  virtual void ssn_hook_prepend(TSHttpHookID id, INKContInternal * cont) {
+    this->api_hooks.prepend(id, cont);
+  }
+
+  APIHook * ssn_hook_get(TSHttpHookID id) const {
+    return this->api_hooks.get(id);
+  }
+
+  void * get_user_arg(unsigned ix) const {
+    ink_assert(ix < countof(user_args));
+    return this->user_args[ix];
+  }
+
+  void set_user_arg(unsigned ix, void * arg) {
+    ink_assert(ix < countof(user_args));
+    user_args[ix] = arg;
+  }
+
+  // Return whether debugging is enabled for this session.
+  bool debug() const {
+    return this->debug_on;
+  }
+
+  bool hooks_enabled() const {
+    return this->hooks_on;
+  }
+
+  bool has_hooks() const {
+    return this->api_hooks.has_hooks() || http_global_hooks->has_hooks();
+  }
+
+  // Initiate an API hook invocation.
+  void do_api_callout(TSHttpHookID id);
+
+  void cleanup();
+
+  static int64_t next_connection_id();
+
+protected:
+
+  // XXX Consider using a bitwise flags variable for the following flags, so that we can make the best
+  // use of internal alignment padding.
+
+  // Session specific debug flag.
+  bool debug_on;
+  bool hooks_on;
+
+private:
+  APIHookScope  api_scope;
+  TSHttpHookID  api_hookid;
+  APIHook *     api_current;
+  HttpAPIHooks  api_hooks;
+  void *        user_args[HTTP_SSN_TXN_MAX_USER_ARG];
+
+  ProxyClientSession(ProxyClientSession &); // noncopyable
+  ProxyClientSession& operator=(const ProxyClientSession &); // noncopyable
+
+  int state_api_callout(int event, void * edata);
+  void handle_api_return(int event);
+
+  friend void TSHttpSsnDebugSet(TSHttpSsn, int);
+};
+
+#endif // __PROXY_CLIENT_SESSION_H__

http://git-wip-us.apache.org/repos/asf/trafficserver/blob/9c0458c4/proxy/http/HttpClientSession.cc
----------------------------------------------------------------------
diff --git a/proxy/http/HttpClientSession.cc b/proxy/http/HttpClientSession.cc
index 9952cf1..c4d1a30 100644
--- a/proxy/http/HttpClientSession.cc
+++ b/proxy/http/HttpClientSession.cc
@@ -38,11 +38,12 @@
 #include "HttpServerSession.h"
 #include "Plugin.h"
 
-#define DebugSsn(tag, ...) DebugSpecific(debug_on, tag, __VA_ARGS__)
-#define STATE_ENTER(state_name, event, vio) { \
+#define DebugHttpSsn(fmt, ...) DebugSsn(this, "http_cs", fmt, __VA_ARGS__)
+
+#define STATE_ENTER(state_name, event, vio) do { \
     /*ink_assert (magic == HTTP_SM_MAGIC_ALIVE);  REMEMBER (event, NULL, reentrancy_count); */ \
-        DebugSsn("http_cs", "[%" PRId64 "] [%s, %s]", con_id, \
-        #state_name, HttpDebugNames::get_event_name(event)); }
+  DebugHttpSsn("[%" PRId64 "] [%s, %s]", con_id, #state_name, HttpDebugNames::get_event_name(event)); \
+} while(0)
 
 enum
 {
@@ -55,68 +56,54 @@ enum
 DLL<HttpClientSession> debug_cs_list;
 ink_mutex debug_cs_list_mutex;
 
-static int64_t next_cs_id = (int64_t) 0;
 ClassAllocator<HttpClientSession> httpClientSessionAllocator("httpClientSessionAllocator");
 
 HttpClientSession::HttpClientSession()
-  : VConnection(NULL), con_id(0), client_vc(NULL), magic(HTTP_CS_MAGIC_DEAD),
-    tcp_init_cwnd_set(false),
-    transact_count(0), half_close(false), conn_decrease(false), bound_ss(NULL),
+  : con_id(0), client_vc(NULL), magic(HTTP_CS_MAGIC_DEAD),
+    transact_count(0), tcp_init_cwnd_set(false),
+    half_close(false), conn_decrease(false), bound_ss(NULL),
     read_buffer(NULL), current_reader(NULL), read_state(HCS_INIT),
     ka_vio(NULL), slave_ka_vio(NULL),
-    cur_hook_id(TS_HTTP_LAST_HOOK), cur_hook(NULL),
-    cur_hooks(0), backdoor_connect(false),
-    hooks_set(0),
     outbound_port(0), f_outbound_transparent(false),
     host_res_style(HOST_RES_IPV4), acl_record(NULL),
-    m_active(false), debug_on(false)
+    m_active(false)
 {
-  memset(user_args, 0, sizeof(user_args));
 }
 
 void
-HttpClientSession::cleanup()
+HttpClientSession::destroy()
 {
-  DebugSsn("http_cs", "[%" PRId64 "] session destroy", con_id);
+  DebugHttpSsn("[%" PRId64 "] session destroy", con_id);
 
   ink_release_assert(client_vc == NULL);
   ink_release_assert(bound_ss == NULL);
   ink_assert(read_buffer);
+
   magic = HTTP_CS_MAGIC_DEAD;
   if (read_buffer) {
     free_MIOBuffer(read_buffer);
     read_buffer = NULL;
   }
+
 #ifdef USE_HTTP_DEBUG_LISTS
   ink_mutex_acquire(&debug_cs_list_mutex);
   debug_cs_list.remove(this, this->debug_link);
   ink_mutex_release(&debug_cs_list_mutex);
 #endif
 
-  ink_assert(client_vc == 0);
-  api_hooks.clear();
-  mutex.clear();
-  debug_on = false;
-
   if (conn_decrease) {
     HTTP_DECREMENT_DYN_STAT(http_current_client_connections_stat);
     conn_decrease = false;
   }
-}
 
-void
-HttpClientSession::destroy()
-{
-  this->cleanup();
+  ProxyClientSession::cleanup();
   THREAD_FREE(this, httpClientSessionAllocator, this_thread());
 }
 
 void
 HttpClientSession::ssn_hook_append(TSHttpHookID id, INKContInternal * cont)
 {
-  api_hooks.append(id, cont);
-  hooks_set = 1;
-
+  ProxyClientSession::ssn_hook_append(id, cont);
   if (current_reader) {
     current_reader->hooks_set = 1;
   }
@@ -125,15 +112,12 @@ HttpClientSession::ssn_hook_append(TSHttpHookID id, INKContInternal * cont)
 void
 HttpClientSession::ssn_hook_prepend(TSHttpHookID id, INKContInternal * cont)
 {
-  api_hooks.prepend(id, cont);
-  hooks_set = 1;
-
+  ProxyClientSession::ssn_hook_prepend(id, cont);
   if (current_reader) {
     current_reader->hooks_set = 1;
   }
 }
 
-
 void
 HttpClientSession::new_transaction()
 {
@@ -144,7 +128,7 @@ HttpClientSession::new_transaction()
   current_reader = HttpSM::allocate();
   current_reader->init();
   transact_count++;
-  DebugSsn("http_cs", "[%" PRId64 "] Starting transaction %d using sm [%" PRId64 "]", con_id, transact_count, current_reader->sm_id);
+  DebugHttpSsn("[%" PRId64 "] Starting transaction %d using sm [%" PRId64 "]", con_id, transact_count, current_reader->sm_id);
 
   current_reader->attach_client_session(this, sm_reader);
   if (pi) {
@@ -155,27 +139,9 @@ HttpClientSession::new_transaction()
   }
 }
 
-inline void
-HttpClientSession::do_api_callout(TSHttpHookID id)
-{
-
-  cur_hook_id = id;
-  ink_assert(cur_hook_id == TS_HTTP_SSN_START_HOOK || cur_hook_id == TS_HTTP_SSN_CLOSE_HOOK);
-
-  if (hooks_set && backdoor_connect == 0) {
-    SET_HANDLER(&HttpClientSession::state_api_callout);
-    cur_hook = NULL;
-    cur_hooks = 0;
-    state_api_callout(0, NULL);
-  } else {
-    handle_api_return(HTTP_API_CONTINUE);
-  }
-}
-
 void
-HttpClientSession::new_connection(NetVConnection * new_vc, bool backdoor, MIOBuffer * iobuf, IOBufferReader * reader)
+HttpClientSession::new_connection(NetVConnection * new_vc, MIOBuffer * iobuf, IOBufferReader * reader, bool backdoor)
 {
-
   ink_assert(new_vc != NULL);
   ink_assert(client_vc == NULL);
   client_vc = new_vc;
@@ -183,10 +149,12 @@ HttpClientSession::new_connection(NetVConnection * new_vc, bool backdoor, MIOBuf
   mutex = new_vc->mutex;
   MUTEX_TRY_LOCK(lock, mutex, this_ethread());
   ink_assert(!!lock);
-  this->backdoor_connect = backdoor;
+
+  // Disable hooks for backdoor connections.
+  this->hooks_on = !backdoor;
 
   // Unique client session identifier.
-  con_id = ink_atomic_increment((int64_t *) (&next_cs_id), 1);
+  con_id = ProxyClientSession::next_connection_id();
 
   HTTP_INCREMENT_DYN_STAT(http_current_client_connections_stat);
   conn_decrease = true;
@@ -216,16 +184,13 @@ HttpClientSession::new_connection(NetVConnection * new_vc, bool backdoor, MIOBuf
     break;
   }
 
-  // Record api hook set state
-  hooks_set = http_global_hooks->has_hooks();
-
 #ifdef USE_HTTP_DEBUG_LISTS
   ink_mutex_acquire(&debug_cs_list_mutex);
   debug_cs_list.push(this, this->debug_link);
   ink_mutex_release(&debug_cs_list_mutex);
 #endif
 
-  DebugSsn("http_cs", "[%" PRId64 "] session born, netvc %p", con_id, new_vc);
+  DebugHttpSsn("[%" PRId64 "] session born, netvc %p", con_id, new_vc);
 
   read_buffer = iobuf ? iobuf : new_MIOBuffer(HTTP_HEADER_BUFFER_SIZE_INDEX);
   sm_reader = reader ? reader : read_buffer->alloc_reader();
@@ -252,7 +217,7 @@ HttpClientSession::do_io_write(Continuation * c, int64_t nbytes, IOBufferReader
 {
   /* conditionally set the tcp initial congestion window
      before our first write. */
-  DebugSsn("http_cs", "tcp_init_cwnd_set %d\n", (int)tcp_init_cwnd_set);
+  DebugHttpSsn("tcp_init_cwnd_set %d\n", (int)tcp_init_cwnd_set);
   if(!tcp_init_cwnd_set) {
     tcp_init_cwnd_set = true;
     set_tcp_init_cwnd();
@@ -264,10 +229,10 @@ void
 HttpClientSession::set_tcp_init_cwnd()
 {
   int desired_tcp_init_cwnd = current_reader->t_state.txn_conf->server_tcp_init_cwnd;
-  DebugSsn("http_cs", "desired TCP congestion window is %d\n", desired_tcp_init_cwnd);
+  DebugHttpSsn("desired TCP congestion window is %d\n", desired_tcp_init_cwnd);
   if(desired_tcp_init_cwnd == 0) return;
   if(get_netvc()->set_tcp_init_cwnd(desired_tcp_init_cwnd) != 0)
-    DebugSsn("http_cs", "set_tcp_init_cwnd(%d) failed", desired_tcp_init_cwnd);
+    DebugHttpSsn("set_tcp_init_cwnd(%d) failed", desired_tcp_init_cwnd);
 }
 
 void
@@ -302,7 +267,7 @@ HttpClientSession::do_io_close(int alerrno)
   if (half_close) {
     read_state = HCS_HALF_CLOSED;
     SET_HANDLER(&HttpClientSession::state_wait_for_close);
-    DebugSsn("http_cs", "[%" PRId64 "] session half close", con_id);
+    DebugHttpSsn("[%" PRId64 "] session half close", con_id);
 
     // We want the client to know that that we're finished
     //  writing.  The write shutdown accomplishes this.  Unfortuantely,
@@ -327,7 +292,7 @@ HttpClientSession::do_io_close(int alerrno)
   } else {
     read_state = HCS_CLOSED;
     client_vc->do_io_close(alerrno);
-    DebugSsn("http_cs", "[%" PRId64 "] session closed", con_id);
+    DebugHttpSsn("[%" PRId64 "] session closed", con_id);
     client_vc = NULL;
     HTTP_SUM_DYN_STAT(http_transactions_per_client_con, transact_count);
     HTTP_DECREMENT_DYN_STAT(http_current_client_connections_stat);
@@ -448,96 +413,6 @@ HttpClientSession::state_keep_alive(int event, void *data)
 
   return 0;
 }
-
-int
-HttpClientSession::state_api_callout(int event, void * /* data ATS_UNUSED */)
-{
-  switch (event) {
-  case EVENT_NONE:
-  case EVENT_INTERVAL:
-  case HTTP_API_CONTINUE:
-    if ((cur_hook_id >= 0) && (cur_hook_id < TS_HTTP_LAST_HOOK)) {
-      if (!cur_hook) {
-        if (cur_hooks == 0) {
-          cur_hook = http_global_hooks->get(cur_hook_id);
-          cur_hooks++;
-        }
-      }
-      if (!cur_hook) {
-        if (cur_hooks == 1) {
-          cur_hook = api_hooks.get(cur_hook_id);
-          cur_hooks++;
-        }
-      }
-
-      if (cur_hook) {
-        bool plugin_lock;
-        Ptr<ProxyMutex> plugin_mutex;
-        if (cur_hook->m_cont->mutex) {
-          plugin_mutex = cur_hook->m_cont->mutex;
-          plugin_lock = MUTEX_TAKE_TRY_LOCK(cur_hook->m_cont->mutex, mutex->thread_holding);
-          if (!plugin_lock) {
-            SET_HANDLER(&HttpClientSession::state_api_callout);
-            mutex->thread_holding->schedule_in(this, HRTIME_MSECONDS(10));
-            return 0;
-          }
-        } else {
-          plugin_lock = false;
-        }
-
-        APIHook *hook = cur_hook;
-        cur_hook = cur_hook->next();
-
-        hook->invoke(TS_EVENT_HTTP_READ_REQUEST_HDR + cur_hook_id, this);
-
-        if (plugin_lock) {
-          // BZ 51246
-          Mutex_unlock(plugin_mutex, this_ethread());
-        }
-
-        return 0;
-      }
-    }
-
-    handle_api_return(event);
-    break;
-
-  // coverity[unterminated_default]
-  default:
-    ink_assert(false);
-  case HTTP_API_ERROR:
-    handle_api_return(event);
-    break;
-  }
-
-  return 0;
-}
-
-void
-HttpClientSession::handle_api_return(int event)
-{
-  SET_HANDLER(&HttpClientSession::state_api_callout);
-
-  cur_hook = NULL;
-  cur_hooks = 0;
-
-  switch (cur_hook_id) {
-  case TS_HTTP_SSN_START_HOOK:
-    if (event != HTTP_API_ERROR) {
-      new_transaction();
-    } else {
-      do_io_close();
-    }
-    break;
-  case TS_HTTP_SSN_CLOSE_HOOK:
-    destroy();
-    break;
-  default:
-    ink_release_assert(0);
-    break;
-  }
-}
-
 void
 HttpClientSession::reenable(VIO * vio)
 {
@@ -551,7 +426,7 @@ HttpClientSession::attach_server_session(HttpServerSession * ssession, bool tran
     ink_assert(bound_ss == NULL);
     ssession->state = HSS_KA_CLIENT_SLAVE;
     bound_ss = ssession;
-    DebugSsn("http_cs", "[%" PRId64 "] attaching server session [%" PRId64 "] as slave", con_id, ssession->con_id);
+    DebugHttpSsn("[%" PRId64 "] attaching server session [%" PRId64 "] as slave", con_id, ssession->con_id);
     ink_assert(ssession->get_reader()->read_avail() == 0);
     ink_assert(ssession->get_netvc() != client_vc);
 
@@ -593,7 +468,7 @@ HttpClientSession::release(IOBufferReader * r)
   ink_assert(current_reader != NULL);
   MgmtInt ka_in = current_reader->t_state.txn_conf->keep_alive_no_activity_timeout_in;
 
-  DebugSsn("http_cs", "[%" PRId64 "] session released by sm [%" PRId64 "]", con_id, current_reader->sm_id);
+  DebugHttpSsn("[%" PRId64 "] session released by sm [%" PRId64 "]", con_id, current_reader->sm_id);
   current_reader = NULL;
 
   // handling potential keep-alive here
@@ -616,10 +491,10 @@ HttpClientSession::release(IOBufferReader * r)
   //  machine to process it.  Otherwise, issue an
   //  IO to wait for new data
   if (sm_reader->read_avail() > 0) {
-    DebugSsn("http_cs", "[%" PRId64 "] data already in buffer, starting new transaction", con_id);
+    DebugHttpSsn("[%" PRId64 "] data already in buffer, starting new transaction", con_id);
     new_transaction();
   } else {
-    DebugSsn("http_cs", "[%" PRId64 "] initiating io for next header", con_id);
+    DebugHttpSsn("[%" PRId64 "] initiating io for next header", con_id);
     read_state = HCS_KEEP_ALIVE;
     SET_HANDLER(&HttpClientSession::state_keep_alive);
     ka_vio = this->do_io_read(this, INT64_MAX, read_buffer);

http://git-wip-us.apache.org/repos/asf/trafficserver/blob/9c0458c4/proxy/http/HttpClientSession.h
----------------------------------------------------------------------
diff --git a/proxy/http/HttpClientSession.h b/proxy/http/HttpClientSession.h
index cb4c5ba..ef0768d 100644
--- a/proxy/http/HttpClientSession.h
+++ b/proxy/http/HttpClientSession.h
@@ -38,6 +38,7 @@
 #include "HTTP.h"
 #include "HttpConfig.h"
 #include "IPAllow.h"
+#include "ProxyClientSession.h"
 
 extern ink_mutex debug_cs_list_mutex;
 
@@ -46,15 +47,21 @@ class HttpServerSession;
 
 class SecurityContext;
 
-class HttpClientSession: public VConnection
+class HttpClientSession: public ProxyClientSession
 {
 public:
   HttpClientSession();
-  void cleanup();
+
+  // Implement ProxyClientSession interface.
   virtual void destroy();
 
-  void new_connection(NetVConnection * new_vc, bool backdoor, MIOBuffer * iobuf, IOBufferReader * reader);
+  virtual void start() {
+    new_transaction();
+  }
+
+  void new_connection(NetVConnection * new_vc, MIOBuffer * iobuf, IOBufferReader * reader, bool backdoor);
 
+  // Implement VConnection interface.
   virtual VIO *do_io_read(Continuation * c, int64_t nbytes = INT64_MAX, MIOBuffer * buf = 0);
   virtual VIO *do_io_write(Continuation * c = NULL, int64_t nbytes = INT64_MAX, IOBufferReader * buf = 0, bool owner = false);
 
@@ -62,6 +69,8 @@ public:
   virtual void do_io_shutdown(ShutdownHowTo_t howto);
   virtual void reenable(VIO * vio);
 
+  void new_transaction();
+
   void set_half_close_flag() { half_close = true; };
   virtual void release(IOBufferReader * r);
   NetVConnection *get_netvc() const { return client_vc;  };
@@ -75,17 +84,9 @@ public:
   // Functions for manipulating api hooks
   void ssn_hook_append(TSHttpHookID id, INKContInternal * cont);
   void ssn_hook_prepend(TSHttpHookID id, INKContInternal * cont);
-  APIHook *ssn_hook_get(TSHttpHookID id);
-
-  // Used to verify we are recording the current
-  //   client transaction stat properly
-  int64_t con_id;
 
   int get_transact_count() const { return  transact_count; }
 
-  void* get_user_arg(int ix) const { return user_args[ix]; }
-  void set_user_arg(int ix, void* arg) { user_args[ix] = arg; }
-
 private:
   HttpClientSession(HttpClientSession &);
 
@@ -94,12 +95,6 @@ private:
   int state_wait_for_close(int event, void *data);
   void set_tcp_init_cwnd();
 
-  void handle_api_return(int event);
-  int state_api_callout(int event, void *data);
-  void do_api_callout(TSHttpHookID id);
-
-  virtual void new_transaction();
-
   enum C_Read_State
   {
     HCS_INIT,
@@ -109,13 +104,13 @@ private:
     HCS_CLOSED
   };
 
+  int64_t con_id;
   NetVConnection *client_vc;
   int magic;
-  bool tcp_init_cwnd_set;
   int transact_count;
+  bool tcp_init_cwnd_set;
   bool half_close;
   bool conn_decrease;
-  void *user_args[HTTP_SSN_TXN_MAX_USER_ARG];
 
   HttpServerSession *bound_ss;
 
@@ -129,18 +124,7 @@ private:
 
   Link<HttpClientSession> debug_link;
 
-  TSHttpHookID cur_hook_id;
-  APIHook *cur_hook;
-  int cur_hooks;
-
-  // api_hooks must not be changed directly
-  //  Use ssn_hook_{ap,pre}pend so hooks_set is
-  //  updated
-  HttpAPIHooks api_hooks;
-
 public:
-  bool backdoor_connect;
-  int hooks_set;
   /// Local address for outbound connection.
   IpAddr outbound_ip4;
   /// Local address for outbound connection.
@@ -161,16 +145,8 @@ public:
   // be active until the transaction goes through or the client
   // aborts.
   bool m_active;
-  // Session specific debug flag
-  bool debug_on;
 };
 
-inline APIHook *
-HttpClientSession::ssn_hook_get(TSHttpHookID id)
-{
-  return api_hooks.get(id);
-}
-
 extern ClassAllocator<HttpClientSession> httpClientSessionAllocator;
 
 #endif

http://git-wip-us.apache.org/repos/asf/trafficserver/blob/9c0458c4/proxy/http/HttpConfig.h
----------------------------------------------------------------------
diff --git a/proxy/http/HttpConfig.h b/proxy/http/HttpConfig.h
index 288e1e8..aea9b79 100644
--- a/proxy/http/HttpConfig.h
+++ b/proxy/http/HttpConfig.h
@@ -53,12 +53,6 @@
 
 #include "P_RecProcess.h"
 
-
-/* Some defines that might be candidates for configurable settings later.
- */
-#define HTTP_SSN_TXN_MAX_USER_ARG         16   /* max number of user arguments for Transactions and Sessions */
-
-
 /* Instead of enumerating the stats in DynamicStats.h, each module needs
    to enumerate its stats separately and register them with librecords
    */

http://git-wip-us.apache.org/repos/asf/trafficserver/blob/9c0458c4/proxy/http/HttpProxyServerMain.cc
----------------------------------------------------------------------
diff --git a/proxy/http/HttpProxyServerMain.cc b/proxy/http/HttpProxyServerMain.cc
index 9eb9291..5c966b8 100644
--- a/proxy/http/HttpProxyServerMain.cc
+++ b/proxy/http/HttpProxyServerMain.cc
@@ -37,6 +37,7 @@
 #include "P_SSLNextProtocolAccept.h"
 #include "ProtocolProbeSessionAccept.h"
 #include "SpdySessionAccept.h"
+#include "http2/Http2SessionAccept.h"
 
 HttpSessionAccept *plugin_http_accept = NULL;
 HttpSessionAccept *plugin_http_transparent_accept = 0;
@@ -184,6 +185,10 @@ MakeHttpProxyAcceptor(HttpProxyAcceptor& acceptor, HttpProxyPort& port, unsigned
   }
 #endif
 
+  if (port.m_session_protocol_preference.intersects(HTTP2_PROTOCOL_SET)) {
+    probe->registerEndpoint(ProtocolProbeSessionAccept::PROTO_HTTP2, new Http2SessionAccept(accept_opt));
+  }
+
   if (port.isSSL()) {
     SSLNextProtocolAccept *ssl = new SSLNextProtocolAccept(probe);
 
@@ -203,6 +208,11 @@ MakeHttpProxyAcceptor(HttpProxyAcceptor& acceptor, HttpProxyPort& port, unsigned
       ssl->registerEndpoint(TS_NPN_PROTOCOL_HTTP_1_1, http);
     }
 
+    // HTTP2
+    if (port.m_session_protocol_preference.contains(TS_NPN_PROTOCOL_INDEX_HTTP_2_0)) {
+      ssl->registerEndpoint(TS_NPN_PROTOCOL_HTTP_2_0, new Http2SessionAccept(accept_opt));
+    }
+
     // SPDY
 #if TS_HAS_SPDY
     if (port.m_session_protocol_preference.contains(TS_NPN_PROTOCOL_INDEX_SPDY_3)) {

http://git-wip-us.apache.org/repos/asf/trafficserver/blob/9c0458c4/proxy/http/HttpSM.cc
----------------------------------------------------------------------
diff --git a/proxy/http/HttpSM.cc b/proxy/http/HttpSM.cc
index 0cdbde2..211fc22 100644
--- a/proxy/http/HttpSM.cc
+++ b/proxy/http/HttpSM.cc
@@ -326,7 +326,7 @@ HttpSM::HttpSM()
     cache_response_hdr_bytes(0), cache_response_body_bytes(0),
     pushed_response_hdr_bytes(0), pushed_response_body_bytes(0),
     plugin_tag(0), plugin_id(0),
-    hooks_set(0), cur_hook_id(TS_HTTP_LAST_HOOK), cur_hook(NULL),
+    hooks_set(false), cur_hook_id(TS_HTTP_LAST_HOOK), cur_hook(NULL),
     cur_hooks(0), callout_state(HTTP_API_NO_CALLOUT), terminate_sm(false), kill_this_async_done(false)
 {
   static int scatter_init = 0;
@@ -529,7 +529,7 @@ HttpSM::attach_client_session(HttpClientSession * client_vc, IOBufferReader * bu
 
   ua_session = client_vc;
   mutex = client_vc->mutex;
-  if (ua_session->debug_on) debug_on = true;
+  if (ua_session->debug()) debug_on = true;
 
   start_sub_sm();
 
@@ -544,13 +544,13 @@ HttpSM::attach_client_session(HttpClientSession * client_vc, IOBufferReader * bu
   ats_ip_copy(&t_state.client_info.addr, netvc->get_remote_addr());
   t_state.client_info.port = netvc->get_local_port();
   t_state.client_info.is_transparent = netvc->get_is_transparent();
-  t_state.backdoor_request = client_vc->backdoor_connect;
+  t_state.backdoor_request = !client_vc->hooks_enabled();
   t_state.client_info.port_attribute = static_cast<HttpProxyPort::TransportType>(netvc->attributes);
 
   HTTP_INCREMENT_DYN_STAT(http_current_client_transactions_stat);
 
   // Record api hook set state
-  hooks_set = http_global_hooks->has_hooks() || client_vc->hooks_set;
+  hooks_set = client_vc->has_hooks();
 
   // Setup for parsing the header
   ua_buffer_reader = buffer_reader;
@@ -718,8 +718,8 @@ HttpSM::state_read_client_request_header(int event, void *data)
       call_transact_and_set_next_state(HttpTransact::BadRequest);
       break;
     } else if (event == VC_EVENT_READ_COMPLETE) {
-	DebugSM("http_parse", "[%" PRId64 "] VC_EVENT_READ_COMPLETE and PARSE CONT state", sm_id);
-	break;
+      DebugSM("http_parse", "[%" PRId64 "] VC_EVENT_READ_COMPLETE and PARSE CONT state", sm_id);
+      break;
     } else {
       if (is_transparent_passthrough_allowed() &&
           ua_raw_buffer_reader != NULL &&

http://git-wip-us.apache.org/repos/asf/trafficserver/blob/9c0458c4/proxy/http/HttpSM.h
----------------------------------------------------------------------
diff --git a/proxy/http/HttpSM.h b/proxy/http/HttpSM.h
index 13121ec..015a59b 100644
--- a/proxy/http/HttpSM.h
+++ b/proxy/http/HttpSM.h
@@ -497,7 +497,7 @@ public:
   // hooks_set records whether there are any hooks relevant
   //  to this transaction.  Used to avoid costly calls
   //  do_api_callout_internal()
-  int hooks_set;
+  bool hooks_set;
 
 protected:
   TSHttpHookID cur_hook_id;

http://git-wip-us.apache.org/repos/asf/trafficserver/blob/9c0458c4/proxy/http/HttpSessionAccept.cc
----------------------------------------------------------------------
diff --git a/proxy/http/HttpSessionAccept.cc b/proxy/http/HttpSessionAccept.cc
index 942a215..9dbbef3 100644
--- a/proxy/http/HttpSessionAccept.cc
+++ b/proxy/http/HttpSessionAccept.cc
@@ -66,7 +66,7 @@ HttpSessionAccept::accept(NetVConnection * netvc, MIOBuffer * iobuf, IOBufferRea
   new_session->host_res_style = ats_host_res_from(client_ip->sa_family, host_res_preference);
   new_session->acl_record = acl_record;
 
-  new_session->new_connection(netvc, backdoor, iobuf, reader);
+  new_session->new_connection(netvc, iobuf, reader, backdoor);
 
   return;
 }

http://git-wip-us.apache.org/repos/asf/trafficserver/blob/9c0458c4/proxy/http2/HTTP2.cc
----------------------------------------------------------------------
diff --git a/proxy/http2/HTTP2.cc b/proxy/http2/HTTP2.cc
new file mode 100644
index 0000000..567fc3c
--- /dev/null
+++ b/proxy/http2/HTTP2.cc
@@ -0,0 +1,256 @@
+/** @file
+ *
+ *  Fundamental HTTP/2 protocol definitions and parsers.
+ *
+ *  @section license License
+ *
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+#include "HTTP2.h"
+#include "ink_assert.h"
+
+const char * const HTTP2_CONNECTION_PREFACE = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n";
+
+union byte_pointer {
+  byte_pointer(void * p) : ptr(p) {}
+
+  void *      ptr;
+  uint8_t *   u8;
+  uint16_t *  u16;
+  uint32_t *  u32;
+};
+
+template <typename T>
+union byte_addressable_value
+{
+  uint8_t   bytes[sizeof(T)];
+  T         value;
+};
+
+static void
+write_and_advance(byte_pointer& dst, uint32_t src)
+{
+  byte_addressable_value<uint32_t> pval;
+
+  pval.value = htonl(src);
+  memcpy(dst.u8, pval.bytes, sizeof(pval.bytes));
+  dst.u8 += sizeof(pval.bytes);
+}
+
+static void
+write_and_advance(byte_pointer& dst, uint16_t src)
+{
+  byte_addressable_value<uint16_t> pval;
+
+  pval.value = htons(src);
+  memcpy(dst.u8, pval.bytes, sizeof(pval.bytes));
+  dst.u8 += sizeof(pval.bytes);
+}
+
+static void
+write_and_advance(byte_pointer& dst, uint8_t src)
+{
+  *dst.u8 = src;
+  dst.u8++;
+}
+
+template<unsigned N> static void
+memcpy_and_advance(uint8_t (&dst)[N], byte_pointer& src)
+{
+  memcpy(dst, src.u8, N);
+  src.u8 += N;
+}
+
+void
+memcpy_and_advance(uint8_t (&dst), byte_pointer& src)
+{
+  dst = *src.u8;
+  ++src.u8;
+}
+
+static bool
+http2_are_frame_flags_valid(uint8_t ftype, uint8_t fflags)
+{
+  static const uint8_t mask[HTTP2_FRAME_TYPE_MAX] = {
+    HTTP2_FLAGS_DATA_MASK,
+    HTTP2_FLAGS_HEADERS_MASK,
+    HTTP2_FLAGS_PRIORITY_MASK,
+    HTTP2_FLAGS_RST_STREAM_MASK,
+    HTTP2_FLAGS_SETTINGS_MASK,
+    HTTP2_FLAGS_PUSH_PROMISE_MASK,
+    HTTP2_FLAGS_PING_MASK,
+    HTTP2_FLAGS_GOAWAY_MASK,
+    HTTP2_FLAGS_WINDOW_UPDATE_MASK,
+    HTTP2_FLAGS_CONTINUATION_MASK,
+    HTTP2_FLAGS_ALTSVC_MASK,
+    HTTP2_FLAGS_BLOCKED_MASK,
+  };
+
+  // The frame flags are valid for this frame if nothing outside the defined bits is set.
+  return (fflags & ~mask[ftype]) == 0;
+}
+
+bool
+http2_frame_header_is_valid(const Http2FrameHeader& hdr)
+{
+  if (hdr.type >= HTTP2_FRAME_TYPE_MAX) {
+    return false;
+  }
+
+  if (hdr.length > HTTP2_MAX_FRAME_PAYLOAD) {
+    return false;
+  }
+
+  if (!http2_are_frame_flags_valid(hdr.type, hdr.flags)) {
+    return false;
+  }
+
+  return true;
+}
+
+bool
+http2_settings_parameter_is_valid(const Http2SettingsParameter& param)
+{
+  // Static maximum values for Settings parameters.
+  static const unsigned settings_max[HTTP2_SETTINGS_MAX] = {
+    0,
+    UINT_MAX, // HTTP2_SETTINGS_HEADER_TABLE_SIZE
+    1,        // HTTP2_SETTINGS_ENABLE_PUSH
+    UINT_MAX, // HTTP2_SETTINGS_MAX_CONCURRENT_STREAMS
+    HTTP2_MAX_WINDOW_SIZE, // HTTP2_SETTINGS_INITIAL_WINDOW_SIZE
+    1,        // HTTP2_SETTINGS_COMPRESS_DATA
+  };
+
+  if (param.id == 0 || param.id >= HTTP2_SETTINGS_MAX) {
+    return false;
+  }
+
+  if (param.value > settings_max[param.id]) {
+    return false;
+  }
+
+  return true;
+}
+
+// 4.1.  Frame Format
+//
+// 0                   1                   2                   3
+// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+// | R |     Length (14)           |   Type (8)    |   Flags (8)   |
+// +-+-+-----------+---------------+-------------------------------+
+// |R|                 Stream Identifier (31)                      |
+// +-+-------------------------------------------------------------+
+// |                   Frame Payload (0...)                      ...
+// +---------------------------------------------------------------+
+
+bool
+http2_parse_frame_header(IOVec iov, Http2FrameHeader& hdr)
+{
+  byte_pointer ptr(iov.iov_base);
+  byte_addressable_value<uint16_t> length;
+  byte_addressable_value<uint32_t> streamid;
+
+  if (unlikely(iov.iov_len < HTTP2_FRAME_HEADER_LEN)) {
+    return false;
+  }
+
+  memcpy_and_advance(length.bytes, ptr);
+  memcpy_and_advance(hdr.type, ptr);
+  memcpy_and_advance(hdr.flags, ptr);
+  memcpy_and_advance(streamid.bytes, ptr);
+
+  length.bytes[0] &= 0x3F;  // Clear the 2 reserved high bits
+  streamid.bytes[0] &= 0x7f;// Clear the high reserved bit
+  hdr.length = ntohs(length.value);
+  hdr.streamid = ntohl(streamid.value);
+
+  return true;
+}
+
+bool
+http2_write_frame_header(const Http2FrameHeader& hdr, IOVec iov)
+{
+  byte_pointer ptr(iov.iov_base);
+
+  if (unlikely(iov.iov_len < HTTP2_FRAME_HEADER_LEN)) {
+    return false;
+  }
+
+  write_and_advance(ptr, hdr.length);
+  write_and_advance(ptr, hdr.type);
+  write_and_advance(ptr, hdr.flags);
+  write_and_advance(ptr, hdr.streamid);
+
+  return true;
+}
+
+// 6.8. GOAWAY
+//
+// 0                   1                   2                   3
+// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+// |R|                  Last-Stream-ID (31)                        |
+// +-+-------------------------------------------------------------+
+// |                      Error Code (32)                          |
+// +---------------------------------------------------------------+
+// |                  Additional Debug Data (*)                    |
+// +---------------------------------------------------------------+
+
+bool
+http2_write_goaway(const Http2Goaway& goaway, IOVec iov)
+{
+  byte_pointer ptr(iov.iov_base);
+
+  if (unlikely(iov.iov_len < HTTP2_GOAWAY_LEN)) {
+    return false;
+  }
+
+  write_and_advance(ptr, goaway.last_streamid);
+  write_and_advance(ptr, goaway.error_code);
+
+  return true;
+}
+
+// 6.5.1.  SETTINGS Format
+//
+// 0                   1                   2                   3
+// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+// | Identifier (8)|        Value (32)                             |
+// +---------------+-----------------------------------------------+
+// |               |
+// +---------------+
+
+bool
+http2_parse_settings_parameter(IOVec iov, Http2SettingsParameter& param)
+{
+  byte_pointer ptr(iov.iov_base);
+  byte_addressable_value<uint32_t> pval;
+
+  if (unlikely(iov.iov_len < HTTP2_SETTINGS_PARAMETER_LEN)) {
+    return false;
+  }
+
+  memcpy_and_advance(param.id, ptr);
+  memcpy_and_advance(pval.bytes, ptr);
+
+  param.value = ntohl(pval.value);
+
+  return true;
+}

http://git-wip-us.apache.org/repos/asf/trafficserver/blob/9c0458c4/proxy/http2/HTTP2.h
----------------------------------------------------------------------
diff --git a/proxy/http2/HTTP2.h b/proxy/http2/HTTP2.h
new file mode 100644
index 0000000..c7c2fec
--- /dev/null
+++ b/proxy/http2/HTTP2.h
@@ -0,0 +1,252 @@
+/** @file
+ *
+ *  Fundamental HTTP/2 protocol definitions and parsers.
+ *
+ *  @section license License
+ *
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+#ifndef __HTTP2_H__
+#define __HTTP2_H__
+
+#include "ink_defs.h"
+#include "ink_memory.h"
+
+typedef unsigned Http2StreamId;
+
+// 6.9.2 Initial Flow Control Window Size - the flow control window can be come negative
+// so we need to track it with a signed type.
+typedef int32_t Http2WindowSize;
+
+extern const char * const HTTP2_CONNECTION_PREFACE;
+const size_t HTTP2_CONNECTION_PREFACE_LEN = 24;
+
+const size_t HTTP2_FRAME_HEADER_LEN = 8;
+const size_t HTTP2_GOAWAY_LEN = 8;
+const size_t HTTP2_SETTINGS_PARAMETER_LEN = 5;
+
+// 4.2. Frame Size. The absolute maximum size of a frame payload is 2^14-1 (16,383) octets.
+const size_t HTTP2_MAX_FRAME_PAYLOAD = 16383;
+
+enum Http2ErrorCode
+{
+  HTTP2_ERROR_NO_ERROR = 0,
+  HTTP2_ERROR_PROTOCOL_ERROR = 1,
+  HTTP2_ERROR_INTERNAL_ERROR = 2,
+  HTTP2_ERROR_FLOW_CONTROL_ERROR = 3,
+  HTTP2_ERROR_SETTINGS_TIMEOUT = 4,
+  HTTP2_ERROR_STREAM_CLOSED = 5,
+  HTTP2_ERROR_FRAME_SIZE_ERROR = 6,
+  HTTP2_ERROR_REFUSED_STREAM = 7,
+  HTTP2_ERROR_CANCEL = 8,
+  HTTP2_ERROR_COMPRESSION_ERROR = 9,
+  HTTP2_ERROR_CONNECT_ERROR = 10,
+  HTTP2_ERROR_ENHANCE_YOUR_CALM = 11,
+  HTTP2_ERROR_INADEQUATE_SECURITY = 12,
+
+  HTTP2_ERROR_MAX,
+};
+
+enum Http2FrameType
+{
+  HTTP2_FRAME_TYPE_DATA = 0,
+  HTTP2_FRAME_TYPE_HEADERS = 1,
+  HTTP2_FRAME_TYPE_PRIORITY = 2,
+  HTTP2_FRAME_TYPE_RST_STREAM = 3,
+  HTTP2_FRAME_TYPE_SETTINGS = 4,
+  HTTP2_FRAME_TYPE_PUSH_PROMISE = 5,
+  HTTP2_FRAME_TYPE_PING = 6,
+  HTTP2_FRAME_TYPE_GOAWAY = 7,
+  HTTP2_FRAME_TYPE_WINDOW_UPDATE = 8,
+  HTTP2_FRAME_TYPE_CONTINUATION = 9,
+  HTTP2_FRAME_TYPE_ALTSVC = 10,
+  HTTP2_FRAME_TYPE_BLOCKED = 11,
+
+  HTTP2_FRAME_TYPE_MAX,
+};
+
+// 6.1 Data
+enum Http2FrameFlagsData
+{
+  HTTP2_FLAGS_DATA_END_STREAM = 0x01,
+  HTTP2_FLAGS_DATA_END_SEGMENT = 0x02,
+  HTTP2_FLAGS_DATA_PAD_LOW = 0x08,
+  HTTP2_FLAGS_DATA_PAD_HIGH = 0x10,
+  HTTP2_FLAGS_DATA_COMPRESSESD = 0x20,
+
+  HTTP2_FLAGS_DATA_MASK = 0x2B,
+};
+
+// 6.2 Headers
+enum Http2FrameFlagsHeaders
+{
+  HTTP2_FLAGS_HEADERS_END_STREAM = 0x01,
+  HTTP2_FLAGS_HEADERS_END_SEGMENT = 0x02,
+  HTTP2_FLAGS_HEADERS_PAD_LOW = 0x08,
+  HTTP2_FLAGS_HEADERS_PAD_HIGH = 0x10,
+  HTTP2_FLAGS_HEADERS_PRIORITY = 0x20,
+
+  HTTP2_FLAGS_HEADERS_MASK = 0x2B,
+};
+
+// 6.3 Priority
+enum Http2FrameFlagsPriority
+{
+  HTTP2_FLAGS_PRIORITY_MASK = 0x00
+};
+
+// 6.3 Rst Stream
+enum Http2FrameFlagsRstStream
+{
+  HTTP2_FLAGS_RST_STREAM_MASK = 0x00
+};
+
+// 6.4 Settings
+enum Http2FrameFlagsSettings
+{
+  HTTP2_FLAGS_SETTINGS_ACK = 0x01,
+
+  HTTP2_FLAGS_SETTINGS_MASK = 0x01
+};
+
+// 6.6 Push Promise
+enum Http2FrameFlagsPushPromise
+{
+  HTTP2_FLAGS_PUSH_PROMISE_END_HEADERS = 0x04,
+  HTTP2_FLAGS_PUSH_PROMISE_PAD_LOW = 0x08,
+  HTTP2_FLAGS_PUSH_PROMISE_PAD_HIGH = 0x10,
+
+  HTTP2_FLAGS_PUSH_PROMISE_MASK = 0x1C,
+};
+
+// 6.7 Ping
+enum Http2FrameFlagsPing
+{
+  HTTP2_FLAGS_PING_ACK = 0x01,
+
+  HTTP2_FLAGS_PING_MASK = 0x01
+};
+
+// 6.8 Goaway
+enum Http2FrameFlagsGoaway
+{
+  HTTP2_FLAGS_GOAWAY_MASK = 0x00
+};
+
+// 6.9 Window Update
+enum Http2FrameFlagsWindowUpdate
+{
+  HTTP2_FLAGS_WINDOW_UPDATE_MASK = 0x00
+};
+
+// 6.10 Continuation
+enum Http2FrameFlagsContinuation
+{
+  HTTP2_FLAGS_CONTINUATION_END_HEADERS = 0x04,
+  HTTP2_FLAGS_CONTINUATION_PAD_LOW = 0x08,
+  HTTP2_FLAGS_CONTINUATION_PAD_HIGH = 0x10,
+
+  HTTP2_FLAGS_CONTINUATION_MASK = 0x1C,
+};
+
+// 6.11 Altsvc
+enum Http2FrameFlagsAltsvc
+{
+  HTTP2_FLAGS_ALTSVC_MASK = 0x00
+};
+
+// 6.12 Blocked
+enum Http2FrameFlagsBlocked
+{
+  HTTP2_FLAGS_BLOCKED_MASK = 0x00
+};
+
+// 6.5.2 Defined SETTINGS Parameters
+enum Http2SettingsIdentifier
+{
+  HTTP2_SETTINGS_HEADER_TABLE_SIZE = 1,
+  HTTP2_SETTINGS_ENABLE_PUSH = 2,
+  HTTP2_SETTINGS_MAX_CONCURRENT_STREAMS = 3,
+  HTTP2_SETTINGS_INITIAL_WINDOW_SIZE = 4,
+  HTTP2_SETTINGS_COMPRESS_DATA = 5,
+
+  HTTP2_SETTINGS_MAX
+};
+
+// 4.1. Frame Format
+struct Http2FrameHeader
+{
+  uint16_t      length;
+  uint8_t       type;
+  uint8_t       flags;
+  Http2StreamId streamid;
+};
+
+// 6.5.1. SETTINGS Format
+struct Http2SettingsParameter
+{
+  uint8_t   id;
+  uint32_t  value;
+};
+
+// 6.8 GOAWAY Format
+struct Http2Goaway
+{
+  Http2StreamId last_streamid;
+  uint32_t      error_code;
+
+  // NOTE: we don't (de)serialize the variable length debug data at this layer because there's
+  // really nothing we can do with it without some out of band agreement. Trying to deal with it
+  // just complicates memory management.
+};
+
+// 6.9.1 The Flow Control Window
+static const Http2WindowSize HTTP2_MAX_WINDOW_SIZE = 0x7FFFFFFF;
+
+// 6.9.2 Initial Flow Control Window Size
+static const Http2WindowSize HTTP2_INITIAL_WINDOW_SIZE = 0x0000FFFF;
+
+static inline bool
+http2_is_client_streamid(Http2StreamId streamid) {
+  return (streamid & 0x1u) == 0x1u;
+}
+
+static inline bool
+http2_is_server_streamid(Http2StreamId streamid) {
+  return (streamid & 0x1u) == 0x0u;
+}
+
+bool
+http2_parse_frame_header(IOVec, Http2FrameHeader&);
+
+bool
+http2_write_frame_header(const Http2FrameHeader&, IOVec);
+
+bool
+http2_write_goaway(const Http2Goaway&, IOVec);
+
+bool
+http2_frame_header_is_valid(const Http2FrameHeader&);
+
+bool
+http2_settings_parameter_is_valid(const Http2SettingsParameter&);
+
+bool
+http2_parse_settings_parameter(IOVec, Http2SettingsParameter&);
+
+#endif /* __HTTP2_H__ */

http://git-wip-us.apache.org/repos/asf/trafficserver/blob/9c0458c4/proxy/http2/Http2ClientSession.cc
----------------------------------------------------------------------
diff --git a/proxy/http2/Http2ClientSession.cc b/proxy/http2/Http2ClientSession.cc
new file mode 100644
index 0000000..5628c0e
--- /dev/null
+++ b/proxy/http2/Http2ClientSession.cc
@@ -0,0 +1,321 @@
+/** @file
+
+  Http2ClientSession.
+
+  @section license License
+
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements.  See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership.  The ASF licenses this file
+  to you under the Apache License, Version 2.0 (the
+  "License"); you may not use this file except in compliance
+  with the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+ */
+
+#include "Http2ClientSession.h"
+#include "HttpDebugNames.h"
+
+#define STATE_ENTER(state_name, event) do { \
+  DebugSsn(this, "http2_cs", "[%" PRId64 "] [%s, %s]", this->connection_id(), \
+    #state_name, HttpDebugNames::get_event_name(event)); \
+} while (0)
+
+#define DebugHttp2Ssn(fmt, ...) \
+  DebugSsn(this, "http2_cs",  "[%" PRId64 "] " fmt, this->connection_id(), __VA_ARGS__)
+
+#define DebugHttp2Ssn0(msg) \
+  DebugSsn(this, "http2_cs",  "[%" PRId64 "] " msg, this->connection_id())
+
+#define HTTP2_SET_SESSION_HANDLER(handler) do { \
+  this->session_handler = (handler); \
+} while (0)
+
+ClassAllocator<Http2ClientSession> http2ClientSessionAllocator("http2ClientSessionAllocator");
+
+// memcpy the requested bytes from the IOBufferReader, returning how many were actually copied.
+static inline unsigned
+copy_from_buffer_reader(void * dst, IOBufferReader * reader, unsigned nbytes)
+{
+    char * end;
+
+    end = reader->memcpy(dst, nbytes, 0 /* offset */);
+    return end - (char *)dst;
+}
+
+static int
+send_connection_event(Continuation * cont, int event, void * edata)
+{
+  MUTEX_LOCK(lock, cont->mutex, this_ethread());
+  return cont->handleEvent(event, edata);
+}
+
+Http2ClientSession::Http2ClientSession()
+  : con_id(0), client_vc(NULL), read_buffer(NULL), sm_reader(NULL), write_buffer(NULL), sm_writer(NULL)
+{
+}
+
+void
+Http2ClientSession::destroy()
+{
+  DebugHttp2Ssn0("session destroy");
+
+  ink_release_assert(this->client_vc == NULL);
+
+  free_MIOBuffer(this->read_buffer);
+  ProxyClientSession::cleanup();
+  http2ClientSessionAllocator.free(this);
+}
+
+void
+Http2ClientSession::start()
+{
+  VIO * read_vio;
+  VIO * write_vio;
+
+  MUTEX_LOCK(lock, this->mutex, this_ethread());
+
+  SET_HANDLER(&Http2ClientSession::main_event_handler);
+  HTTP2_SET_SESSION_HANDLER(&Http2ClientSession::state_read_connection_preface);
+
+  read_vio = this->do_io_read(this, INT64_MAX, this->read_buffer);
+  write_vio = this->do_io_write(this, INT64_MAX, this->sm_writer);
+
+  // 3.5 HTTP/2 Connection Preface. Upon establishment of a TCP connection and
+  // determination that HTTP/2 will be used by both peers, each endpoint MUST
+  // send a connection preface as a final confirmation ...
+  //this->write_buffer->write(HTTP2_CONNECTION_PREFACE, HTTP2_CONNECTION_PREFACE_LEN);
+
+  send_connection_event(&this->connection_state, HTTP2_SESSION_EVENT_INIT, this);
+  this->handleEvent(VC_EVENT_READ_READY, read_vio);
+}
+
+void
+Http2ClientSession::new_connection(NetVConnection * new_vc, MIOBuffer * iobuf, IOBufferReader * reader, bool backdoor)
+{
+  // HTTP/2 for the backdoor connections? Let's not deal woth that yet.
+  ink_release_assert(backdoor == false);
+
+  // Unique client session identifier.
+  this->con_id = ProxyClientSession::next_connection_id();
+  this->client_vc = new_vc;
+  this->mutex = new_vc->mutex;
+
+  this->connection_state.mutex = new_ProxyMutex();
+
+  DebugHttp2Ssn("session born, netvc %p", this->client_vc);
+
+  this->read_buffer = iobuf ? iobuf : new_MIOBuffer(HTTP2_HEADER_BUFFER_SIZE_INDEX);
+  this->sm_reader = reader ? reader : this->read_buffer->alloc_reader();
+
+  this->write_buffer = new_MIOBuffer(HTTP2_HEADER_BUFFER_SIZE_INDEX);
+  this->sm_writer = this->write_buffer->alloc_reader();
+
+  do_api_callout(TS_HTTP_SSN_START_HOOK);
+}
+
+VIO *
+Http2ClientSession::do_io_read(Continuation * c, int64_t nbytes, MIOBuffer * buf)
+{
+  return this->client_vc->do_io_read(c, nbytes, buf);
+}
+
+VIO *
+Http2ClientSession::do_io_write(Continuation * c, int64_t nbytes, IOBufferReader * buf, bool owner)
+{
+  return this->client_vc->do_io_write(c, nbytes, buf, owner);
+}
+
+void
+Http2ClientSession::do_io_shutdown(ShutdownHowTo_t howto)
+{
+  this->client_vc->do_io_shutdown(howto);
+}
+
+// XXX Currently, we don't have a half-closed state, but we will need to implement that. After we send a GOAWAY, there
+// are scenarios where we would like to complete the outstanding streams.
+
+void
+Http2ClientSession::do_io_close(int alerrno)
+{
+  DebugHttp2Ssn0("session closed");
+
+  send_connection_event(&this->connection_state, HTTP2_SESSION_EVENT_FINI, this);
+
+  this->client_vc->do_io_close(alerrno);
+  this->client_vc = NULL;
+
+  do_api_callout(TS_HTTP_SSN_CLOSE_HOOK);
+}
+
+void
+Http2ClientSession::reenable(VIO * vio)
+{
+  this->client_vc->reenable(vio);
+}
+
+int
+Http2ClientSession::main_event_handler(int event, void * edata)
+{
+  ink_assert(this->mutex->thread_holding == this_ethread());
+
+  switch (event) {
+  case VC_EVENT_READ_COMPLETE:
+  case VC_EVENT_READ_READY:
+    return (this->*session_handler)(event, edata);
+
+  case HTTP2_SESSION_EVENT_XMIT: {
+    Http2Frame * frame = (Http2Frame *)edata;
+    frame->xmit(this->write_buffer);
+    return 0;
+  }
+
+  case VC_EVENT_ACTIVE_TIMEOUT:
+  case VC_EVENT_INACTIVITY_TIMEOUT:
+  case VC_EVENT_ERROR:
+  case VC_EVENT_EOS:
+    this->do_io_close();
+    return 0;
+
+  case VC_EVENT_WRITE_COMPLETE:
+  case VC_EVENT_WRITE_READY:
+    return 0;
+
+  default:
+    DebugHttp2Ssn("unexpected event=%d edata=%p", event, edata);
+    ink_release_assert(0);
+    return 0;
+  }
+
+}
+
+int
+Http2ClientSession::state_read_connection_preface(int event, void * edata)
+{
+  VIO * vio = (VIO *)edata;
+
+  STATE_ENTER(&Http2ClientSession::state_read_connection_preface, event);
+  ink_assert(event == VC_EVENT_READ_COMPLETE || event == VC_EVENT_READ_READY);
+
+  if (this->sm_reader->read_avail() >= HTTP2_CONNECTION_PREFACE_LEN) {
+    char buf[HTTP2_CONNECTION_PREFACE_LEN];
+    unsigned nbytes;
+
+    nbytes = copy_from_buffer_reader(buf, this->sm_reader, sizeof(buf));
+    ink_release_assert(nbytes == HTTP2_CONNECTION_PREFACE_LEN);
+
+    if (memcmp(HTTP2_CONNECTION_PREFACE, buf, nbytes) != 0) {
+      DebugHttp2Ssn0("invalid connection preface");
+      this->do_io_close();
+      return 0;
+    }
+
+    DebugHttp2Ssn0("received connection preface");
+    this->sm_reader->consume(nbytes);
+    HTTP2_SET_SESSION_HANDLER(&Http2ClientSession::state_start_frame_read);
+
+    // XXX set activity timeouts ...
+
+    // XXX start the write VIO ...
+
+    // If we have unconsumed data, start tranferring frames now.
+    if (this->sm_reader->is_read_avail_more_than(0)) {
+      return this->handleEvent(VC_EVENT_READ_READY, vio);
+    }
+  }
+
+  // XXX We don't have enough data to check the connection preface. We should reset the accept inactivity
+  // timeout. We should have a maximum timeout to get the session started though.
+
+  vio->reenable();
+  return 0;
+}
+
+int
+Http2ClientSession::state_start_frame_read(int event, void * edata)
+{
+  VIO * vio = (VIO *)edata;
+
+  STATE_ENTER(&Http2ClientSession::state_start_frame_read, event);
+  ink_assert(event == VC_EVENT_READ_COMPLETE || event == VC_EVENT_READ_READY);
+
+  if (this->sm_reader->read_avail() >= HTTP2_FRAME_HEADER_LEN) {
+    uint8_t buf[HTTP2_FRAME_HEADER_LEN];
+    unsigned nbytes;
+
+    DebugHttp2Ssn0("receiving frame header");
+    nbytes = copy_from_buffer_reader(buf, this->sm_reader, sizeof(buf));
+
+    if (!http2_parse_frame_header(make_iovec(buf), this->current_hdr)) {
+      DebugHttp2Ssn0("frame header parse failure");
+      this->do_io_close();
+      return 0;
+    }
+
+    DebugHttp2Ssn("frame header length=%u, type=%u, flags=0x%x, streamid=%u",
+        (unsigned)this->current_hdr.length, (unsigned)this->current_hdr.type,
+        (unsigned)this->current_hdr.flags, this->current_hdr.streamid);
+
+    this->sm_reader->consume(nbytes);
+
+    if (!http2_frame_header_is_valid(this->current_hdr)) {
+      // XXX nuke it with HTTP2_ERROR_PROTOCOL_ERROR!
+    }
+
+    // If we know up front that the payload is too long, nuke this connection.
+    if (this->current_hdr.length > HTTP2_MAX_FRAME_PAYLOAD) {
+      // XXX nuke it with HTTP2_ERROR_FRAME_SIZE_ERROR!
+    }
+
+    if (!http2_is_client_streamid(this->current_hdr.streamid)) {
+      // XXX nuke it with HTTP2_ERROR_PROTOCOL_ERROR!
+    }
+
+    HTTP2_SET_SESSION_HANDLER(&Http2ClientSession::state_complete_frame_read);
+    if (this->sm_reader->read_avail() >= this->current_hdr.length) {
+      return this->handleEvent(VC_EVENT_READ_READY, vio);
+    }
+  }
+
+  vio->reenable();
+  return 0;
+}
+
+int
+Http2ClientSession::state_complete_frame_read(int event, void * edata)
+{
+  VIO * vio = (VIO *)edata;
+
+  STATE_ENTER(&Http2ClientSession::state_complete_frame_read, event);
+  ink_assert(event == VC_EVENT_READ_COMPLETE || event == VC_EVENT_READ_READY);
+
+  if (this->sm_reader->read_avail() < this->current_hdr.length) {
+    vio->reenable();
+    return 0;
+  }
+
+  DebugHttp2Ssn("completed frame read, %" PRId64 " bytes available", this->sm_reader->read_avail());
+
+  // XXX parse the frame and handle it ...
+
+  Http2Frame frame(this->current_hdr, this->sm_reader);
+
+  send_connection_event(&this->connection_state, HTTP2_SESSION_EVENT_RECV, &frame);
+  this->sm_reader->consume(this->current_hdr.length);
+
+  HTTP2_SET_SESSION_HANDLER(&Http2ClientSession::state_start_frame_read);
+  if (this->sm_reader->is_read_avail_more_than(0)) {
+    return this->handleEvent(VC_EVENT_READ_READY, vio);
+  }
+
+  vio->reenable();
+  return 0;
+}

http://git-wip-us.apache.org/repos/asf/trafficserver/blob/9c0458c4/proxy/http2/Http2ClientSession.h
----------------------------------------------------------------------
diff --git a/proxy/http2/Http2ClientSession.h b/proxy/http2/Http2ClientSession.h
new file mode 100644
index 0000000..9d1a13a
--- /dev/null
+++ b/proxy/http2/Http2ClientSession.h
@@ -0,0 +1,160 @@
+/** @file
+
+  Http2ClientSession.
+
+  @section license License
+
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements.  See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership.  The ASF licenses this file
+  to you under the Apache License, Version 2.0 (the
+  "License"); you may not use this file except in compliance
+  with the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+ */
+
+#ifndef __HTTP2_CLIENT_SESSION_H__
+#define __HTTP2_CLIENT_SESSION_H__
+
+#include "HTTP2.h"
+#include "ProxyClientSession.h"
+#include "Http2ConnectionState.h"
+
+// Name                       Edata                 Description
+// HTTP2_SESSION_EVENT_INIT   Http2ClientSession *  HTTP/2 session is born
+// HTTP2_SESSION_EVENT_FINI   Http2ClientSession *  HTTP/2 session is ended
+// HTTP2_SESSION_EVENT_RECV   Http2Frame *          Received a frame
+// HTTP2_SESSION_EVENT_XMIT   Http2Frame *          Send this frame
+
+#define HTTP2_SESSION_EVENT_INIT  (HTTP2_SESSION_EVENTS_START + 1)
+#define HTTP2_SESSION_EVENT_FINI  (HTTP2_SESSION_EVENTS_START + 2)
+#define HTTP2_SESSION_EVENT_RECV  (HTTP2_SESSION_EVENTS_START + 3)
+#define HTTP2_SESSION_EVENT_XMIT  (HTTP2_SESSION_EVENTS_START + 4)
+
+static size_t const HTTP2_HEADER_BUFFER_SIZE_INDEX = CLIENT_CONNECTION_FIRST_READ_BUFFER_SIZE_INDEX;
+
+class Http2Frame
+{
+public:
+  Http2Frame(const Http2FrameHeader& h, IOBufferReader * r) {
+    this->hdr.cooked = h;
+    this->ioreader = r;
+  }
+
+  Http2Frame(Http2FrameType type, Http2StreamId streamid, uint8_t flags = 0) {
+    Http2FrameHeader hdr = { 0, (uint8_t)type, flags, streamid };
+    http2_write_frame_header(hdr, make_iovec(this->hdr.raw));
+  }
+
+  IOBufferReader * reader() const {
+    return ioreader;
+  }
+
+  const Http2FrameHeader& header() const {
+    return this->hdr.cooked;
+  }
+
+  // Allocate an IOBufferBlock for this frame. This switches us from using the in-line header
+  // buffer, to an external buffer block.
+  void alloc(int index) {
+    this->ioblock = new_IOBufferBlock();
+    this->ioblock->alloc(index);
+    memcpy(this->ioblock->start(), this->hdr.raw, sizeof(this->hdr.raw));
+    this->ioblock->fill(sizeof(this->hdr.raw));
+
+    http2_parse_frame_header(make_iovec(this->ioblock->start(), HTTP2_FRAME_HEADER_LEN), this->hdr.cooked);
+  }
+
+  // Return the writeable buffer space.
+  IOVec write() {
+    return make_iovec(this->ioblock->end(), this->ioblock->write_avail());
+  }
+
+  // Once the frame has been serialized, update the length.
+  void finalize(size_t nbytes) {
+    if (this->ioblock) {
+      ink_assert(nbytes <= this->ioblock->write_avail());
+      this->ioblock->fill(nbytes);
+
+      this->hdr.cooked.length = this->ioblock->size() - HTTP2_FRAME_HEADER_LEN;
+      http2_write_frame_header(this->hdr.cooked, make_iovec(this->ioblock->start(), HTTP2_FRAME_HEADER_LEN));
+    }
+  }
+
+  void xmit(MIOBuffer * iobuffer) {
+    if (ioblock) {
+      iobuffer->append_block(this->ioblock);
+    } else {
+      iobuffer->write(this->hdr.raw, sizeof(this->hdr.raw));
+    }
+  }
+
+private:
+  Http2Frame(Http2Frame &); // noncopyable
+  Http2Frame& operator=(const Http2Frame &); // noncopyable
+
+  Ptr<IOBufferBlock>  ioblock;
+  IOBufferReader *    ioreader;
+
+  union {
+    Http2FrameHeader cooked;
+    uint8_t raw[HTTP2_FRAME_HEADER_LEN];
+  } hdr;
+};
+
+class Http2ClientSession : public ProxyClientSession
+{
+public:
+  Http2ClientSession();
+
+  typedef int (Http2ClientSession::*SessionHandler)(int, void *);
+
+  // Implement ProxyClientSession interface.
+  void start();
+  void destroy();
+  void new_connection(NetVConnection * new_vc, MIOBuffer * iobuf, IOBufferReader * reader, bool backdoor);
+
+  // Implement VConnection interface.
+  VIO * do_io_read(Continuation * c, int64_t nbytes = INT64_MAX, MIOBuffer * buf = 0);
+  VIO * do_io_write(Continuation * c = NULL, int64_t nbytes = INT64_MAX, IOBufferReader * buf = 0, bool owner = false);
+  void do_io_close(int lerrno = -1);
+  void do_io_shutdown(ShutdownHowTo_t howto);
+  void reenable(VIO * vio);
+
+  int64_t connection_id() const {
+    return this->con_id;
+  }
+
+private:
+
+  Http2ClientSession(Http2ClientSession &); // noncopyable
+  Http2ClientSession& operator=(const Http2ClientSession &); // noncopyable
+
+  int main_event_handler(int, void *);
+
+  int state_read_connection_preface(int, void *);
+  int state_start_frame_read(int, void *);
+  int state_complete_frame_read(int, void *);
+
+  int64_t               con_id;
+  SessionHandler        session_handler;
+  NetVConnection *      client_vc;
+  MIOBuffer *           read_buffer;
+  IOBufferReader *      sm_reader;
+  MIOBuffer *           write_buffer;
+  IOBufferReader *      sm_writer;
+  Http2FrameHeader      current_hdr;
+  Http2ConnectionState  connection_state;
+};
+
+extern ClassAllocator<Http2ClientSession> http2ClientSessionAllocator;
+
+#endif // __HTTP2_CLIENT_SESSION_H__

http://git-wip-us.apache.org/repos/asf/trafficserver/blob/9c0458c4/proxy/http2/Http2ConnectionState.cc
----------------------------------------------------------------------
diff --git a/proxy/http2/Http2ConnectionState.cc b/proxy/http2/Http2ConnectionState.cc
new file mode 100644
index 0000000..a1d2539
--- /dev/null
+++ b/proxy/http2/Http2ConnectionState.cc
@@ -0,0 +1,167 @@
+/** @file
+
+  Http2ConnectionState.
+
+  @section license License
+
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements.  See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership.  The ASF licenses this file
+  to you under the Apache License, Version 2.0 (the
+  "License"); you may not use this file except in compliance
+  with the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+ */
+
+#include "P_Net.h"
+#include "Http2ConnectionState.h"
+#include "Http2ClientSession.h"
+
+#define DebugHttp2Ssn(fmt, ...) \
+  DebugSsn("http2_cs",  "[%" PRId64 "] " fmt, this->con_id, __VA_ARGS__)
+
+typedef Http2ErrorCode (*http2_frame_dispatch)(Http2ClientSession&, Http2ConnectionState&, const Http2Frame&);
+
+static Http2ErrorCode
+rcv_settings_frame(Http2ClientSession& cs, Http2ConnectionState& cstate, const Http2Frame& frame)
+{
+  Http2SettingsParameter  param;
+  char      buf[HTTP2_SETTINGS_PARAMETER_LEN];
+  unsigned  nbytes = 0;
+  char *    end;
+
+  // 6.5 The stream identifier for a SETTINGS frame MUST be zero.
+  if (frame.header().streamid != 0) {
+    return HTTP2_ERROR_PROTOCOL_ERROR;
+  }
+
+  // 6.5 Receipt of a SETTINGS frame with the ACK flag set and a
+  // length field value other than 0 MUST be treated as a connection
+  // error of type FRAME_SIZE_ERROR.
+  if (frame.header().flags & HTTP2_FLAGS_SETTINGS_ACK) {
+    return frame.header().length == 0 ? HTTP2_ERROR_NO_ERROR : HTTP2_ERROR_FRAME_SIZE_ERROR;
+  }
+
+  while (nbytes < frame.header().length) {
+    end = frame.reader()->memcpy(buf, sizeof(buf), nbytes);
+    nbytes += (end - buf);
+
+    if (!http2_parse_settings_parameter(make_iovec(buf, end - buf), param)) {
+      return HTTP2_ERROR_PROTOCOL_ERROR;
+    }
+
+    if (!http2_settings_parameter_is_valid(param)) {
+      return param.id == HTTP2_SETTINGS_INITIAL_WINDOW_SIZE
+        ? HTTP2_ERROR_FLOW_CONTROL_ERROR : HTTP2_ERROR_PROTOCOL_ERROR;
+    }
+
+    DebugSsn(&cs, "http2_cs",  "[%" PRId64 "] setting param=%d value=%u",
+        cs.connection_id(), param.id, param.value);
+
+    cstate.client_settings.set((Http2SettingsIdentifier)param.id, param.value);
+  }
+
+  return HTTP2_ERROR_NO_ERROR;
+}
+
+static const int buffer_size_index[HTTP2_FRAME_TYPE_MAX] =
+{
+  -1,   // HTTP2_FRAME_TYPE_DATA
+  -1,   // HTTP2_FRAME_TYPE_HEADERS
+  -1,   // HTTP2_FRAME_TYPE_PRIORITY
+  -1,   // HTTP2_FRAME_TYPE_RST_STREAM
+  -1,   // HTTP2_FRAME_TYPE_SETTINGS
+  -1,   // HTTP2_FRAME_TYPE_PUSH_PROMISE
+  -1,   // HTTP2_FRAME_TYPE_PING
+  BUFFER_SIZE_INDEX_128,   // HTTP2_FRAME_TYPE_GOAWAY
+  -1,   // HTTP2_FRAME_TYPE_WINDOW_UPDATE
+  -1,   // HTTP2_FRAME_TYPE_CONTINUATION
+  -1,   // HTTP2_FRAME_TYPE_ALTSVC
+  -1,   // HTTP2_FRAME_TYPE_BLOCKED
+};
+
+static const http2_frame_dispatch frame_handlers[HTTP2_FRAME_TYPE_MAX] =
+{
+  NULL,   // HTTP2_FRAME_TYPE_DATA
+  NULL,   // HTTP2_FRAME_TYPE_HEADERS
+  NULL,   // HTTP2_FRAME_TYPE_PRIORITY
+  NULL,   // HTTP2_FRAME_TYPE_RST_STREAM
+  rcv_settings_frame,   // HTTP2_FRAME_TYPE_SETTINGS
+  NULL,   // HTTP2_FRAME_TYPE_PUSH_PROMISE
+  NULL,   // HTTP2_FRAME_TYPE_PING
+  NULL,   // HTTP2_FRAME_TYPE_GOAWAY
+  NULL,   // HTTP2_FRAME_TYPE_WINDOW_UPDATE
+  NULL,   // HTTP2_FRAME_TYPE_CONTINUATION
+  NULL,   // HTTP2_FRAME_TYPE_ALTSVC
+  NULL,   // HTTP2_FRAME_TYPE_BLOCKED
+};
+
+int
+Http2ConnectionState::main_event_handler(int event, void * edata)
+{
+  if (event == HTTP2_SESSION_EVENT_INIT) {
+    ink_assert(this->ua_session == NULL);
+    this->ua_session = (Http2ClientSession *)edata;
+
+    return 0;
+  }
+
+  if (event == HTTP2_SESSION_EVENT_FINI) {
+    this->ua_session = NULL;
+    SET_HANDLER(&Http2ConnectionState::state_closed);
+    return 0;
+  }
+
+  if (event == HTTP2_SESSION_EVENT_RECV) {
+    Http2Frame * frame = (Http2Frame *)edata;
+    Http2ErrorCode error;
+
+    // The session layer should have validated the frame already.
+    ink_assert(frame->header().type < countof(frame_handlers));
+
+    if (frame_handlers[frame->header().type]) {
+      error = frame_handlers[frame->header().type](*this->ua_session, *this, *frame);
+    } else {
+      error = HTTP2_ERROR_INTERNAL_ERROR;
+    }
+
+    if (error != HTTP2_ERROR_NO_ERROR) {
+      Http2Frame frame(HTTP2_FRAME_TYPE_GOAWAY, 0, 0);
+      Http2Goaway goaway;
+
+      goaway.last_streamid = 0;
+      goaway.error_code = error;
+
+      frame.alloc(buffer_size_index[HTTP2_FRAME_TYPE_GOAWAY]);
+      http2_write_goaway(goaway, frame.write());
+      frame.finalize(HTTP2_GOAWAY_LEN);
+
+      this->ua_session->handleEvent(HTTP2_SESSION_EVENT_XMIT, &frame);
+      eventProcessor.schedule_imm(this->ua_session, ET_NET, VC_EVENT_ERROR);
+
+      // XXX We need to think a bit harder about how to coordinate the client session and the
+      // protocol connection. At this point, the protocol is shutting down, but there's no way
+      // to tell that to the client session. Perhaps this could be solved by implementing the
+      // half-closed state ...
+      SET_HANDLER(&Http2ConnectionState::state_closed);
+    }
+
+    return 0;
+  }
+
+  return 0;
+}
+
+int
+Http2ConnectionState::state_closed(int event, void * edata)
+{
+  return 0;
+}

http://git-wip-us.apache.org/repos/asf/trafficserver/blob/9c0458c4/proxy/http2/Http2ConnectionState.h
----------------------------------------------------------------------
diff --git a/proxy/http2/Http2ConnectionState.h b/proxy/http2/Http2ConnectionState.h
new file mode 100644
index 0000000..3dc74a2
--- /dev/null
+++ b/proxy/http2/Http2ConnectionState.h
@@ -0,0 +1,79 @@
+/** @file
+
+  Http2ConnectionState.
+
+  @section license License
+
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements.  See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership.  The ASF licenses this file
+  to you under the Apache License, Version 2.0 (the
+  "License"); you may not use this file except in compliance
+  with the License.  You may obtain a copy of the License at
+
+      http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+ */
+
+#ifndef __HTTP2_CONNECTION_STATE_H__
+#define __HTTP2_CONNECTION_STATE_H__
+
+#include "HTTP2.h"
+
+class Http2ClientSession;
+
+class Http2ConnectionSettings
+{
+public:
+  unsigned get(Http2SettingsIdentifier id) const {
+    return this->settings[indexof(id)];
+  }
+
+  unsigned set(Http2SettingsIdentifier id, unsigned value) {
+    return this->settings[indexof(id)] = value;
+  }
+
+private:
+
+  // Settings ID is 1-based, so convert it to a 0-based index.
+  static unsigned indexof(Http2SettingsIdentifier id) {
+    return id - 1;
+  }
+
+  unsigned settings[HTTP2_SETTINGS_MAX - 1];
+};
+
+// Http2ConnectionState
+//
+// Capture the semantics of a HTTP/2 connection. The client session captures the frame layer, and the
+// connection state captures the connection-wide state.
+
+class Http2ConnectionState : public Continuation
+{
+public:
+
+  Http2ConnectionState() : Continuation(NULL), ua_session(NULL) {
+    SET_HANDLER(&Http2ConnectionState::main_event_handler);
+  }
+
+  Http2ClientSession * ua_session;
+
+  // Settings.
+  Http2ConnectionSettings server_settings;
+  Http2ConnectionSettings client_settings;
+
+  int main_event_handler(int, void *);
+  int state_closed(int, void *);
+
+private:
+  Http2ConnectionState(const Http2ConnectionState&); // noncopyable
+  Http2ConnectionState& operator=(const Http2ConnectionState&); // noncopyable
+};
+
+#endif // __HTTP2_CONNECTION_STATE_H__