Merge branch 'master' of github.com:ctiller/grpc

changes/47/217547/1
Craig Tiller 10 years ago
commit 43db6265c9
  1. 57
      .clang-format
  2. 15
      .gitignore
  3. 4
      .gitmodules
  4. 5
      INSTALL
  5. 5998
      Makefile
  6. 1038
      build.json
  7. 4
      include/grpc++/channel_interface.h
  8. 1
      include/grpc++/config.h
  9. 1
      include/grpc++/credentials.h
  10. 16
      include/grpc++/impl/rpc_service_method.h
  11. 1
      include/grpc++/status_code_enum.h
  12. 6
      include/grpc++/stream.h
  13. 2
      include/grpc++/stream_context_interface.h
  14. 37
      include/grpc/grpc.h
  15. 1
      include/grpc/status.h
  16. 2
      include/grpc/support/atm_win32.h
  17. 8
      include/grpc/support/port_platform.h
  18. 2
      include/grpc/support/slice.h
  19. 159
      src/compiler/cpp_generator.cc
  20. 10
      src/compiler/cpp_generator.h
  21. 26
      src/compiler/cpp_generator_helpers.h
  22. 23
      src/compiler/cpp_plugin.cc
  23. 520
      src/compiler/go_generator.cc
  24. 83
      src/compiler/go_plugin.cc
  25. 46
      src/compiler/ruby_generator.cc
  26. 4
      src/compiler/ruby_generator.h
  27. 12
      src/compiler/ruby_generator_helpers-inl.h
  28. 15
      src/compiler/ruby_generator_map-inl.h
  29. 39
      src/compiler/ruby_generator_string-inl.h
  30. 15
      src/compiler/ruby_plugin.cc
  31. 2
      src/core/channel/child_channel.h
  32. 17
      src/core/channel/http_client_filter.c
  33. 2
      src/core/channel/http_client_filter.h
  34. 4
      src/core/iomgr/alarm.c
  35. 6
      src/core/iomgr/alarm_internal.h
  36. 10
      src/core/iomgr/iomgr.c
  37. 4
      src/core/iomgr/iomgr.h
  38. 8
      src/core/iomgr/iomgr_internal.h
  39. 4
      src/core/iomgr/iomgr_posix.c
  40. 4
      src/core/iomgr/iomgr_posix.h
  41. 68
      src/core/iomgr/pollset_kick.h
  42. 161
      src/core/iomgr/pollset_kick_posix.c
  43. 47
      src/core/iomgr/pollset_kick_posix.h
  44. 9
      src/core/iomgr/pollset_multipoller_with_poll_posix.c
  45. 90
      src/core/iomgr/pollset_posix.c
  46. 5
      src/core/iomgr/pollset_posix.h
  47. 4
      src/core/iomgr/socket_utils_common_posix.c
  48. 2
      src/core/iomgr/socket_utils_posix.h
  49. 2
      src/core/iomgr/tcp_server.h
  50. 6
      src/core/iomgr/tcp_server_posix.c
  51. 4
      src/core/security/credentials.c
  52. 12
      src/core/security/secure_endpoint.c
  53. 4
      src/core/security/secure_transport_setup.c
  54. 34
      src/core/security/security_context.c
  55. 3
      src/core/security/server_secure_chttp2.c
  56. 4
      src/core/statistics/census_init.c
  57. 6
      src/core/statistics/census_interface.h
  58. 10
      src/core/statistics/census_log.c
  59. 8
      src/core/statistics/census_log.h
  60. 13
      src/core/statistics/census_rpc_stats.c
  61. 6
      src/core/statistics/census_rpc_stats.h
  62. 19
      src/core/statistics/census_tracing.c
  63. 8
      src/core/statistics/census_tracing.h
  64. 4
      src/core/support/alloc.c
  65. 4
      src/core/support/cpu.h
  66. 4
      src/core/support/cpu_linux.c
  67. 4
      src/core/support/cpu_posix.c
  68. 2
      src/core/support/log_linux.c
  69. 15
      src/core/support/log_posix.c
  70. 9
      src/core/support/log_win32.c
  71. 8
      src/core/support/murmur_hash.c
  72. 2
      src/core/support/slice.c
  73. 2
      src/core/support/string.c
  74. 2
      src/core/support/time.c
  75. 55
      src/core/surface/call.c
  76. 3
      src/core/surface/client.c
  77. 11
      src/core/surface/completion_queue.c
  78. 2
      src/core/surface/completion_queue.h
  79. 3
      src/core/surface/event_string.c
  80. 4
      src/core/surface/init.c
  81. 25
      src/core/surface/server.c
  82. 2
      src/core/transport/chttp2/alpn.c
  83. 2
      src/core/transport/chttp2/alpn.h
  84. 1
      src/core/transport/chttp2/frame_data.c
  85. 2
      src/core/transport/chttp2/frame_settings.c
  86. 2
      src/core/transport/chttp2/frame_settings.h
  87. 14
      src/core/transport/chttp2/gen_hpack_tables.c
  88. 2
      src/core/transport/chttp2/varint.h
  89. 13
      src/core/transport/chttp2_transport.c
  90. 2
      src/core/transport/metadata.c
  91. 2
      src/core/transport/metadata.h
  92. 78
      src/core/tsi/fake_transport_security.c
  93. 3
      src/core/tsi/fake_transport_security.h
  94. 131
      src/core/tsi/ssl_transport_security.c
  95. 14
      src/core/tsi/ssl_transport_security.h
  96. 49
      src/core/tsi/transport_security.c
  97. 26
      src/core/tsi/transport_security.h
  98. 54
      src/core/tsi/transport_security_interface.h
  99. 56
      src/cpp/client/channel.cc
  100. 22
      src/cpp/client/channel.h
  101. Some files were not shown because too many files have changed in this diff Show More

@ -0,0 +1,57 @@
---
Language: Cpp
# BasedOnStyle: Google
AccessModifierOffset: -1
ConstructorInitializerIndentWidth: 4
AlignEscapedNewlinesLeft: true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: false
AllowShortIfStatementsOnASingleLine: true
AllowShortLoopsOnASingleLine: true
AllowShortFunctionsOnASingleLine: All
AlwaysBreakTemplateDeclarations: true
AlwaysBreakBeforeMultilineStrings: true
BreakBeforeBinaryOperators: false
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BinPackParameters: true
ColumnLimit: 80
ConstructorInitializerAllOnOneLineOrOnePerLine: true
DerivePointerAlignment: true
ExperimentalAutoDetectBinPacking: false
IndentCaseLabels: true
IndentWrappedFunctionNames: false
IndentFunctionDeclarationAfterType: false
MaxEmptyLinesToKeep: 1
KeepEmptyLinesAtTheStartOfBlocks: false
NamespaceIndentation: None
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: false
PenaltyBreakBeforeFirstCallParameter: 1
PenaltyBreakComment: 300
PenaltyBreakString: 1000
PenaltyBreakFirstLessLess: 120
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 200
PointerAlignment: Left
SpacesBeforeTrailingComments: 2
Cpp11BracedListStyle: true
Standard: Auto
IndentWidth: 2
TabWidth: 8
UseTab: Never
BreakBeforeBraces: Attach
SpacesInParentheses: false
SpacesInAngles: false
SpaceInEmptyParentheses: false
SpacesInCStyleCastParentheses: false
SpacesInContainerLiterals: true
SpaceBeforeAssignmentOperators: true
ContinuationIndentWidth: 4
CommentPragmas: '^ IWYU pragma:'
ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ]
SpaceBeforeParens: ControlStatements
DisableFormat: false
...

15
.gitignore vendored

@ -1,6 +1,19 @@
# C/C++ build outputs
bins
deps
gens
libs
objs
# gcov coverage data
coverage
*.gcno
# profiler output
*.prof
# python compiled objects
*.pyc
# cache for run_tests.py
.run_tests_cache

4
.gitmodules vendored

@ -9,10 +9,6 @@
path = third_party/protobuf
url = https://github.com/google/protobuf.git
branch = v3.0.0-alpha-1
[submodule "third_party/libevent"]
path = third_party/libevent
url = https://github.com/libevent/libevent.git
branch = patches-2.0
[submodule "third_party/gflags"]
path = third_party/gflags
url = https://code.google.com/p/gflags

@ -12,8 +12,7 @@ Note that the Makefile makes it much easier for you to compile from sources
if you were to clone recursively our git repository.
grpc core currently depends on zlib and OpenSSL 1.0.2beta3, and also requires
libevent2 for the Linux port.
grpc core currently depends on zlib and OpenSSL 1.0.2beta3.
grpc++'s tests depends on protobuf 3.0.0, gtests and gflags.
@ -46,7 +45,7 @@ and let the Makefile build them itself.
You may also install the dependencies yourself, from the sources, or from
your distribution's package manager.
The development packages needed for grpc are libevent2 under Linux, and zlib.
The only development package needed for grpc is zlib.
The development packages needed for grpc++'s tests are gtests, and gflags.
To the best of our knowledge, no distribution has an OpenSSL package that

5998
Makefile

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

@ -57,8 +57,8 @@ class ChannelInterface {
const google::protobuf::Message& request,
google::protobuf::Message* result) = 0;
virtual StreamContextInterface* CreateStream(const RpcMethod& method,
ClientContext* context,
virtual StreamContextInterface* CreateStream(
const RpcMethod& method, ClientContext* context,
const google::protobuf::Message* request,
google::protobuf::Message* result) = 0;
};

@ -39,7 +39,6 @@
namespace grpc {
typedef std::string string;
}
#endif // __GRPCPP_CONFIG_H__

@ -112,7 +112,6 @@ class CredentialsFactory {
const grpc::string& authorization_token,
const grpc::string& authority_selector);
// Combines two credentials objects into a composite credentials
static std::unique_ptr<Credentials> ComposeCredentials(
const std::unique_ptr<Credentials>& creds1,

@ -55,14 +55,17 @@ class MethodHandler {
public:
virtual ~MethodHandler() {}
struct HandlerParameter {
HandlerParameter(ServerContext* context, const google::protobuf::Message* req,
HandlerParameter(ServerContext* context,
const google::protobuf::Message* req,
google::protobuf::Message* resp)
: server_context(context),
request(req),
response(resp),
stream_context(nullptr) {}
HandlerParameter(ServerContext* context, const google::protobuf::Message* req,
google::protobuf::Message* resp, StreamContextInterface* stream)
HandlerParameter(ServerContext* context,
const google::protobuf::Message* req,
google::protobuf::Message* resp,
StreamContextInterface* stream)
: server_context(context),
request(req),
response(resp),
@ -171,7 +174,8 @@ class RpcServiceMethod : public RpcMethod {
public:
// Takes ownership of the handler and two prototype objects.
RpcServiceMethod(const char* name, RpcMethod::RpcType type,
MethodHandler* handler, google::protobuf::Message* request_prototype,
MethodHandler* handler,
google::protobuf::Message* request_prototype,
google::protobuf::Message* response_prototype)
: RpcMethod(name, type),
handler_(handler),
@ -180,7 +184,9 @@ class RpcServiceMethod : public RpcMethod {
MethodHandler* handler() { return handler_.get(); }
google::protobuf::Message* AllocateRequestProto() { return request_prototype_->New(); }
google::protobuf::Message* AllocateRequestProto() {
return request_prototype_->New();
}
google::protobuf::Message* AllocateResponseProto() {
return response_prototype_->New();
}

@ -34,7 +34,6 @@
#ifndef __GRPCPP_STATUS_CODE_ENUM_H__
#define __GRPCPP_STATUS_CODE_ENUM_H__
namespace grpc {
enum StatusCode {

@ -96,7 +96,7 @@ class ClientReader : public ClientStreamingInterface,
virtual bool Read(R* msg) { return context_->Read(msg); }
virtual void Cancel() { context_->FinishStream(Status::Cancelled, true); }
virtual void Cancel() { context_->Cancel(); }
virtual const Status& Wait() { return context_->Wait(); }
@ -122,7 +122,7 @@ class ClientWriter : public ClientStreamingInterface,
virtual void WritesDone() { context_->Write(nullptr, true); }
virtual void Cancel() { context_->FinishStream(Status::Cancelled, true); }
virtual void Cancel() { context_->Cancel(); }
// Read the final response and wait for the final status.
virtual const Status& Wait() {
@ -165,7 +165,7 @@ class ClientReaderWriter : public ClientStreamingInterface,
virtual void WritesDone() { context_->Write(nullptr, true); }
virtual void Cancel() { context_->FinishStream(Status::Cancelled, true); }
virtual void Cancel() { context_->Cancel(); }
virtual const Status& Wait() { return context_->Wait(); }

@ -53,7 +53,7 @@ class StreamContextInterface {
virtual bool Read(google::protobuf::Message* msg) = 0;
virtual bool Write(const google::protobuf::Message* msg, bool is_last) = 0;
virtual const Status& Wait() = 0;
virtual void FinishStream(const Status& status, bool send) = 0;
virtual void Cancel() = 0;
virtual google::protobuf::Message* request() = 0;
virtual google::protobuf::Message* response() = 0;

@ -194,6 +194,7 @@ typedef enum grpc_completion_type {
GRPC_FINISHED, /* An RPC has finished. The event contains status.
On the server this will be OK or Cancelled. */
GRPC_SERVER_RPC_NEW, /* A new RPC has arrived at the server */
GRPC_SERVER_SHUTDOWN, /* The server has finished shutting down */
GRPC_COMPLETION_DO_NOT_USE /* must be last, forces users to include
a default: case */
} grpc_completion_type;
@ -232,12 +233,12 @@ typedef struct grpc_event {
} grpc_event;
/* Initialize the grpc library */
void grpc_init();
void grpc_init(void);
/* Shutdown the grpc library */
void grpc_shutdown();
void grpc_shutdown(void);
grpc_completion_queue *grpc_completion_queue_create();
grpc_completion_queue *grpc_completion_queue_create(void);
/* Blocks until an event is available, the completion queue is being shutdown,
or deadline is reached. Returns NULL on timeout, otherwise the event that
@ -325,22 +326,6 @@ grpc_call_error grpc_call_start_invoke(grpc_call *call,
void *metadata_read_tag,
void *finished_tag, gpr_uint32 flags);
/* DEPRECATED: users should use grpc_call_server_accept, and
grpc_call_server_end_initial_metadata instead now.
Accept an incoming RPC, binding a completion queue to it.
To be called after adding metadata to the call, but before sending
messages.
flags is a bit-field combination of the write flags defined above.
REQUIRES: Can be called at most once per call.
Can only be called on the server.
Produces a GRPC_FINISHED event with finished_tag when the call has been
completed (there may be other events for the call pending at this
time) */
grpc_call_error grpc_call_accept(grpc_call *call, grpc_completion_queue *cq,
void *finished_tag, gpr_uint32 flags);
/* Accept an incoming RPC, binding a completion queue to it.
To be called before sending or receiving messages.
REQUIRES: Can be called at most once per call.
@ -365,6 +350,16 @@ grpc_call_error grpc_call_server_end_initial_metadata(grpc_call *call,
Can be called multiple times, from any thread. */
grpc_call_error grpc_call_cancel(grpc_call *call);
/* Called by clients to cancel an RPC on the server.
Can be called multiple times, from any thread.
If a status has not been received for the call, set it to the status code
and description passed in.
Importantly, this function does not send status nor description to the
remote endpoint. */
grpc_call_error grpc_call_cancel_with_status(grpc_call *call,
grpc_status_code status,
const char *description);
/* Queue a byte buffer for writing.
flags is a bit-field combination of the write flags defined above.
A write with byte_buffer null is allowed, and will not send any bytes on the
@ -445,6 +440,10 @@ void grpc_server_start(grpc_server *server);
Existing calls will be allowed to complete. */
void grpc_server_shutdown(grpc_server *server);
/* As per grpc_server_shutdown, but send a GRPC_SERVER_SHUTDOWN event when
there are no more calls being serviced. */
void grpc_server_shutdown_and_notify(grpc_server *server, void *tag);
/* Destroy a server.
Forcefully cancels all existing calls. */
void grpc_server_destroy(grpc_server *server);

@ -34,7 +34,6 @@
#ifndef __GRPC_STATUS_H__
#define __GRPC_STATUS_H__
#ifdef __cplusplus
extern "C" {
#endif

@ -55,7 +55,7 @@ static __inline void gpr_atm_rel_store(gpr_atm *p, gpr_atm value) {
}
static __inline int gpr_atm_no_barrier_cas(gpr_atm *p, gpr_atm o, gpr_atm n) {
/* InterlockedCompareExchangePointerNoFence() not available on vista or
/* InterlockedCompareExchangePointerNoFence() not available on vista or
windows7 */
#ifdef GPR_ARCH_64
return o == (gpr_atm)InterlockedCompareExchangeAcquire64(p, n, o);

@ -45,15 +45,16 @@
#if defined(_WIN64) || defined(WIN64)
#define GPR_WIN32 1
#define GPR_ARCH_64 1
#define GPR_GETPID_IN_PROCESS_H 1
#elif defined(_WIN32) || defined(WIN32)
#define GPR_ARCH_32 1
#define GPR_WIN32 1
#define GPR_GETPID_IN_PROCESS_H 1
#elif defined(ANDROID) || defined(__ANDROID__)
#define GPR_ANDROID 1
#define GPR_ARCH_32 1
#define GPR_CPU_LINUX 1
#define GPR_GCC_SYNC 1
#define GPR_LIBEVENT 1
#define GPR_POSIX_MULTIPOLL_WITH_POLL 1
#define GPR_POSIX_SOCKET 1
#define GPR_POSIX_SOCKETADDR 1
@ -61,10 +62,10 @@
#define GPR_POSIX_STRING 1
#define GPR_POSIX_SYNC 1
#define GPR_POSIX_TIME 1
#define GPR_GETPID_IN_UNISTD_H 1
#elif defined(__linux__)
#define GPR_CPU_LINUX 1
#define GPR_GCC_ATOMIC 1
#define GPR_LIBEVENT 1
#define GPR_LINUX 1
#define GPR_POSIX_MULTIPOLL_WITH_POLL 1
#define GPR_POSIX_SOCKET 1
@ -72,6 +73,7 @@
#define GPR_POSIX_STRING 1
#define GPR_POSIX_SYNC 1
#define GPR_POSIX_TIME 1
#define GPR_GETPID_IN_UNISTD_H 1
#ifdef _LP64
#define GPR_ARCH_64 1
#else /* _LP64 */
@ -80,7 +82,6 @@
#elif defined(__APPLE__)
#define GPR_CPU_POSIX 1
#define GPR_GCC_ATOMIC 1
#define GPR_LIBEVENT 1
#define GPR_POSIX_LOG 1
#define GPR_POSIX_MULTIPOLL_WITH_POLL 1
#define GPR_POSIX_SOCKET 1
@ -89,6 +90,7 @@
#define GPR_POSIX_STRING 1
#define GPR_POSIX_SYNC 1
#define GPR_POSIX_TIME 1
#define GPR_GETPID_IN_UNISTD_H 1
#ifdef _LP64
#define GPR_ARCH_64 1
#else /* _LP64 */

@ -163,7 +163,7 @@ gpr_slice gpr_slice_split_tail(gpr_slice *s, size_t split);
Requires s intialized, split <= s.length */
gpr_slice gpr_slice_split_head(gpr_slice *s, size_t split);
gpr_slice gpr_empty_slice();
gpr_slice gpr_empty_slice(void);
/* Returns <0 if a < b, ==0 if a == b, >0 if a > b */
int gpr_slice_cmp(gpr_slice a, gpr_slice b);

@ -31,6 +31,9 @@
*
*/
#include <string>
#include <map>
#include "src/compiler/cpp_generator.h"
#include "src/compiler/cpp_generator_helpers.h"
@ -42,26 +45,23 @@
namespace grpc_cpp_generator {
namespace {
bool NoStreaming(const google::protobuf::MethodDescriptor* method) {
return !method->client_streaming() &&
!method->server_streaming();
bool NoStreaming(const google::protobuf::MethodDescriptor *method) {
return !method->client_streaming() && !method->server_streaming();
}
bool ClientOnlyStreaming(const google::protobuf::MethodDescriptor* method) {
return method->client_streaming() &&
!method->server_streaming();
bool ClientOnlyStreaming(const google::protobuf::MethodDescriptor *method) {
return method->client_streaming() && !method->server_streaming();
}
bool ServerOnlyStreaming(const google::protobuf::MethodDescriptor* method) {
bool ServerOnlyStreaming(const google::protobuf::MethodDescriptor *method) {
return !method->client_streaming() && method->server_streaming();
}
bool BidiStreaming(const google::protobuf::MethodDescriptor* method) {
return method->client_streaming() &&
method->server_streaming();
bool BidiStreaming(const google::protobuf::MethodDescriptor *method) {
return method->client_streaming() && method->server_streaming();
}
bool HasClientOnlyStreaming(const google::protobuf::FileDescriptor* file) {
bool HasClientOnlyStreaming(const google::protobuf::FileDescriptor *file) {
for (int i = 0; i < file->service_count(); i++) {
for (int j = 0; j < file->service(i)->method_count(); j++) {
if (ClientOnlyStreaming(file->service(i)->method(j))) {
@ -72,7 +72,7 @@ bool HasClientOnlyStreaming(const google::protobuf::FileDescriptor* file) {
return false;
}
bool HasServerOnlyStreaming(const google::protobuf::FileDescriptor* file) {
bool HasServerOnlyStreaming(const google::protobuf::FileDescriptor *file) {
for (int i = 0; i < file->service_count(); i++) {
for (int j = 0; j < file->service(i)->method_count(); j++) {
if (ServerOnlyStreaming(file->service(i)->method(j))) {
@ -83,7 +83,7 @@ bool HasServerOnlyStreaming(const google::protobuf::FileDescriptor* file) {
return false;
}
bool HasBidiStreaming(const google::protobuf::FileDescriptor* file) {
bool HasBidiStreaming(const google::protobuf::FileDescriptor *file) {
for (int i = 0; i < file->service_count(); i++) {
for (int j = 0; j < file->service(i)->method_count(); j++) {
if (BidiStreaming(file->service(i)->method(j))) {
@ -95,8 +95,8 @@ bool HasBidiStreaming(const google::protobuf::FileDescriptor* file) {
}
} // namespace
string GetHeaderIncludes(const google::protobuf::FileDescriptor* file) {
string temp =
std::string GetHeaderIncludes(const google::protobuf::FileDescriptor *file) {
std::string temp =
"#include \"grpc++/impl/internal_stub.h\"\n"
"#include \"grpc++/status.h\"\n"
"\n"
@ -124,16 +124,16 @@ string GetHeaderIncludes(const google::protobuf::FileDescriptor* file) {
return temp;
}
string GetSourceIncludes() {
std::string GetSourceIncludes() {
return "#include \"grpc++/channel_interface.h\"\n"
"#include \"grpc++/impl/rpc_method.h\"\n"
"#include \"grpc++/impl/rpc_service_method.h\"\n"
"#include \"grpc++/stream.h\"\n";
}
void PrintHeaderClientMethod(google::protobuf::io::Printer* printer,
const google::protobuf::MethodDescriptor* method,
map<string, string>* vars) {
void PrintHeaderClientMethod(google::protobuf::io::Printer *printer,
const google::protobuf::MethodDescriptor *method,
std::map<std::string, std::string> *vars) {
(*vars)["Method"] = method->name();
(*vars)["Request"] =
grpc_cpp_generator::ClassName(method->input_type(), true);
@ -146,23 +146,23 @@ void PrintHeaderClientMethod(google::protobuf::io::Printer* printer,
} else if (ClientOnlyStreaming(method)) {
printer->Print(
*vars,
"::grpc::ClientWriter<$Request$>* $Method$("
"::grpc::ClientWriter< $Request$>* $Method$("
"::grpc::ClientContext* context, $Response$* response);\n\n");
} else if (ServerOnlyStreaming(method)) {
printer->Print(
*vars,
"::grpc::ClientReader<$Response$>* $Method$("
"::grpc::ClientReader< $Response$>* $Method$("
"::grpc::ClientContext* context, const $Request$* request);\n\n");
} else if (BidiStreaming(method)) {
printer->Print(*vars,
"::grpc::ClientReaderWriter<$Request$, $Response$>* "
"::grpc::ClientReaderWriter< $Request$, $Response$>* "
"$Method$(::grpc::ClientContext* context);\n\n");
}
}
void PrintHeaderServerMethod(google::protobuf::io::Printer* printer,
const google::protobuf::MethodDescriptor* method,
map<string, string>* vars) {
void PrintHeaderServerMethod(google::protobuf::io::Printer *printer,
const google::protobuf::MethodDescriptor *method,
std::map<std::string, std::string> *vars) {
(*vars)["Method"] = method->name();
(*vars)["Request"] =
grpc_cpp_generator::ClassName(method->input_type(), true);
@ -177,25 +177,26 @@ void PrintHeaderServerMethod(google::protobuf::io::Printer* printer,
printer->Print(*vars,
"virtual ::grpc::Status $Method$("
"::grpc::ServerContext* context, "
"::grpc::ServerReader<$Request$>* reader, "
"::grpc::ServerReader< $Request$>* reader, "
"$Response$* response);\n");
} else if (ServerOnlyStreaming(method)) {
printer->Print(*vars,
"virtual ::grpc::Status $Method$("
"::grpc::ServerContext* context, const $Request$* request, "
"::grpc::ServerWriter<$Response$>* writer);\n");
"::grpc::ServerWriter< $Response$>* writer);\n");
} else if (BidiStreaming(method)) {
printer->Print(*vars,
printer->Print(
*vars,
"virtual ::grpc::Status $Method$("
"::grpc::ServerContext* context, "
"::grpc::ServerReaderWriter<$Response$, $Request$>* stream);"
"::grpc::ServerReaderWriter< $Response$, $Request$>* stream);"
"\n");
}
}
void PrintHeaderService(google::protobuf::io::Printer* printer,
const google::protobuf::ServiceDescriptor* service,
map<string, string>* vars) {
void PrintHeaderService(google::protobuf::io::Printer *printer,
const google::protobuf::ServiceDescriptor *service,
std::map<std::string, std::string> *vars) {
(*vars)["Service"] = service->name();
printer->Print(*vars,
@ -204,7 +205,8 @@ void PrintHeaderService(google::protobuf::io::Printer* printer,
printer->Indent();
// Client side
printer->Print("class Stub : public ::grpc::InternalStub {\n"
printer->Print(
"class Stub : public ::grpc::InternalStub {\n"
" public:\n");
printer->Indent();
for (int i = 0; i < service->method_count(); ++i) {
@ -213,13 +215,14 @@ void PrintHeaderService(google::protobuf::io::Printer* printer,
printer->Outdent();
printer->Print("};\n");
printer->Print(
"static Stub* NewStub(const std::shared_ptr<::grpc::ChannelInterface>& "
"static Stub* NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& "
"channel);\n");
printer->Print("\n");
// Server side
printer->Print("class Service {\n"
printer->Print(
"class Service {\n"
" public:\n");
printer->Indent();
printer->Print("Service() : service_(nullptr) {}\n");
@ -229,7 +232,8 @@ void PrintHeaderService(google::protobuf::io::Printer* printer,
}
printer->Print("::grpc::RpcService* service();\n");
printer->Outdent();
printer->Print(" private:\n"
printer->Print(
" private:\n"
" ::grpc::RpcService* service_;\n");
printer->Print("};\n");
@ -237,11 +241,11 @@ void PrintHeaderService(google::protobuf::io::Printer* printer,
printer->Print("};\n");
}
string GetHeaderServices(const google::protobuf::FileDescriptor* file) {
string output;
std::string GetHeaderServices(const google::protobuf::FileDescriptor *file) {
std::string output;
google::protobuf::io::StringOutputStream output_stream(&output);
google::protobuf::io::Printer printer(&output_stream, '$');
map<string, string> vars;
std::map<std::string, std::string> vars;
for (int i = 0; i < file->service_count(); ++i) {
PrintHeaderService(&printer, file->service(i), &vars);
@ -250,9 +254,9 @@ string GetHeaderServices(const google::protobuf::FileDescriptor* file) {
return output;
}
void PrintSourceClientMethod(google::protobuf::io::Printer* printer,
const google::protobuf::MethodDescriptor* method,
map<string, string>* vars) {
void PrintSourceClientMethod(google::protobuf::io::Printer *printer,
const google::protobuf::MethodDescriptor *method,
std::map<std::string, std::string> *vars) {
(*vars)["Method"] = method->name();
(*vars)["Request"] =
grpc_cpp_generator::ClassName(method->input_type(), true);
@ -269,11 +273,12 @@ void PrintSourceClientMethod(google::protobuf::io::Printer* printer,
"context, request, response);\n"
"}\n\n");
} else if (ClientOnlyStreaming(method)) {
printer->Print(*vars,
"::grpc::ClientWriter<$Request$>* $Service$::Stub::$Method$("
printer->Print(
*vars,
"::grpc::ClientWriter< $Request$>* $Service$::Stub::$Method$("
"::grpc::ClientContext* context, $Response$* response) {\n");
printer->Print(*vars,
" return new ::grpc::ClientWriter<$Request$>("
" return new ::grpc::ClientWriter< $Request$>("
"channel()->CreateStream("
"::grpc::RpcMethod(\"/$Package$$Service$/$Method$\", "
"::grpc::RpcMethod::RpcType::CLIENT_STREAMING), "
@ -282,10 +287,10 @@ void PrintSourceClientMethod(google::protobuf::io::Printer* printer,
} else if (ServerOnlyStreaming(method)) {
printer->Print(
*vars,
"::grpc::ClientReader<$Response$>* $Service$::Stub::$Method$("
"::grpc::ClientReader< $Response$>* $Service$::Stub::$Method$("
"::grpc::ClientContext* context, const $Request$* request) {\n");
printer->Print(*vars,
" return new ::grpc::ClientReader<$Response$>("
" return new ::grpc::ClientReader< $Response$>("
"channel()->CreateStream("
"::grpc::RpcMethod(\"/$Package$$Service$/$Method$\", "
"::grpc::RpcMethod::RpcType::SERVER_STREAMING), "
@ -294,11 +299,11 @@ void PrintSourceClientMethod(google::protobuf::io::Printer* printer,
} else if (BidiStreaming(method)) {
printer->Print(
*vars,
"::grpc::ClientReaderWriter<$Request$, $Response$>* "
"::grpc::ClientReaderWriter< $Request$, $Response$>* "
"$Service$::Stub::$Method$(::grpc::ClientContext* context) {\n");
printer->Print(
*vars,
" return new ::grpc::ClientReaderWriter<$Request$, $Response$>("
" return new ::grpc::ClientReaderWriter< $Request$, $Response$>("
"channel()->CreateStream("
"::grpc::RpcMethod(\"/$Package$$Service$/$Method$\", "
"::grpc::RpcMethod::RpcType::BIDI_STREAMING), "
@ -307,9 +312,9 @@ void PrintSourceClientMethod(google::protobuf::io::Printer* printer,
}
}
void PrintSourceServerMethod(google::protobuf::io::Printer* printer,
const google::protobuf::MethodDescriptor* method,
map<string, string>* vars) {
void PrintSourceServerMethod(google::protobuf::io::Printer *printer,
const google::protobuf::MethodDescriptor *method,
std::map<std::string, std::string> *vars) {
(*vars)["Method"] = method->name();
(*vars)["Request"] =
grpc_cpp_generator::ClassName(method->input_type(), true);
@ -328,7 +333,7 @@ void PrintSourceServerMethod(google::protobuf::io::Printer* printer,
printer->Print(*vars,
"::grpc::Status $Service$::Service::$Method$("
"::grpc::ServerContext* context, "
"::grpc::ServerReader<$Request$>* reader, "
"::grpc::ServerReader< $Request$>* reader, "
"$Response$* response) {\n");
printer->Print(
" return ::grpc::Status("
@ -339,7 +344,7 @@ void PrintSourceServerMethod(google::protobuf::io::Printer* printer,
"::grpc::Status $Service$::Service::$Method$("
"::grpc::ServerContext* context, "
"const $Request$* request, "
"::grpc::ServerWriter<$Response$>* writer) {\n");
"::grpc::ServerWriter< $Response$>* writer) {\n");
printer->Print(
" return ::grpc::Status("
"::grpc::StatusCode::UNIMPLEMENTED);\n");
@ -348,7 +353,7 @@ void PrintSourceServerMethod(google::protobuf::io::Printer* printer,
printer->Print(*vars,
"::grpc::Status $Service$::Service::$Method$("
"::grpc::ServerContext* context, "
"::grpc::ServerReaderWriter<$Response$, $Request$>* "
"::grpc::ServerReaderWriter< $Response$, $Request$>* "
"stream) {\n");
printer->Print(
" return ::grpc::Status("
@ -357,13 +362,14 @@ void PrintSourceServerMethod(google::protobuf::io::Printer* printer,
}
}
void PrintSourceService(google::protobuf::io::Printer* printer,
const google::protobuf::ServiceDescriptor* service,
map<string, string>* vars) {
void PrintSourceService(google::protobuf::io::Printer *printer,
const google::protobuf::ServiceDescriptor *service,
std::map<std::string, std::string> *vars) {
(*vars)["Service"] = service->name();
printer->Print(*vars,
printer->Print(
*vars,
"$Service$::Stub* $Service$::NewStub("
"const std::shared_ptr<::grpc::ChannelInterface>& channel) {\n"
"const std::shared_ptr< ::grpc::ChannelInterface>& channel) {\n"
" $Service$::Stub* stub = new $Service$::Stub();\n"
" stub->set_channel(channel);\n"
" return stub;\n"
@ -382,12 +388,13 @@ void PrintSourceService(google::protobuf::io::Printer* printer,
printer->Print(*vars,
"::grpc::RpcService* $Service$::Service::service() {\n");
printer->Indent();
printer->Print("if (service_ != nullptr) {\n"
printer->Print(
"if (service_ != nullptr) {\n"
" return service_;\n"
"}\n");
printer->Print("service_ = new ::grpc::RpcService();\n");
for (int i = 0; i < service->method_count(); ++i) {
const google::protobuf::MethodDescriptor* method = service->method(i);
const google::protobuf::MethodDescriptor *method = service->method(i);
(*vars)["Method"] = method->name();
(*vars)["Request"] =
grpc_cpp_generator::ClassName(method->input_type(), true);
@ -399,9 +406,9 @@ void PrintSourceService(google::protobuf::io::Printer* printer,
"service_->AddMethod(new ::grpc::RpcServiceMethod(\n"
" \"/$Package$$Service$/$Method$\",\n"
" ::grpc::RpcMethod::NORMAL_RPC,\n"
" new ::grpc::RpcMethodHandler<$Service$::Service, $Request$, "
" new ::grpc::RpcMethodHandler< $Service$::Service, $Request$, "
"$Response$>(\n"
" std::function<::grpc::Status($Service$::Service*, "
" std::function< ::grpc::Status($Service$::Service*, "
"::grpc::ServerContext*, const $Request$*, $Response$*)>("
"&$Service$::Service::$Method$), this),\n"
" new $Request$, new $Response$));\n");
@ -411,11 +418,11 @@ void PrintSourceService(google::protobuf::io::Printer* printer,
"service_->AddMethod(new ::grpc::RpcServiceMethod(\n"
" \"/$Package$$Service$/$Method$\",\n"
" ::grpc::RpcMethod::CLIENT_STREAMING,\n"
" new ::grpc::ClientStreamingHandler<"
" new ::grpc::ClientStreamingHandler< "
"$Service$::Service, $Request$, $Response$>(\n"
" std::function<::grpc::Status($Service$::Service*, "
" std::function< ::grpc::Status($Service$::Service*, "
"::grpc::ServerContext*, "
"::grpc::ServerReader<$Request$>*, $Response$*)>("
"::grpc::ServerReader< $Request$>*, $Response$*)>("
"&$Service$::Service::$Method$), this),\n"
" new $Request$, new $Response$));\n");
} else if (ServerOnlyStreaming(method)) {
@ -424,11 +431,11 @@ void PrintSourceService(google::protobuf::io::Printer* printer,
"service_->AddMethod(new ::grpc::RpcServiceMethod(\n"
" \"/$Package$$Service$/$Method$\",\n"
" ::grpc::RpcMethod::SERVER_STREAMING,\n"
" new ::grpc::ServerStreamingHandler<"
" new ::grpc::ServerStreamingHandler< "
"$Service$::Service, $Request$, $Response$>(\n"
" std::function<::grpc::Status($Service$::Service*, "
" std::function< ::grpc::Status($Service$::Service*, "
"::grpc::ServerContext*, "
"const $Request$*, ::grpc::ServerWriter<$Response$>*)>("
"const $Request$*, ::grpc::ServerWriter< $Response$>*)>("
"&$Service$::Service::$Method$), this),\n"
" new $Request$, new $Response$));\n");
} else if (BidiStreaming(method)) {
@ -437,11 +444,11 @@ void PrintSourceService(google::protobuf::io::Printer* printer,
"service_->AddMethod(new ::grpc::RpcServiceMethod(\n"
" \"/$Package$$Service$/$Method$\",\n"
" ::grpc::RpcMethod::BIDI_STREAMING,\n"
" new ::grpc::BidiStreamingHandler<"
" new ::grpc::BidiStreamingHandler< "
"$Service$::Service, $Request$, $Response$>(\n"
" std::function<::grpc::Status($Service$::Service*, "
" std::function< ::grpc::Status($Service$::Service*, "
"::grpc::ServerContext*, "
"::grpc::ServerReaderWriter<$Response$, $Request$>*)>("
"::grpc::ServerReaderWriter< $Response$, $Request$>*)>("
"&$Service$::Service::$Method$), this),\n"
" new $Request$, new $Response$));\n");
}
@ -451,11 +458,11 @@ void PrintSourceService(google::protobuf::io::Printer* printer,
printer->Print("}\n\n");
}
string GetSourceServices(const google::protobuf::FileDescriptor* file) {
string output;
std::string GetSourceServices(const google::protobuf::FileDescriptor *file) {
std::string output;
google::protobuf::io::StringOutputStream output_stream(&output);
google::protobuf::io::Printer printer(&output_stream, '$');
map<string, string> vars;
std::map<std::string, std::string> vars;
// Package string is empty or ends with a dot. It is used to fully qualify
// method names.
vars["Package"] = file->package();

@ -42,21 +42,19 @@ class FileDescriptor;
} // namespace protobuf
} // namespace google
using namespace std;
namespace grpc_cpp_generator {
// Return the includes needed for generated header file.
string GetHeaderIncludes(const google::protobuf::FileDescriptor* file);
std::string GetHeaderIncludes(const google::protobuf::FileDescriptor *file);
// Return the includes needed for generated source file.
string GetSourceIncludes();
std::string GetSourceIncludes();
// Return the services for generated header file.
string GetHeaderServices(const google::protobuf::FileDescriptor* file);
std::string GetHeaderServices(const google::protobuf::FileDescriptor *file);
// Return the services for generated source file.
string GetSourceServices(const google::protobuf::FileDescriptor* file);
std::string GetSourceServices(const google::protobuf::FileDescriptor *file);
} // namespace grpc_cpp_generator

@ -39,14 +39,12 @@
#include <google/protobuf/descriptor.h>
#include <google/protobuf/descriptor.pb.h>
using namespace std;
namespace grpc_cpp_generator {
inline bool StripSuffix(string* filename, const string& suffix) {
inline bool StripSuffix(std::string *filename, const std::string &suffix) {
if (filename->length() >= suffix.length()) {
size_t suffix_pos = filename->length() - suffix.length();
if (filename->compare(suffix_pos, string::npos, suffix) == 0) {
if (filename->compare(suffix_pos, std::string::npos, suffix) == 0) {
filename->resize(filename->size() - suffix.size());
return true;
}
@ -55,19 +53,20 @@ inline bool StripSuffix(string* filename, const string& suffix) {
return false;
}
inline string StripProto(string filename) {
inline std::string StripProto(std::string filename) {
if (!StripSuffix(&filename, ".protodevel")) {
StripSuffix(&filename, ".proto");
}
return filename;
}
inline string StringReplace(string str, const string& from, const string& to) {
inline std::string StringReplace(std::string str, const std::string &from,
const std::string &to) {
size_t pos = 0;
for (;;) {
pos = str.find(from, pos);
if (pos == string::npos) {
if (pos == std::string::npos) {
break;
}
str.replace(pos, from.length(), to);
@ -77,22 +76,23 @@ inline string StringReplace(string str, const string& from, const string& to) {
return str;
}
inline string DotsToColons(const string& name) {
inline std::string DotsToColons(const std::string &name) {
return StringReplace(name, ".", "::");
}
inline string DotsToUnderscores(const string& name) {
inline std::string DotsToUnderscores(const std::string &name) {
return StringReplace(name, ".", "_");
}
inline string ClassName(const google::protobuf::Descriptor* descriptor, bool qualified) {
inline std::string ClassName(const google::protobuf::Descriptor *descriptor,
bool qualified) {
// Find "outer", the descriptor of the top-level message in which
// "descriptor" is embedded.
const google::protobuf::Descriptor* outer = descriptor;
const google::protobuf::Descriptor *outer = descriptor;
while (outer->containing_type() != NULL) outer = outer->containing_type();
const string& outer_name = outer->full_name();
string inner_name = descriptor->full_name().substr(outer_name.size());
const std::string &outer_name = outer->full_name();
std::string inner_name = descriptor->full_name().substr(outer_name.size());
if (qualified) {
return "::" + DotsToColons(outer_name) + DotsToUnderscores(inner_name);

@ -35,6 +35,8 @@
//
#include <memory>
#include <string>
#include "src/compiler/cpp_generator.h"
#include "src/compiler/cpp_generator_helpers.h"
#include <google/protobuf/descriptor.h>
@ -49,18 +51,19 @@ class CppGrpcGenerator : public google::protobuf::compiler::CodeGenerator {
CppGrpcGenerator() {}
virtual ~CppGrpcGenerator() {}
virtual bool Generate(const google::protobuf::FileDescriptor* file,
const string& parameter,
google::protobuf::compiler::GeneratorContext* context,
string* error) const {
virtual bool Generate(const google::protobuf::FileDescriptor *file,
const std::string &parameter,
google::protobuf::compiler::GeneratorContext *context,
std::string *error) const {
if (file->options().cc_generic_services()) {
*error = "cpp grpc proto compiler plugin does not work with generic "
*error =
"cpp grpc proto compiler plugin does not work with generic "
"services. To generate cpp grpc APIs, please set \""
"cc_generic_service = false\".";
return false;
}
string file_name = grpc_cpp_generator::StripProto(file->name());
std::string file_name = grpc_cpp_generator::StripProto(file->name());
// Generate .pb.h
Insert(context, file_name + ".pb.h", "includes",
@ -78,9 +81,9 @@ class CppGrpcGenerator : public google::protobuf::compiler::CodeGenerator {
private:
// Insert the given code into the given file at the given insertion point.
void Insert(google::protobuf::compiler::GeneratorContext* context,
const string& filename, const string& insertion_point,
const string& code) const {
void Insert(google::protobuf::compiler::GeneratorContext *context,
const std::string &filename, const std::string &insertion_point,
const std::string &code) const {
std::unique_ptr<google::protobuf::io::ZeroCopyOutputStream> output(
context->OpenForInsert(filename, insertion_point));
google::protobuf::io::CodedOutputStream coded_out(output.get());
@ -88,7 +91,7 @@ class CppGrpcGenerator : public google::protobuf::compiler::CodeGenerator {
}
};
int main(int argc, char* argv[]) {
int main(int argc, char *argv[]) {
CppGrpcGenerator generator;
return google::protobuf::compiler::PluginMain(argc, argv, &generator);
}

@ -1,520 +0,0 @@
/*
*
* Copyright 2014, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
using namespace std;
#include "src/compiler/go_generator.h"
#include <cctype>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
#include <google/protobuf/descriptor.pb.h>
#include <google/protobuf/descriptor.h>
namespace grpc_go_generator {
bool NoStreaming(const google::protobuf::MethodDescriptor* method) {
return !method->client_streaming() &&
!method->server_streaming();
}
bool ClientOnlyStreaming(const google::protobuf::MethodDescriptor* method) {
return method->client_streaming() &&
!method->server_streaming();
}
bool ServerOnlyStreaming(const google::protobuf::MethodDescriptor* method) {
return !method->client_streaming() &&
method->server_streaming();
}
bool BidiStreaming(const google::protobuf::MethodDescriptor* method) {
return method->client_streaming() &&
method->server_streaming();
}
bool HasClientOnlyStreaming(const google::protobuf::FileDescriptor* file) {
for (int i = 0; i < file->service_count(); i++) {
for (int j = 0; j < file->service(i)->method_count(); j++) {
if (ClientOnlyStreaming(file->service(i)->method(j))) {
return true;
}
}
}
return false;
}
string LowerCaseService(const string& service) {
string ret = service;
if (!ret.empty() && ret[0] >= 'A' && ret[0] <= 'Z') {
ret[0] = ret[0] - 'A' + 'a';
}
return ret;
}
void PrintClientMethodDef(google::protobuf::io::Printer* printer,
const google::protobuf::MethodDescriptor* method,
map<string, string>* vars) {
(*vars)["Method"] = method->name();
(*vars)["Request"] = method->input_type()->name();
(*vars)["Response"] = method->output_type()->name();
if (NoStreaming(method)) {
printer->Print(*vars,
"\t$Method$(ctx context.Context, in *$Request$, opts ...rpc.CallOption) "
"(*$Response$, error)\n");
} else if (BidiStreaming(method)) {
printer->Print(*vars,
"\t$Method$(ctx context.Context, opts ...rpc.CallOption) "
"($Service$_$Method$Client, error)\n");
} else if (ServerOnlyStreaming(method)) {
printer->Print(*vars,
"\t$Method$(ctx context.Context, m *$Request$, opts ...rpc.CallOption) "
"($Service$_$Method$Client, error)\n");
} else if (ClientOnlyStreaming(method)) {
printer->Print(*vars,
"\t$Method$(ctx context.Context, opts ...rpc.CallOption) "
"($Service$_$Method$Client, error)\n");
}
}
void PrintClientMethodImpl(google::protobuf::io::Printer* printer,
const google::protobuf::MethodDescriptor* method,
map<string, string>* vars) {
(*vars)["Method"] = method->name();
(*vars)["Request"] = method->input_type()->name();
(*vars)["Response"] = method->output_type()->name();
if (NoStreaming(method)) {
printer->Print(*vars,
"func (c *$ServiceStruct$Client) $Method$(ctx context.Context, "
"in *$Request$, opts ...rpc.CallOption) (*$Response$, error) {\n");
printer->Print(*vars,
"\tout := new($Response$)\n");
printer->Print(*vars,
"\terr := rpc.Invoke(ctx, \"/$Package$$Service$/$Method$\", "
"in, out, c.cc, opts...)\n");
printer->Print("\tif err != nil {\n");
printer->Print("\t\treturn nil, err\n");
printer->Print("\t}\n");
printer->Print("\treturn out, nil\n");
printer->Print("}\n\n");
} else if (BidiStreaming(method)) {
printer->Print(
*vars,
"func (c *$ServiceStruct$Client) $Method$(ctx context.Context, opts "
"...rpc.CallOption) ($Service$_$Method$Client, error) {\n"
"\tstream, err := rpc.NewClientStream(ctx, c.cc, "
"\"/$Package$$Service$/$Method$\", opts...)\n"
"\tif err != nil {\n"
"\t\treturn nil, err\n"
"\t}\n"
"\treturn &$ServiceStruct$$Method$Client{stream}, nil\n"
"}\n\n");
printer->Print(*vars,
"type $Service$_$Method$Client interface {\n"
"\tSend(*$Request$) error\n"
"\tRecv() (*$Response$, error)\n"
"\trpc.ClientStream\n"
"}\n\n");
printer->Print(*vars,
"type $ServiceStruct$$Method$Client struct {\n"
"\trpc.ClientStream\n"
"}\n\n");
printer->Print(*vars,
"func (x *$ServiceStruct$$Method$Client) Send(m *$Request$) error {\n"
"\treturn x.ClientStream.SendProto(m)\n"
"}\n\n");
printer->Print(*vars,
"func (x *$ServiceStruct$$Method$Client) Recv() (*$Response$, error) "
"{\n"
"\tm := new($Response$)\n"
"\tif err := x.ClientStream.RecvProto(m); err != nil {\n"
"\t\treturn nil, err\n"
"\t}\n"
"\treturn m, nil\n"
"}\n\n");
} else if (ServerOnlyStreaming(method)) {
printer->Print(
*vars,
"func (c *$ServiceStruct$Client) $Method$(ctx context.Context, m "
"*$Request$, "
"opts ...rpc.CallOption) ($Service$_$Method$Client, error) {\n"
"\tstream, err := rpc.NewClientStream(ctx, c.cc, "
"\"/$Package$$Service$/$Method$\", opts...)\n"
"\tif err != nil {\n"
"\t\treturn nil, err\n"
"\t}\n"
"\tx := &$ServiceStruct$$Method$Client{stream}\n"
"\tif err := x.ClientStream.SendProto(m); err != nil {\n"
"\t\treturn nil, err\n"
"\t}\n"
"\tif err := x.ClientStream.CloseSend(); err != nil {\n"
"\t\treturn nil, err\n"
"\t}\n"
"\treturn x, nil\n"
"}\n\n");
printer->Print(*vars,
"type $Service$_$Method$Client interface {\n"
"\tRecv() (*$Response$, error)\n"
"\trpc.ClientStream\n"
"}\n\n");
printer->Print(*vars,
"type $ServiceStruct$$Method$Client struct {\n"
"\trpc.ClientStream\n"
"}\n\n");
printer->Print(*vars,
"func (x *$ServiceStruct$$Method$Client) Recv() (*$Response$, error) "
"{\n"
"\tm := new($Response$)\n"
"\tif err := x.ClientStream.RecvProto(m); err != nil {\n"
"\t\treturn nil, err\n"
"\t}\n"
"\treturn m, nil\n"
"}\n\n");
} else if (ClientOnlyStreaming(method)) {
printer->Print(
*vars,
"func (c *$ServiceStruct$Client) $Method$(ctx context.Context, opts "
"...rpc.CallOption) ($Service$_$Method$Client, error) {\n"
"\tstream, err := rpc.NewClientStream(ctx, c.cc, "
"\"/$Package$$Service$/$Method$\", opts...)\n"
"\tif err != nil {\n"
"\t\treturn nil, err\n"
"\t}\n"
"\treturn &$ServiceStruct$$Method$Client{stream}, nil\n"
"}\n\n");
printer->Print(*vars,
"type $Service$_$Method$Client interface {\n"
"\tSend(*$Request$) error\n"
"\tCloseAndRecv() (*$Response$, error)\n"
"\trpc.ClientStream\n"
"}\n\n");
printer->Print(*vars,
"type $ServiceStruct$$Method$Client struct {\n"
"\trpc.ClientStream\n"
"}\n\n");
printer->Print(*vars,
"func (x *$ServiceStruct$$Method$Client) Send(m *$Request$) error {\n"
"\treturn x.ClientStream.SendProto(m)\n"
"}\n\n");
printer->Print(*vars,
"func (x *$ServiceStruct$$Method$Client) CloseAndRecv() (*$Response$, "
"error) {\n"
"\tif err := x.ClientStream.CloseSend(); err != nil {\n"
"\t\treturn nil, err\n"
"\t}\n"
"\tm := new($Response$)\n"
"\tif err := x.ClientStream.RecvProto(m); err != nil {\n"
"\t\treturn nil, err\n"
"\t}\n"
"\t// Read EOF.\n"
"\tif err := x.ClientStream.RecvProto(m); err == io.EOF {\n"
"\t\treturn m, io.EOF\n"
"\t}\n"
"\t// gRPC protocol violation.\n"
"\treturn m, fmt.Errorf(\"Violate gRPC client streaming protocol: no "
"EOF after the response.\")\n"
"}\n\n");
}
}
void PrintClient(google::protobuf::io::Printer* printer,
const google::protobuf::ServiceDescriptor* service,
map<string, string>* vars) {
(*vars)["Service"] = service->name();
(*vars)["ServiceStruct"] = LowerCaseService(service->name());
printer->Print(*vars, "type $Service$Client interface {\n");
for (int i = 0; i < service->method_count(); ++i) {
PrintClientMethodDef(printer, service->method(i), vars);
}
printer->Print("}\n\n");
printer->Print(*vars,
"type $ServiceStruct$Client struct {\n"
"\tcc *rpc.ClientConn\n"
"}\n\n");
printer->Print(*vars,
"func New$Service$Client(cc *rpc.ClientConn) $Service$Client {\n"
"\treturn &$ServiceStruct$Client{cc}\n"
"}\n\n");
for (int i = 0; i < service->method_count(); ++i) {
PrintClientMethodImpl(printer, service->method(i), vars);
}
}
void PrintServerMethodDef(google::protobuf::io::Printer* printer,
const google::protobuf::MethodDescriptor* method,
map<string, string>* vars) {
(*vars)["Method"] = method->name();
(*vars)["Request"] = method->input_type()->name();
(*vars)["Response"] = method->output_type()->name();
if (NoStreaming(method)) {
printer->Print(*vars,
"\t$Method$(context.Context, *$Request$) (*$Response$, error)\n");
} else if (BidiStreaming(method)) {
printer->Print(*vars,
"\t$Method$($Service$_$Method$Server) error\n");
} else if (ServerOnlyStreaming(method)) {
printer->Print(*vars,
"\t$Method$(*$Request$, $Service$_$Method$Server) error\n");
} else if (ClientOnlyStreaming(method)) {
printer->Print(*vars,
"\t$Method$($Service$_$Method$Server) error\n");
}
}
void PrintServerHandler(google::protobuf::io::Printer* printer,
const google::protobuf::MethodDescriptor* method,
map<string, string>* vars) {
(*vars)["Method"] = method->name();
(*vars)["Request"] = method->input_type()->name();
(*vars)["Response"] = method->output_type()->name();
if (NoStreaming(method)) {
printer->Print(*vars,
"func _$Service$_$Method$_Handler(srv interface{}, ctx context.Context,"
" buf []byte) (proto.Message, error) {\n");
printer->Print(*vars,
"\tin := new($Request$)\n");
printer->Print("\tif err := proto.Unmarshal(buf, in); err != nil {\n");
printer->Print("\t\treturn nil, err\n");
printer->Print("\t}\n");
printer->Print(*vars,
"\tout, err := srv.($Service$Server).$Method$(ctx, in)\n");
printer->Print("\tif err != nil {\n");
printer->Print("\t\treturn nil, err\n");
printer->Print("\t}\n");
printer->Print("\treturn out, nil\n");
printer->Print("}\n\n");
} else if (BidiStreaming(method)) {
printer->Print(*vars,
"func _$Service$_$Method$_Handler(srv interface{}, stream rpc.Stream) "
"error {\n"
"\treturn srv.($Service$Server).$Method$(&$ServiceStruct$$Method$Server"
"{stream})\n"
"}\n\n");
printer->Print(*vars,
"type $Service$_$Method$Server interface {\n"
"\tSend(*$Response$) error\n"
"\tRecv() (*$Request$, error)\n"
"\trpc.Stream\n"
"}\n\n");
printer->Print(*vars,
"type $ServiceStruct$$Method$Server struct {\n"
"\trpc.Stream\n"
"}\n\n");
printer->Print(*vars,
"func (x *$ServiceStruct$$Method$Server) Send(m *$Response$) error {\n"
"\treturn x.Stream.SendProto(m)\n"
"}\n\n");
printer->Print(*vars,
"func (x *$ServiceStruct$$Method$Server) Recv() (*$Request$, error) "
"{\n"
"\tm := new($Request$)\n"
"\tif err := x.Stream.RecvProto(m); err != nil {\n"
"\t\treturn nil, err\n"
"\t}\n"
"\treturn m, nil\n"
"}\n\n");
} else if (ServerOnlyStreaming(method)) {
printer->Print(*vars,
"func _$Service$_$Method$_Handler(srv interface{}, stream rpc.Stream) "
"error {\n"
"\tm := new($Request$)\n"
"\tif err := stream.RecvProto(m); err != nil {\n"
"\t\treturn err\n"
"\t}\n"
"\treturn srv.($Service$Server).$Method$(m, "
"&$ServiceStruct$$Method$Server{stream})\n"
"}\n\n");
printer->Print(*vars,
"type $Service$_$Method$Server interface {\n"
"\tSend(*$Response$) error\n"
"\trpc.Stream\n"
"}\n\n");
printer->Print(*vars,
"type $ServiceStruct$$Method$Server struct {\n"
"\trpc.Stream\n"
"}\n\n");
printer->Print(*vars,
"func (x *$ServiceStruct$$Method$Server) Send(m *$Response$) error {\n"
"\treturn x.Stream.SendProto(m)\n"
"}\n\n");
} else if (ClientOnlyStreaming(method)) {
printer->Print(*vars,
"func _$Service$_$Method$_Handler(srv interface{}, stream rpc.Stream) "
"error {\n"
"\treturn srv.($Service$Server).$Method$(&$ServiceStruct$$Method$Server"
"{stream})\n"
"}\n\n");
printer->Print(*vars,
"type $Service$_$Method$Server interface {\n"
"\tSendAndClose(*$Response$) error\n"
"\tRecv() (*$Request$, error)\n"
"\trpc.Stream\n"
"}\n\n");
printer->Print(*vars,
"type $ServiceStruct$$Method$Server struct {\n"
"\trpc.Stream\n"
"}\n\n");
printer->Print(*vars,
"func (x *$ServiceStruct$$Method$Server) SendAndClose(m *$Response$) "
"error {\n"
"\tif err := x.Stream.SendProto(m); err != nil {\n"
"\t\treturn err\n"
"\t}\n"
"\treturn nil\n"
"}\n\n");
printer->Print(*vars,
"func (x *$ServiceStruct$$Method$Server) Recv() (*$Request$, error) {\n"
"\tm := new($Request$)\n"
"\tif err := x.Stream.RecvProto(m); err != nil {\n"
"\t\treturn nil, err\n"
"\t}\n"
"\treturn m, nil\n"
"}\n\n");
}
}
void PrintServerMethodDesc(google::protobuf::io::Printer* printer,
const google::protobuf::MethodDescriptor* method,
map<string, string>* vars) {
(*vars)["Method"] = method->name();
printer->Print("\t\t{\n");
printer->Print(*vars,
"\t\t\tMethodName:\t\"$Method$\",\n");
printer->Print(*vars,
"\t\t\tHandler:\t_$Service$_$Method$_Handler,\n");
printer->Print("\t\t},\n");
}
void PrintServerStreamingMethodDesc(google::protobuf::io::Printer* printer,
const google::protobuf::MethodDescriptor* method,
map<string, string>* vars) {
(*vars)["Method"] = method->name();
printer->Print("\t\t{\n");
printer->Print(*vars,
"\t\t\tStreamName:\t\"$Method$\",\n");
printer->Print(*vars,
"\t\t\tHandler:\t_$Service$_$Method$_Handler,\n");
printer->Print("\t\t},\n");
}
void PrintServer(google::protobuf::io::Printer* printer,
const google::protobuf::ServiceDescriptor* service,
map<string, string>* vars) {
(*vars)["Service"] = service->name();
printer->Print(*vars, "type $Service$Server interface {\n");
for (int i = 0; i < service->method_count(); ++i) {
PrintServerMethodDef(printer, service->method(i), vars);
}
printer->Print("}\n\n");
printer->Print(*vars,
"func RegisterService(s *rpc.Server, srv $Service$Server) {\n"
"\ts.RegisterService(&_$Service$_serviceDesc, srv)\n"
"}\n\n");
for (int i = 0; i < service->method_count(); ++i) {
PrintServerHandler(printer, service->method(i), vars);
}
printer->Print(*vars,
"var _$Service$_serviceDesc = rpc.ServiceDesc{\n"
"\tServiceName: \"$Package$$Service$\",\n"
"\tHandlerType: (*$Service$Server)(nil),\n"
"\tMethods: []rpc.MethodDesc{\n");
for (int i = 0; i < service->method_count(); ++i) {
if (NoStreaming(service->method(i))) {
PrintServerMethodDesc(printer, service->method(i), vars);
}
}
printer->Print("\t},\n");
printer->Print("\tStreams: []rpc.StreamDesc{\n");
for (int i = 0; i < service->method_count(); ++i) {
if (!NoStreaming(service->method(i))) {
PrintServerStreamingMethodDesc(printer, service->method(i), vars);
}
}
printer->Print("\t},\n"
"}\n\n");
}
std::string BadToUnderscore(std::string str) {
for (unsigned i = 0; i < str.size(); ++i) {
if (!std::isalnum(str[i])) {
str[i] = '_';
}
}
return str;
}
string GetServices(const google::protobuf::FileDescriptor* file) {
string output;
google::protobuf::io::StringOutputStream output_stream(&output);
google::protobuf::io::Printer printer(&output_stream, '$');
map<string, string> vars;
string package_name = !file->options().go_package().empty()
? file->options().go_package()
: file->package();
vars["PackageName"] = BadToUnderscore(package_name);
printer.Print(vars, "package $PackageName$\n\n");
printer.Print("import (\n");
if (HasClientOnlyStreaming(file)) {
printer.Print("\t\"fmt\"\n"
"\t\"io\"\n");
}
printer.Print(
"\t\"google/net/grpc/go/rpc\"\n"
"\tcontext \"google/third_party/golang/go_net/context/context\"\n"
"\tproto \"google/net/proto2/go/proto\"\n"
")\n\n");
// $Package$ is used to fully qualify method names.
vars["Package"] = file->package();
if (!file->package().empty()) {
vars["Package"].append(".");
}
for (int i = 0; i < file->service_count(); ++i) {
PrintClient(&printer, file->service(0), &vars);
printer.Print("\n");
PrintServer(&printer, file->service(0), &vars);
printer.Print("\n");
}
return output;
}
} // namespace grpc_go_generator

@ -1,83 +0,0 @@
/*
*
* Copyright 2014, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
// Generates go gRPC service interface out of Protobuf IDL.
//
// This is a Proto2 compiler plugin. See net/proto2/compiler/proto/plugin.proto
// and net/proto2/compiler/public/plugin.h for more information on plugins.
#include <fstream>
#include <memory>
using namespace std;
#include "src/compiler/go_generator.h"
#include <google/protobuf/compiler/code_generator.h>
#include <google/protobuf/compiler/plugin.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/descriptor.h>
class GoGrpcGenerator : public google::protobuf::compiler::CodeGenerator {
public:
GoGrpcGenerator() {}
virtual ~GoGrpcGenerator() {}
virtual bool Generate(const google::protobuf::FileDescriptor* file,
const string& parameter,
google::protobuf::compiler::GeneratorContext* context,
string* error) const {
// Get output file name.
string file_name;
if (file->name().size() > 6 &&
file->name().find_last_of(".proto") == file->name().size() - 1) {
file_name = file->name().substr(0, file->name().size() - 6) +
"_grpc.pb.go";
} else {
*error = "Invalid proto file name. Proto file must end with .proto";
return false;
}
std::unique_ptr<google::protobuf::io::ZeroCopyOutputStream> output(
context->Open(file_name));
google::protobuf::io::CodedOutputStream coded_out(output.get());
string code = grpc_go_generator::GetServices(file);
coded_out.WriteRaw(code.data(), code.size());
return true;
}
};
int main(int argc, char* argv[]) {
GoGrpcGenerator generator;
return google::protobuf::compiler::PluginMain(argc, argv, &generator);
}

@ -32,6 +32,7 @@
*/
#include <cctype>
#include <string>
#include <map>
#include <vector>
@ -56,41 +57,40 @@ namespace grpc_ruby_generator {
namespace {
// Prints out the method using the ruby gRPC DSL.
void PrintMethod(const MethodDescriptor* method, const string& package,
Printer* out) {
string input_type = RubyTypeOf(method->input_type()->name(), package);
void PrintMethod(const MethodDescriptor *method, const std::string &package,
Printer *out) {
std::string input_type = RubyTypeOf(method->input_type()->name(), package);
if (method->client_streaming()) {
input_type = "stream(" + input_type + ")";
}
string output_type = RubyTypeOf(method->output_type()->name(), package);
std::string output_type = RubyTypeOf(method->output_type()->name(), package);
if (method->server_streaming()) {
output_type = "stream(" + output_type + ")";
}
map<string, string> method_vars = ListToDict({
"mth.name", method->name(),
"input.type", input_type,
"output.type", output_type,
std::map<std::string, std::string> method_vars = ListToDict({
"mth.name", method->name(), "input.type", input_type, "output.type",
output_type,
});
out->Print(method_vars, "rpc :$mth.name$, $input.type$, $output.type$\n");
}
// Prints out the service using the ruby gRPC DSL.
void PrintService(const ServiceDescriptor* service, const string& package,
Printer* out) {
void PrintService(const ServiceDescriptor *service, const std::string &package,
Printer *out) {
if (service->method_count() == 0) {
return;
}
// Begin the service module
map<string, string> module_vars = ListToDict({
std::map<std::string, std::string> module_vars = ListToDict({
"module.name", CapitalizeFirst(service->name()),
});
out->Print(module_vars, "module $module.name$\n");
out->Indent();
// TODO(temiola): add documentation
string doc = "TODO: add proto service documentation here";
map<string, string> template_vars = ListToDict({
std::string doc = "TODO: add proto service documentation here";
std::map<std::string, std::string> template_vars = ListToDict({
"Documentation", doc,
});
out->Print("\n");
@ -104,9 +104,8 @@ void PrintService(const ServiceDescriptor* service, const string& package,
out->Print("\n");
out->Print("self.marshal_class_method = :encode\n");
out->Print("self.unmarshal_class_method = :decode\n");
map<string, string> pkg_vars = ListToDict({
"service.name", service->name(),
"pkg.name", package,
std::map<std::string, std::string> pkg_vars = ListToDict({
"service.name", service->name(), "pkg.name", package,
});
out->Print(pkg_vars, "self.service_name = '$pkg.name$.$service.name$'\n");
out->Print("\n");
@ -126,8 +125,8 @@ void PrintService(const ServiceDescriptor* service, const string& package,
} // namespace
string GetServices(const FileDescriptor* file) {
string output;
std::string GetServices(const FileDescriptor *file) {
std::string output;
StringOutputStream output_stream(&output);
Printer out(&output_stream, '$');
@ -138,9 +137,8 @@ string GetServices(const FileDescriptor* file) {
}
// Write out a file header.
map<string, string> header_comment_vars = ListToDict({
"file.name", file->name(),
"file.package", file->package(),
std::map<std::string, std::string> header_comment_vars = ListToDict({
"file.name", file->name(), "file.package", file->package(),
});
out.Print("# Generated by the protocol buffer compiler. DO NOT EDIT!\n");
out.Print(header_comment_vars,
@ -151,16 +149,16 @@ string GetServices(const FileDescriptor* file) {
// Write out require statemment to import the separately generated file
// that defines the messages used by the service. This is generated by the
// main ruby plugin.
map<string, string> dep_vars = ListToDict({
std::map<std::string, std::string> dep_vars = ListToDict({
"dep.name", MessagesRequireName(file),
});
out.Print(dep_vars, "require '$dep.name$'\n");
// Write out services within the modules
out.Print("\n");
vector<string> modules = Split(file->package(), '.');
std::vector<std::string> modules = Split(file->package(), '.');
for (size_t i = 0; i < modules.size(); ++i) {
map<string, string> module_vars = ListToDict({
std::map<std::string, std::string> module_vars = ListToDict({
"module.name", CapitalizeFirst(modules[i]),
});
out.Print(module_vars, "module $module.name$\n");

@ -36,8 +36,6 @@
#include <string>
using namespace std;
namespace google {
namespace protobuf {
class FileDescriptor;
@ -46,7 +44,7 @@ class FileDescriptor;
namespace grpc_ruby_generator {
string GetServices(const google::protobuf::FileDescriptor* file);
std::string GetServices(const google::protobuf::FileDescriptor *file);
} // namespace grpc_ruby_generator

@ -41,14 +41,15 @@
namespace grpc_ruby_generator {
inline bool ServicesFilename(const google::protobuf::FileDescriptor* file,
string* file_name_or_error) {
inline bool ServicesFilename(const google::protobuf::FileDescriptor *file,
std::string *file_name_or_error) {
// Get output file name.
static const unsigned proto_suffix_length = 6; // length of ".proto"
if (file->name().size() > proto_suffix_length &&
file->name().find_last_of(".proto") == file->name().size() - 1) {
*file_name_or_error = file->name().substr(
0, file->name().size() - proto_suffix_length) + "_services.rb";
*file_name_or_error =
file->name().substr(0, file->name().size() - proto_suffix_length) +
"_services.rb";
return true;
} else {
*file_name_or_error = "Invalid proto file name: must end with .proto";
@ -56,7 +57,8 @@ inline bool ServicesFilename(const google::protobuf::FileDescriptor* file,
}
}
inline string MessagesRequireName(const google::protobuf::FileDescriptor* file) {
inline std::string MessagesRequireName(
const google::protobuf::FileDescriptor *file) {
return Replace(file->name(), ".proto", "");
}

@ -40,7 +40,6 @@
#include <string>
#include <vector>
using std::initializer_list;
using std::map;
using std::vector;
@ -49,16 +48,18 @@ namespace grpc_ruby_generator {
// Converts an initializer list of the form { key0, value0, key1, value1, ... }
// into a map of key* to value*. Is merely a readability helper for later code.
inline map<string, string> ListToDict(const initializer_list<string>& values) {
inline std::map<std::string, std::string> ListToDict(
const initializer_list<std::string> &values) {
if (values.size() % 2 != 0) {
// MOE: insert std::cerr << "Not every 'key' has a value in `values`." << std::endl;
// MOE: insert std::cerr << "Not every 'key' has a value in `values`."
// << std::endl;
}
map<string, string> value_map;
std::map<std::string, std::string> value_map;
auto value_iter = values.begin();
for (unsigned i = 0; i < values.size()/2; ++i) {
string key = *value_iter;
for (unsigned i = 0; i < values.size() / 2; ++i) {
std::string key = *value_iter;
++value_iter;
string value = *value_iter;
std::string value = *value_iter;
value_map[key] = value;
++value_iter;
}

@ -45,10 +45,10 @@ using std::transform;
namespace grpc_ruby_generator {
// Split splits a string using char into elems.
inline vector<string> &Split(const string &s, char delim,
vector<string>* elems) {
stringstream ss(s);
string item;
inline std::vector<std::string> &Split(const std::string &s, char delim,
std::vector<std::string> *elems) {
std::stringstream ss(s);
std::string item;
while (getline(ss, item, delim)) {
elems->push_back(item);
}
@ -56,16 +56,17 @@ inline vector<string> &Split(const string &s, char delim,
}
// Split splits a string using char, returning the result in a vector.
inline vector<string> Split(const string &s, char delim) {
vector<string> elems;
inline std::vector<std::string> Split(const std::string &s, char delim) {
std::vector<std::string> elems;
Split(s, delim, &elems);
return elems;
}
// Replace replaces from with to in s.
inline string Replace(string s, const string& from, const string& to) {
inline std::string Replace(std::string s, const std::string &from,
const std::string &to) {
size_t start_pos = s.find(from);
if (start_pos == string::npos) {
if (start_pos == std::string::npos) {
return s;
}
s.replace(start_pos, from.length(), to);
@ -73,10 +74,10 @@ inline string Replace(string s, const string& from, const string& to) {
}
// ReplaceAll replaces all instances of search with replace in s.
inline string ReplaceAll(string s, const string& search,
const string& replace) {
inline std::string ReplaceAll(std::string s, const std::string &search,
const std::string &replace) {
size_t pos = 0;
while ((pos = s.find(search, pos)) != string::npos) {
while ((pos = s.find(search, pos)) != std::string::npos) {
s.replace(pos, search.length(), replace);
pos += replace.length();
}
@ -84,9 +85,10 @@ inline string ReplaceAll(string s, const string& search,
}
// ReplacePrefix replaces from with to in s if search is a prefix of s.
inline bool ReplacePrefix(string* s, const string& from, const string& to) {
inline bool ReplacePrefix(std::string *s, const std::string &from,
const std::string &to) {
size_t start_pos = s->find(from);
if (start_pos == string::npos || start_pos != 0) {
if (start_pos == std::string::npos || start_pos != 0) {
return false;
}
s->replace(start_pos, from.length(), to);
@ -94,7 +96,7 @@ inline bool ReplacePrefix(string* s, const string& from, const string& to) {
}
// CapitalizeFirst capitalizes the first char in a string.
inline string CapitalizeFirst(string s) {
inline std::string CapitalizeFirst(std::string s) {
if (s.empty()) {
return s;
}
@ -103,14 +105,15 @@ inline string CapitalizeFirst(string s) {
}
// RubyTypeOf updates a proto type to the required ruby equivalent.
inline string RubyTypeOf(const string& a_type, const string& package) {
string res(a_type);
inline std::string RubyTypeOf(const std::string &a_type,
const std::string &package) {
std::string res(a_type);
ReplacePrefix(&res, package, ""); // remove the leading package if present
ReplacePrefix(&res, ".", ""); // remove the leading . (no package)
if (res.find('.') == string::npos) {
if (res.find('.') == std::string::npos) {
return res;
} else {
vector<string> prefixes_and_type = Split(res, '.');
std::vector<std::string> prefixes_and_type = Split(res, '.');
for (unsigned int i = 0; i < prefixes_and_type.size(); ++i) {
if (i != 0) {
res += "::"; // switch '.' to the ruby module delim

@ -37,6 +37,7 @@
// and net/proto2/compiler/public/plugin.h for more information on plugins.
#include <memory>
#include <string>
#include "src/compiler/ruby_generator.h"
#include "src/compiler/ruby_generator_helpers-inl.h"
@ -51,17 +52,17 @@ class RubyGrpcGenerator : public google::protobuf::compiler::CodeGenerator {
RubyGrpcGenerator() {}
~RubyGrpcGenerator() override {}
bool Generate(const google::protobuf::FileDescriptor* file,
const string& parameter,
google::protobuf::compiler::GeneratorContext* context,
string* error) const override {
string code = grpc_ruby_generator::GetServices(file);
bool Generate(const google::protobuf::FileDescriptor *file,
const std::string &parameter,
google::protobuf::compiler::GeneratorContext *context,
std::string *error) const override {
std::string code = grpc_ruby_generator::GetServices(file);
if (code.size() == 0) {
return true; // don't generate a file if there are no services
}
// Get output file name.
string file_name;
std::string file_name;
if (!grpc_ruby_generator::ServicesFilename(file, &file_name)) {
return false;
}
@ -73,7 +74,7 @@ class RubyGrpcGenerator : public google::protobuf::compiler::CodeGenerator {
}
};
int main(int argc, char* argv[]) {
int main(int argc, char *argv[]) {
RubyGrpcGenerator generator;
return google::protobuf::compiler::PluginMain(argc, argv, &generator);
}

@ -39,7 +39,7 @@
/* helper for filters that need to host child channel stacks... handles
lifetime and upwards propagation cleanly */
const grpc_channel_filter grpc_child_channel_top_filter;
extern const grpc_channel_filter grpc_child_channel_top_filter;
typedef grpc_channel_stack grpc_child_channel;
typedef grpc_call_stack grpc_child_call;

@ -32,6 +32,7 @@
*/
#include "src/core/channel/http_client_filter.h"
#include <string.h>
#include <grpc/support/log.h>
typedef struct call_data { int sent_headers; } call_data;
@ -130,6 +131,19 @@ static void destroy_call_elem(grpc_call_element *elem) {
ignore_unused(channeld);
}
static const char *scheme_from_args(const grpc_channel_args *args) {
int i;
if (args != NULL) {
for (i = 0; i < args->num_args; ++i) {
if (args->args[i].type == GRPC_ARG_STRING &&
strcmp(args->args[i].key, GRPC_ARG_HTTP2_SCHEME) == 0) {
return args->args[i].value.string;
}
}
}
return "http";
}
/* Constructor for channel_data */
static void init_channel_elem(grpc_channel_element *elem,
const grpc_channel_args *args, grpc_mdctx *mdctx,
@ -146,7 +160,8 @@ static void init_channel_elem(grpc_channel_element *elem,
/* initialize members */
channeld->te_trailers = grpc_mdelem_from_strings(mdctx, "te", "trailers");
channeld->method = grpc_mdelem_from_strings(mdctx, ":method", "POST");
channeld->scheme = grpc_mdelem_from_strings(mdctx, ":scheme", "grpc");
channeld->scheme =
grpc_mdelem_from_strings(mdctx, ":scheme", scheme_from_args(args));
channeld->content_type =
grpc_mdelem_from_strings(mdctx, "content-type", "application/grpc");
}

@ -39,4 +39,6 @@
/* Processes metadata on the client side for HTTP2 transports */
extern const grpc_channel_filter grpc_http_client_filter;
#define GRPC_ARG_HTTP2_SCHEME "grpc.http2_scheme"
#endif /* __GRPC_INTERNAL_CHANNEL_HTTP_CLIENT_FILTER_H__ */

@ -100,7 +100,7 @@ void grpc_alarm_list_init(gpr_timespec now) {
}
}
void grpc_alarm_list_shutdown() {
void grpc_alarm_list_shutdown(void) {
int i;
while (run_some_expired_alarms(NULL, gpr_inf_future, NULL, 0))
;
@ -360,7 +360,7 @@ int grpc_alarm_check(gpr_mu *drop_mu, gpr_timespec now, gpr_timespec *next) {
return run_some_expired_alarms(drop_mu, now, next, 1);
}
gpr_timespec grpc_alarm_list_next_timeout() {
gpr_timespec grpc_alarm_list_next_timeout(void) {
gpr_timespec out;
gpr_mu_lock(&g_mu);
out = g_shard_queue[0]->min_deadline;

@ -42,12 +42,12 @@
int grpc_alarm_check(gpr_mu *drop_mu, gpr_timespec now, gpr_timespec *next);
void grpc_alarm_list_init(gpr_timespec now);
void grpc_alarm_list_shutdown();
void grpc_alarm_list_shutdown(void);
gpr_timespec grpc_alarm_list_next_timeout();
gpr_timespec grpc_alarm_list_next_timeout(void);
/* the following must be implemented by each iomgr implementation */
void grpc_kick_poller();
void grpc_kick_poller(void);
#endif /* __GRPC_INTERNAL_IOMGR_ALARM_INTERNAL_H_ */

@ -80,9 +80,9 @@ static void background_callback_executor(void *ignored) {
gpr_event_set(&g_background_callback_executor_done, (void *)1);
}
void grpc_kick_poller() { gpr_cv_broadcast(&g_cv); }
void grpc_kick_poller(void) { gpr_cv_broadcast(&g_cv); }
void grpc_iomgr_init() {
void grpc_iomgr_init(void) {
gpr_thd_id id;
gpr_mu_init(&g_mu);
gpr_cv_init(&g_cv);
@ -93,7 +93,7 @@ void grpc_iomgr_init() {
gpr_thd_new(&id, background_callback_executor, NULL, NULL);
}
void grpc_iomgr_shutdown() {
void grpc_iomgr_shutdown(void) {
delayed_callback *cb;
gpr_timespec shutdown_deadline =
gpr_time_add(gpr_now(), gpr_time_from_seconds(10));
@ -134,13 +134,13 @@ void grpc_iomgr_shutdown() {
gpr_cv_destroy(&g_cv);
}
void grpc_iomgr_ref() {
void grpc_iomgr_ref(void) {
gpr_mu_lock(&g_mu);
++g_refs;
gpr_mu_unlock(&g_mu);
}
void grpc_iomgr_unref() {
void grpc_iomgr_unref(void) {
gpr_mu_lock(&g_mu);
if (0 == --g_refs) {
gpr_cv_signal(&g_cv);

@ -37,8 +37,8 @@
/* gRPC Callback definition */
typedef void (*grpc_iomgr_cb_func)(void *arg, int success);
void grpc_iomgr_init();
void grpc_iomgr_shutdown();
void grpc_iomgr_init(void);
void grpc_iomgr_shutdown(void);
/* This function is called from within a callback or from anywhere else
and causes the invocation of a callback at some point in the future */

@ -42,10 +42,10 @@ int grpc_maybe_call_delayed_callbacks(gpr_mu *drop_mu, int success);
void grpc_iomgr_add_delayed_callback(grpc_iomgr_cb_func cb, void *cb_arg,
int success);
void grpc_iomgr_ref();
void grpc_iomgr_unref();
void grpc_iomgr_ref(void);
void grpc_iomgr_unref(void);
void grpc_iomgr_platform_init();
void grpc_iomgr_platform_shutdown();
void grpc_iomgr_platform_init(void);
void grpc_iomgr_platform_shutdown(void);
#endif /* __GRPC_INTERNAL_IOMGR_IOMGR_INTERNAL_H_ */

@ -33,6 +33,6 @@
#include "src/core/iomgr/iomgr_posix.h"
void grpc_iomgr_platform_init() { grpc_pollset_global_init(); }
void grpc_iomgr_platform_init(void) { grpc_pollset_global_init(); }
void grpc_iomgr_platform_shutdown() { grpc_pollset_global_shutdown(); }
void grpc_iomgr_platform_shutdown(void) { grpc_pollset_global_shutdown(); }

@ -36,7 +36,7 @@
#include "src/core/iomgr/iomgr_internal.h"
void grpc_pollset_global_init();
void grpc_pollset_global_shutdown();
void grpc_pollset_global_init(void);
void grpc_pollset_global_shutdown(void);
#endif /* __GRPC_INTERNAL_IOMGR_IOMGR_POSIX_H_ */

@ -0,0 +1,68 @@
/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef __GRPC_INTERNAL_IOMGR_POLLSET_KICK_H_
#define __GRPC_INTERNAL_IOMGR_POLLSET_KICK_H_
#include <grpc/support/port_platform.h>
/* This is an abstraction around the typical pipe mechanism for waking up a
thread sitting in a poll() style call. */
#ifdef GPR_POSIX_SOCKET
#include "src/core/iomgr/pollset_kick_posix.h"
#else
#error "No pollset kick support on platform"
#endif
void grpc_pollset_kick_global_init(void);
void grpc_pollset_kick_global_destroy(void);
void grpc_pollset_kick_init(grpc_pollset_kick_state *kick_state);
void grpc_pollset_kick_destroy(grpc_pollset_kick_state *kick_state);
/* Must be called before entering poll(). If return value is -1, this consumed
an existing kick. Otherwise the return value is an FD to add to the poll set.
*/
int grpc_pollset_kick_pre_poll(grpc_pollset_kick_state *kick_state);
/* Consume an existing kick. Must be called after poll returns that the fd was
readable, and before calling kick_post_poll. */
void grpc_pollset_kick_consume(grpc_pollset_kick_state *kick_state);
/* Must be called after pre_poll, and after consume if applicable */
void grpc_pollset_kick_post_poll(grpc_pollset_kick_state *kick_state);
void grpc_pollset_kick_kick(grpc_pollset_kick_state *kick_state);
#endif /* __GRPC_INTERNAL_IOMGR_POLLSET_KICK_H_ */

@ -0,0 +1,161 @@
/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "src/core/iomgr/pollset_kick_posix.h"
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include "src/core/iomgr/socket_utils_posix.h"
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
/* This implementation is based on a freelist of pipes. */
typedef struct grpc_kick_pipe_info {
int pipe_read_fd;
int pipe_write_fd;
struct grpc_kick_pipe_info *next;
} grpc_kick_pipe_info;
static grpc_kick_pipe_info *pipe_freelist = NULL;
static gpr_mu pipe_freelist_mu;
static grpc_kick_pipe_info *allocate_pipe() {
grpc_kick_pipe_info *info;
gpr_mu_lock(&pipe_freelist_mu);
if (pipe_freelist != NULL) {
info = pipe_freelist;
pipe_freelist = pipe_freelist->next;
} else {
int pipefd[2];
/* TODO(klempner): Make this nonfatal */
GPR_ASSERT(0 == pipe(pipefd));
GPR_ASSERT(grpc_set_socket_nonblocking(pipefd[0], 1));
GPR_ASSERT(grpc_set_socket_nonblocking(pipefd[1], 1));
info = gpr_malloc(sizeof(*info));
info->pipe_read_fd = pipefd[0];
info->pipe_write_fd = pipefd[1];
info->next = NULL;
}
gpr_mu_unlock(&pipe_freelist_mu);
return info;
}
static void free_pipe(grpc_kick_pipe_info *pipe_info) {
/* TODO(klempner): Start closing pipes if the free list gets too large */
gpr_mu_lock(&pipe_freelist_mu);
pipe_info->next = pipe_freelist;
pipe_freelist = pipe_info;
gpr_mu_unlock(&pipe_freelist_mu);
}
void grpc_pollset_kick_global_init() {
pipe_freelist = NULL;
gpr_mu_init(&pipe_freelist_mu);
}
void grpc_pollset_kick_global_destroy() {
while (pipe_freelist != NULL) {
grpc_kick_pipe_info *current = pipe_freelist;
pipe_freelist = pipe_freelist->next;
close(current->pipe_read_fd);
close(current->pipe_write_fd);
gpr_free(current);
}
gpr_mu_destroy(&pipe_freelist_mu);
}
void grpc_pollset_kick_init(grpc_pollset_kick_state *kick_state) {
gpr_mu_init(&kick_state->mu);
kick_state->kicked = 0;
kick_state->pipe_info = NULL;
}
void grpc_pollset_kick_destroy(grpc_pollset_kick_state *kick_state) {
gpr_mu_destroy(&kick_state->mu);
GPR_ASSERT(kick_state->pipe_info == NULL);
}
int grpc_pollset_kick_pre_poll(grpc_pollset_kick_state *kick_state) {
gpr_mu_lock(&kick_state->mu);
if (kick_state->kicked) {
kick_state->kicked = 0;
gpr_mu_unlock(&kick_state->mu);
return -1;
}
kick_state->pipe_info = allocate_pipe();
gpr_mu_unlock(&kick_state->mu);
return kick_state->pipe_info->pipe_read_fd;
}
void grpc_pollset_kick_consume(grpc_pollset_kick_state *kick_state) {
char buf[128];
int r;
for (;;) {
r = read(kick_state->pipe_info->pipe_read_fd, buf, sizeof(buf));
if (r > 0) continue;
if (r == 0) return;
switch (errno) {
case EAGAIN:
return;
case EINTR:
continue;
default:
gpr_log(GPR_ERROR, "error reading pipe: %s", strerror(errno));
return;
}
}
}
void grpc_pollset_kick_post_poll(grpc_pollset_kick_state *kick_state) {
gpr_mu_lock(&kick_state->mu);
free_pipe(kick_state->pipe_info);
kick_state->pipe_info = NULL;
gpr_mu_unlock(&kick_state->mu);
}
void grpc_pollset_kick_kick(grpc_pollset_kick_state *kick_state) {
gpr_mu_lock(&kick_state->mu);
if (kick_state->pipe_info != NULL) {
char c = 0;
while (write(kick_state->pipe_info->pipe_write_fd, &c, 1) != 1 &&
errno == EINTR)
;
} else {
kick_state->kicked = 1;
}
gpr_mu_unlock(&kick_state->mu);
}

@ -0,0 +1,47 @@
/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef __GRPC_INTERNAL_IOMGR_POLLSET_KICK_POSIX_H_
#define __GRPC_INTERNAL_IOMGR_POLLSET_KICK_POSIX_H_
#include <grpc/support/sync.h>
struct grpc_kick_pipe_info;
typedef struct grpc_pollset_kick_state {
gpr_mu mu;
int kicked;
struct grpc_kick_pipe_info *pipe_info;
} grpc_pollset_kick_state;
#endif /* __GRPC_INTERNAL_IOMGR_POLLSET_KICK_POSIX_H_ */

@ -131,7 +131,11 @@ static int multipoll_with_poll_pollset_maybe_work(
}
nf = 0;
np = 1;
h->pfds[0].fd = grpc_kick_read_fd(pollset);
h->pfds[0].fd = grpc_pollset_kick_pre_poll(&pollset->kick_state);
if (h->pfds[0].fd < 0) {
/* Already kicked */
return 1;
}
h->pfds[0].events = POLLIN;
h->pfds[0].revents = POLLOUT;
for (i = 0; i < h->fd_count; i++) {
@ -173,7 +177,7 @@ static int multipoll_with_poll_pollset_maybe_work(
/* do nothing */
} else {
if (h->pfds[0].revents & POLLIN) {
grpc_kick_drain(pollset);
grpc_pollset_kick_consume(&pollset->kick_state);
}
for (i = 1; i < np; i++) {
if (h->pfds[i].revents & POLLIN) {
@ -184,6 +188,7 @@ static int multipoll_with_poll_pollset_maybe_work(
}
}
}
grpc_pollset_kick_post_poll(&pollset->kick_state);
end_polling(pollset);
gpr_mu_lock(&pollset->mu);

@ -48,18 +48,6 @@
#include <grpc/support/thd.h>
#include <grpc/support/useful.h>
/* kick pipes: we keep a sharded set of pipes to allow breaking from poll.
Ideally this would be 1:1 with pollsets, but we'd like to avoid associating
full kernel objects with each pollset to keep them lightweight, so instead
keep a sharded set and allow associating a pollset with one of the shards.
TODO(ctiller): move this out from this file, and allow an eventfd
implementation on linux */
#define LOG2_KICK_SHARDS 6
#define KICK_SHARDS (1 << LOG2_KICK_SHARDS)
static int g_kick_pipes[KICK_SHARDS][2];
static grpc_pollset g_backup_pollset;
static int g_shutdown_backup_poller;
static gpr_event g_backup_poller_done;
@ -82,65 +70,22 @@ static void backup_poller(void *p) {
gpr_event_set(&g_backup_poller_done, (void *)1);
}
static size_t kick_shard(const grpc_pollset *info) {
size_t x = (size_t)info;
return ((x >> 4) ^ (x >> 9) ^ (x >> 14)) & (KICK_SHARDS - 1);
}
int grpc_kick_read_fd(grpc_pollset *p) {
return g_kick_pipes[kick_shard(p)][0];
}
static int grpc_kick_write_fd(grpc_pollset *p) {
return g_kick_pipes[kick_shard(p)][1];
}
void grpc_pollset_force_kick(grpc_pollset *p) {
char c = 0;
while (write(grpc_kick_write_fd(p), &c, 1) != 1 && errno == EINTR)
;
}
void grpc_pollset_kick(grpc_pollset *p) {
if (!p->counter) return;
grpc_pollset_force_kick(p);
grpc_pollset_kick_kick(&p->kick_state);
}
void grpc_kick_drain(grpc_pollset *p) {
int fd = grpc_kick_read_fd(p);
char buf[128];
int r;
for (;;) {
r = read(fd, buf, sizeof(buf));
if (r > 0) continue;
if (r == 0) return;
switch (errno) {
case EAGAIN:
return;
case EINTR:
continue;
default:
gpr_log(GPR_ERROR, "error reading pipe: %s", strerror(errno));
return;
}
}
}
void grpc_pollset_force_kick(grpc_pollset *p) { grpc_pollset_kick(p); }
/* global state management */
grpc_pollset *grpc_backup_pollset() { return &g_backup_pollset; }
grpc_pollset *grpc_backup_pollset(void) { return &g_backup_pollset; }
void grpc_pollset_global_init() {
int i;
void grpc_pollset_global_init(void) {
gpr_thd_id id;
/* initialize the kick shards */
for (i = 0; i < KICK_SHARDS; i++) {
GPR_ASSERT(0 == pipe(g_kick_pipes[i]));
GPR_ASSERT(grpc_set_socket_nonblocking(g_kick_pipes[i][0], 1));
GPR_ASSERT(grpc_set_socket_nonblocking(g_kick_pipes[i][1], 1));
}
/* Initialize kick fd state */
grpc_pollset_kick_global_init();
/* initialize the backup pollset */
grpc_pollset_init(&g_backup_pollset);
@ -151,9 +96,7 @@ void grpc_pollset_global_init() {
gpr_thd_new(&id, backup_poller, NULL, NULL);
}
void grpc_pollset_global_shutdown() {
int i;
void grpc_pollset_global_shutdown(void) {
/* terminate the backup poller thread */
gpr_mu_lock(&g_backup_pollset.mu);
g_shutdown_backup_poller = 1;
@ -163,11 +106,8 @@ void grpc_pollset_global_shutdown() {
/* destroy the backup pollset */
grpc_pollset_destroy(&g_backup_pollset);
/* destroy the kick shards */
for (i = 0; i < KICK_SHARDS; i++) {
close(g_kick_pipes[i][0]);
close(g_kick_pipes[i][1]);
}
/* destroy the kick pipes */
grpc_pollset_kick_global_destroy();
}
/* main interface */
@ -178,6 +118,7 @@ static void become_unary_pollset(grpc_pollset *pollset, grpc_fd *fd);
void grpc_pollset_init(grpc_pollset *pollset) {
gpr_mu_init(&pollset->mu);
gpr_cv_init(&pollset->cv);
grpc_pollset_kick_init(&pollset->kick_state);
become_empty_pollset(pollset);
}
@ -213,6 +154,7 @@ int grpc_pollset_work(grpc_pollset *pollset, gpr_timespec deadline) {
void grpc_pollset_destroy(grpc_pollset *pollset) {
pollset->vtable->destroy(pollset);
grpc_pollset_kick_destroy(&pollset->kick_state);
gpr_mu_destroy(&pollset->mu);
gpr_cv_destroy(&pollset->cv);
}
@ -290,7 +232,11 @@ static int unary_poll_pollset_maybe_work(grpc_pollset *pollset,
return 1;
}
}
pfd[0].fd = grpc_kick_read_fd(pollset);
pfd[0].fd = grpc_pollset_kick_pre_poll(&pollset->kick_state);
if (pfd[0].fd < 0) {
/* Already kicked */
return 1;
}
pfd[0].events = POLLIN;
pfd[0].revents = 0;
pfd[1].fd = fd->fd;
@ -308,7 +254,7 @@ static int unary_poll_pollset_maybe_work(grpc_pollset *pollset,
/* do nothing */
} else {
if (pfd[0].revents & POLLIN) {
grpc_kick_drain(pollset);
grpc_pollset_kick_consume(&pollset->kick_state);
}
if (pfd[1].revents & POLLIN) {
grpc_fd_become_readable(fd, allow_synchronous_callback);
@ -318,6 +264,8 @@ static int unary_poll_pollset_maybe_work(grpc_pollset *pollset,
}
}
grpc_pollset_kick_post_poll(&pollset->kick_state);
gpr_mu_lock(&pollset->mu);
grpc_fd_end_poll(fd, pollset);
pollset->counter = 0;

@ -36,6 +36,8 @@
#include <grpc/support/sync.h>
#include "src/core/iomgr/pollset_kick.h"
typedef struct grpc_pollset_vtable grpc_pollset_vtable;
/* forward declare only in this file to avoid leaking impl details via
@ -51,6 +53,7 @@ typedef struct grpc_pollset {
const grpc_pollset_vtable *vtable;
gpr_mu mu;
gpr_cv cv;
grpc_pollset_kick_state kick_state;
int counter;
union {
int fd;
@ -86,7 +89,7 @@ void grpc_kick_drain(grpc_pollset *p);
regardless of applications listening to events. Relying on this is slow
however (the backup pollset only listens every 100ms or so) - so it's not
to be relied on. */
grpc_pollset *grpc_backup_pollset();
grpc_pollset *grpc_backup_pollset(void);
/* turn a pollset into a multipoller: platform specific */
void grpc_platform_become_multipoller(grpc_pollset *pollset,

@ -115,7 +115,7 @@ int grpc_set_socket_low_latency(int fd, int low_latency) {
static gpr_once g_probe_ipv6_once = GPR_ONCE_INIT;
static int g_ipv6_loopback_available;
static void probe_ipv6_once() {
static void probe_ipv6_once(void) {
int fd = socket(AF_INET6, SOCK_STREAM, 0);
g_ipv6_loopback_available = 0;
if (fd < 0) {
@ -135,7 +135,7 @@ static void probe_ipv6_once() {
}
}
int grpc_ipv6_loopback_available() {
int grpc_ipv6_loopback_available(void) {
gpr_once_init(&g_probe_ipv6_once, probe_ipv6_once);
return g_ipv6_loopback_available;
}

@ -61,7 +61,7 @@ int grpc_set_socket_low_latency(int fd, int low_latency);
and bind IPv6 sockets, but cannot connect to a getsockname() of [::]:port
without a valid loopback interface. Rather than expose this half-broken
state to library users, we turn off IPv6 sockets. */
int grpc_ipv6_loopback_available();
int grpc_ipv6_loopback_available(void);
/* An enum to keep track of IPv4/IPv6 socket modes.

@ -46,7 +46,7 @@ typedef struct grpc_tcp_server grpc_tcp_server;
typedef void (*grpc_tcp_server_cb)(void *arg, grpc_endpoint *ep);
/* Create a server, initially not bound to any ports */
grpc_tcp_server *grpc_tcp_server_create();
grpc_tcp_server *grpc_tcp_server_create(void);
/* Start listening to bound ports */
void grpc_tcp_server_start(grpc_tcp_server *server, grpc_pollset *pollset,

@ -84,7 +84,7 @@ struct grpc_tcp_server {
size_t port_capacity;
};
grpc_tcp_server *grpc_tcp_server_create() {
grpc_tcp_server *grpc_tcp_server_create(void) {
grpc_tcp_server *s = gpr_malloc(sizeof(grpc_tcp_server));
gpr_mu_init(&s->mu);
gpr_cv_init(&s->cv);
@ -120,7 +120,7 @@ void grpc_tcp_server_destroy(grpc_tcp_server *s) {
}
/* get max listen queue size on linux */
static void init_max_accept_queue_size() {
static void init_max_accept_queue_size(void) {
int n = SOMAXCONN;
char buf[64];
FILE *fp = fopen("/proc/sys/net/core/somaxconn", "r");
@ -147,7 +147,7 @@ static void init_max_accept_queue_size() {
}
}
static int get_max_accept_queue_size() {
static int get_max_accept_queue_size(void) {
gpr_once_init(&s_init_max_accept_queue_size, init_max_accept_queue_size);
return s_max_accept_queue_size;
}

@ -637,8 +637,8 @@ grpc_credentials *grpc_fake_transport_security_credentials_create(void) {
return c;
}
grpc_server_credentials *
grpc_fake_transport_security_server_credentials_create() {
grpc_server_credentials *grpc_fake_transport_security_server_credentials_create(
void) {
grpc_server_credentials *c = gpr_malloc(sizeof(grpc_server_credentials));
memset(c, 0, sizeof(grpc_server_credentials));
c->type = GRPC_CREDENTIALS_TYPE_FAKE_TRANSPORT_SECURITY;

@ -126,8 +126,8 @@ static void on_read(void *user_data, gpr_slice *slices, size_t nslices,
size_t message_size = GPR_SLICE_LENGTH(encrypted);
while (message_size > 0 || keep_looping) {
gpr_uint32 unprotected_buffer_size_written = end - cur;
gpr_uint32 processed_message_size = message_size;
size_t unprotected_buffer_size_written = end - cur;
size_t processed_message_size = message_size;
gpr_mu_lock(&ep->protector_mu);
result = tsi_frame_protector_unprotect(ep->protector, message_bytes,
&processed_message_size, cur,
@ -245,8 +245,8 @@ static grpc_endpoint_write_status endpoint_write(grpc_endpoint *secure_ep,
gpr_uint8 *message_bytes = GPR_SLICE_START_PTR(plain);
size_t message_size = GPR_SLICE_LENGTH(plain);
while (message_size > 0) {
gpr_uint32 protected_buffer_size_to_send = end - cur;
gpr_uint32 processed_message_size = message_size;
size_t protected_buffer_size_to_send = end - cur;
size_t processed_message_size = message_size;
gpr_mu_lock(&ep->protector_mu);
result = tsi_frame_protector_protect(ep->protector, message_bytes,
&processed_message_size, cur,
@ -268,9 +268,9 @@ static grpc_endpoint_write_status endpoint_write(grpc_endpoint *secure_ep,
if (result != TSI_OK) break;
}
if (result == TSI_OK) {
gpr_uint32 still_pending_size;
size_t still_pending_size;
do {
gpr_uint32 protected_buffer_size_to_send = end - cur;
size_t protected_buffer_size_to_send = end - cur;
gpr_mu_lock(&ep->protector_mu);
result = tsi_frame_protector_protect_flush(ep->protector, cur,
&protected_buffer_size_to_send,

@ -131,7 +131,7 @@ static void send_handshake_bytes_to_peer(grpc_secure_transport_setup *s) {
grpc_endpoint_write_status write_status;
do {
uint32_t to_send_size = s->handshake_buffer_size - offset;
size_t to_send_size = s->handshake_buffer_size - offset;
result = tsi_handshaker_get_bytes_to_send_to_peer(
s->handshaker, s->handshake_buffer + offset, &to_send_size);
offset += to_send_size;
@ -174,7 +174,7 @@ static void on_handshake_data_received_from_peer(
void *setup, gpr_slice *slices, size_t nslices,
grpc_endpoint_cb_status error) {
grpc_secure_transport_setup *s = setup;
uint32_t consumed_slice_size = 0;
size_t consumed_slice_size = 0;
tsi_result result = TSI_OK;
size_t i;
size_t num_left_overs;

@ -35,6 +35,8 @@
#include <string.h>
#include "src/core/channel/channel_args.h"
#include "src/core/channel/http_client_filter.h"
#include "src/core/security/credentials.h"
#include "src/core/security/secure_endpoint.h"
#include "src/core/surface/lame_client.h"
@ -100,8 +102,7 @@ grpc_arg grpc_security_context_to_arg(grpc_security_context *ctx) {
return result;
}
grpc_security_context *grpc_security_context_from_arg(
const grpc_arg *arg) {
grpc_security_context *grpc_security_context_from_arg(const grpc_arg *arg) {
if (strcmp(arg->key, GRPC_SECURITY_CONTEXT_ARG)) return NULL;
if (arg->type != GRPC_ARG_POINTER) {
gpr_log(GPR_ERROR, "Invalid type %d for arg %s", arg->type,
@ -140,9 +141,7 @@ static void fake_channel_destroy(grpc_security_context *ctx) {
gpr_free(ctx);
}
static void fake_server_destroy(grpc_security_context *ctx) {
gpr_free(ctx);
}
static void fake_server_destroy(grpc_security_context *ctx) { gpr_free(ctx); }
static grpc_security_status fake_channel_create_handshaker(
grpc_security_context *ctx, tsi_handshaker **handshaker) {
@ -234,8 +233,7 @@ static void ssl_channel_destroy(grpc_security_context *ctx) {
}
static void ssl_server_destroy(grpc_security_context *ctx) {
grpc_ssl_server_security_context *c =
(grpc_ssl_server_security_context *)ctx;
grpc_ssl_server_security_context *c = (grpc_ssl_server_security_context *)ctx;
if (c->handshaker_factory != NULL) {
tsi_ssl_handshaker_factory_destroy(c->handshaker_factory);
}
@ -267,8 +265,7 @@ static grpc_security_status ssl_channel_create_handshaker(
static grpc_security_status ssl_server_create_handshaker(
grpc_security_context *ctx, tsi_handshaker **handshaker) {
grpc_ssl_server_security_context *c =
(grpc_ssl_server_security_context *)ctx;
grpc_ssl_server_security_context *c = (grpc_ssl_server_security_context *)ctx;
return ssl_create_handshaker(c->handshaker_factory, 0, NULL, handshaker);
}
@ -414,12 +411,12 @@ grpc_security_status grpc_ssl_server_security_context_create(
c->base.vtable = &ssl_server_vtable;
result = tsi_create_ssl_server_handshaker_factory(
(const unsigned char **)&config->pem_private_key,
(const gpr_uint32 *)&config->pem_private_key_size,
&config->pem_private_key_size,
(const unsigned char **)&config->pem_cert_chain,
(const gpr_uint32 *)&config->pem_cert_chain_size, 1,
config->pem_root_certs, config->pem_root_certs_size,
GRPC_SSL_CIPHER_SUITES, alpn_protocol_strings,
alpn_protocol_string_lengths, num_alpn_protocols, &c->handshaker_factory);
&config->pem_cert_chain_size, 1, config->pem_root_certs,
config->pem_root_certs_size, GRPC_SSL_CIPHER_SUITES,
alpn_protocol_strings, alpn_protocol_string_lengths, num_alpn_protocols,
&c->handshaker_factory);
if (result != TSI_OK) {
gpr_log(GPR_ERROR, "Handshaker factory creation failed with %s.",
tsi_result_to_string(result));
@ -449,6 +446,8 @@ grpc_channel *grpc_ssl_channel_create(grpc_credentials *ssl_creds,
grpc_security_status status = GRPC_SECURITY_OK;
size_t i = 0;
const char *secure_peer_name = target;
grpc_arg arg;
grpc_channel_args *new_args;
for (i = 0; args && i < args->num_args; i++) {
grpc_arg *arg = &args->args[i];
@ -464,8 +463,13 @@ grpc_channel *grpc_ssl_channel_create(grpc_credentials *ssl_creds,
if (status != GRPC_SECURITY_OK) {
return grpc_lame_client_channel_create();
}
channel = grpc_secure_channel_create_internal(target, args, ctx);
arg.type = GRPC_ARG_STRING;
arg.key = GRPC_ARG_HTTP2_SCHEME;
arg.value.string = "https";
new_args = grpc_channel_args_copy_and_add(args, &arg);
channel = grpc_secure_channel_create_internal(target, new_args, ctx);
grpc_security_context_unref(&ctx->base);
grpc_channel_args_destroy(new_args);
return channel;
}

@ -70,8 +70,7 @@ static void on_accept(void *server, grpc_endpoint *tcp) {
const grpc_channel_args *args = grpc_server_get_channel_args(server);
grpc_security_context *ctx = grpc_find_security_context_in_args(args);
GPR_ASSERT(ctx);
grpc_setup_secure_transport(ctx, tcp, on_secure_transport_setup_done,
server);
grpc_setup_secure_transport(ctx, tcp, on_secure_transport_setup_done, server);
}
/* Note: the following code is the same with server_chttp2.c */

@ -37,13 +37,13 @@
#include "src/core/statistics/census_rpc_stats.h"
#include "src/core/statistics/census_tracing.h"
void census_init() {
void census_init(void) {
gpr_log(GPR_INFO, "Initialize census library.");
census_tracing_init();
census_stats_store_init();
}
void census_shutdown() {
void census_shutdown(void) {
gpr_log(GPR_INFO, "Shutdown census library.");
census_stats_store_shutdown();
census_tracing_shutdown();

@ -49,10 +49,10 @@ typedef struct census_op_id {
typedef struct census_rpc_stats census_rpc_stats;
/* Initializes Census library. No-op if Census is already initialized. */
void census_init();
void census_init(void);
/* Shutdown Census Library. */
void census_shutdown();
void census_shutdown(void);
/* Annotates grpc method name on a census_op_id. The method name has the format
of <full quantified rpc service name>/<rpc function name>. Returns 0 iff
@ -68,7 +68,7 @@ int census_add_method_tag(census_op_id op_id, const char* method_name);
void census_tracing_print(census_op_id op_id, const char* annotation);
/* Starts tracing for an RPC. Returns a locally unique census_op_id */
census_op_id census_tracing_start_op();
census_op_id census_tracing_start_op(void);
/* Ends tracing. Calling this function will invalidate the input op_id. */
void census_tracing_end_op(census_op_id op_id);

@ -368,7 +368,7 @@ static void cl_block_end_read(cl_block* block) {
/* Allocates a new free block (or recycles an available dirty block if log is
configured to discard old records). Returns NULL if out-of-space. */
static cl_block* cl_allocate_block() {
static cl_block* cl_allocate_block(void) {
cl_block* block = cl_block_list_head(&g_log.free_block_list);
if (block != NULL) {
cl_block_list_remove(&g_log.free_block_list, block);
@ -496,7 +496,7 @@ void census_log_initialize(size_t size_in_mb, int discard_old_records) {
g_log.initialized = 1;
}
void census_log_shutdown() {
void census_log_shutdown(void) {
GPR_ASSERT(g_log.initialized);
gpr_mu_destroy(&g_log.lock);
gpr_free_aligned(g_log.core_local_blocks);
@ -551,7 +551,7 @@ void census_log_end_write(void* record, size_t bytes_written) {
cl_block_end_write(cl_get_block(record), bytes_written);
}
void census_log_init_reader() {
void census_log_init_reader(void) {
GPR_ASSERT(g_log.initialized);
gpr_mu_lock(&g_log.lock);
/* If a block is locked for reading unlock it. */
@ -584,7 +584,7 @@ const void* census_log_read_next(size_t* bytes_available) {
return NULL;
}
size_t census_log_remaining_space() {
size_t census_log_remaining_space(void) {
size_t space;
GPR_ASSERT(g_log.initialized);
gpr_mu_lock(&g_log.lock);
@ -598,7 +598,7 @@ size_t census_log_remaining_space() {
return space;
}
int census_log_out_of_space_count() {
int census_log_out_of_space_count(void) {
GPR_ASSERT(g_log.initialized);
return gpr_atm_acq_load(&g_log.out_of_space_count);
}

@ -53,7 +53,7 @@ void census_log_initialize(size_t size_in_mb, int discard_old_records);
- no in progress or future call to any census_log functions
- no incomplete records
*/
void census_log_shutdown();
void census_log_shutdown(void);
/* Allocates and returns a 'size' bytes record and marks it in use. A
subsequent census_log_end_write() marks the record complete. The
@ -74,7 +74,7 @@ void census_log_end_write(void* record, size_t bytes_written);
is read. census_log_init_reader() starts the iteration or aborts the
current iteration.
*/
void census_log_init_reader();
void census_log_init_reader(void);
const void* census_log_read_next(size_t* bytes_available);
/* Returns estimated remaining space across all blocks, in bytes. If log is
@ -82,10 +82,10 @@ const void* census_log_read_next(size_t* bytes_available);
returns space available in empty blocks (partially filled blocks are
treated as full).
*/
size_t census_log_remaining_space();
size_t census_log_remaining_space(void);
/* Returns the number of times gprc_stats_log_start_write() failed due to
out-of-space. */
int census_log_out_of_space_count();
int census_log_out_of_space_count(void);
#endif /* __GRPC_INTERNAL_STATISTICS_LOG_H__ */

@ -59,9 +59,9 @@ static gpr_mu g_mu;
static census_ht* g_client_stats_store = NULL;
static census_ht* g_server_stats_store = NULL;
static void init_mutex() { gpr_mu_init(&g_mu); }
static void init_mutex(void) { gpr_mu_init(&g_mu); }
static void init_mutex_once() {
static void init_mutex_once(void) {
gpr_once_init(&g_stats_store_mu_init, init_mutex);
}
@ -86,7 +86,8 @@ static void delete_key(void* key) { gpr_free(key); }
static const census_ht_option ht_opt = {
CENSUS_HT_POINTER /* key type */, 1999 /* n_of_buckets */,
simple_hash /* hash function */, cmp_str_keys /* key comparator */,
delete_stats /* data deleter */, delete_key /* key deleter */};
delete_stats /* data deleter */, delete_key /* key deleter */
};
static void init_rpc_stats(void* stats) {
memset(stats, 0, sizeof(census_rpc_stats));
@ -115,7 +116,7 @@ static gpr_timespec min_hour_total_intervals[3] = {
static const census_window_stats_stat_info window_stats_settings = {
sizeof(census_rpc_stats), init_rpc_stats, stat_add, stat_add_proportion};
census_rpc_stats* census_rpc_stats_create_empty() {
census_rpc_stats* census_rpc_stats_create_empty(void) {
census_rpc_stats* ret =
(census_rpc_stats*)gpr_malloc(sizeof(census_rpc_stats));
memset(ret, 0, sizeof(census_rpc_stats));
@ -220,7 +221,7 @@ void census_get_server_stats(census_aggregated_rpc_stats* data) {
get_stats(g_server_stats_store, data);
}
void census_stats_store_init() {
void census_stats_store_init(void) {
gpr_log(GPR_INFO, "Initialize census stats store.");
init_mutex_once();
gpr_mu_lock(&g_mu);
@ -233,7 +234,7 @@ void census_stats_store_init() {
gpr_mu_unlock(&g_mu);
}
void census_stats_store_shutdown() {
void census_stats_store_shutdown(void) {
gpr_log(GPR_INFO, "Shutdown census stats store.");
init_mutex_once();
gpr_mu_lock(&g_mu);

@ -53,7 +53,7 @@ struct census_rpc_stats {
};
/* Creates an empty rpc stats object on heap. */
census_rpc_stats* census_rpc_stats_create_empty();
census_rpc_stats* census_rpc_stats_create_empty(void);
typedef struct census_per_method_rpc_stats {
const char* method;
@ -91,8 +91,8 @@ void census_get_server_stats(census_aggregated_rpc_stats* data_map);
DO NOT CALL from outside of grpc code. */
void census_get_client_stats(census_aggregated_rpc_stats* data_map);
void census_stats_store_init();
void census_stats_store_shutdown();
void census_stats_store_init(void);
void census_stats_store_shutdown(void);
#ifdef __cplusplus
}

@ -76,7 +76,8 @@ static void delete_trace_obj(void* obj) { trace_obj_destroy((trace_obj*)obj); }
static const census_ht_option ht_opt = {
CENSUS_HT_UINT64 /* key type*/, 571 /* n_of_buckets */, NULL /* hash */,
NULL /* compare_keys */, delete_trace_obj /* delete data */,
NULL /* delete key */};
NULL /* delete key */
};
static gpr_once g_init_mutex_once = GPR_ONCE_INIT;
static gpr_mu g_mu; /* Guards following two static variables. */
@ -93,11 +94,13 @@ static gpr_uint64 op_id_2_uint64(census_op_id* id) {
return ret;
}
static void init_mutex() { gpr_mu_init(&g_mu); }
static void init_mutex(void) { gpr_mu_init(&g_mu); }
static void init_mutex_once() { gpr_once_init(&g_init_mutex_once, init_mutex); }
static void init_mutex_once(void) {
gpr_once_init(&g_init_mutex_once, init_mutex);
}
census_op_id census_tracing_start_op() {
census_op_id census_tracing_start_op(void) {
gpr_mu_lock(&g_mu);
{
trace_obj* ret = (trace_obj*)gpr_malloc(sizeof(trace_obj));
@ -164,7 +167,7 @@ void census_tracing_end_op(census_op_id op_id) {
gpr_mu_unlock(&g_mu);
}
void census_tracing_init() {
void census_tracing_init(void) {
gpr_log(GPR_INFO, "Initialize census trace store.");
init_mutex_once();
gpr_mu_lock(&g_mu);
@ -177,7 +180,7 @@ void census_tracing_init() {
gpr_mu_unlock(&g_mu);
}
void census_tracing_shutdown() {
void census_tracing_shutdown(void) {
gpr_log(GPR_INFO, "Shutdown census trace store.");
gpr_mu_lock(&g_mu);
if (g_trace_store != NULL) {
@ -189,9 +192,9 @@ void census_tracing_shutdown() {
gpr_mu_unlock(&g_mu);
}
void census_internal_lock_trace_store() { gpr_mu_lock(&g_mu); }
void census_internal_lock_trace_store(void) { gpr_mu_lock(&g_mu); }
void census_internal_unlock_trace_store() { gpr_mu_unlock(&g_mu); }
void census_internal_unlock_trace_store(void) { gpr_mu_unlock(&g_mu); }
trace_obj* census_get_trace_obj_locked(census_op_id op_id) {
if (g_trace_store == NULL) {

@ -38,10 +38,10 @@
typedef struct trace_obj trace_obj;
/* Initializes trace store. This function is thread safe. */
void census_tracing_init();
void census_tracing_init(void);
/* Shutsdown trace store. This function is thread safe. */
void census_tracing_shutdown();
void census_tracing_shutdown(void);
/* Gets trace obj corresponding to the input op_id. Returns NULL if trace store
is not initialized or trace obj is not found. Requires trace store being
@ -50,8 +50,8 @@ trace_obj* census_get_trace_obj_locked(census_op_id op_id);
/* The following two functions acquire and release the trace store global lock.
They are for census internal use only. */
void census_internal_lock_trace_store();
void census_internal_unlock_trace_store();
void census_internal_lock_trace_store(void);
void census_internal_unlock_trace_store(void);
/* Gets method tag name associated with the input trace object. */
const char* census_get_trace_method_name(const trace_obj* trace);

@ -62,6 +62,4 @@ void *gpr_malloc_aligned(size_t size, size_t alignment) {
return (void *)ret;
}
void gpr_free_aligned(void *ptr) {
free(((void **)ptr)[-1]);
}
void gpr_free_aligned(void *ptr) { free(((void **)ptr)[-1]); }

@ -38,12 +38,12 @@
/* Return the number of CPU cores on the current system. Will return 0 if
if information is not available. */
int gpr_cpu_num_cores();
int gpr_cpu_num_cores(void);
/* Return the CPU on which the current thread is executing; N.B. This should
be considered advisory only - it is possible that the thread is switched
to a different CPU at any time. Returns a value in range
[0, gpr_cpu_num_cores() - 1] */
int gpr_cpu_current_cpu();
int gpr_cpu_current_cpu(void);
#endif /* __GRPC_INTERNAL_SUPPORT_CPU_H__ */

@ -75,7 +75,7 @@
#include <grpc/support/log.h>
int gpr_cpu_num_cores() {
int gpr_cpu_num_cores(void) {
static int ncpus = 0;
if (ncpus == 0) {
ncpus = sysconf(_SC_NPROCESSORS_ONLN);
@ -87,7 +87,7 @@ int gpr_cpu_num_cores() {
return ncpus;
}
int gpr_cpu_current_cpu() {
int gpr_cpu_current_cpu(void) {
int cpu = sched_getcpu();
if (cpu < 0) {
gpr_log(GPR_ERROR, "Error determining current CPU: %s\n", strerror(errno));

@ -45,7 +45,7 @@
static __thread char magic_thread_local;
int gpr_cpu_num_cores() {
int gpr_cpu_num_cores(void) {
static int ncpus = 0;
if (ncpus == 0) {
ncpus = sysconf(_SC_NPROCESSORS_ONLN);
@ -63,7 +63,7 @@ static size_t shard_ptr(const void *info) {
return ((x >> 4) ^ (x >> 9) ^ (x >> 14)) % gpr_cpu_num_cores();
}
int gpr_cpu_current_cpu() {
int gpr_cpu_current_cpu(void) {
/* NOTE: there's no way I know to return the actual cpu index portably...
most code that's using this is using it to shard across work queues though,
so here we use thread identity instead to achieve a similar though not

@ -47,7 +47,7 @@
#include <sys/syscall.h>
#include <unistd.h>
static long gettid() { return syscall(__NR_gettid); }
static long gettid(void) { return syscall(__NR_gettid); }
void gpr_log(const char *file, int line, gpr_log_severity severity,
const char *format, ...) {

@ -31,21 +31,26 @@
*
*/
#define _POSIX_SOURCE
#ifndef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 200112L
#endif
#define _GNU_SOURCE
#include <grpc/support/port_platform.h>
#if defined(GPR_POSIX_LOG)
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/time.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
#include <pthread.h>
static long gettid() { return pthread_self(); }
static gpr_intptr gettid(void) { return (gpr_intptr)pthread_self(); }
void gpr_log(const char *file, int line, gpr_log_severity severity,
const char *format, ...) {
@ -55,7 +60,7 @@ void gpr_log(const char *file, int line, gpr_log_severity severity,
int ret;
va_list args;
va_start(args, format);
ret = vsnprintf(buf, format, args);
ret = vsnprintf(buf, sizeof(buf), format, args);
va_end(args);
if (ret < 0) {
message = NULL;
@ -64,7 +69,7 @@ void gpr_log(const char *file, int line, gpr_log_severity severity,
} else {
message = allocated = gpr_malloc(ret + 1);
va_start(args, format);
vsnprintf(message, format, args);
vsnprintf(message, ret, format, args);
va_end(args);
}
gpr_log_message(file, line, severity, message);
@ -91,7 +96,7 @@ void gpr_default_log(gpr_log_func_args *args) {
strcpy(time_buffer, "error:strftime");
}
fprintf(stderr, "%s%s.%09d %7ld %s:%d] %s\n",
fprintf(stderr, "%s%s.%09d %7tu %s:%d] %s\n",
gpr_log_severity_string(args->severity), time_buffer,
(int)(now.tv_nsec), gettid(), display_file, args->line,
args->message);

@ -36,12 +36,13 @@
#ifdef GPR_WIN32
#include <grpc/support/log.h>
#include <grpc/support/alloc.h>
#include <stdio.h>
#include <stdarg.h>
void gpr_log(const char *file, int line, gpr_log_severity severity,
const char *message) {
const char *message = NULL;
const char *format, ...) {
char *message = NULL;
va_list args;
int ret;
@ -53,7 +54,7 @@ void gpr_log(const char *file, int line, gpr_log_severity severity,
message = NULL;
} else {
/* Allocate a new buffer, with space for the NUL terminator. */
strp_buflen = (size_t)ret + 1;
size_t strp_buflen = (size_t)ret + 1;
message = gpr_malloc(strp_buflen);
/* Print to the buffer. */
@ -73,7 +74,7 @@ void gpr_log(const char *file, int line, gpr_log_severity severity,
/* Simple starter implementation */
void gpr_default_log(gpr_log_func_args *args) {
fprintf(stderr, "%s %s:%d: %s\n", gpr_log_severity_string(severity),
fprintf(stderr, "%s %s:%d: %s\n", gpr_log_severity_string(args->severity),
args->file, args->line, args->message);
}

@ -46,8 +46,8 @@
handle aligned reads, do the conversion here */
#define GETBLOCK32(p, i) (p)[(i)]
gpr_uint32 gpr_murmur_hash3(const void* key, size_t len, gpr_uint32 seed) {
const gpr_uint8* data = (const gpr_uint8*)key;
gpr_uint32 gpr_murmur_hash3(const void *key, size_t len, gpr_uint32 seed) {
const gpr_uint8 *data = (const gpr_uint8 *)key;
const int nblocks = len / 4;
int i;
@ -57,8 +57,8 @@ gpr_uint32 gpr_murmur_hash3(const void* key, size_t len, gpr_uint32 seed) {
const gpr_uint32 c1 = 0xcc9e2d51;
const gpr_uint32 c2 = 0x1b873593;
const gpr_uint32* blocks = (const uint32_t*)(data + nblocks * 4);
const uint8_t* tail = (const uint8_t*)(data + nblocks * 4);
const gpr_uint32 *blocks = (const uint32_t *)(data + nblocks * 4);
const uint8_t *tail = (const uint8_t *)(data + nblocks * 4);
/* body */
for (i = -nblocks; i; i++) {

@ -37,7 +37,7 @@
#include <string.h>
gpr_slice gpr_empty_slice() {
gpr_slice gpr_empty_slice(void) {
gpr_slice out;
out.refcount = 0;
out.data.inlined.length = 0;

@ -63,7 +63,7 @@ typedef struct {
char *data;
} hexout;
static hexout hexout_create() {
static hexout hexout_create(void) {
hexout r = {0, 0, NULL};
return r;
}

@ -259,7 +259,7 @@ gpr_int32 gpr_time_to_millis(gpr_timespec t) {
} else if (t.tv_sec <= -2147483) {
/* TODO(ctiller): correct handling here (it's so far in the past do we
care?) */
return -2147483648;
return -2147483647;
} else {
return t.tv_sec * GPR_MS_PER_SEC + t.tv_nsec / GPR_NS_PER_MS;
}

@ -178,6 +178,7 @@ struct grpc_call {
gpr_uint8 received_metadata;
gpr_uint8 have_read;
gpr_uint8 have_alarm;
gpr_uint8 got_status_code;
/* The current outstanding read message tag (only valid if have_read == 1) */
void *read_tag;
void *metadata_tag;
@ -225,6 +226,7 @@ grpc_call *grpc_call_create(grpc_channel *channel,
call->have_write = 0;
call->have_alarm = 0;
call->received_metadata = 0;
call->got_status_code = 0;
call->status_code =
server_transport_data != NULL ? GRPC_STATUS_OK : GRPC_STATUS_UNKNOWN;
call->status_details = NULL;
@ -268,6 +270,19 @@ void grpc_call_destroy(grpc_call *c) {
grpc_call_internal_unref(c);
}
static void maybe_set_status_code(grpc_call *call, gpr_uint32 status) {
if (!call->got_status_code) {
call->status_code = status;
call->got_status_code = 1;
}
}
static void maybe_set_status_details(grpc_call *call, grpc_mdstr *status) {
if (!call->status_details) {
call->status_details = grpc_mdstr_ref(status);
}
}
grpc_call_error grpc_call_cancel(grpc_call *c) {
grpc_call_element *elem;
grpc_call_op op;
@ -284,6 +299,21 @@ grpc_call_error grpc_call_cancel(grpc_call *c) {
return GRPC_CALL_OK;
}
grpc_call_error grpc_call_cancel_with_status(grpc_call *c,
grpc_status_code status,
const char *description) {
grpc_mdstr *details =
description ? grpc_mdstr_from_string(c->metadata_context, description)
: NULL;
gpr_mu_lock(&c->read_mu);
maybe_set_status_code(c, status);
if (details) {
maybe_set_status_details(c, details);
}
gpr_mu_unlock(&c->read_mu);
return grpc_call_cancel(c);
}
void grpc_call_execute_op(grpc_call *call, grpc_call_op *op) {
grpc_call_element *elem;
GPR_ASSERT(op->dir == GRPC_CALL_DOWN);
@ -505,17 +535,6 @@ grpc_call_error grpc_call_server_end_initial_metadata(grpc_call *call,
return GRPC_CALL_OK;
}
grpc_call_error grpc_call_accept(grpc_call *call, grpc_completion_queue *cq,
void *finished_tag, gpr_uint32 flags) {
grpc_call_error err;
err = grpc_call_server_accept(call, cq, finished_tag);
if (err != GRPC_CALL_OK) return err;
err = grpc_call_server_end_initial_metadata(call, flags);
if (err != GRPC_CALL_OK) return err;
return GRPC_CALL_OK;
}
static void done_writes_done(void *user_data, grpc_op_error error) {
grpc_call *call = user_data;
void *tag = call->write_tag;
@ -782,7 +801,7 @@ static gpr_uint32 decode_status(grpc_mdelem *md) {
gpr_uint32 status;
void *user_data = grpc_mdelem_get_user_data(md, destroy_status);
if (user_data) {
status = ((gpr_uint32)(gpr_intptr)user_data) - STATUS_OFFSET;
status = ((gpr_uint32)(gpr_intptr) user_data) - STATUS_OFFSET;
} else {
if (!gpr_parse_bytes_to_uint32(grpc_mdstr_as_c_string(md->value),
GPR_SLICE_LENGTH(md->value->slice),
@ -800,14 +819,11 @@ void grpc_call_recv_metadata(grpc_call_element *elem, grpc_call_op *op) {
grpc_mdelem *md = op->data.metadata;
grpc_mdstr *key = md->key;
if (key == grpc_channel_get_status_string(call->channel)) {
call->status_code = decode_status(md);
maybe_set_status_code(call, decode_status(md));
grpc_mdelem_unref(md);
op->done_cb(op->user_data, GRPC_OP_OK);
} else if (key == grpc_channel_get_message_string(call->channel)) {
if (call->status_details) {
grpc_mdstr_unref(call->status_details);
}
call->status_details = grpc_mdstr_ref(md->value);
maybe_set_status_details(call, md->value);
grpc_mdelem_unref(md);
op->done_cb(op->user_data, GRPC_OP_OK);
} else {
@ -881,8 +897,13 @@ grpc_metadata_buffer *grpc_call_get_metadata_buffer(grpc_call *call) {
static void call_alarm(void *arg, int success) {
grpc_call *call = arg;
if (success) {
if (call->is_client) {
grpc_call_cancel_with_status(call, GRPC_STATUS_DEADLINE_EXCEEDED,
"Deadline Exceeded");
} else {
grpc_call_cancel(call);
}
}
grpc_call_internal_unref(call);
}

@ -106,8 +106,7 @@ static void init_channel_elem(grpc_channel_element *elem,
GPR_ASSERT(!is_last);
}
static void destroy_channel_elem(grpc_channel_element *elem) {
}
static void destroy_channel_elem(grpc_channel_element *elem) {}
const grpc_channel_filter grpc_client_surface_filter = {
call_op, channel_op,

@ -85,7 +85,7 @@ struct grpc_completion_queue {
/* Default do-nothing on_finish function */
static void null_on_finish(void *user_data, grpc_op_error error) {}
grpc_completion_queue *grpc_completion_queue_create() {
grpc_completion_queue *grpc_completion_queue_create(void) {
grpc_completion_queue *cc = gpr_malloc(sizeof(grpc_completion_queue));
memset(cc, 0, sizeof(*cc));
/* Initial ref is dropped by grpc_completion_queue_shutdown */
@ -155,6 +155,13 @@ static void end_op_locked(grpc_completion_queue *cc,
}
}
void grpc_cq_end_server_shutdown(grpc_completion_queue *cc, void *tag) {
gpr_mu_lock(GRPC_POLLSET_MU(&cc->pollset));
add_locked(cc, GRPC_SERVER_SHUTDOWN, tag, NULL, NULL, NULL);
end_op_locked(cc, GRPC_SERVER_SHUTDOWN);
gpr_mu_unlock(GRPC_POLLSET_MU(&cc->pollset));
}
void grpc_cq_end_read(grpc_completion_queue *cc, void *tag, grpc_call *call,
grpc_event_finish_func on_finish, void *user_data,
grpc_byte_buffer *read) {
@ -251,7 +258,7 @@ void grpc_cq_end_new_rpc(grpc_completion_queue *cc, void *tag, grpc_call *call,
}
/* Create a GRPC_QUEUE_SHUTDOWN event without queuing it anywhere */
static event *create_shutdown_event() {
static event *create_shutdown_event(void) {
event *ev = gpr_malloc(sizeof(event));
ev->base.type = GRPC_QUEUE_SHUTDOWN;
ev->base.call = NULL;

@ -97,6 +97,8 @@ void grpc_cq_end_new_rpc(grpc_completion_queue *cc, void *tag, grpc_call *call,
gpr_timespec deadline, size_t metadata_count,
grpc_metadata *metadata_elements);
void grpc_cq_end_server_shutdown(grpc_completion_queue *cc, void *tag);
/* disable polling for some tests */
void grpc_completion_queue_dont_poll_test_only(grpc_completion_queue *cc);

@ -63,6 +63,9 @@ char *grpc_event_string(grpc_event *ev) {
if (ev == NULL) return gpr_strdup("null");
switch (ev->type) {
case GRPC_SERVER_SHUTDOWN:
p += sprintf(p, "SERVER_SHUTDOWN");
break;
case GRPC_QUEUE_SHUTDOWN:
p += sprintf(p, "QUEUE_SHUTDOWN");
break;

@ -35,12 +35,12 @@
#include "src/core/statistics/census_interface.h"
#include "src/core/iomgr/iomgr.h"
void grpc_init() {
void grpc_init(void) {
grpc_iomgr_init();
census_init();
}
void grpc_shutdown() {
void grpc_shutdown(void) {
grpc_iomgr_shutdown();
census_shutdown();
}

@ -81,6 +81,8 @@ struct grpc_server {
size_t tag_cap;
gpr_uint8 shutdown;
gpr_uint8 have_shutdown_tag;
void *shutdown_tag;
call_data *lists[CALL_LIST_COUNT];
channel_data root_channel_data;
@ -375,6 +377,10 @@ static void destroy_call_elem(grpc_call_element *elem) {
for (i = 0; i < CALL_LIST_COUNT; i++) {
call_list_remove(chand->server, elem->call_data, i);
}
if (chand->server->shutdown && chand->server->have_shutdown_tag &&
chand->server->lists[ALL_CALLS] == NULL) {
grpc_cq_end_server_shutdown(chand->server->cq, chand->server->shutdown_tag);
}
gpr_mu_unlock(&chand->server->mu);
server_unref(chand->server);
@ -513,7 +519,8 @@ grpc_transport_setup_result grpc_server_setup_transport(
grpc_channel_get_channel_stack(channel), transport);
}
void grpc_server_shutdown(grpc_server *server) {
void shutdown_internal(grpc_server *server, gpr_uint8 have_shutdown_tag,
void *shutdown_tag) {
listener *l;
void **tags;
size_t ntags;
@ -551,6 +558,14 @@ void grpc_server_shutdown(grpc_server *server) {
server->ntags = 0;
server->shutdown = 1;
server->have_shutdown_tag = have_shutdown_tag;
server->shutdown_tag = shutdown_tag;
if (have_shutdown_tag) {
grpc_cq_begin_op(server->cq, NULL, GRPC_SERVER_SHUTDOWN);
if (server->lists[ALL_CALLS] == NULL) {
grpc_cq_end_server_shutdown(server->cq, shutdown_tag);
}
}
gpr_mu_unlock(&server->mu);
for (i = 0; i < nchannels; i++) {
@ -583,6 +598,14 @@ void grpc_server_shutdown(grpc_server *server) {
}
}
void grpc_server_shutdown(grpc_server *server) {
shutdown_internal(server, 0, NULL);
}
void grpc_server_shutdown_and_notify(grpc_server *server, void *tag) {
shutdown_internal(server, 1, tag);
}
void grpc_server_destroy(grpc_server *server) {
channel_data *c;
gpr_mu_lock(&server->mu);

@ -46,7 +46,7 @@ int grpc_chttp2_is_alpn_version_supported(const char *version, size_t size) {
return 0;
}
size_t grpc_chttp2_num_alpn_versions() {
size_t grpc_chttp2_num_alpn_versions(void) {
return GPR_ARRAY_SIZE(supported_versions);
}

@ -40,7 +40,7 @@
int grpc_chttp2_is_alpn_version_supported(const char *version, size_t size);
/* Returns the number of protocol versions to advertise */
size_t grpc_chttp2_num_alpn_versions();
size_t grpc_chttp2_num_alpn_versions(void);
/* Returns the protocol version at index i (0 <= i <
* grpc_chttp2_num_alpn_versions()) */

@ -161,4 +161,3 @@ grpc_chttp2_parse_error grpc_chttp2_data_parser_parse(
abort();
return GRPC_CHTTP2_CONNECTION_ERROR;
}

@ -102,7 +102,7 @@ gpr_slice grpc_chttp2_settings_create(gpr_uint32 *old, const gpr_uint32 *new,
return output;
}
gpr_slice grpc_chttp2_settings_ack_create() {
gpr_slice grpc_chttp2_settings_ack_create(void) {
gpr_slice output = gpr_slice_malloc(9);
fill_header(GPR_SLICE_START_PTR(output), 0, GRPC_CHTTP2_FLAG_ACK);
return output;

@ -88,7 +88,7 @@ extern const grpc_chttp2_setting_parameters
gpr_slice grpc_chttp2_settings_create(gpr_uint32 *old, const gpr_uint32 *new,
gpr_uint32 force_mask, size_t count);
/* Create an ack settings frame */
gpr_slice grpc_chttp2_settings_ack_create();
gpr_slice grpc_chttp2_settings_ack_create(void);
grpc_chttp2_parse_error grpc_chttp2_settings_parser_begin_frame(
grpc_chttp2_settings_parser *parser, gpr_uint32 length, gpr_uint8 flags,

@ -86,7 +86,7 @@ static unsigned char suffix_mask(unsigned char prefix_len) {
return ~prefix_mask(prefix_len);
}
static void generate_first_byte_lut() {
static void generate_first_byte_lut(void) {
int i, j, n;
const spec *chrspec;
unsigned char suffix;
@ -136,21 +136,21 @@ typedef struct { char included[GRPC_CHTTP2_NUM_HUFFSYMS]; } symset;
typedef struct { int values[16]; } nibblelut;
/* returns a symset that includes all possible symbols */
static symset symset_all() {
static symset symset_all(void) {
symset x;
memset(x.included, 1, sizeof(x.included));
return x;
}
/* returns a symset that includes no symbols */
static symset symset_none() {
static symset symset_none(void) {
symset x;
memset(x.included, 0, sizeof(x.included));
return x;
}
/* returns an empty nibblelut */
static nibblelut nibblelut_empty() {
static nibblelut nibblelut_empty(void) {
nibblelut x;
int i;
for (i = 0; i < 16; i++) {
@ -296,7 +296,7 @@ static void dump_ctbl(const char *name) {
printf("};\n");
}
static void generate_huff_tables() {
static void generate_huff_tables(void) {
int i;
build_dec_tbl(state_index(0, symset_all(), &i), 0, 0, 0, -1, symset_all());
@ -317,7 +317,7 @@ static void generate_huff_tables() {
dump_ctbl("emit_sub_tbl");
}
static void generate_base64_huff_encoder_table() {
static void generate_base64_huff_encoder_table(void) {
static const char alphabet[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
int i;
@ -332,7 +332,7 @@ static void generate_base64_huff_encoder_table() {
printf("};\n");
}
static void generate_base64_inverse_table() {
static void generate_base64_inverse_table(void) {
static const char alphabet[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
unsigned char inverse[256];

@ -66,7 +66,7 @@ void grpc_chttp2_hpack_write_varint_tail(gpr_uint32 tail_value,
} else { \
(tgt)[0] = (prefix_or) | GRPC_CHTTP2_MAX_IN_PREFIX(prefix_bits); \
grpc_chttp2_hpack_write_varint_tail( \
(n)-GRPC_CHTTP2_MAX_IN_PREFIX(prefix_bits), (tgt) + 1, (length)-1); \
(n)-GRPC_CHTTP2_MAX_IN_PREFIX(prefix_bits), (tgt)+1, (length)-1); \
} \
} while (0)

@ -525,7 +525,7 @@ static int init_stream(grpc_transport *gt, grpc_stream *gs,
lock(t);
s->id = 0;
} else {
s->id = (gpr_uint32)(gpr_uintptr)server_data;
s->id = (gpr_uint32)(gpr_uintptr) server_data;
t->incoming_stream = s;
grpc_chttp2_stream_map_add(&t->stream_map, s->id, s);
}
@ -1238,7 +1238,7 @@ static int init_header_frame_parser(transport *t, int is_continuation) {
t->incoming_stream = NULL;
/* if stream is accepted, we set incoming_stream in init_stream */
t->cb->accept_stream(t->cb_user_data, &t->base,
(void *)(gpr_uintptr)t->incoming_stream_id);
(void *)(gpr_uintptr) t->incoming_stream_id);
s = t->incoming_stream;
if (!s) {
gpr_log(GPR_ERROR, "stream not accepted");
@ -1503,8 +1503,9 @@ static int process_read(transport *t, gpr_slice slice) {
"Connect string mismatch: expected '%c' (%d) got '%c' (%d) "
"at byte %d",
CLIENT_CONNECT_STRING[t->deframe_state],
(int)(gpr_uint8)CLIENT_CONNECT_STRING[t->deframe_state], *cur,
(int)*cur, t->deframe_state);
(int)(gpr_uint8) CLIENT_CONNECT_STRING[t->deframe_state],
*cur, (int)*cur, t->deframe_state);
drop_connection(t);
return 0;
}
++cur;
@ -1738,8 +1739,8 @@ static void add_to_pollset(grpc_transport *gt, grpc_pollset *pollset) {
static const grpc_transport_vtable vtable = {
sizeof(stream), init_stream, send_batch, set_allow_window_updates,
add_to_pollset, destroy_stream, abort_stream, goaway, close_transport,
send_ping, destroy_transport};
add_to_pollset, destroy_stream, abort_stream, goaway,
close_transport, send_ping, destroy_transport};
void grpc_create_chttp2_transport(grpc_transport_setup_callback setup,
void *arg,

@ -154,7 +154,7 @@ grpc_mdctx *grpc_mdctx_create_with_seed(gpr_uint32 seed) {
return ctx;
}
grpc_mdctx *grpc_mdctx_create() {
grpc_mdctx *grpc_mdctx_create(void) {
/* This seed is used to prevent remote connections from controlling hash table
* collisions. It needs to be somewhat unpredictable to a remote connection.
*/

@ -82,7 +82,7 @@ struct grpc_mdelem {
};
/* Create/orphan a metadata context */
grpc_mdctx *grpc_mdctx_create();
grpc_mdctx *grpc_mdctx_create(void);
grpc_mdctx *grpc_mdctx_create_with_seed(gpr_uint32 seed);
void grpc_mdctx_orphan(grpc_mdctx *mdctx);

@ -37,6 +37,7 @@
#include <string.h>
#include <grpc/support/log.h>
#include <grpc/support/port_platform.h>
#include "src/core/tsi/transport_security.h"
/* --- Constants. ---*/
@ -52,9 +53,9 @@
the data encoded in little endian on 4 bytes. */
typedef struct {
unsigned char* data;
uint32_t size;
uint32_t allocated_size;
uint32_t offset;
size_t size;
size_t allocated_size;
size_t offset;
int needs_draining;
} tsi_fake_frame;
@ -80,10 +81,9 @@ typedef struct {
tsi_frame_protector base;
tsi_fake_frame protect_frame;
tsi_fake_frame unprotect_frame;
uint32_t max_frame_size;
size_t max_frame_size;
} tsi_fake_frame_protector;
/* --- Utils. ---*/
static const char* tsi_fake_handshake_message_strings[] = {
@ -111,12 +111,12 @@ static tsi_result tsi_fake_handshake_message_from_string(
return TSI_DATA_CORRUPTED;
}
static uint32_t load32_little_endian(const unsigned char* buf) {
return ((uint32_t)(buf[0]) | (uint32_t)(buf[1] << 8) |
(uint32_t)(buf[2] << 16) | (uint32_t)(buf[3] << 24));
static gpr_uint32 load32_little_endian(const unsigned char* buf) {
return ((gpr_uint32)(buf[0]) | (gpr_uint32)(buf[1] << 8) |
(gpr_uint32)(buf[2] << 16) | (gpr_uint32)(buf[3] << 24));
}
static void store32_little_endian(uint32_t value, unsigned char* buf) {
static void store32_little_endian(gpr_uint32 value, unsigned char* buf) {
buf[3] = (unsigned char)(value >> 24) & 0xFF;
buf[2] = (unsigned char)(value >> 16) & 0xFF;
buf[1] = (unsigned char)(value >> 8) & 0xFF;
@ -150,10 +150,10 @@ static int tsi_fake_frame_ensure_size(tsi_fake_frame* frame) {
/* This method should not be called if frame->needs_framing is not 0. */
static tsi_result fill_frame_from_bytes(const unsigned char* incoming_bytes,
uint32_t* incoming_bytes_size,
size_t* incoming_bytes_size,
tsi_fake_frame* frame) {
uint32_t available_size = *incoming_bytes_size;
uint32_t to_read_size = 0;
size_t available_size = *incoming_bytes_size;
size_t to_read_size = 0;
const unsigned char* bytes_cursor = incoming_bytes;
if (frame->needs_draining) return TSI_INTERNAL_ERROR;
@ -198,9 +198,9 @@ static tsi_result fill_frame_from_bytes(const unsigned char* incoming_bytes,
/* This method should not be called if frame->needs_framing is 0. */
static tsi_result drain_frame_to_bytes(unsigned char* outgoing_bytes,
uint32_t* outgoing_bytes_size,
size_t* outgoing_bytes_size,
tsi_fake_frame* frame) {
uint32_t to_write_size = frame->size - frame->offset;
size_t to_write_size = frame->size - frame->offset;
if (!frame->needs_draining) return TSI_INTERNAL_ERROR;
if (*outgoing_bytes_size < to_write_size) {
memcpy(outgoing_bytes, frame->data + frame->offset, *outgoing_bytes_size);
@ -213,7 +213,7 @@ static tsi_result drain_frame_to_bytes(unsigned char* outgoing_bytes,
return TSI_OK;
}
static tsi_result bytes_to_frame(unsigned char* bytes, uint32_t bytes_size,
static tsi_result bytes_to_frame(unsigned char* bytes, size_t bytes_size,
tsi_fake_frame* frame) {
frame->offset = 0;
frame->size = bytes_size + TSI_FAKE_FRAME_HEADER_SIZE;
@ -230,24 +230,25 @@ static void tsi_fake_frame_destruct(tsi_fake_frame* frame) {
/* --- tsi_frame_protector methods implementation. ---*/
static tsi_result fake_protector_protect(
tsi_frame_protector* self, const unsigned char* unprotected_bytes,
uint32_t* unprotected_bytes_size, unsigned char* protected_output_frames,
uint32_t* protected_output_frames_size) {
static tsi_result fake_protector_protect(tsi_frame_protector* self,
const unsigned char* unprotected_bytes,
size_t* unprotected_bytes_size,
unsigned char* protected_output_frames,
size_t* protected_output_frames_size) {
tsi_result result = TSI_OK;
tsi_fake_frame_protector* impl = (tsi_fake_frame_protector*)self;
unsigned char frame_header[TSI_FAKE_FRAME_HEADER_SIZE];
tsi_fake_frame* frame = &impl->protect_frame;
uint32_t saved_output_size = *protected_output_frames_size;
uint32_t drained_size = 0;
uint32_t* num_bytes_written = protected_output_frames_size;
size_t saved_output_size = *protected_output_frames_size;
size_t drained_size = 0;
size_t* num_bytes_written = protected_output_frames_size;
*num_bytes_written = 0;
/* Try to drain first. */
if (frame->needs_draining) {
drained_size = saved_output_size - *num_bytes_written;
result = drain_frame_to_bytes(protected_output_frames,
&drained_size, frame);
result =
drain_frame_to_bytes(protected_output_frames, &drained_size, frame);
*num_bytes_written += drained_size;
protected_output_frames += drained_size;
if (result != TSI_OK) {
@ -263,7 +264,7 @@ static tsi_result fake_protector_protect(
if (frame->needs_draining) return TSI_INTERNAL_ERROR;
if (frame->size == 0) {
/* New frame, create a header. */
uint32_t written_in_frame_size = 0;
size_t written_in_frame_size = 0;
store32_little_endian(impl->max_frame_size, frame_header);
written_in_frame_size = TSI_FAKE_FRAME_HEADER_SIZE;
result = fill_frame_from_bytes(frame_header, &written_in_frame_size, frame);
@ -273,8 +274,8 @@ static tsi_result fake_protector_protect(
return result;
}
}
result = fill_frame_from_bytes(unprotected_bytes, unprotected_bytes_size,
frame);
result =
fill_frame_from_bytes(unprotected_bytes, unprotected_bytes_size, frame);
if (result != TSI_OK) {
if (result == TSI_INCOMPLETE_DATA) result = TSI_OK;
return result;
@ -292,7 +293,7 @@ static tsi_result fake_protector_protect(
static tsi_result fake_protector_protect_flush(
tsi_frame_protector* self, unsigned char* protected_output_frames,
uint32_t* protected_output_frames_size, uint32_t* still_pending_size) {
size_t* protected_output_frames_size, size_t* still_pending_size) {
tsi_result result = TSI_OK;
tsi_fake_frame_protector* impl = (tsi_fake_frame_protector*)self;
tsi_fake_frame* frame = &impl->protect_frame;
@ -312,14 +313,14 @@ static tsi_result fake_protector_protect_flush(
static tsi_result fake_protector_unprotect(
tsi_frame_protector* self, const unsigned char* protected_frames_bytes,
uint32_t* protected_frames_bytes_size, unsigned char* unprotected_bytes,
uint32_t* unprotected_bytes_size) {
size_t* protected_frames_bytes_size, unsigned char* unprotected_bytes,
size_t* unprotected_bytes_size) {
tsi_result result = TSI_OK;
tsi_fake_frame_protector* impl = (tsi_fake_frame_protector*)self;
tsi_fake_frame* frame = &impl->unprotect_frame;
uint32_t saved_output_size = *unprotected_bytes_size;
uint32_t drained_size = 0;
uint32_t* num_bytes_written = unprotected_bytes_size;
size_t saved_output_size = *unprotected_bytes_size;
size_t drained_size = 0;
size_t* num_bytes_written = unprotected_bytes_size;
*num_bytes_written = 0;
/* Try to drain first. */
@ -327,8 +328,7 @@ static tsi_result fake_protector_unprotect(
/* Go past the header if needed. */
if (frame->offset == 0) frame->offset = TSI_FAKE_FRAME_HEADER_SIZE;
drained_size = saved_output_size - *num_bytes_written;
result = drain_frame_to_bytes(unprotected_bytes, &drained_size,
frame);
result = drain_frame_to_bytes(unprotected_bytes, &drained_size, frame);
unprotected_bytes += drained_size;
*num_bytes_written += drained_size;
if (result != TSI_OK) {
@ -375,7 +375,7 @@ static const tsi_frame_protector_vtable frame_protector_vtable = {
/* --- tsi_handshaker methods implementation. ---*/
static tsi_result fake_handshaker_get_bytes_to_send_to_peer(
tsi_handshaker* self, unsigned char* bytes, uint32_t* bytes_size) {
tsi_handshaker* self, unsigned char* bytes, size_t* bytes_size) {
tsi_fake_handshaker* impl = (tsi_fake_handshaker*)self;
tsi_result result = TSI_OK;
if (impl->needs_incoming_message || impl->result == TSI_OK) {
@ -410,7 +410,7 @@ static tsi_result fake_handshaker_get_bytes_to_send_to_peer(
}
static tsi_result fake_handshaker_process_bytes_from_peer(
tsi_handshaker* self, const unsigned char* bytes, uint32_t* bytes_size) {
tsi_handshaker* self, const unsigned char* bytes, size_t* bytes_size) {
tsi_result result = TSI_OK;
tsi_fake_handshaker* impl = (tsi_fake_handshaker*)self;
int expected_msg = impl->next_message_to_send - 1;
@ -465,7 +465,7 @@ static tsi_result fake_handshaker_extract_peer(tsi_handshaker* self,
}
static tsi_result fake_handshaker_create_frame_protector(
tsi_handshaker* self, uint32_t* max_protected_frame_size,
tsi_handshaker* self, size_t* max_protected_frame_size,
tsi_frame_protector** protector) {
*protector = tsi_create_fake_protector(max_protected_frame_size);
if (*protector == NULL) return TSI_OUT_OF_RESOURCES;
@ -504,7 +504,7 @@ tsi_handshaker* tsi_create_fake_handshaker(int is_client) {
}
tsi_frame_protector* tsi_create_fake_protector(
uint32_t* max_protected_frame_size) {
size_t* max_protected_frame_size) {
tsi_fake_frame_protector* impl = calloc(1, sizeof(tsi_fake_frame_protector));
if (impl == NULL) return NULL;
impl->max_frame_size = (max_protected_frame_size == NULL)

@ -50,10 +50,9 @@ extern "C" {
cleartext data for the protector. */
tsi_handshaker* tsi_create_fake_handshaker(int is_client);
/* Creates a protector directly without going through the handshake phase. */
tsi_frame_protector* tsi_create_fake_protector(
uint32_t* max_protected_frame_size);
size_t* max_protected_frame_size);
#ifdef __cplusplus
}

@ -54,7 +54,6 @@
* SSL structure. This is what we would ultimately want though... */
#define TSI_SSL_MAX_PROTECTION_OVERHEAD 100
/* --- Structure definitions. ---*/
struct tsi_ssl_handshaker_factory {
@ -77,9 +76,9 @@ typedef struct {
associated with the contexts at the same index. */
SSL_CTX** ssl_contexts;
tsi_peer* ssl_context_x509_subject_names;
uint32_t ssl_context_count;
size_t ssl_context_count;
unsigned char* alpn_protocol_list;
uint32_t alpn_protocol_list_length;
size_t alpn_protocol_list_length;
} tsi_ssl_server_handshaker_factory;
typedef struct {
@ -96,11 +95,10 @@ typedef struct {
BIO* into_ssl;
BIO* from_ssl;
unsigned char* buffer;
uint32_t buffer_size;
uint32_t buffer_offset;
size_t buffer_size;
size_t buffer_offset;
} tsi_ssl_frame_protector;
/* --- Library Initialization. ---*/
static gpr_once init_openssl_once = GPR_ONCE_INIT;
@ -161,7 +159,7 @@ static void ssl_info_callback(const SSL* ssl, int where, int ret) {
/* Gets the subject CN from an X509 cert. */
static tsi_result ssl_get_x509_common_name(X509* cert, unsigned char** utf8,
uint32_t* utf8_size) {
size_t* utf8_size) {
int common_name_index = -1;
X509_NAME_ENTRY* common_name_entry = NULL;
ASN1_STRING* common_name_asn1 = NULL;
@ -202,7 +200,7 @@ static tsi_result ssl_get_x509_common_name(X509* cert, unsigned char** utf8,
static tsi_result peer_property_from_x509_common_name(
X509* cert, tsi_peer_property* property) {
unsigned char* common_name;
uint32_t common_name_size;
size_t common_name_size;
tsi_result result =
ssl_get_x509_common_name(cert, &common_name, &common_name_size);
if (result != TSI_OK) return result;
@ -268,7 +266,7 @@ static tsi_result peer_property_from_x509_subject_alt_names(
static tsi_result peer_from_x509(X509* cert, int include_certificate_type,
tsi_peer* peer) {
/* TODO(jboeuf): Maybe add more properties. */
uint32_t property_count = include_certificate_type ? 3 : 2;
size_t property_count = include_certificate_type ? 3 : 2;
tsi_result result = tsi_construct_peer(property_count, peer);
if (result != TSI_OK) return result;
do {
@ -299,12 +297,10 @@ static void log_ssl_error_stack(void) {
}
}
/* Performs an SSL_read and handle errors. */
static tsi_result do_ssl_read(SSL* ssl, unsigned char* unprotected_bytes,
uint32_t* unprotected_bytes_size) {
int read_from_ssl = SSL_read(ssl, unprotected_bytes,
*unprotected_bytes_size);
size_t* unprotected_bytes_size) {
int read_from_ssl = SSL_read(ssl, unprotected_bytes, *unprotected_bytes_size);
if (read_from_ssl == 0) {
gpr_log(GPR_ERROR, "SSL_read returned 0 unexpectedly.");
return TSI_INTERNAL_ERROR;
@ -337,7 +333,7 @@ static tsi_result do_ssl_read(SSL* ssl, unsigned char* unprotected_bytes,
/* Performs an SSL_write and handle errors. */
static tsi_result do_ssl_write(SSL* ssl, unsigned char* unprotected_bytes,
uint32_t unprotected_bytes_size) {
size_t unprotected_bytes_size) {
int ssl_write_result =
SSL_write(ssl, unprotected_bytes, unprotected_bytes_size);
if (ssl_write_result < 0) {
@ -358,7 +354,7 @@ static tsi_result do_ssl_write(SSL* ssl, unsigned char* unprotected_bytes,
/* Loads an in-memory PEM certificate chain into the SSL context. */
static tsi_result ssl_ctx_use_certificate_chain(
SSL_CTX* context, const unsigned char* pem_cert_chain,
uint32_t pem_cert_chain_size) {
size_t pem_cert_chain_size) {
tsi_result result = TSI_OK;
X509* certificate = NULL;
BIO* pem = BIO_new_mem_buf((void*)pem_cert_chain, pem_cert_chain_size);
@ -399,7 +395,7 @@ static tsi_result ssl_ctx_use_certificate_chain(
/* Loads an in-memory PEM private key into the SSL context. */
static tsi_result ssl_ctx_use_private_key(SSL_CTX* context,
const unsigned char* pem_key,
uint32_t pem_key_size) {
size_t pem_key_size) {
tsi_result result = TSI_OK;
EVP_PKEY* private_key = NULL;
BIO* pem = BIO_new_mem_buf((void*)pem_key, pem_key_size);
@ -423,10 +419,10 @@ static tsi_result ssl_ctx_use_private_key(SSL_CTX* context,
/* Loads in-memory PEM verification certs into the SSL context and optionally
returns the verification cert names (root_names can be NULL). */
static tsi_result ssl_ctx_load_verification_certs(
SSL_CTX* context, const unsigned char* pem_roots,
uint32_t pem_roots_size, STACK_OF(X509_NAME)** root_names) {
SSL_CTX* context, const unsigned char* pem_roots, size_t pem_roots_size,
STACK_OF(X509_NAME) * *root_names) {
tsi_result result = TSI_OK;
uint32_t num_roots = 0;
size_t num_roots = 0;
X509* root = NULL;
X509_NAME* root_name = NULL;
BIO* pem = BIO_new_mem_buf((void*)pem_roots, pem_roots_size);
@ -485,14 +481,12 @@ static tsi_result ssl_ctx_load_verification_certs(
return result;
}
/* Populates the SSL context with a private key and a cert chain, and sets the
cipher list and the ephemeral ECDH key. */
static tsi_result populate_ssl_context(
SSL_CTX* context, const unsigned char* pem_private_key,
uint32_t pem_private_key_size,
const unsigned char* pem_certificate_chain,
uint32_t pem_certificate_chain_size, const char* cipher_list) {
size_t pem_private_key_size, const unsigned char* pem_certificate_chain,
size_t pem_certificate_chain_size, const char* cipher_list) {
tsi_result result = TSI_OK;
if (pem_certificate_chain != NULL) {
result = ssl_ctx_use_certificate_chain(context, pem_certificate_chain,
@ -528,7 +522,7 @@ static tsi_result populate_ssl_context(
/* Extracts the CN and the SANs from an X509 cert as a peer object. */
static tsi_result extract_x509_subject_names_from_pem_cert(
const unsigned char* pem_cert, uint32_t pem_cert_size, tsi_peer* peer) {
const unsigned char* pem_cert, size_t pem_cert_size, tsi_peer* peer) {
tsi_result result = TSI_OK;
X509* cert = NULL;
BIO* pem = BIO_new_mem_buf((void*)pem_cert, pem_cert_size);
@ -550,7 +544,7 @@ static tsi_result extract_x509_subject_names_from_pem_cert(
static tsi_result build_alpn_protocol_name_list(
const unsigned char** alpn_protocols,
const unsigned char* alpn_protocols_lengths, uint16_t num_alpn_protocols,
unsigned char** protocol_name_list, uint32_t* protocol_name_list_length) {
unsigned char** protocol_name_list, size_t* protocol_name_list_length) {
uint16_t i;
unsigned char* current;
*protocol_name_list = NULL;
@ -579,18 +573,18 @@ static tsi_result build_alpn_protocol_name_list(
/* --- tsi_frame_protector methods implementation. ---*/
static tsi_result ssl_protector_protect(
tsi_frame_protector* self, const unsigned char* unprotected_bytes,
uint32_t* unprotected_bytes_size,
static tsi_result ssl_protector_protect(tsi_frame_protector* self,
const unsigned char* unprotected_bytes,
size_t* unprotected_bytes_size,
unsigned char* protected_output_frames,
uint32_t* protected_output_frames_size) {
size_t* protected_output_frames_size) {
tsi_ssl_frame_protector* impl = (tsi_ssl_frame_protector*)self;
int read_from_ssl;
uint32_t available;
size_t available;
tsi_result result = TSI_OK;
/* First see if we have some pending data in the SSL BIO. */
uint32_t pending_in_ssl = BIO_ctrl_pending(impl->from_ssl);
size_t pending_in_ssl = BIO_ctrl_pending(impl->from_ssl);
if (pending_in_ssl > 0) {
*unprotected_bytes_size = 0;
read_from_ssl = BIO_read(impl->from_ssl, protected_output_frames,
@ -634,8 +628,7 @@ static tsi_result ssl_protector_protect(
static tsi_result ssl_protector_protect_flush(
tsi_frame_protector* self, unsigned char* protected_output_frames,
uint32_t* protected_output_frames_size,
uint32_t* still_pending_size) {
size_t* protected_output_frames_size, size_t* still_pending_size) {
tsi_result result = TSI_OK;
tsi_ssl_frame_protector* impl = (tsi_ssl_frame_protector*)self;
int read_from_ssl = 0;
@ -662,13 +655,12 @@ static tsi_result ssl_protector_protect_flush(
static tsi_result ssl_protector_unprotect(
tsi_frame_protector* self, const unsigned char* protected_frames_bytes,
uint32_t* protected_frames_bytes_size,
unsigned char* unprotected_bytes,
uint32_t* unprotected_bytes_size) {
size_t* protected_frames_bytes_size, unsigned char* unprotected_bytes,
size_t* unprotected_bytes_size) {
tsi_result result = TSI_OK;
int written_into_ssl = 0;
uint32_t output_bytes_size = *unprotected_bytes_size;
uint32_t output_bytes_offset = 0;
size_t output_bytes_size = *unprotected_bytes_size;
size_t output_bytes_offset = 0;
tsi_ssl_frame_protector* impl = (tsi_ssl_frame_protector*)self;
/* First, try to read remaining data from ssl. */
@ -684,8 +676,8 @@ static tsi_result ssl_protector_unprotect(
*unprotected_bytes_size = output_bytes_size - output_bytes_offset;
/* Then, try to write some data to ssl. */
written_into_ssl = BIO_write(
impl->into_ssl, protected_frames_bytes, *protected_frames_bytes_size);
written_into_ssl = BIO_write(impl->into_ssl, protected_frames_bytes,
*protected_frames_bytes_size);
if (written_into_ssl < 0) {
gpr_log(GPR_ERROR, "Sending protected frame to ssl failed with %d",
written_into_ssl);
@ -710,17 +702,15 @@ static void ssl_protector_destroy(tsi_frame_protector* self) {
}
static const tsi_frame_protector_vtable frame_protector_vtable = {
ssl_protector_protect,
ssl_protector_protect_flush,
ssl_protector_unprotect,
ssl_protector_protect, ssl_protector_protect_flush, ssl_protector_unprotect,
ssl_protector_destroy,
};
/* --- tsi_handshaker methods implementation. ---*/
static tsi_result ssl_handshaker_get_bytes_to_send_to_peer(
tsi_handshaker* self, unsigned char* bytes, uint32_t* bytes_size) {
static tsi_result ssl_handshaker_get_bytes_to_send_to_peer(tsi_handshaker* self,
unsigned char* bytes,
size_t* bytes_size) {
tsi_ssl_handshaker* impl = (tsi_ssl_handshaker*)self;
int bytes_read_from_ssl = 0;
if (bytes == NULL || bytes_size == NULL || *bytes_size == 0 ||
@ -737,7 +727,7 @@ static tsi_result ssl_handshaker_get_bytes_to_send_to_peer(
return TSI_OK;
}
}
*bytes_size = (uint32_t)bytes_read_from_ssl;
*bytes_size = (size_t)bytes_read_from_ssl;
return BIO_ctrl_pending(impl->from_ssl) == 0 ? TSI_OK : TSI_INCOMPLETE_DATA;
}
@ -751,8 +741,7 @@ static tsi_result ssl_handshaker_get_result(tsi_handshaker* self) {
}
static tsi_result ssl_handshaker_process_bytes_from_peer(
tsi_handshaker* self, const unsigned char* bytes,
uint32_t* bytes_size) {
tsi_handshaker* self, const unsigned char* bytes, size_t* bytes_size) {
tsi_ssl_handshaker* impl = (tsi_ssl_handshaker*)self;
int bytes_written_into_ssl_size = 0;
if (bytes == NULL || bytes_size == 0 || *bytes_size > INT_MAX) {
@ -809,7 +798,7 @@ static tsi_result ssl_handshaker_extract_peer(tsi_handshaker* self,
}
SSL_get0_alpn_selected(impl->ssl, &alpn_selected, &alpn_selected_len);
if (alpn_selected != NULL) {
uint32_t i;
size_t i;
tsi_peer_property* new_properties =
calloc(1, sizeof(tsi_peer_property) * (peer->property_count + 1));
if (new_properties == NULL) return TSI_OUT_OF_RESOURCES;
@ -831,9 +820,9 @@ static tsi_result ssl_handshaker_extract_peer(tsi_handshaker* self,
}
static tsi_result ssl_handshaker_create_frame_protector(
tsi_handshaker* self, uint32_t* max_output_protected_frame_size,
tsi_handshaker* self, size_t* max_output_protected_frame_size,
tsi_frame_protector** protector) {
uint32_t actual_max_output_protected_frame_size =
size_t actual_max_output_protected_frame_size =
TSI_SSL_MAX_PROTECTED_FRAME_SIZE_UPPER_BOUND;
tsi_ssl_handshaker* impl = (tsi_ssl_handshaker*)self;
tsi_ssl_frame_protector* protector_impl =
@ -891,7 +880,6 @@ static const tsi_handshaker_vtable handshaker_vtable = {
ssl_handshaker_destroy,
};
/* --- tsi_ssl_handshaker_factory common methods. --- */
tsi_result tsi_ssl_handshaker_factory_create_handshaker(
@ -971,7 +959,6 @@ static tsi_result create_tsi_ssl_handshaker(SSL_CTX* ctx, int is_client,
return TSI_OK;
}
/* --- tsi_ssl__client_handshaker_factory methods implementation. --- */
static tsi_result ssl_client_handshaker_factory_create_handshaker(
@ -991,7 +978,6 @@ static void ssl_client_handshaker_factory_destroy(
free(impl);
}
/* --- tsi_ssl_server_handshaker_factory methods implementation. --- */
static tsi_result ssl_server_handshaker_factory_create_handshaker(
@ -1011,7 +997,7 @@ static void ssl_server_handshaker_factory_destroy(
tsi_ssl_handshaker_factory* self) {
tsi_ssl_server_handshaker_factory* impl =
(tsi_ssl_server_handshaker_factory*)self;
uint32_t i;
size_t i;
for (i = 0; i < impl->ssl_context_count; i++) {
if (impl->ssl_contexts[i] != NULL) {
SSL_CTX_free(impl->ssl_contexts[i]);
@ -1026,7 +1012,7 @@ static void ssl_server_handshaker_factory_destroy(
free(impl);
}
static int does_entry_match_name(const char* entry, uint32_t entry_length,
static int does_entry_match_name(const char* entry, size_t entry_length,
const char* name) {
const char* name_subdomain = NULL;
if (entry_length == 0) return 0;
@ -1053,7 +1039,7 @@ static int ssl_server_handshaker_factory_servername_callback(SSL* ssl, int* ap,
void* arg) {
tsi_ssl_server_handshaker_factory* impl =
(tsi_ssl_server_handshaker_factory*)arg;
uint32_t i = 0;
size_t i = 0;
const char* servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
if (servername == NULL || strlen(servername) == 0) {
return SSL_TLSEXT_ERR_NOACK;
@ -1095,13 +1081,12 @@ static int server_handshaker_factory_alpn_callback(
return SSL_TLSEXT_ERR_NOACK;
}
/* --- tsi_ssl_handshaker_factory constructors. --- */
tsi_result tsi_create_ssl_client_handshaker_factory(
const unsigned char* pem_private_key, uint32_t pem_private_key_size,
const unsigned char* pem_cert_chain, uint32_t pem_cert_chain_size,
const unsigned char* pem_root_certs, uint32_t pem_root_certs_size,
const unsigned char* pem_private_key, size_t pem_private_key_size,
const unsigned char* pem_cert_chain, size_t pem_cert_chain_size,
const unsigned char* pem_root_certs, size_t pem_root_certs_size,
const char* cipher_list, const unsigned char** alpn_protocols,
const unsigned char* alpn_protocols_lengths, uint16_t num_alpn_protocols,
tsi_ssl_handshaker_factory** factory) {
@ -1134,7 +1119,7 @@ tsi_result tsi_create_ssl_client_handshaker_factory(
if (num_alpn_protocols != 0) {
unsigned char* alpn_protocol_list = NULL;
uint32_t alpn_protocol_list_length = 0;
size_t alpn_protocol_list_length = 0;
int ssl_failed;
result = build_alpn_protocol_name_list(
alpn_protocols, alpn_protocols_lengths, num_alpn_protocols,
@ -1176,17 +1161,16 @@ tsi_result tsi_create_ssl_client_handshaker_factory(
tsi_result tsi_create_ssl_server_handshaker_factory(
const unsigned char** pem_private_keys,
const uint32_t* pem_private_keys_sizes,
const unsigned char** pem_cert_chains,
const uint32_t* pem_cert_chains_sizes, uint32_t key_cert_pair_count,
const size_t* pem_private_keys_sizes, const unsigned char** pem_cert_chains,
const size_t* pem_cert_chains_sizes, size_t key_cert_pair_count,
const unsigned char* pem_client_root_certs,
uint32_t pem_client_root_certs_size, const char* cipher_list,
size_t pem_client_root_certs_size, const char* cipher_list,
const unsigned char** alpn_protocols,
const unsigned char* alpn_protocols_lengths, uint16_t num_alpn_protocols,
tsi_ssl_handshaker_factory** factory) {
tsi_ssl_server_handshaker_factory* impl = NULL;
tsi_result result = TSI_OK;
uint32_t i = 0;
size_t i = 0;
gpr_once_init(&init_openssl_once, init_openssl);
@ -1274,13 +1258,11 @@ tsi_result tsi_create_ssl_server_handshaker_factory(
/* --- tsi_ssl utils. --- */
int tsi_ssl_peer_matches_name(const tsi_peer* peer, const char* name) {
uint32_t i = 0;
size_t i = 0;
const tsi_peer_property* property = tsi_peer_get_property_by_name(
peer, TSI_X509_SUBJECT_COMMON_NAME_PEER_PROPERTY);
if (property == NULL ||
property->type != TSI_PEER_PROPERTY_TYPE_STRING) {
gpr_log(GPR_ERROR,
"Invalid x509 subject common name property.");
if (property == NULL || property->type != TSI_PEER_PROPERTY_TYPE_STRING) {
gpr_log(GPR_ERROR, "Invalid x509 subject common name property.");
return 0;
}
if (does_entry_match_name(property->value.string.data,
@ -1291,8 +1273,7 @@ int tsi_ssl_peer_matches_name(const tsi_peer* peer, const char* name) {
property = tsi_peer_get_property_by_name(
peer, TSI_X509_SUBJECT_ALTERNATIVE_NAMES_PEER_PROPERTY);
if (property == NULL || property->type != TSI_PEER_PROPERTY_TYPE_LIST) {
gpr_log(GPR_ERROR,
"Invalid x509 subject alternative names property.");
gpr_log(GPR_ERROR, "Invalid x509 subject alternative names property.");
return 0;
}

@ -89,9 +89,9 @@ typedef struct tsi_ssl_handshaker_factory tsi_ssl_handshaker_factory;
- This method returns TSI_OK on success or TSI_INVALID_PARAMETER in the case
where a parameter is invalid. */
tsi_result tsi_create_ssl_client_handshaker_factory(
const unsigned char* pem_private_key, uint32_t pem_private_key_size,
const unsigned char* pem_cert_chain, uint32_t pem_cert_chain_size,
const unsigned char* pem_root_certs, uint32_t pem_root_certs_size,
const unsigned char* pem_private_key, size_t pem_private_key_size,
const unsigned char* pem_cert_chain, size_t pem_cert_chain_size,
const unsigned char* pem_root_certs, size_t pem_root_certs_size,
const char* cipher_suites, const unsigned char** alpn_protocols,
const unsigned char* alpn_protocols_lengths, uint16_t num_alpn_protocols,
tsi_ssl_handshaker_factory** factory);
@ -132,11 +132,10 @@ tsi_result tsi_create_ssl_client_handshaker_factory(
where a parameter is invalid. */
tsi_result tsi_create_ssl_server_handshaker_factory(
const unsigned char** pem_private_keys,
const uint32_t* pem_private_keys_sizes,
const unsigned char** pem_cert_chains,
const uint32_t* pem_cert_chains_sizes, uint32_t key_cert_pair_count,
const size_t* pem_private_keys_sizes, const unsigned char** pem_cert_chains,
const size_t* pem_cert_chains_sizes, size_t key_cert_pair_count,
const unsigned char* pem_client_root_certs,
uint32_t pem_client_root_certs_size, const char* cipher_suites,
size_t pem_client_root_certs_size, const char* cipher_suites,
const unsigned char** alpn_protocols,
const unsigned char* alpn_protocols_lengths, uint16_t num_alpn_protocols,
tsi_ssl_handshaker_factory** factory);
@ -162,7 +161,6 @@ void tsi_ssl_handshaker_factory_destroy(tsi_ssl_handshaker_factory* self);
/* Util that checks that an ssl peer matches a specific name. */
int tsi_ssl_peer_matches_name(const tsi_peer* peer, const char* name);
#ifdef __cplusplus
}
#endif

@ -40,7 +40,7 @@
char* tsi_strdup(const char* src) {
char* dst;
uint32_t len;
size_t len;
if (!src) return NULL;
len = strlen(src) + 1;
dst = malloc(len);
@ -84,17 +84,15 @@ const char* tsi_result_to_string(tsi_result result) {
}
}
/* --- tsi_frame_protector common implementation. ---
Calls specific implementation after state/input validation. */
tsi_result tsi_frame_protector_protect(
tsi_frame_protector* self,
tsi_result tsi_frame_protector_protect(tsi_frame_protector* self,
const unsigned char* unprotected_bytes,
uint32_t* unprotected_bytes_size,
size_t* unprotected_bytes_size,
unsigned char* protected_output_frames,
uint32_t* protected_output_frames_size) {
size_t* protected_output_frames_size) {
if (self == NULL || unprotected_bytes == NULL ||
unprotected_bytes_size == NULL || protected_output_frames == NULL ||
protected_output_frames_size == NULL) {
@ -106,10 +104,8 @@ tsi_result tsi_frame_protector_protect(
}
tsi_result tsi_frame_protector_protect_flush(
tsi_frame_protector* self,
unsigned char* protected_output_frames,
uint32_t* protected_output_frames_size,
uint32_t* still_pending_size) {
tsi_frame_protector* self, unsigned char* protected_output_frames,
size_t* protected_output_frames_size, size_t* still_pending_size) {
if (self == NULL || protected_output_frames == NULL ||
protected_output_frames == NULL || still_pending_size == NULL) {
return TSI_INVALID_ARGUMENT;
@ -120,11 +116,9 @@ tsi_result tsi_frame_protector_protect_flush(
}
tsi_result tsi_frame_protector_unprotect(
tsi_frame_protector* self,
const unsigned char* protected_frames_bytes,
uint32_t* protected_frames_bytes_size,
unsigned char* unprotected_bytes,
uint32_t* unprotected_bytes_size) {
tsi_frame_protector* self, const unsigned char* protected_frames_bytes,
size_t* protected_frames_bytes_size, unsigned char* unprotected_bytes,
size_t* unprotected_bytes_size) {
if (self == NULL || protected_frames_bytes == NULL ||
protected_frames_bytes_size == NULL || unprotected_bytes == NULL ||
unprotected_bytes_size == NULL) {
@ -140,23 +134,21 @@ void tsi_frame_protector_destroy(tsi_frame_protector* self) {
self->vtable->destroy(self);
}
/* --- tsi_handshaker common implementation. ---
Calls specific implementation after state/input validation. */
tsi_result tsi_handshaker_get_bytes_to_send_to_peer(tsi_handshaker* self,
unsigned char* bytes,
uint32_t* bytes_size) {
size_t* bytes_size) {
if (self == NULL) return TSI_INVALID_ARGUMENT;
if (self->frame_protector_created) return TSI_FAILED_PRECONDITION;
return self->vtable->get_bytes_to_send_to_peer(self, bytes, bytes_size);
}
tsi_result tsi_handshaker_process_bytes_from_peer(tsi_handshaker* self,
const unsigned char* bytes,
uint32_t* bytes_size) {
size_t* bytes_size) {
if (self == NULL) return TSI_INVALID_ARGUMENT;
if (self->frame_protector_created) return TSI_FAILED_PRECONDITION;
return self->vtable->process_bytes_from_peer(self, bytes, bytes_size);
@ -179,8 +171,7 @@ tsi_result tsi_handshaker_extract_peer(tsi_handshaker* self, tsi_peer* peer) {
}
tsi_result tsi_handshaker_create_frame_protector(
tsi_handshaker* self,
uint32_t* max_protected_frame_size,
tsi_handshaker* self, size_t* max_protected_frame_size,
tsi_frame_protector** protector) {
tsi_result result;
if (self == NULL || protector == NULL) return TSI_INVALID_ARGUMENT;
@ -201,12 +192,11 @@ void tsi_handshaker_destroy(tsi_handshaker* self) {
self->vtable->destroy(self);
}
/* --- tsi_peer implementation. --- */
const tsi_peer_property* tsi_peer_get_property_by_name(const tsi_peer* self,
const char* name) {
uint32_t i;
size_t i;
if (self == NULL) return NULL;
for (i = 0; i < self->property_count; i++) {
const tsi_peer_property* property = &self->properties[i];
@ -227,10 +217,9 @@ tsi_peer_property tsi_init_peer_property(void) {
return property;
}
static void tsi_peer_destroy_list_property(tsi_peer_property* children,
uint32_t child_count) {
uint32_t i;
size_t child_count) {
size_t i;
for (i = 0; i < child_count; i++) {
tsi_peer_property_destruct(&children[i]);
}
@ -303,7 +292,7 @@ tsi_result tsi_construct_real_peer_property(const char* name, double value,
}
tsi_result tsi_construct_allocated_string_peer_property(
const char* name, uint32_t value_length, tsi_peer_property* property) {
const char* name, size_t value_length, tsi_peer_property* property) {
*property = tsi_init_peer_property();
property->type = TSI_PEER_PROPERTY_TYPE_STRING;
if (name != NULL) {
@ -329,7 +318,7 @@ tsi_result tsi_construct_string_peer_property_from_cstring(
tsi_result tsi_construct_string_peer_property(const char* name,
const char* value,
uint32_t value_length,
size_t value_length,
tsi_peer_property* property) {
tsi_result result = tsi_construct_allocated_string_peer_property(
name, value_length, property);
@ -341,7 +330,7 @@ tsi_result tsi_construct_string_peer_property(const char* name,
}
tsi_result tsi_construct_list_peer_property(const char* name,
uint32_t child_count,
size_t child_count,
tsi_peer_property* property) {
*property = tsi_init_peer_property();
property->type = TSI_PEER_PROPERTY_TYPE_LIST;
@ -361,7 +350,7 @@ tsi_result tsi_construct_list_peer_property(const char* name,
return TSI_OK;
}
tsi_result tsi_construct_peer(uint32_t property_count, tsi_peer* peer) {
tsi_result tsi_construct_peer(size_t property_count, tsi_peer* peer) {
memset(peer, 0, sizeof(tsi_peer));
if (property_count > 0) {
peer->properties = calloc(property_count, sizeof(tsi_peer_property));

@ -45,18 +45,18 @@ extern "C" {
typedef struct {
tsi_result (*protect)(tsi_frame_protector* self,
const unsigned char* unprotected_bytes,
uint32_t* unprotected_bytes_size,
size_t* unprotected_bytes_size,
unsigned char* protected_output_frames,
uint32_t* protected_output_frames_size);
size_t* protected_output_frames_size);
tsi_result (*protect_flush)(tsi_frame_protector* self,
unsigned char* protected_output_frames,
uint32_t* protected_output_frames_size,
uint32_t* still_pending_size);
size_t* protected_output_frames_size,
size_t* still_pending_size);
tsi_result (*unprotect)(tsi_frame_protector* self,
const unsigned char* protected_frames_bytes,
uint32_t* protected_frames_bytes_size,
size_t* protected_frames_bytes_size,
unsigned char* unprotected_bytes,
uint32_t* unprotected_bytes_size);
size_t* unprotected_bytes_size);
void (*destroy)(tsi_frame_protector* self);
} tsi_frame_protector_vtable;
@ -69,14 +69,14 @@ struct tsi_frame_protector {
typedef struct {
tsi_result (*get_bytes_to_send_to_peer)(tsi_handshaker* self,
unsigned char* bytes,
uint32_t* bytes_size);
size_t* bytes_size);
tsi_result (*process_bytes_from_peer)(tsi_handshaker* self,
const unsigned char* bytes,
uint32_t* bytes_size);
size_t* bytes_size);
tsi_result (*get_result)(tsi_handshaker* self);
tsi_result (*extract_peer)(tsi_handshaker* self, tsi_peer* peer);
tsi_result (*create_frame_protector)(tsi_handshaker* self,
uint32_t* max_protected_frame_size,
size_t* max_protected_frame_size,
tsi_frame_protector** protector);
void (*destroy)(tsi_handshaker* self);
} tsi_handshaker_vtable;
@ -87,7 +87,7 @@ struct tsi_handshaker {
};
/* Peer and property construction/destruction functions. */
tsi_result tsi_construct_peer(uint32_t property_count, tsi_peer* peer);
tsi_result tsi_construct_peer(size_t property_count, tsi_peer* peer);
tsi_peer_property tsi_init_peer_property(void);
void tsi_peer_property_destruct(tsi_peer_property* property);
tsi_result tsi_construct_signed_integer_peer_property(
@ -98,14 +98,14 @@ tsi_result tsi_construct_real_peer_property(const char* name, double value,
tsi_peer_property* property);
tsi_result tsi_construct_string_peer_property(const char* name,
const char* value,
uint32_t value_length,
size_t value_length,
tsi_peer_property* property);
tsi_result tsi_construct_allocated_string_peer_property(
const char* name, uint32_t value_length, tsi_peer_property* property);
const char* name, size_t value_length, tsi_peer_property* property);
tsi_result tsi_construct_string_peer_property_from_cstring(
const char* name, const char* value, tsi_peer_property* property);
tsi_result tsi_construct_list_peer_property(const char* name,
uint32_t child_count,
size_t child_count,
tsi_peer_property* property);
/* Utils. */

@ -35,6 +35,7 @@
#define __TRANSPORT_SECURITY_INTERFACE_H_
#include <stdint.h>
#include <stdlib.h>
#ifdef __cplusplus
extern "C" {
@ -60,7 +61,6 @@ typedef enum {
const char* tsi_result_to_string(tsi_result result);
/* --- tsi_frame_protector object ---
This object protects and unprotects buffers once the handshake is done.
@ -90,11 +90,11 @@ typedef struct tsi_frame_protector tsi_frame_protector;
------------------------------------------------------------------------
unsigned char protected_buffer[4096];
uint32_t protected_buffer_size = sizeof(protected_buffer);
size_t protected_buffer_size = sizeof(protected_buffer);
tsi_result result = TSI_OK;
while (message_size > 0) {
uint32_t protected_buffer_size_to_send = protected_buffer_size;
uint32_t processed_message_size = message_size;
size_t protected_buffer_size_to_send = protected_buffer_size;
size_t processed_message_size = message_size;
result = tsi_frame_protector_protect(protector,
message_bytes,
&processed_message_size,
@ -107,7 +107,7 @@ typedef struct tsi_frame_protector tsi_frame_protector;
// Don't forget to flush.
if (message_size == 0) {
uint32_t still_pending_size;
size_t still_pending_size;
do {
protected_buffer_size_to_send = protected_buffer_size;
result = tsi_frame_protector_protect_flush(
@ -121,12 +121,11 @@ typedef struct tsi_frame_protector tsi_frame_protector;
if (result != TSI_OK) HandleError(result);
------------------------------------------------------------------------ */
tsi_result tsi_frame_protector_protect(
tsi_frame_protector* self,
tsi_result tsi_frame_protector_protect(tsi_frame_protector* self,
const unsigned char* unprotected_bytes,
uint32_t* unprotected_bytes_size,
size_t* unprotected_bytes_size,
unsigned char* protected_output_frames,
uint32_t* protected_output_frames_size);
size_t* protected_output_frames_size);
/* Indicates that we need to flush the bytes buffered in the protector and get
the resulting frame.
@ -137,10 +136,8 @@ tsi_result tsi_frame_protector_protect(
- still_pending_bytes is an output parameter indicating the number of bytes
that still need to be flushed from the protector.*/
tsi_result tsi_frame_protector_protect_flush(
tsi_frame_protector* self,
unsigned char* protected_output_frames,
uint32_t* protected_output_frames_size,
uint32_t* still_pending_size);
tsi_frame_protector* self, unsigned char* protected_output_frames,
size_t* protected_output_frames_size, size_t* still_pending_size);
/* Outputs unprotected bytes.
- protected_frames_bytes is an input only parameter and points to the
@ -163,16 +160,13 @@ tsi_result tsi_frame_protector_protect_flush(
needs to be read before new protected data can be processed in which case
protected_frames_size will be set to 0. */
tsi_result tsi_frame_protector_unprotect(
tsi_frame_protector* self,
const unsigned char* protected_frames_bytes,
uint32_t* protected_frames_bytes_size,
unsigned char* unprotected_bytes,
uint32_t* unprotected_bytes_size);
tsi_frame_protector* self, const unsigned char* protected_frames_bytes,
size_t* protected_frames_bytes_size, unsigned char* unprotected_bytes,
size_t* unprotected_bytes_size);
/* Destroys the tsi_frame_protector object. */
void tsi_frame_protector_destroy(tsi_frame_protector* self);
/* --- tsi_peer objects ---
tsi_peer objects are a set of properties. The peer owns the properties. */
@ -201,18 +195,18 @@ typedef struct tsi_peer_property {
double real;
struct {
char* data;
uint32_t length;
size_t length;
} string;
struct {
struct tsi_peer_property* children;
uint32_t child_count;
size_t child_count;
} list;
} value;
} tsi_peer_property;
typedef struct {
tsi_peer_property* properties;
uint32_t property_count;
size_t property_count;
} tsi_peer;
/* Gets the first property with the specified name. Iteration over the
@ -234,12 +228,12 @@ void tsi_peer_destruct(tsi_peer* self);
------------------------------------------------------------------------
tsi_result result = TSI_OK;
unsigned char buf[4096];
uint32_t buf_offset;
uint32_t buf_size;
size_t buf_offset;
size_t buf_size;
while (1) {
// See if we need to send some bytes to the peer.
do {
uint32_t buf_size_to_send = sizeof(buf);
size_t buf_size_to_send = sizeof(buf);
result = tsi_handshaker_get_bytes_to_send_to_peer(handshaker, buf,
&buf_size_to_send);
if (buf_size_to_send > 0) send_bytes_to_peer(buf, buf_size_to_send);
@ -257,7 +251,7 @@ void tsi_peer_destruct(tsi_peer* self);
// Process the bytes from the peer. We have to be careful as these bytes
// may contain non-handshake data (protected data). If this is the case,
// we will exit from the loop with buf_size > 0.
uint32_t consumed_by_handshaker = buf_size;
size_t consumed_by_handshaker = buf_size;
result = tsi_handshaker_process_bytes_from_peer(
handshaker, buf, &consumed_by_handshaker);
buf_size -= consumed_by_handshaker;
@ -307,7 +301,7 @@ typedef struct tsi_handshaker tsi_handshaker;
error in the handshake, another specific error code is returned. */
tsi_result tsi_handshaker_get_bytes_to_send_to_peer(tsi_handshaker* self,
unsigned char* bytes,
uint32_t* bytes_size);
size_t* bytes_size);
/* Processes bytes received from the peer.
- bytes is the buffer containing the data.
@ -320,7 +314,7 @@ tsi_result tsi_handshaker_get_bytes_to_send_to_peer(tsi_handshaker* self,
returned. */
tsi_result tsi_handshaker_process_bytes_from_peer(tsi_handshaker* self,
const unsigned char* bytes,
uint32_t* bytes_size);
size_t* bytes_size);
/* Gets the result of the handshaker.
Returns TSI_OK if the hanshake completed successfully and there has been no
@ -333,7 +327,6 @@ tsi_result tsi_handshaker_get_result(tsi_handshaker* self);
#define tsi_handshaker_is_in_progress(h) \
(tsi_handshaker_get_result((h)) == TSI_HANDSHAKE_IN_PROGRESS)
/* This method may return TSI_FAILED_PRECONDITION if
tsi_handshaker_is_in_progress returns 1, it returns TSI_OK otherwise
assuming the handshaker is not in a fatal error state.
@ -357,8 +350,7 @@ tsi_result tsi_handshaker_extract_peer(tsi_handshaker* self, tsi_peer* peer);
the handshaker is not in a fatal error state.
The caller is responsible for destroying the protector. */
tsi_result tsi_handshaker_create_frame_protector(
tsi_handshaker* self,
uint32_t* max_output_protected_frame_size,
tsi_handshaker* self, size_t* max_output_protected_frame_size,
tsi_frame_protector** protector);
/* This method releases the tsi_handshaker object. After this method is called,

@ -53,7 +53,7 @@
namespace grpc {
Channel::Channel(const grpc::string& target, const ChannelArguments& args)
Channel::Channel(const grpc::string &target, const ChannelArguments &args)
: target_(target) {
grpc_channel_args channel_args;
args.SetChannelArgs(&channel_args);
@ -61,15 +61,15 @@ Channel::Channel(const grpc::string& target, const ChannelArguments& args)
target_.c_str(), channel_args.num_args > 0 ? &channel_args : nullptr);
}
Channel::Channel(const grpc::string& target,
const std::unique_ptr<Credentials>& creds,
const ChannelArguments& args)
Channel::Channel(const grpc::string &target,
const std::unique_ptr<Credentials> &creds,
const ChannelArguments &args)
: target_(args.GetSslTargetNameOverride().empty()
? target
: args.GetSslTargetNameOverride()) {
grpc_channel_args channel_args;
args.SetChannelArgs(&channel_args);
grpc_credentials* c_creds = creds ? creds->GetRawCreds() : nullptr;
grpc_credentials *c_creds = creds ? creds->GetRawCreds() : nullptr;
c_channel_ = grpc_secure_channel_create(
c_creds, target.c_str(),
channel_args.num_args > 0 ? &channel_args : nullptr);
@ -79,9 +79,9 @@ Channel::~Channel() { grpc_channel_destroy(c_channel_); }
namespace {
// Pluck the finished event and set to status when it is not nullptr.
void GetFinalStatus(grpc_completion_queue* cq, void* finished_tag,
Status* status) {
grpc_event* ev =
void GetFinalStatus(grpc_completion_queue *cq, void *finished_tag,
Status *status) {
grpc_event *ev =
grpc_completion_queue_pluck(cq, finished_tag, gpr_inf_future);
if (status) {
StatusCode error_code = static_cast<StatusCode>(ev->data.finished.status);
@ -94,23 +94,23 @@ void GetFinalStatus(grpc_completion_queue* cq, void* finished_tag,
} // namespace
// TODO(yangg) more error handling
Status Channel::StartBlockingRpc(const RpcMethod& method,
ClientContext* context,
const google::protobuf::Message& request,
google::protobuf::Message* result) {
Status Channel::StartBlockingRpc(const RpcMethod &method,
ClientContext *context,
const google::protobuf::Message &request,
google::protobuf::Message *result) {
Status status;
grpc_call* call = grpc_channel_create_call(
grpc_call *call = grpc_channel_create_call(
c_channel_, method.name(), target_.c_str(), context->RawDeadline());
context->set_call(call);
grpc_event* ev;
void* finished_tag = reinterpret_cast<char*>(call);
void* invoke_tag = reinterpret_cast<char*>(call) + 1;
void* metadata_read_tag = reinterpret_cast<char*>(call) + 2;
void* write_tag = reinterpret_cast<char*>(call) + 3;
void* halfclose_tag = reinterpret_cast<char*>(call) + 4;
void* read_tag = reinterpret_cast<char*>(call) + 5;
grpc_event *ev;
void *finished_tag = reinterpret_cast<char *>(call);
void *invoke_tag = reinterpret_cast<char *>(call) + 1;
void *metadata_read_tag = reinterpret_cast<char *>(call) + 2;
void *write_tag = reinterpret_cast<char *>(call) + 3;
void *halfclose_tag = reinterpret_cast<char *>(call) + 4;
void *read_tag = reinterpret_cast<char *>(call) + 5;
grpc_completion_queue* cq = grpc_completion_queue_create();
grpc_completion_queue *cq = grpc_completion_queue_create();
context->set_cq(cq);
// add_metadata from context
//
@ -126,7 +126,7 @@ Status Channel::StartBlockingRpc(const RpcMethod& method,
return status;
}
// write request
grpc_byte_buffer* write_buffer = nullptr;
grpc_byte_buffer *write_buffer = nullptr;
success = SerializeProto(request, &write_buffer);
if (!success) {
grpc_call_cancel(call);
@ -172,14 +172,14 @@ Status Channel::StartBlockingRpc(const RpcMethod& method,
return status;
}
StreamContextInterface* Channel::CreateStream(const RpcMethod& method,
ClientContext* context,
const google::protobuf::Message* request,
google::protobuf::Message* result) {
grpc_call* call = grpc_channel_create_call(
StreamContextInterface *Channel::CreateStream(
const RpcMethod &method, ClientContext *context,
const google::protobuf::Message *request,
google::protobuf::Message *result) {
grpc_call *call = grpc_channel_create_call(
c_channel_, method.name(), target_.c_str(), context->RawDeadline());
context->set_call(call);
grpc_completion_queue* cq = grpc_completion_queue_create();
grpc_completion_queue *cq = grpc_completion_queue_create();
context->set_cq(cq);
return new StreamContext(method, context, request, result);
}

@ -48,24 +48,24 @@ class StreamContextInterface;
class Channel : public ChannelInterface {
public:
Channel(const grpc::string& target, const ChannelArguments& args);
Channel(const grpc::string& target, const std::unique_ptr<Credentials>& creds,
const ChannelArguments& args);
Channel(const grpc::string &target, const ChannelArguments &args);
Channel(const grpc::string &target, const std::unique_ptr<Credentials> &creds,
const ChannelArguments &args);
~Channel() override;
Status StartBlockingRpc(const RpcMethod& method, ClientContext* context,
const google::protobuf::Message& request,
google::protobuf::Message* result) override;
Status StartBlockingRpc(const RpcMethod &method, ClientContext *context,
const google::protobuf::Message &request,
google::protobuf::Message *result) override;
StreamContextInterface* CreateStream(const RpcMethod& method,
ClientContext* context,
const google::protobuf::Message* request,
google::protobuf::Message* result) override;
StreamContextInterface *CreateStream(
const RpcMethod &method, ClientContext *context,
const google::protobuf::Message *request,
google::protobuf::Message *result) override;
private:
const grpc::string target_;
grpc_channel* c_channel_; // owned
grpc_channel *c_channel_; // owned
};
} // namespace grpc

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save