diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..d7df7b3f22b47f9166b429c8913c14b3b60989b1 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,6 @@ +TestService.java.txt binary +TestServiceLite.java.txt binary +TestServiceNano.java.txt binary +TestDeprecatedService.java.txt binary +TestDeprecatedServiceLite.java.txt binary +TestDeprecatedServiceNano.java.txt binary diff --git a/.github/ISSUE_TEMPLATE b/.github/ISSUE_TEMPLATE new file mode 100644 index 0000000000000000000000000000000000000000..431fcb1f09c932edd4ba0bf6fc91077ef539f77c --- /dev/null +++ b/.github/ISSUE_TEMPLATE @@ -0,0 +1,8 @@ +Please answer these questions before submitting your issue. + +### What version of gRPC are you using? + + +### What did you expect to see? + + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..e82cb67ccfc4a7bbc773f82691e0aca4bfdfb783 --- /dev/null +++ b/.gitignore @@ -0,0 +1,35 @@ +# Gradle +build +gradle.properties +.gradle +local.properties +out + +# Maven (examples) +target + +# Bazel +bazel-bin +bazel-examples +bazel-genfiles +bazel-grpc-java +bazel-out +bazel-testlogs + +# IntelliJ IDEA +.idea +*.iml + +# Eclipse +.classpath +.project +.settings +.gitignore +bin + +# OS X +.DS_Store + +# Emacs +*~ +\#*\# diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..e3b59ff022e71229bafe07a5e9e2d811b463b243 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,66 @@ +sudo: false + +language: java + +env: + global: + - GRADLE_OPTS=-Xmx512m + - LDFLAGS=-L/tmp/protobuf/lib + - CXXFLAGS=-I/tmp/protobuf/include + - LD_LIBRARY_PATH=/tmp/protobuf/lib + +before_install: + - rm ~/.m2/settings.xml || true # Avoid repository.apache.org, which has QPS limits and is useless + - mkdir -p $HOME/.gradle/caches && + ln -s /tmp/gradle-caches-modules-2 $HOME/.gradle/caches/modules-2 + - mkdir -p $HOME/.gradle && + ln -s /tmp/gradle-wrapper $HOME/.gradle/wrapper + - buildscripts/make_dependencies.sh # build protoc into /tmp/protobuf + - mkdir -p $HOME/.gradle + - echo "checkstyle.ignoreFailures=false" >> $HOME/.gradle/gradle.properties + - echo "failOnWarnings=true" >> $HOME/.gradle/gradle.properties + - echo "errorProne=true" >> $HOME/.gradle/gradle.properties + +install: + - ./gradlew assemble generateTestProto install + - pushd examples && ./gradlew build && popd + - pushd examples && mvn verify && popd + +before_script: + - test -z "$(git status --porcelain)" || (git status && echo Error Working directory is not clean. Forget to commit generated files? && false) + +script: + - ./gradlew check :grpc-all:jacocoTestReport + +after_success: + # Upload to coveralls once, instead of for each job in the matrix + - if [[ "$TRAVIS_JOB_NUMBER" == *.1 ]]; then ./gradlew :grpc-all:coveralls; fi + - bash <(curl -s https://codecov.io/bash) + +os: + - linux + +jdk: + # net.ltgt.errorprone supports jdk8 and jdk9, but has problems with jdk10 + # For jdk10, we need to switch over to using net.ltgt.errorprone-javacplugin, + # and likely update to the latest com.google.errorprone:error_prone_core. + # We have decided not to make our build.gradle support both plugins, so when + # we finally move off of jdk8 and jdk9 we will need use the javac annotation + # processor based plugin. + - oraclejdk8 # if both jdk 8 and 9 are removed, migrate to net.ltgt.errorprone-javacplugin (see above comment) + - oraclejdk9 # if both jdk 8 and 9 are removed, migrate to net.ltgt.errorprone-javacplugin (see above comment) + - oraclejdk10 + +notifications: + email: false + +cache: + directories: + - /tmp/protobuf-cache + - /tmp/gradle-caches-modules-2 + - /tmp/gradle-wrapper + +before_cache: + # The lock changes based on folder name; normally $HOME/.gradle/caches/modules-2/modules-2.lock + - rm /tmp/gradle-caches-modules-2/gradle-caches-modules-2.lock + - find $HOME/.gradle/wrapper -not -name "*-all.zip" -and -not -name "*-bin.zip" -delete diff --git a/AUTHORS b/AUTHORS new file mode 100644 index 0000000000000000000000000000000000000000..e491a9e7f7831fbb6134d23144dd6c3e66891773 --- /dev/null +++ b/AUTHORS @@ -0,0 +1 @@ +Google Inc. diff --git a/BUILD.bazel b/BUILD.bazel new file mode 100644 index 0000000000000000000000000000000000000000..e4175b0ecee1bbc183a14e9eb558d7f335dcf90b --- /dev/null +++ b/BUILD.bazel @@ -0,0 +1,26 @@ +# Copyright 2017 The gRPC Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +load(":java_grpc_library.bzl", "java_grpc_library") + +java_proto_library( + name = "api_proto_java", + deps = ["@com_google_protobuf//:api_proto"], +) + +java_grpc_library( + name = "java_grpc_library__external_repo_test", + srcs = ["@com_google_protobuf//:api_proto"], + deps = [":api_proto_java"], +) diff --git a/COMPILING.md b/COMPILING.md new file mode 100644 index 0000000000000000000000000000000000000000..f75023cde27a69727c6ffdc289897003b248f2cf --- /dev/null +++ b/COMPILING.md @@ -0,0 +1,117 @@ +Building gRPC-Java +================== + +Building is only necessary if you are making changes to gRPC-Java. + +Building requires JDK 8, as our tests use TLS. + +grpc-java has a C++ code generation plugin for protoc. Since many Java +developers don't have C compilers installed and don't need to modify the +codegen, the build can skip it. To skip, create the file +`/gradle.properties` and add `skipCodegen=true`. + +Then, to build, run: +``` +$ ./gradlew build +``` + +To install the artifacts to your Maven local repository for use in your own +project, run: +``` +$ ./gradlew install +``` + +### Notes for IntelliJ +Building in IntelliJ works best when you import the project as a Gradle project and delegate IDE +build/run actions to Gradle. + +You can find this setting at: +```Settings -> Build, Execution, Deployment + -> Build Tools -> Gradle -> Runner + -> Delegate IDE build/run actions to gradle. +``` + +How to Build Code Generation Plugin +----------------------------------- +This section is only necessary if you are making changes to the code +generation. Most users only need to use `skipCodegen=true` as discussed above. + +### Build Protobuf +The codegen plugin is C++ code and requires protobuf 3.0.0 or later. + +For Linux, Mac and MinGW: +``` +$ git clone https://github.com/google/protobuf.git +$ cd protobuf +$ git checkout v3.5.1 +$ ./autogen.sh +$ ./configure +$ make +$ make check +$ sudo make install +``` + +If you are comfortable with C++ compilation and autotools, you can specify a +``--prefix`` for Protobuf and use ``-I`` in ``CXXFLAGS``, ``-L`` in +``LDFLAGS``, ``LD_LIBRARY_PATH``, and ``PATH`` to reference it. The +environment variables will be used when building grpc-java. + +Protobuf installs to ``/usr/local`` by default. + +For Visual C++, please refer to the [Protobuf README](https://github.com/google/protobuf/blob/master/cmake/README.md) +for how to compile Protobuf. gRPC-java assumes a Release build. + +#### Linux and MinGW +If ``/usr/local/lib`` is not in your library search path, you can add it by running: +``` +$ sudo sh -c 'echo /usr/local/lib >> /etc/ld.so.conf' +$ sudo ldconfig +``` + +#### Mac +Some versions of Mac OS X (e.g., 10.10) doesn't have ``/usr/local`` in the +default search paths for header files and libraries. It will fail the build of +the codegen. To work around this, you will need to set environment variables: +``` +$ export CXXFLAGS="-I/usr/local/include" LDFLAGS="-L/usr/local/lib" +``` + +### Notes for Visual C++ + +When building on Windows and VC++, you need to specify project properties for +Gradle to find protobuf: +``` +.\gradlew install ^ + -PvcProtobufInclude=C:\path\to\protobuf-3.5.1\src ^ + -PvcProtobufLibs=C:\path\to\protobuf-3.5.1\vsprojects\Release ^ + -PtargetArch=x86_32 +``` + +Since specifying those properties every build is bothersome, you can instead +create ``\gradle.properties`` with contents like: +``` +vcProtobufInclude=C:\\path\\to\\protobuf-3.5.1\\src +vcProtobufLibs=C:\\path\\to\\protobuf-3.5.1\\vsprojects\\Release +targetArch=x86_32 +``` + +By default, the build script will build the codegen for the same architecture as +the Java runtime installed on your system. If you are using 64-bit JVM, the +codegen will be compiled for 64-bit. Since Protobuf is only built for 32-bit by +default, the `targetArch=x86_32` is necessary. + +### Notes for MinGW on Windows +If you have both MinGW and VC++ installed on Windows, VC++ will be used by +default. To override this default and use MinGW, add ``-PvcDisable=true`` +to your Gradle command line or add ``vcDisable=true`` to your +``\gradle.properties``. + +### Notes for Unsupported Operating Systems +The build script pulls pre-compiled ``protoc`` from Maven Central by default. +We have built ``protoc`` binaries for popular systems, but they may not work +for your system. If ``protoc`` cannot be downloaded or would not run, you can +use the one that has been built by your own, by adding this property to +``/gradle.properties``: +``` +protoc=/path/to/protoc +``` diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..9027b8f2c6fcaac5cf197627ae35ce81ded68dc6 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,83 @@ +# How to contribute + +We definitely welcome your patches and contributions to gRPC! + +If you are new to github, please start by reading [Pull Request howto](https://help.github.com/articles/about-pull-requests/) + +## Legal requirements + +In order to protect both you and ourselves, you will need to sign the +[Contributor License Agreement](https://identity.linuxfoundation.org/projects/cncf). + +## Compiling + +See [COMPILING.md](COMPILING.md). Specifically, you'll generally want to set +`skipCodegen=true` so you don't need to deal with the C++ compilation. + +## Code style + +We follow the [Google Java Style +Guide](https://google-styleguide.googlecode.com/svn/trunk/javaguide.html). Our +build automatically will provide warnings for style issues. +[Eclipse](https://raw.githubusercontent.com/google/styleguide/gh-pages/eclipse-java-google-style.xml) +and +[IntelliJ](https://raw.githubusercontent.com/google/styleguide/gh-pages/intellij-java-google-style.xml) +style configurations are commonly useful. For IntelliJ 14, copy the style to +`~/.IdeaIC14/config/codestyles/`, start IntelliJ, go to File > Settings > Code +Style, and set the Scheme to `GoogleStyle`. + +## Maintaining clean commit history + +We have few conventions for keeping history clean and making code reviews easier +for reviewers: + +* First line of commit messages should be in format of + + `package-name: summary of change` + + where the summary finishes the sentence: `This commit improves gRPC to ____________.` + + for example: + + `core,netty,interop-testing: add capacitive duractance to turbo encabulators` + +* Every time you receive a feedback on your pull request, push changes that + address it as a separate one or multiple commits with a descriptive commit + message (try avoid using vauge `addressed pr feedback` type of messages). + + Project maintainers are obligated to squash those commits into one when + merging. + +## Running tests + +### Jetty ALPN setup for IntelliJ + +The tests in interop-testing project require jetty-alpn agent running in the background +otherwise they'll fail. Here are instructions on how to setup IntellJ IDEA to enable running +those tests in IDE: + +* Settings -> Build Tools -> Gradle -> Runner -> select Gradle Test Runner +* View -> Tool Windows -> Gradle -> Edit Run Configuration -> Defaults -> JUnit -> Before lauch -> + -> Run Gradle task, enter the task in the build.gradle that sets the javaagent. + +Step 1 must be taken, otherwise by the default JUnit Test Runner running a single test in IDE will trigger all the tests. + +## Guidelines for Pull Requests +How to get your contributions merged smoothly and quickly. + +- Create **small PRs** that are narrowly focused on **addressing a single concern**. We often times receive PRs that are trying to fix several things at a time, but only one fix is considered acceptable, nothing gets merged and both author's & review's time is wasted. Create more PRs to address different concerns and everyone will be happy. + +- For speculative changes, consider opening an issue and discussing it first. If you are suggesting a behavioral or API change, consider starting with a [gRFC proposal](https://github.com/grpc/proposal). + +- Provide a good **PR description** as a record of **what** change is being made and **why** it was made. Link to a github issue if it exists. + +- Don't fix code style and formatting unless you are already changing that line to address an issue. PRs with irrelevant changes won't be merged. If you do want to fix formatting or style, do that in a separate PR. + +- Unless your PR is trivial, you should expect there will be reviewer comments that you'll need to address before merging. We expect you to be reasonably responsive to those comments, otherwise the PR will be closed after 2-3 weeks of inactivity. + +- Maintain **clean commit history** and use **meaningful commit messages**. See [maintaining clean commit history](#maintaining-clean-commit-history) for details. + +- Keep your PR up to date with upstream/master (if there are merge conflicts, we can't really merge your change). + +- **All tests need to be passing** before your change can be merged. We recommend you **run tests locally** before creating your PR to catch breakages early on. Also, `./gradlew build` (`gradlew build` on Windows) **must not introduce any new warnings**. + +- Exceptions to the rules can be made if there's a compelling reason for doing so. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/NOTICE.txt b/NOTICE.txt new file mode 100644 index 0000000000000000000000000000000000000000..79a48ce2d718c9c3700836e17360df7c92dc65e2 --- /dev/null +++ b/NOTICE.txt @@ -0,0 +1,36 @@ +Copyright 2014 The gRPC Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +----------------------------------------------------------------------- + +This product contains a modified portion of 'OkHttp', an open source +HTTP & SPDY client for Android and Java applications, which can be obtained +at: + + * LICENSE: + * okhttp/third_party/okhttp/LICENSE (Apache License 2.0) + * HOMEPAGE: + * https://github.com/square/okhttp + * LOCATION_IN_GRPC: + * okhttp/third_party/okhttp + +This product contains a modified portion of 'Netty', an open source +networking library, which can be obtained at: + + * LICENSE: + * netty/third_party/netty/LICENSE.txt (Apache License 2.0) + * HOMEPAGE: + * https://netty.io + * LOCATION_IN_GRPC: + * netty/third_party/netty diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..bbede99f20d70c318f84744c0ce139f3ae6140ef --- /dev/null +++ b/README.md @@ -0,0 +1,220 @@ +gRPC-Java - An RPC library and framework +======================================== + +gRPC-Java works with JDK 7. gRPC-Java clients are supported on Android API +levels 14 and up (Ice Cream Sandwich and later). Deploying gRPC servers on an +Android device is not supported. + +TLS usage typically requires using Java 8, or Play Services Dynamic Security +Provider on Android. Please see the [Security Readme](SECURITY.md). + + + + + + + + + + +
Homepage:grpc.io
Mailing List:grpc-io@googlegroups.com
+ +[![Join the chat at https://gitter.im/grpc/grpc](https://badges.gitter.im/grpc/grpc.svg)](https://gitter.im/grpc/grpc?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +[![Build Status](https://travis-ci.org/grpc/grpc-java.svg?branch=master)](https://travis-ci.org/grpc/grpc-java) +[![Coverage Status](https://coveralls.io/repos/grpc/grpc-java/badge.svg?branch=master&service=github)](https://coveralls.io/github/grpc/grpc-java?branch=master) + +Getting Started +--------------- + +For a guided tour, take a look at the [quick start +guide](https://grpc.io/docs/quickstart/java.html) or the more explanatory [gRPC +basics](https://grpc.io/docs/tutorials/basic/java.html). + +The [examples](https://github.com/grpc/grpc-java/tree/v1.15.0/examples) and the +[Android example](https://github.com/grpc/grpc-java/tree/v1.15.0/examples/android) +are standalone projects that showcase the usage of gRPC. + +Download +-------- + +Download [the JARs][]. Or for Maven with non-Android, add to your `pom.xml`: +```xml + + io.grpc + grpc-netty-shaded + 1.15.0 + + + io.grpc + grpc-protobuf + 1.15.0 + + + io.grpc + grpc-stub + 1.15.0 + +``` + +Or for Gradle with non-Android, add to your dependencies: +```gradle +compile 'io.grpc:grpc-netty-shaded:1.15.0' +compile 'io.grpc:grpc-protobuf:1.15.0' +compile 'io.grpc:grpc-stub:1.15.0' +``` + +For Android client, use `grpc-okhttp` instead of `grpc-netty-shaded` and +`grpc-protobuf-lite` instead of `grpc-protobuf`: +```gradle +compile 'io.grpc:grpc-okhttp:1.15.0' +compile 'io.grpc:grpc-protobuf-lite:1.15.0' +compile 'io.grpc:grpc-stub:1.15.0' +``` + +[the JARs]: +https://search.maven.org/search?q=g:io.grpc%20AND%20v:1.15.0 + +Development snapshots are available in [Sonatypes's snapshot +repository](https://oss.sonatype.org/content/repositories/snapshots/). + +Generated Code +-------------- + +For protobuf-based codegen, you can put your proto files in the `src/main/proto` +and `src/test/proto` directories along with an appropriate plugin. + +For protobuf-based codegen integrated with the Maven build system, you can use +[protobuf-maven-plugin][] (Eclipse and NetBeans users should also look at +`os-maven-plugin`'s +[IDE documentation](https://github.com/trustin/os-maven-plugin#issues-with-eclipse-m2e-or-other-ides)): +```xml + + + + kr.motd.maven + os-maven-plugin + 1.5.0.Final + + + + + org.xolstice.maven.plugins + protobuf-maven-plugin + 0.5.1 + + com.google.protobuf:protoc:3.5.1-1:exe:${os.detected.classifier} + grpc-java + io.grpc:protoc-gen-grpc-java:1.15.0:exe:${os.detected.classifier} + + + + + compile + compile-custom + + + + + + +``` + +[protobuf-maven-plugin]: https://www.xolstice.org/protobuf-maven-plugin/ + +For protobuf-based codegen integrated with the Gradle build system, you can use +[protobuf-gradle-plugin][]: +```gradle +apply plugin: 'com.google.protobuf' + +buildscript { + repositories { + mavenCentral() + } + dependencies { + classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.5' + } +} + +protobuf { + protoc { + artifact = "com.google.protobuf:protoc:3.5.1-1" + } + plugins { + grpc { + artifact = 'io.grpc:protoc-gen-grpc-java:1.15.0' + } + } + generateProtoTasks { + all()*.plugins { + grpc {} + } + } +} +``` + +[protobuf-gradle-plugin]: https://github.com/google/protobuf-gradle-plugin + +The prebuilt protoc-gen-grpc-java binary uses glibc on Linux. If you are +compiling on Alpine Linux, you may want to use the [Alpine grpc-java package][] +which uses musl instead. + +[Alpine grpc-java package]: https://pkgs.alpinelinux.org/package/edge/testing/x86_64/grpc-java + +API Stability +------------- + +APIs annotated with `@Internal` are for internal use by the gRPC library and +should not be used by gRPC users. APIs annotated with `@ExperimentalApi` are +subject to change in future releases, and library code that other projects +may depend on should not use these APIs. + +We recommend using the +[grpc-java-api-checker](https://github.com/grpc/grpc-java-api-checker) +(an [Error Prone](https://github.com/google/error-prone) plugin) +to check for usages of `@ExperimentalApi` and `@Internal` in any library code +that depends on gRPC. It may also be used to check for `@Internal` usage or +unintended `@ExperimentalApi` consumption in non-library code. + +How to Build +------------ + +If you are making changes to gRPC-Java, see the [compiling +instructions](COMPILING.md). + +High-level Components +--------------------- + +At a high level there are three distinct layers to the library: *Stub*, +*Channel*, and *Transport*. + +### Stub + +The Stub layer is what is exposed to most developers and provides type-safe +bindings to whatever datamodel/IDL/interface you are adapting. gRPC comes with +a [plugin](https://github.com/google/grpc-java/blob/master/compiler) to the +protocol-buffers compiler that generates Stub interfaces out of `.proto` files, +but bindings to other datamodel/IDL are easy and encouraged. + +### Channel + +The Channel layer is an abstraction over Transport handling that is suitable for +interception/decoration and exposes more behavior to the application than the +Stub layer. It is intended to be easy for application frameworks to use this +layer to address cross-cutting concerns such as logging, monitoring, auth, etc. + +### Transport + +The Transport layer does the heavy lifting of putting and taking bytes off the +wire. The interfaces to it are abstract just enough to allow plugging in of +different implementations. Note the transport layer API is considered internal +to gRPC and has weaker API guarantees than the core API under package `io.grpc`. + +gRPC comes with three Transport implementations: + +1. The Netty-based transport is the main transport implementation based on + [Netty](http://netty.io). It is for both the client and the server. +2. The OkHttp-based transport is a lightweight transport based on + [OkHttp](http://square.github.io/okhttp/). It is mainly for use on Android + and is for client only. +3. The in-process transport is for when a server is in the same process as the + client. It is useful for testing, while also being safe for production use. diff --git a/RELEASING.md b/RELEASING.md new file mode 100644 index 0000000000000000000000000000000000000000..9fee632b56a754d924f6083d7e876cb0db1aa906 --- /dev/null +++ b/RELEASING.md @@ -0,0 +1,223 @@ +How to Create a Release of GRPC Java (for Maintainers Only) +=============================================================== + +Build Environments +------------------ +We deploy GRPC to Maven Central under the following systems: +- Ubuntu 14.04 with Docker 13.03.0 that runs CentOS 6.9 +- Windows 7 64-bit with Visual Studio +- Mac OS X 10.12.6 + +Other systems may also work, but we haven't verified them. + +Prerequisites +------------- + +### Set Up OSSRH Account + +If you haven't deployed artifacts to Maven Central before, you need to setup +your OSSRH (OSS Repository Hosting) account. +- Follow the instructions on [this + page](http://central.sonatype.org/pages/ossrh-guide.html) to set up an + account with OSSRH. + - You only need to create the account, not set up a new project + - Contact a gRPC maintainer to add your account after you have created it. + +Common Variables +---------------- +Many of the following commands expect release-specific variables to be set. Set +them before continuing, and set them again when resuming. + +```bash +$ MAJOR=1 MINOR=7 PATCH=0 # Set appropriately for new release +$ VERSION_FILES=( + build.gradle + android/build.gradle + android-interop-testing/app/build.gradle + core/src/main/java/io/grpc/internal/GrpcUtil.java + cronet/build.gradle + documentation/android-channel-builder.md + examples/build.gradle + examples/pom.xml + examples/android/clientcache/app/build.gradle + examples/android/helloworld/app/build.gradle + examples/android/routeguide/app/build.gradle + examples/example-kotlin/build.gradle + examples/example-kotlin/android/helloworld/app/build.gradle + ) +``` + + +Branching the Release +--------------------- +The first step in the release process is to create a release branch and bump +the SNAPSHOT version. Our release branches follow the naming +convention of `v..x`, while the tags include the patch version +`v..`. For example, the same branch `v1.7.x` +would be used to create all `v1.7` tags (e.g. `v1.7.0`, `v1.7.1`). + +1. For `master`, change root build files to the next minor snapshot (e.g. + ``1.8.0-SNAPSHOT``). + + ```bash + $ git checkout -b bump-version master + # Change version to next minor (and keep -SNAPSHOT) + $ sed -i 's/[0-9]\+\.[0-9]\+\.[0-9]\+\(.*CURRENT_GRPC_VERSION\)/'$MAJOR.$((MINOR+1)).0'\1/' \ + "${VERSION_FILES[@]}" + $ sed -i s/$MAJOR.$MINOR.$PATCH/$MAJOR.$((MINOR+1)).0/ \ + compiler/src/test{,Lite,Nano}/golden/Test{,Deprecated}Service.java.txt + $ ./gradlew build + $ git commit -a -m "Start $MAJOR.$((MINOR+1)).0 development cycle" + ``` +2. Go through PR review and submit. +3. Create the release branch starting just before your commit and push it to GitHub: + + ```bash + $ git fetch upstream + $ git checkout -b v$MAJOR.$MINOR.x \ + $(git log --pretty=format:%H --grep "^Start $MAJOR.$((MINOR+1)).0 development cycle$" upstream/master)^ + $ git push upstream v$MAJOR.$MINOR.x + ``` +4. Go to [Travis CI settings](https://travis-ci.org/grpc/grpc-java/settings) and + add a _Cron Job_: + * Branch: `v$MAJOR.$MINOR.x` + * Interval: `weekly` + * Options: `Do not run if there has been a build in the last 24h` + * Click _Add_ button +5. Continue with Google-internal steps at go/grpc/java/releasing. +6. Create a milestone for the next release. +7. Move items out of the release milestone that didn't make the cut. Issues that + may be backported should stay in the release milestone. Treat issues with the + 'release blocker' label with special care. + +Tagging the Release +------------------- + +1. Verify there are no open issues in the release milestone. Open issues should + either be deferred or resolved and the fix backported. +2. For vMajor.Minor.x branch, change `README.md` to refer to the next release + version. _Also_ update the version numbers for protoc if the protobuf library + version was updated since the last release. + + ```bash + $ git checkout v$MAJOR.$MINOR.x + $ git pull upstream v$MAJOR.$MINOR.x + $ git checkout -b release + # Bump documented versions. Don't forget protobuf version + $ ${EDITOR:-nano -w} README.md + $ git commit -a -m "Update README to reference $MAJOR.$MINOR.$PATCH" + ``` +3. Change root build files to remove "-SNAPSHOT" for the next release version + (e.g. `0.7.0`). Commit the result and make a tag: + + ```bash + # Change version to remove -SNAPSHOT + $ sed -i 's/-SNAPSHOT\(.*CURRENT_GRPC_VERSION\)/\1/' "${VERSION_FILES[@]}" + $ sed -i s/-SNAPSHOT// compiler/src/test{,Lite,Nano}/golden/TestService.java.txt + $ ./gradlew build + $ git commit -a -m "Bump version to $MAJOR.$MINOR.$PATCH" + $ git tag -a v$MAJOR.$MINOR.$PATCH -m "Version $MAJOR.$MINOR.$PATCH" + ``` +4. Change root build files to the next snapshot version (e.g. `0.7.1-SNAPSHOT`). + Commit the result: + + ```bash + # Change version to next patch and add -SNAPSHOT + $ sed -i 's/[0-9]\+\.[0-9]\+\.[0-9]\+\(.*CURRENT_GRPC_VERSION\)/'$MAJOR.$MINOR.$((PATCH+1))-SNAPSHOT'\1/' \ + "${VERSION_FILES[@]}" + $ sed -i s/$MAJOR.$MINOR.$PATCH/$MAJOR.$MINOR.$((PATCH+1))-SNAPSHOT/ compiler/src/test{,Lite,Nano}/golden/TestService.java.txt + $ ./gradlew build + $ git commit -a -m "Bump version to $MAJOR.$MINOR.$((PATCH+1))-SNAPSHOT" + ``` +5. Go through PR review and push the release tag and updated release branch to + GitHub: + + ```bash + $ git checkout v$MAJOR.$MINOR.x + $ git merge --ff-only release + $ git push upstream v$MAJOR.$MINOR.x + $ git push upstream v$MAJOR.$MINOR.$PATCH + ``` +6. Close the release milestone. + +Build Artifacts +--------------- + +Trigger build as described in "Auto releasing using kokoro" at +go/grpc/java/releasing. + +It runs three jobs on Kokoro, one on each platform. See their scripts: +`linux_artifacts.sh`, `windows.bat`, and `unix.sh` (called directly for OS X; +called within the Docker environment on Linux). The mvn-artifacts/ outputs of +each script is combined into a single folder and then processed by +`upload_artifacts.sh`, which signs the files and uploads to Sonatype. + +Releasing on Maven Central +-------------------------- + +Once all of the artifacts have been pushed to the staging repository, the +repository should have been closed by `upload_artifacts.sh`. Closing triggers +several sanity checks on the repository. If this completes successfully, the +repository can then be `released`, which will begin the process of pushing the +new artifacts to Maven Central (the staging repository will be destroyed in the +process). You can see the complete process for releasing to Maven Central on the +[OSSRH site](http://central.sonatype.org/pages/releasing-the-deployment.html). + +Build interop container image +----------------------------- + +We have containers for each release to detect compatibility regressions with old +releases. Generate one for the new release by following the +[GCR image generation instructions](https://github.com/grpc/grpc/blob/master/tools/interop_matrix/README.md#step-by-step-instructions-for-adding-a-gcr-image-for-a-new-release-for-compatibility-test). + +Update README.md +---------------- +After waiting ~1 day and verifying that the release appears on [Maven +Central](http://mvnrepository.com/), cherry-pick the commit that updated the +README into the master branch and go through review process. + +``` +$ git checkout -b bump-readme master +$ git cherry-pick v$MAJOR.$MINOR.$PATCH^ +``` + +Update version referenced by tutorials +-------------------------------------- + +Update the `grpc_java_release_tag` in +[\_data/config.yml](https://github.com/grpc/grpc.github.io/blob/master/_data/config.yml) +of the grpc.github.io repository. + +Notify the Community +-------------------- +Finally, document and publicize the release. + +1. Add [Release Notes](https://github.com/grpc/grpc-java/releases) for the new tag. + The description should include any major fixes or features since the last release. + You may choose to add links to bugs, PRs, or commits if appropriate. +2. Post a release announcement to [grpc-io](https://groups.google.com/forum/#!forum/grpc-io) + (`grpc-io@googlegroups.com`). The title should be something that clearly identifies + the release (e.g.`GRPC-Java Released`). + 1. Check if JCenter has picked up the new release (https://jcenter.bintray.com/io/grpc/) + and include its availability in the release announcement email. JCenter should mirror + everything on Maven Central, but users have reported delays. + +Update Hosted Javadoc +--------------------- + +Now we need to update gh-pages with the new Javadoc: + +```bash +git checkout gh-pages +rm -r javadoc/ +wget -O grpc-all-javadoc.jar "http://search.maven.org/remotecontent?filepath=io/grpc/grpc-all/$MAJOR.$MINOR.$PATCH/grpc-all-$MAJOR.$MINOR.$PATCH-javadoc.jar" +unzip -d javadoc grpc-all-javadoc.jar +patch -p1 < ga.patch +rm grpc-all-javadoc.jar +rm -r javadoc/META-INF/ +git add -A javadoc +git commit -m "Javadoc for $MAJOR.$MINOR.$PATCH" +``` + +Push gh-pages to the main repository and verify the current version is [live +on grpc.io](https://grpc.io/grpc-java/javadoc/). diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000000000000000000000000000000000000..296aad2f54a818d480bf117981561d8870ae99cb --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,417 @@ +# Authentication + +gRPC supports a number of different mechanisms for asserting identity between an client and server. This document provides code samples demonstrating how to provide SSL/TLS encryption support and identity assertions in Java, as well as passing OAuth2 tokens to services that support it. + +# Transport Security (TLS) + +HTTP/2 over TLS mandates the use of [ALPN](https://tools.ietf.org/html/draft-ietf-tls-applayerprotoneg-05) to negotiate the use of the h2 protocol. ALPN is a fairly new standard and (where possible) gRPC also supports protocol negotiation via [NPN](https://tools.ietf.org/html/draft-agl-tls-nextprotoneg-04) for systems that do not yet support ALPN. + +On Android, use the [Play Services Provider](#tls-on-android). For non-Android systems, use [OpenSSL](#tls-with-openssl). + +## TLS on Android + +On Android we recommend the use of the [Play Services Dynamic Security +Provider](https://www.appfoundry.be/blog/2014/11/18/Google-Play-Services-Dynamic-Security-Provider/) +to ensure your application has an up-to-date OpenSSL library with the necessary +ciper-suites and a reliable ALPN implementation. This requires [updating the +security provider at +runtime](https://developer.android.com/training/articles/security-gms-provider.html). + +Although ALPN mostly works on newer Android releases (especially since 5.0), +there are bugs and discovered security vulnerabilities that are only fixed by +upgrading the security provider. Thus, we recommend using the Play Service +Dynamic Security Provider for all Android versions. + +*Note: The Dynamic Security Provider must be installed **before** creating a gRPC OkHttp channel. gRPC's OkHttpProtocolNegotiator statically initializes the security protocol(s) available to gRPC, which means that changes to the security provider after the first channel is created will not be picked up by gRPC.* + +### Bundling Conscrypt + +If depending on Play Services is not an option for your app, then you may bundle +[Conscrypt](https://conscrypt.org) with your application. Binaries are available +on [Maven +Central](https://search.maven.org/#search%7Cga%7C1%7Cg%3Aorg.conscrypt%20a%3Aconscrypt-android). + +Like the Play Services Dynamic Security Provider, you must still "install" +Conscrypt before use. + +```java +import org.conscrypt.Conscrypt; +import java.security.Security; +... + +Security.insertProviderAt(Conscrypt.newProvider(), 1); +``` + +## TLS with OpenSSL + +This is currently the recommended approach for using gRPC over TLS (on non-Android systems). + +The main benefits of using OpenSSL are: + +1. **Speed**: In local testing, we've seen performance improvements of 3x over the JDK. GCM, which is used by the only cipher suite required by the HTTP/2 spec, is 10-500x faster. +2. **Ciphers**: OpenSSL has its own ciphers and is not dependent on the limitations of the JDK. This allows supporting GCM on Java 7. +3. **ALPN to NPN Fallback**: if the remote endpoint doesn't support ALPN. +4. **Version Independence**: does not require using a different library version depending on the JDK update. + +Support for OpenSSL is only provided for the Netty transport via [netty-tcnative](https://github.com/netty/netty-tcnative), which is a fork of +[Apache Tomcat's tcnative](http://tomcat.apache.org/native-doc/), a JNI wrapper around OpenSSL. + +### OpenSSL: Dynamic vs Static (which to use?) + +As of version `1.1.33.Fork14`, netty-tcnative provides two options for usage: statically or dynamically linked. For simplification of initial setup, +we recommend that users first look at `netty-tcnative-boringssl-static`, which is statically linked against BoringSSL and Apache APR. Using this artifact requires no extra installation and guarantees that ALPN and the ciphers required for +HTTP/2 are available. In addition, starting with `1.1.33.Fork16` binaries for +all supported platforms can be included at compile time and the correct binary +for the platform can be selected at runtime. + +Production systems, however, may require an easy upgrade path for OpenSSL security patches. In this case, relying on the statically linked artifact also implies waiting for the Netty team +to release the new artifact to Maven Central, which can take some time. A better solution in this case is to use the dynamically linked `netty-tcnative` artifact, which allows the site administrator +to easily upgrade OpenSSL in the standard way (e.g. apt-get) without relying on any new builds from Netty. + +### OpenSSL: Statically Linked (netty-tcnative-boringssl-static) + +This is the simplest way to configure the Netty transport for OpenSSL. You just need to add the appropriate `netty-tcnative-boringssl-static` artifact to your application's classpath. + +Artifacts are available on [Maven Central](http://repo1.maven.org/maven2/io/netty/netty-tcnative-boringssl-static/) for the following platforms: + +Maven Classifier | Description +---------------- | ----------- +windows-x86_64 | Windows distribution +osx-x86_64 | Mac distribution +linux-x86_64 | Linux distribution + +##### Getting netty-tcnative-boringssl-static from Maven + +In Maven, you can use the [os-maven-plugin](https://github.com/trustin/os-maven-plugin) to help simplify the dependency. + +```xml + + + + io.netty + netty-tcnative-boringssl-static + 2.0.7.Final + + + +``` + +##### Getting netty-tcnative-boringssl-static from Gradle + +Gradle you can use the [osdetector-gradle-plugin](https://github.com/google/osdetector-gradle-plugin), which is a wrapper around the os-maven-plugin. + +```gradle +buildscript { + repositories { + mavenCentral() + } +} + +dependencies { + compile 'io.netty:netty-tcnative-boringssl-static:2.0.7.Final' +} +``` + +### OpenSSL: Dynamically Linked (netty-tcnative) + +If for any reason you need to dynamically link against OpenSSL (e.g. you need control over the version of OpenSSL), you can instead use the `netty-tcnative` artifact. + +Requirements: + +1. [OpenSSL](https://www.openssl.org/) version >= 1.0.2 for ALPN support, or version >= 1.0.1 for NPN. +2. [Apache APR library (libapr-1)](https://apr.apache.org/) version >= 1.5.2. +3. [netty-tcnative](https://github.com/netty/netty-tcnative) version >= 1.1.33.Fork7 must be on classpath. Prior versions only supported NPN and only Fedora-derivatives were supported for Linux. + +Artifacts are available on [Maven Central](http://repo1.maven.org/maven2/io/netty/netty-tcnative/) for the following platforms: + +Classifier | Description +---------------- | ----------- +windows-x86_64 | Windows distribution +osx-x86_64 | Mac distribution +linux-x86_64 | Used for non-Fedora derivatives of Linux +linux-x86_64-fedora | Used for Fedora derivatives + +On Linux it should be noted that OpenSSL uses a different soname for Fedora derivatives than other Linux releases. To work around this limitation, netty-tcnative deploys two separate versions for linux. + +##### Getting netty-tcnative from Maven + +In Maven, you can use the [os-maven-plugin](https://github.com/trustin/os-maven-plugin) to help simplify the dependency. + +```xml + + + + io.netty + netty-tcnative + 2.0.7.Final + ${tcnative.classifier} + + + + + + + + kr.motd.maven + os-maven-plugin + 1.5.0.Final + + + + + + org.apache.maven.plugins + maven-antrun-plugin + + + initialize + + true + + + + + + + + run + + + + + + + +``` + +##### Getting netty-tcnative from Gradle + +Gradle you can use the [osdetector-gradle-plugin](https://github.com/google/osdetector-gradle-plugin), which is a wrapper around the os-maven-plugin. + +```gradle +buildscript { + repositories { + mavenCentral() + } + dependencies { + classpath 'com.google.gradle:osdetector-gradle-plugin:1.4.0' + } +} + +// Use the osdetector-gradle-plugin +apply plugin: "com.google.osdetector" + +def tcnative_classifier = osdetector.classifier; +// Fedora variants use a different soname for OpenSSL than other linux distributions +// (see http://netty.io/wiki/forked-tomcat-native.html). +if (osdetector.os == "linux" && osdetector.release.isLike("fedora")) { + tcnative_classifier += "-fedora"; +} + +dependencies { + compile 'io.netty:netty-tcnative:2.0.7.Final:' + tcnative_classifier +} +``` + +## TLS with JDK (Jetty ALPN/NPN) + +**WARNING: DON'T DO THIS!!** + +*For non-Android systems, the recommended approach is to use [OpenSSL](#tls-with-openssl). Using the JDK for ALPN is generally much slower and may not support the necessary ciphers for HTTP2.* + +*Jetty ALPN brings its own baggage in that the Java bootclasspath needs to be modified, which may not be an option for some environments. In addition, a specific version of Jetty ALPN has to be used for a given version of the JRE. If the versions don't match the negotiation will fail, but you won't really know why. And since there is such a tight coupling between Jetty ALPN and the JRE, there are no guarantees that Jetty ALPN will support every JRE out in the wild.* + +*The moral of the story is: Don't use the JDK for ALPN! But if you absolutely have to, here's how you do it... :)* + +--- + +If not using the Netty transport (or you are unable to use OpenSSL for some reason) another alternative is to use the JDK for TLS. + +No standard Java release has built-in support for ALPN today ([there is a tracking issue](https://bugs.openjdk.java.net/browse/JDK-8051498) so go upvote it!) so we need to use the [Jetty-ALPN](https://github.com/jetty-project/jetty-alpn) (or [Jetty-NPN](https://github.com/jetty-project/jetty-npn) if on Java < 8) bootclasspath extension for OpenJDK. To do this, add an `Xbootclasspath` JVM option referencing the path to the Jetty `alpn-boot` jar. + +```sh +java -Xbootclasspath/p:/path/to/jetty/alpn/extension.jar ... +``` + +Note that you must use the [release of the Jetty-ALPN jar](http://www.eclipse.org/jetty/documentation/current/alpn-chapter.html#alpn-versions) specific to the version of Java you are using. However, you can use the JVM agent [Jetty-ALPN-Agent](https://github.com/jetty-project/jetty-alpn-agent) to load the correct Jetty `alpn-boot` jar file for the current Java version. To do this, instead of adding an `Xbootclasspath` option, add a `javaagent` JVM option referencing the path to the Jetty `alpn-agent` jar. + +```sh +java -javaagent:/path/to/jetty-alpn-agent.jar ... +``` + +### JDK Ciphers + +Java 7 does not support [the cipher suites recommended](https://tools.ietf.org/html/draft-ietf-httpbis-http2-17#section-9.2.2) by the HTTP2 specification. To address this we suggest servers use Java 8 where possible or use an alternative JCE implementation such as [Bouncy Castle](https://www.bouncycastle.org/java.html). If this is not practical it is possible to use other ciphers but you need to ensure that the services you intend to call have [allowed out-of-spec ciphers](https://github.com/grpc/grpc/issues/681) and have evaluated the security risks of doing so. + +Users should be aware that GCM is [_very_ slow (1 MB/s)](https://bugzilla.redhat.com/show_bug.cgi?id=1135504) before Java 8u60. With Java 8u60 GCM is 10x faster (10-20 MB/s), but that is still slow compared to OpenSSL (~200 MB/s), especially with AES-NI support (~1 GB/s). GCM cipher suites are the only suites available that comply with HTTP2's cipher requirements. + +### Configuring Jetty ALPN in Web Containers + +Some web containers, such as [Jetty](http://www.eclipse.org/jetty/documentation/current/jetty-classloading.html) restrict access to server classes for web applications. A gRPC client running within such a container must be properly configured to allow access to the ALPN classes. In Jetty, this is done by including a `WEB-INF/jetty-env.xml` file containing the following: + +```xml + + + + + + + + -org.eclipse.jetty.alpn. + + +``` +## Enabling TLS on a server + +To use TLS on the server, a certificate chain and private key need to be +specified in PEM format. The standard TLS port is 443, but we use 8443 below to +avoid needing extra permissions from the OS. + +```java +Server server = ServerBuilder.forPort(8443) + // Enable TLS + .useTransportSecurity(certChainFile, privateKeyFile) + .addService(serviceImplementation) + .build(); +server.start(); +``` + +If the issuing certificate authority is not known to the client then a properly +configured SslContext or SSLSocketFactory should be provided to the +NettyChannelBuilder or OkHttpChannelBuilder, respectively. + +## Mutual TLS + +[Mutual authentication][] (or "client-side authentication") configuration is similar to the server by providing truststores, a client certificate and private key to the client channel. The server must also be configured to request a certificate from clients, as well as truststores for which client certificates it should allow. + +```java +Server server = NettyServerBuilder.forPort(8443) + .sslContext(GrpcSslContexts.forServer(certChainFile, privateKeyFile) + .trustManager(clientCAsFile) + .clientAuth(ClientAuth.REQUIRE) + .build()); +``` + +Negotiated client certificates are available in the SSLSession, which is found in the `TRANSPORT_ATTR_SSL_SESSION` attribute of Grpc. A server interceptor can provide details in the current Context. + +```java +public final static Context.Key SSL_SESSION_CONTEXT = Context.key("SSLSession"); + +@Override +public ServerCall.Listener interceptCall(ServerCall call, + Metadata headers, ServerCallHandler next) { + SSLSession sslSession = call.attributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION); + if (sslSession == null) { + return next.startCall(call, headers) + } + return Contexts.interceptCall( + Context.current().withValue(SSL_SESSION_CONTEXT, clientContext), call, headers, next); +} +``` + +[Mutual authentication]: http://en.wikipedia.org/wiki/Transport_Layer_Security#Client-authenticated_TLS_handshake + +## Troubleshooting + +If you received an error message "ALPN is not configured properly" or "Jetty ALPN/NPN has not been properly configured", it most likely means that: + - ALPN related dependencies are either not present in the classpath + - or that there is a classpath conflict + - or that a wrong version is used due to dependency management + - or you are on an unsupported platform (e.g., 32-bit OS, Alpine with `musl` libc). See [Transport Security](#transport-security-tls) for supported platforms. + +### Netty +If you aren't using gRPC on Android devices, you are most likely using `grpc-netty` transport. + +If you are developing for Android and have a dependency on `grpc-netty`, you should remove it as `grpc-netty` is unsupported on Android. Use `grpc-okhttp` instead. + +If you are on a 32-bit operating system, or not on a [Transport Security supported platform](#transport-security-tls), you should use Jetty ALPN (and beware of potential issues), or you'll need to build your own 32-bit version of `netty-tcnative`. + +If you are using `musl` libc (e.g., with Alpine Linux), then +`netty-tcnative-boringssl-static` won't work. There are several alternatives: + - Use [netty-tcnative-alpine](https://github.com/pires/netty-tcnative-alpine) + - Use a distribution with `glibc` + +If you are running inside of an embedded Tomcat runtime (e.g., Spring Boot), +then some versions of `netty-tcnative-boringssl-static` will have conflicts and +won't work. You must use gRPC 1.4.0 or later. + +Most dependency versioning problems can be solved by using +`io.grpc:grpc-netty-shaded` instead of `io.grpc:grpc-netty`, although this also +limits your usage of the Netty-specific APIs. `io.grpc:grpc-netty-shaded` +includes the proper version of Netty and `netty-tcnative-boringssl-static` in a +way that won't conflict with other Netty usages. + +Find the dependency tree (e.g., `mvn dependency:tree`), and look for versions of: + - `io.grpc:grpc-netty` + - `io.netty:netty-handler` (really, make sure all of io.netty except for + netty-tcnative has the same version) + - `io.netty:netty-tcnative-boringssl-static:jar` + +If `netty-tcnative-boringssl-static` is missing, then you either need to add it as a dependency, or use alternative methods of providing ALPN capability by reading the *Transport Security (TLS)* section carefully. + +If you have both `netty-handler` and `netty-tcnative-boringssl-static` dependencies, then check the versions carefully. These versions could've been overridden by dependency management from another BOM. You would receive the "ALPN is not configured properly" exception if you are using incompatible versions. + +If you have other `netty` dependencies, such as `netty-all`, that are pulled in from other libraries, then ultimately you should make sure only one `netty` dependency is used to avoid classpath conflict. The easiest way is to exclude transitive Netty dependencies from all the immediate dependencies, e.g., in Maven use ``, and then add an explict Netty dependency in your project along with the corresponding `tcnative` versions. See the versions table below. + +If you are running in a runtime environment that also uses Netty (e.g., Hadoop, Spark, Spring Boot 2) and you have no control over the Netty version at all, then you should use a shaded gRPC Netty dependency to avoid classpath conflicts with other Netty versions in runtime the classpath: + - Remove `io.grpc:grpc-netty` dependency + - Add `io.grpc:grpc-netty-shaded` dependency + +Below are known to work version combinations: + +grpc-netty version | netty-handler version | netty-tcnative-boringssl-static version +------------------ | --------------------- | --------------------------------------- +1.0.0-1.0.1 | 4.1.3.Final | 1.1.33.Fork19 +1.0.2-1.0.3 | 4.1.6.Final | 1.1.33.Fork23 +1.1.x-1.3.x | 4.1.8.Final | 1.1.33.Fork26 +1.4.x | 4.1.11.Final | 2.0.1.Final +1.5.x | 4.1.12.Final | 2.0.5.Final +1.6.x | 4.1.14.Final | 2.0.5.Final +1.7.x-1.8.x | 4.1.16.Final | 2.0.6.Final +1.9.x-1.10.x | 4.1.17.Final | 2.0.7.Final +1.11.x-1.12.x | 4.1.22.Final | 2.0.7.Final +1.13.x | 4.1.25.Final | 2.0.8.Final +1.14.x- | 4.1.27.Final | 2.0.12.Final + +_(grpc-netty-shaded avoids issues with keeping these versions in sync.)_ + +### OkHttp +If you are using gRPC on Android devices, you are most likely using `grpc-okhttp` transport. + +Find the dependency tree (e.g., `mvn dependency:tree`), and look for versions of: + - `io.grpc:grpc-okhttp` + - `com.squareup.okhttp:okhttp` + +If you don't have `grpc-okhttp`, you should add it as a dependency. + +If you have both `io.grpc:grpc-netty` and `io.grpc:grpc-okhttp`, you may also have issues. Remove `grpc-netty` if you are on Android. + +If you have `okhttp` version below 2.5.0, then it may not work with gRPC. + +It is OK to have both `okhttp` 2.x and 3.x since they have different group name and under different packages. + +# gRPC over plaintext + +An option is provided to use gRPC over plaintext without TLS. While this is convenient for testing environments, users must be aware of the security risks of doing so for real production systems. + +# Using OAuth2 + +The following code snippet shows how you can call the Google Cloud PubSub API using gRPC with a service account. The credentials are loaded from a key stored in a well-known location or by detecting that the application is running in an environment that can provide one automatically, e.g. Google Compute Engine. While this example is specific to Google and it's services, similar patterns can be followed for other service providers. + +```java +// Create a channel to the test service. +ManagedChannel channel = ManagedChannelBuilder.forTarget("pubsub.googleapis.com") + .build(); +// Get the default credentials from the environment +GoogleCredentials creds = GoogleCredentials.getApplicationDefault(); +// Down-scope the credential to just the scopes required by the service +creds = creds.createScoped(Arrays.asList("https://www.googleapis.com/auth/pubsub")); +// Create an instance of {@link io.grpc.CallCredentials} +CallCredentials callCreds = MoreCallCredentials.from(creds); +// Create a stub with credential +PublisherGrpc.PublisherBlockingStub publisherStub = + PublisherGrpc.newBlockingStub(channel).withCallCredentials(callCreds); +publisherStub.publish(someMessage); +``` diff --git a/WORKSPACE b/WORKSPACE new file mode 100644 index 0000000000000000000000000000000000000000..65bf26a8b2535dd2ddb0c88b0a3b84eb51accf9d --- /dev/null +++ b/WORKSPACE @@ -0,0 +1,5 @@ +workspace(name = "io_grpc_grpc_java") + +load("//:repositories.bzl", "grpc_java_repositories") + +grpc_java_repositories() diff --git a/all/build.gradle b/all/build.gradle new file mode 100644 index 0000000000000000000000000000000000000000..438ec1b223c2f916c71a30be26479e60567b2d70 --- /dev/null +++ b/all/build.gradle @@ -0,0 +1,81 @@ +apply plugin: 'com.github.kt3k.coveralls' + +description = "gRPC: All" + +buildscript { + repositories { + maven { // The google mirror is less flaky than mavenCentral() + url "https://maven-central.storage-download.googleapis.com/repos/central/data/" } + } + dependencies { classpath 'org.kt3k.gradle.plugin:coveralls-gradle-plugin:2.0.1' } +} + +def subprojects = [ + project(':grpc-auth'), + project(':grpc-core'), + project(':grpc-context'), + project(':grpc-netty'), + project(':grpc-okhttp'), + project(':grpc-protobuf'), + project(':grpc-protobuf-lite'), + project(':grpc-protobuf-nano'), + project(':grpc-stub'), + project(':grpc-testing'), +] + +for (subproject in rootProject.subprojects) { + if (subproject == project) { + continue + } + evaluationDependsOn(subproject.path) +} + +dependencies { + compile subprojects.minus(project(':grpc-protobuf-lite')) +} + +javadoc { + classpath = files(subprojects.collect { subproject -> + subproject.javadoc.classpath + }) + for (subproject in subprojects) { + if (subproject == project) { + continue; + } + source subproject.javadoc.source + options.links subproject.javadoc.options.links.toArray(new String[0]) + } +} + +task jacocoMerge(type: JacocoMerge) { + dependsOn(subprojects.jacocoTestReport.dependsOn) + mustRunAfter(subprojects.jacocoTestReport.mustRunAfter) + destinationFile = file("${buildDir}/jacoco/test.exec") + executionData = files(subprojects.jacocoTestReport.executionData) + .plus(project(':grpc-interop-testing').jacocoTestReport.executionData) + .filter { f -> f.exists() } +} + +jacocoTestReport { + dependsOn(jacocoMerge) + reports { + xml.enabled = true + html.enabled = true + } + + additionalSourceDirs = files(subprojects.sourceSets.main.allSource.srcDirs) + sourceDirectories = files(subprojects.sourceSets.main.allSource.srcDirs) + classDirectories = files(subprojects.sourceSets.main.output) + classDirectories = files(classDirectories.files.collect { + fileTree(dir: it, + exclude: [ + '**/io/grpc/okhttp/internal/**' + ]) + }) +} + +coveralls { + sourceDirs = subprojects.sourceSets.main.allSource.srcDirs.flatten() +} + +tasks.coveralls { dependsOn(jacocoTestReport) } diff --git a/alts/BUILD.bazel b/alts/BUILD.bazel new file mode 100644 index 0000000000000000000000000000000000000000..4e3d266b4d5ae890a7fc0ffb3e123ca347e4636d --- /dev/null +++ b/alts/BUILD.bazel @@ -0,0 +1,83 @@ +load("//:java_grpc_library.bzl", "java_grpc_library") + +java_library( + name = "alts_internal", + srcs = glob([ + "src/main/java/io/grpc/alts/internal/*.java", + ]), + deps = [ + ":handshaker_java_grpc", + ":handshaker_java_proto", + "//core", + "//core:internal", + "//netty", + "//stub", + "@com_google_code_findbugs_jsr305//jar", + "@com_google_guava_guava//jar", + "@com_google_protobuf//:protobuf_java", + "@com_google_protobuf//:protobuf_java_util", + "@io_netty_netty_buffer//jar", + "@io_netty_netty_codec//jar", + "@io_netty_netty_common//jar", + "@io_netty_netty_handler//jar", + "@io_netty_netty_transport//jar", + ], +) + +java_library( + name = "alts", + srcs = glob([ + "src/main/java/io/grpc/alts/*.java", + ]), + visibility = ["//visibility:public"], + runtime_deps = ["//grpclb"], + deps = [ + ":alts_internal", + ":handshaker_java_grpc", + "//core", + "//core:internal", + "//auth", + "//netty", + "@com_google_auth_google_auth_library_oauth2_http//jar", + "@com_google_code_findbugs_jsr305//jar", + "@com_google_guava_guava//jar", + "@io_netty_netty_common//jar", + "@io_netty_netty_handler//jar", + "@io_netty_netty_transport//jar", + "@org_apache_commons_commons_lang3//jar", + ], +) + +# bazel only accepts proto import with absolute path. +genrule( + name = "protobuf_imports", + srcs = glob(["src/main/proto/grpc/gcp/*.proto"]), + outs = [ + "protobuf_out/grpc/gcp/altscontext.proto", + "protobuf_out/grpc/gcp/handshaker.proto", + "protobuf_out/grpc/gcp/transport_security_common.proto", + ], + cmd = "for fname in $(SRCS); do " + + "sed 's,import \",import \"alts/protobuf_out/,g' $$fname > " + + "$(@D)/protobuf_out/grpc/gcp/$$(basename $$fname); done", +) + +proto_library( + name = "handshaker_proto", + srcs = [ + "protobuf_out/grpc/gcp/altscontext.proto", + "protobuf_out/grpc/gcp/handshaker.proto", + "protobuf_out/grpc/gcp/transport_security_common.proto", + ], +) + +java_proto_library( + name = "handshaker_java_proto", + deps = [":handshaker_proto"], +) + +java_grpc_library( + name = "handshaker_java_grpc", + srcs = [":handshaker_proto"], + deps = [":handshaker_java_proto"], +) diff --git a/alts/build.gradle b/alts/build.gradle new file mode 100644 index 0000000000000000000000000000000000000000..5a8c9e376657b3f8e4b17c3cc1a1ca9c80425852 --- /dev/null +++ b/alts/build.gradle @@ -0,0 +1,90 @@ +buildscript { + repositories { jcenter() } + dependencies { classpath 'com.github.jengelman.gradle.plugins:shadow:2.0.4' } +} + +apply plugin: 'com.github.johnrengelman.shadow' + +description = "gRPC: ALTS" + +sourceCompatibility = 1.7 +targetCompatibility = 1.7 + +buildscript { + repositories { + maven { // The google mirror is less flaky than mavenCentral() + url "https://maven-central.storage-download.googleapis.com/repos/central/data/" } + } + dependencies { classpath libraries.protobuf_plugin } +} + +dependencies { + compile project(':grpc-auth'), + project(':grpc-core'), + project(':grpc-netty'), + project(':grpc-protobuf'), + project(':grpc-stub'), + libraries.lang, + libraries.protobuf + compile (libraries.google_auth_oauth2_http) { + // prefer 3.0.0 from libraries instead of 1.3.9 + exclude group: 'com.google.code.findbugs', module: 'jsr305' + // prefer 20.0 from libraries instead of 19.0 + exclude group: 'com.google.guava', module: 'guava' + } + runtime project(':grpc-grpclb') + testCompile libraries.guava, + libraries.guava_testlib, + libraries.junit, + libraries.mockito, + libraries.truth + testRuntime libraries.netty_tcnative, + libraries.conscrypt + signature 'org.codehaus.mojo.signature:java17:1.0@signature' +} + +configureProtoCompilation() + +[compileJava, compileTestJava].each() { + // ALTS retuns a lot of futures that we mostly don't care about. + // protobuf calls valueof. Will be fixed in next release (google/protobuf#4046) + it.options.compilerArgs += [ + "-Xlint:-deprecation", + "-Xep:FutureReturnValueIgnored:OFF" + ] +} + +javadoc { exclude 'io/grpc/alts/internal/**' } + +artifacts { + archives shadowJar +} + +jar { + // Must use a different classifier to avoid conflicting with shadowJar + classifier = 'original' +} +configurations.archives.artifacts.removeAll { it.classifier == "original" } + +// We want to use grpc-netty-shaded instead of grpc-netty. But we also want our +// source to work with Bazel, so we rewrite the code as part of the build. +shadowJar { + classifier = null + dependencies { + exclude(dependency {true}) + } + relocate 'io.grpc.netty', 'io.grpc.netty.shaded.io.grpc.netty' + relocate 'io.netty', 'io.grpc.netty.shaded.io.netty' +} + +[ + install.repositories.mavenInstaller, + uploadArchives.repositories.mavenDeployer, +]*.pom*.whenConfigured { pom -> + def netty = pom.dependencies.find {dep -> dep.artifactId == 'grpc-netty'} + // Swap our dependency to grpc-netty-shaded. Projects depending on this via + // project(':grpc-alts') will still be using the non-shaded form. + netty.artifactId = "grpc-netty-shaded" + // Depend on specific version of grpc-netty-shaded because it is unstable API + netty.version = "[" + netty.version + "]" +} diff --git a/alts/src/generated/main/grpc/io/grpc/alts/internal/HandshakerServiceGrpc.java b/alts/src/generated/main/grpc/io/grpc/alts/internal/HandshakerServiceGrpc.java new file mode 100644 index 0000000000000000000000000000000000000000..012748d1107c949508a5b412457b541ecda646c9 --- /dev/null +++ b/alts/src/generated/main/grpc/io/grpc/alts/internal/HandshakerServiceGrpc.java @@ -0,0 +1,280 @@ +package io.grpc.alts.internal; + +import static io.grpc.MethodDescriptor.generateFullMethodName; +import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall; +import static io.grpc.stub.ClientCalls.asyncClientStreamingCall; +import static io.grpc.stub.ClientCalls.asyncServerStreamingCall; +import static io.grpc.stub.ClientCalls.asyncUnaryCall; +import static io.grpc.stub.ClientCalls.blockingServerStreamingCall; +import static io.grpc.stub.ClientCalls.blockingUnaryCall; +import static io.grpc.stub.ClientCalls.futureUnaryCall; +import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall; +import static io.grpc.stub.ServerCalls.asyncClientStreamingCall; +import static io.grpc.stub.ServerCalls.asyncServerStreamingCall; +import static io.grpc.stub.ServerCalls.asyncUnaryCall; +import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall; +import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall; + +/** + */ +@javax.annotation.Generated( + value = "by gRPC proto compiler", + comments = "Source: grpc/gcp/handshaker.proto") +public final class HandshakerServiceGrpc { + + private HandshakerServiceGrpc() {} + + public static final String SERVICE_NAME = "grpc.gcp.HandshakerService"; + + // Static method descriptors that strictly reflect the proto. + private static volatile io.grpc.MethodDescriptor getDoHandshakeMethod; + + @io.grpc.stub.annotations.RpcMethod( + fullMethodName = SERVICE_NAME + '/' + "DoHandshake", + requestType = io.grpc.alts.internal.Handshaker.HandshakerReq.class, + responseType = io.grpc.alts.internal.Handshaker.HandshakerResp.class, + methodType = io.grpc.MethodDescriptor.MethodType.BIDI_STREAMING) + public static io.grpc.MethodDescriptor getDoHandshakeMethod() { + io.grpc.MethodDescriptor getDoHandshakeMethod; + if ((getDoHandshakeMethod = HandshakerServiceGrpc.getDoHandshakeMethod) == null) { + synchronized (HandshakerServiceGrpc.class) { + if ((getDoHandshakeMethod = HandshakerServiceGrpc.getDoHandshakeMethod) == null) { + HandshakerServiceGrpc.getDoHandshakeMethod = getDoHandshakeMethod = + io.grpc.MethodDescriptor.newBuilder() + .setType(io.grpc.MethodDescriptor.MethodType.BIDI_STREAMING) + .setFullMethodName(generateFullMethodName( + "grpc.gcp.HandshakerService", "DoHandshake")) + .setSampledToLocalTracing(true) + .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( + io.grpc.alts.internal.Handshaker.HandshakerReq.getDefaultInstance())) + .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( + io.grpc.alts.internal.Handshaker.HandshakerResp.getDefaultInstance())) + .setSchemaDescriptor(new HandshakerServiceMethodDescriptorSupplier("DoHandshake")) + .build(); + } + } + } + return getDoHandshakeMethod; + } + + /** + * Creates a new async stub that supports all call types for the service + */ + public static HandshakerServiceStub newStub(io.grpc.Channel channel) { + return new HandshakerServiceStub(channel); + } + + /** + * Creates a new blocking-style stub that supports unary and streaming output calls on the service + */ + public static HandshakerServiceBlockingStub newBlockingStub( + io.grpc.Channel channel) { + return new HandshakerServiceBlockingStub(channel); + } + + /** + * Creates a new ListenableFuture-style stub that supports unary calls on the service + */ + public static HandshakerServiceFutureStub newFutureStub( + io.grpc.Channel channel) { + return new HandshakerServiceFutureStub(channel); + } + + /** + */ + public static abstract class HandshakerServiceImplBase implements io.grpc.BindableService { + + /** + *
+     * Handshaker service accepts a stream of handshaker request, returning a
+     * stream of handshaker response. Client is expected to send exactly one
+     * message with either client_start or server_start followed by one or more
+     * messages with next. Each time client sends a request, the handshaker
+     * service expects to respond. Client does not have to wait for service's
+     * response before sending next request.
+     * 
+ */ + public io.grpc.stub.StreamObserver doHandshake( + io.grpc.stub.StreamObserver responseObserver) { + return asyncUnimplementedStreamingCall(getDoHandshakeMethod(), responseObserver); + } + + @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { + return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) + .addMethod( + getDoHandshakeMethod(), + asyncBidiStreamingCall( + new MethodHandlers< + io.grpc.alts.internal.Handshaker.HandshakerReq, + io.grpc.alts.internal.Handshaker.HandshakerResp>( + this, METHODID_DO_HANDSHAKE))) + .build(); + } + } + + /** + */ + public static final class HandshakerServiceStub extends io.grpc.stub.AbstractStub { + private HandshakerServiceStub(io.grpc.Channel channel) { + super(channel); + } + + private HandshakerServiceStub(io.grpc.Channel channel, + io.grpc.CallOptions callOptions) { + super(channel, callOptions); + } + + @java.lang.Override + protected HandshakerServiceStub build(io.grpc.Channel channel, + io.grpc.CallOptions callOptions) { + return new HandshakerServiceStub(channel, callOptions); + } + + /** + *
+     * Handshaker service accepts a stream of handshaker request, returning a
+     * stream of handshaker response. Client is expected to send exactly one
+     * message with either client_start or server_start followed by one or more
+     * messages with next. Each time client sends a request, the handshaker
+     * service expects to respond. Client does not have to wait for service's
+     * response before sending next request.
+     * 
+ */ + public io.grpc.stub.StreamObserver doHandshake( + io.grpc.stub.StreamObserver responseObserver) { + return asyncBidiStreamingCall( + getChannel().newCall(getDoHandshakeMethod(), getCallOptions()), responseObserver); + } + } + + /** + */ + public static final class HandshakerServiceBlockingStub extends io.grpc.stub.AbstractStub { + private HandshakerServiceBlockingStub(io.grpc.Channel channel) { + super(channel); + } + + private HandshakerServiceBlockingStub(io.grpc.Channel channel, + io.grpc.CallOptions callOptions) { + super(channel, callOptions); + } + + @java.lang.Override + protected HandshakerServiceBlockingStub build(io.grpc.Channel channel, + io.grpc.CallOptions callOptions) { + return new HandshakerServiceBlockingStub(channel, callOptions); + } + } + + /** + */ + public static final class HandshakerServiceFutureStub extends io.grpc.stub.AbstractStub { + private HandshakerServiceFutureStub(io.grpc.Channel channel) { + super(channel); + } + + private HandshakerServiceFutureStub(io.grpc.Channel channel, + io.grpc.CallOptions callOptions) { + super(channel, callOptions); + } + + @java.lang.Override + protected HandshakerServiceFutureStub build(io.grpc.Channel channel, + io.grpc.CallOptions callOptions) { + return new HandshakerServiceFutureStub(channel, callOptions); + } + } + + private static final int METHODID_DO_HANDSHAKE = 0; + + private static final class MethodHandlers implements + io.grpc.stub.ServerCalls.UnaryMethod, + io.grpc.stub.ServerCalls.ServerStreamingMethod, + io.grpc.stub.ServerCalls.ClientStreamingMethod, + io.grpc.stub.ServerCalls.BidiStreamingMethod { + private final HandshakerServiceImplBase serviceImpl; + private final int methodId; + + MethodHandlers(HandshakerServiceImplBase serviceImpl, int methodId) { + this.serviceImpl = serviceImpl; + this.methodId = methodId; + } + + @java.lang.Override + @java.lang.SuppressWarnings("unchecked") + public void invoke(Req request, io.grpc.stub.StreamObserver responseObserver) { + switch (methodId) { + default: + throw new AssertionError(); + } + } + + @java.lang.Override + @java.lang.SuppressWarnings("unchecked") + public io.grpc.stub.StreamObserver invoke( + io.grpc.stub.StreamObserver responseObserver) { + switch (methodId) { + case METHODID_DO_HANDSHAKE: + return (io.grpc.stub.StreamObserver) serviceImpl.doHandshake( + (io.grpc.stub.StreamObserver) responseObserver); + default: + throw new AssertionError(); + } + } + } + + private static abstract class HandshakerServiceBaseDescriptorSupplier + implements io.grpc.protobuf.ProtoFileDescriptorSupplier, io.grpc.protobuf.ProtoServiceDescriptorSupplier { + HandshakerServiceBaseDescriptorSupplier() {} + + @java.lang.Override + public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() { + return io.grpc.alts.internal.Handshaker.getDescriptor(); + } + + @java.lang.Override + public com.google.protobuf.Descriptors.ServiceDescriptor getServiceDescriptor() { + return getFileDescriptor().findServiceByName("HandshakerService"); + } + } + + private static final class HandshakerServiceFileDescriptorSupplier + extends HandshakerServiceBaseDescriptorSupplier { + HandshakerServiceFileDescriptorSupplier() {} + } + + private static final class HandshakerServiceMethodDescriptorSupplier + extends HandshakerServiceBaseDescriptorSupplier + implements io.grpc.protobuf.ProtoMethodDescriptorSupplier { + private final String methodName; + + HandshakerServiceMethodDescriptorSupplier(String methodName) { + this.methodName = methodName; + } + + @java.lang.Override + public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() { + return getServiceDescriptor().findMethodByName(methodName); + } + } + + private static volatile io.grpc.ServiceDescriptor serviceDescriptor; + + public static io.grpc.ServiceDescriptor getServiceDescriptor() { + io.grpc.ServiceDescriptor result = serviceDescriptor; + if (result == null) { + synchronized (HandshakerServiceGrpc.class) { + result = serviceDescriptor; + if (result == null) { + serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME) + .setSchemaDescriptor(new HandshakerServiceFileDescriptorSupplier()) + .addMethod(getDoHandshakeMethod()) + .build(); + } + } + } + return result; + } +} diff --git a/alts/src/generated/main/java/io/grpc/alts/internal/Altscontext.java b/alts/src/generated/main/java/io/grpc/alts/internal/Altscontext.java new file mode 100644 index 0000000000000000000000000000000000000000..d036c2e143bb8192cecda0726fc2c41220413e72 --- /dev/null +++ b/alts/src/generated/main/java/io/grpc/alts/internal/Altscontext.java @@ -0,0 +1,1526 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: grpc/gcp/altscontext.proto + +package io.grpc.alts.internal; + +public final class Altscontext { + private Altscontext() {} + public static void registerAllExtensions( + com.google.protobuf.ExtensionRegistryLite registry) { + } + + public static void registerAllExtensions( + com.google.protobuf.ExtensionRegistry registry) { + registerAllExtensions( + (com.google.protobuf.ExtensionRegistryLite) registry); + } + public interface AltsContextOrBuilder extends + // @@protoc_insertion_point(interface_extends:grpc.gcp.AltsContext) + com.google.protobuf.MessageOrBuilder { + + /** + *
+     * The application protocol negotiated for this connection.
+     * 
+ * + * string application_protocol = 1; + */ + java.lang.String getApplicationProtocol(); + /** + *
+     * The application protocol negotiated for this connection.
+     * 
+ * + * string application_protocol = 1; + */ + com.google.protobuf.ByteString + getApplicationProtocolBytes(); + + /** + *
+     * The record protocol negotiated for this connection.
+     * 
+ * + * string record_protocol = 2; + */ + java.lang.String getRecordProtocol(); + /** + *
+     * The record protocol negotiated for this connection.
+     * 
+ * + * string record_protocol = 2; + */ + com.google.protobuf.ByteString + getRecordProtocolBytes(); + + /** + *
+     * The security level of the created secure channel.
+     * 
+ * + * .grpc.gcp.SecurityLevel security_level = 3; + */ + int getSecurityLevelValue(); + /** + *
+     * The security level of the created secure channel.
+     * 
+ * + * .grpc.gcp.SecurityLevel security_level = 3; + */ + io.grpc.alts.internal.TransportSecurityCommon.SecurityLevel getSecurityLevel(); + + /** + *
+     * The peer service account.
+     * 
+ * + * string peer_service_account = 4; + */ + java.lang.String getPeerServiceAccount(); + /** + *
+     * The peer service account.
+     * 
+ * + * string peer_service_account = 4; + */ + com.google.protobuf.ByteString + getPeerServiceAccountBytes(); + + /** + *
+     * The local service account.
+     * 
+ * + * string local_service_account = 5; + */ + java.lang.String getLocalServiceAccount(); + /** + *
+     * The local service account.
+     * 
+ * + * string local_service_account = 5; + */ + com.google.protobuf.ByteString + getLocalServiceAccountBytes(); + + /** + *
+     * The RPC protocol versions supported by the peer.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions peer_rpc_versions = 6; + */ + boolean hasPeerRpcVersions(); + /** + *
+     * The RPC protocol versions supported by the peer.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions peer_rpc_versions = 6; + */ + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions getPeerRpcVersions(); + /** + *
+     * The RPC protocol versions supported by the peer.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions peer_rpc_versions = 6; + */ + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersionsOrBuilder getPeerRpcVersionsOrBuilder(); + } + /** + * Protobuf type {@code grpc.gcp.AltsContext} + */ + public static final class AltsContext extends + com.google.protobuf.GeneratedMessageV3 implements + // @@protoc_insertion_point(message_implements:grpc.gcp.AltsContext) + AltsContextOrBuilder { + private static final long serialVersionUID = 0L; + // Use AltsContext.newBuilder() to construct. + private AltsContext(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + private AltsContext() { + applicationProtocol_ = ""; + recordProtocol_ = ""; + securityLevel_ = 0; + peerServiceAccount_ = ""; + localServiceAccount_ = ""; + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return this.unknownFields; + } + private AltsContext( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownFieldProto3( + input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 10: { + java.lang.String s = input.readStringRequireUtf8(); + + applicationProtocol_ = s; + break; + } + case 18: { + java.lang.String s = input.readStringRequireUtf8(); + + recordProtocol_ = s; + break; + } + case 24: { + int rawValue = input.readEnum(); + + securityLevel_ = rawValue; + break; + } + case 34: { + java.lang.String s = input.readStringRequireUtf8(); + + peerServiceAccount_ = s; + break; + } + case 42: { + java.lang.String s = input.readStringRequireUtf8(); + + localServiceAccount_ = s; + break; + } + case 50: { + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Builder subBuilder = null; + if (peerRpcVersions_ != null) { + subBuilder = peerRpcVersions_.toBuilder(); + } + peerRpcVersions_ = input.readMessage(io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.parser(), extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(peerRpcVersions_); + peerRpcVersions_ = subBuilder.buildPartial(); + } + + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return io.grpc.alts.internal.Altscontext.internal_static_grpc_gcp_AltsContext_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return io.grpc.alts.internal.Altscontext.internal_static_grpc_gcp_AltsContext_fieldAccessorTable + .ensureFieldAccessorsInitialized( + io.grpc.alts.internal.Altscontext.AltsContext.class, io.grpc.alts.internal.Altscontext.AltsContext.Builder.class); + } + + public static final int APPLICATION_PROTOCOL_FIELD_NUMBER = 1; + private volatile java.lang.Object applicationProtocol_; + /** + *
+     * The application protocol negotiated for this connection.
+     * 
+ * + * string application_protocol = 1; + */ + public java.lang.String getApplicationProtocol() { + java.lang.Object ref = applicationProtocol_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + applicationProtocol_ = s; + return s; + } + } + /** + *
+     * The application protocol negotiated for this connection.
+     * 
+ * + * string application_protocol = 1; + */ + public com.google.protobuf.ByteString + getApplicationProtocolBytes() { + java.lang.Object ref = applicationProtocol_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (java.lang.String) ref); + applicationProtocol_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int RECORD_PROTOCOL_FIELD_NUMBER = 2; + private volatile java.lang.Object recordProtocol_; + /** + *
+     * The record protocol negotiated for this connection.
+     * 
+ * + * string record_protocol = 2; + */ + public java.lang.String getRecordProtocol() { + java.lang.Object ref = recordProtocol_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + recordProtocol_ = s; + return s; + } + } + /** + *
+     * The record protocol negotiated for this connection.
+     * 
+ * + * string record_protocol = 2; + */ + public com.google.protobuf.ByteString + getRecordProtocolBytes() { + java.lang.Object ref = recordProtocol_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (java.lang.String) ref); + recordProtocol_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int SECURITY_LEVEL_FIELD_NUMBER = 3; + private int securityLevel_; + /** + *
+     * The security level of the created secure channel.
+     * 
+ * + * .grpc.gcp.SecurityLevel security_level = 3; + */ + public int getSecurityLevelValue() { + return securityLevel_; + } + /** + *
+     * The security level of the created secure channel.
+     * 
+ * + * .grpc.gcp.SecurityLevel security_level = 3; + */ + public io.grpc.alts.internal.TransportSecurityCommon.SecurityLevel getSecurityLevel() { + io.grpc.alts.internal.TransportSecurityCommon.SecurityLevel result = io.grpc.alts.internal.TransportSecurityCommon.SecurityLevel.valueOf(securityLevel_); + return result == null ? io.grpc.alts.internal.TransportSecurityCommon.SecurityLevel.UNRECOGNIZED : result; + } + + public static final int PEER_SERVICE_ACCOUNT_FIELD_NUMBER = 4; + private volatile java.lang.Object peerServiceAccount_; + /** + *
+     * The peer service account.
+     * 
+ * + * string peer_service_account = 4; + */ + public java.lang.String getPeerServiceAccount() { + java.lang.Object ref = peerServiceAccount_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + peerServiceAccount_ = s; + return s; + } + } + /** + *
+     * The peer service account.
+     * 
+ * + * string peer_service_account = 4; + */ + public com.google.protobuf.ByteString + getPeerServiceAccountBytes() { + java.lang.Object ref = peerServiceAccount_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (java.lang.String) ref); + peerServiceAccount_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int LOCAL_SERVICE_ACCOUNT_FIELD_NUMBER = 5; + private volatile java.lang.Object localServiceAccount_; + /** + *
+     * The local service account.
+     * 
+ * + * string local_service_account = 5; + */ + public java.lang.String getLocalServiceAccount() { + java.lang.Object ref = localServiceAccount_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + localServiceAccount_ = s; + return s; + } + } + /** + *
+     * The local service account.
+     * 
+ * + * string local_service_account = 5; + */ + public com.google.protobuf.ByteString + getLocalServiceAccountBytes() { + java.lang.Object ref = localServiceAccount_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (java.lang.String) ref); + localServiceAccount_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int PEER_RPC_VERSIONS_FIELD_NUMBER = 6; + private io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions peerRpcVersions_; + /** + *
+     * The RPC protocol versions supported by the peer.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions peer_rpc_versions = 6; + */ + public boolean hasPeerRpcVersions() { + return peerRpcVersions_ != null; + } + /** + *
+     * The RPC protocol versions supported by the peer.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions peer_rpc_versions = 6; + */ + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions getPeerRpcVersions() { + return peerRpcVersions_ == null ? io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.getDefaultInstance() : peerRpcVersions_; + } + /** + *
+     * The RPC protocol versions supported by the peer.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions peer_rpc_versions = 6; + */ + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersionsOrBuilder getPeerRpcVersionsOrBuilder() { + return getPeerRpcVersions(); + } + + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + if (!getApplicationProtocolBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 1, applicationProtocol_); + } + if (!getRecordProtocolBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 2, recordProtocol_); + } + if (securityLevel_ != io.grpc.alts.internal.TransportSecurityCommon.SecurityLevel.SECURITY_NONE.getNumber()) { + output.writeEnum(3, securityLevel_); + } + if (!getPeerServiceAccountBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 4, peerServiceAccount_); + } + if (!getLocalServiceAccountBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 5, localServiceAccount_); + } + if (peerRpcVersions_ != null) { + output.writeMessage(6, getPeerRpcVersions()); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (!getApplicationProtocolBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, applicationProtocol_); + } + if (!getRecordProtocolBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, recordProtocol_); + } + if (securityLevel_ != io.grpc.alts.internal.TransportSecurityCommon.SecurityLevel.SECURITY_NONE.getNumber()) { + size += com.google.protobuf.CodedOutputStream + .computeEnumSize(3, securityLevel_); + } + if (!getPeerServiceAccountBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, peerServiceAccount_); + } + if (!getLocalServiceAccountBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, localServiceAccount_); + } + if (peerRpcVersions_ != null) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(6, getPeerRpcVersions()); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof io.grpc.alts.internal.Altscontext.AltsContext)) { + return super.equals(obj); + } + io.grpc.alts.internal.Altscontext.AltsContext other = (io.grpc.alts.internal.Altscontext.AltsContext) obj; + + boolean result = true; + result = result && getApplicationProtocol() + .equals(other.getApplicationProtocol()); + result = result && getRecordProtocol() + .equals(other.getRecordProtocol()); + result = result && securityLevel_ == other.securityLevel_; + result = result && getPeerServiceAccount() + .equals(other.getPeerServiceAccount()); + result = result && getLocalServiceAccount() + .equals(other.getLocalServiceAccount()); + result = result && (hasPeerRpcVersions() == other.hasPeerRpcVersions()); + if (hasPeerRpcVersions()) { + result = result && getPeerRpcVersions() + .equals(other.getPeerRpcVersions()); + } + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + hash = (37 * hash) + APPLICATION_PROTOCOL_FIELD_NUMBER; + hash = (53 * hash) + getApplicationProtocol().hashCode(); + hash = (37 * hash) + RECORD_PROTOCOL_FIELD_NUMBER; + hash = (53 * hash) + getRecordProtocol().hashCode(); + hash = (37 * hash) + SECURITY_LEVEL_FIELD_NUMBER; + hash = (53 * hash) + securityLevel_; + hash = (37 * hash) + PEER_SERVICE_ACCOUNT_FIELD_NUMBER; + hash = (53 * hash) + getPeerServiceAccount().hashCode(); + hash = (37 * hash) + LOCAL_SERVICE_ACCOUNT_FIELD_NUMBER; + hash = (53 * hash) + getLocalServiceAccount().hashCode(); + if (hasPeerRpcVersions()) { + hash = (37 * hash) + PEER_RPC_VERSIONS_FIELD_NUMBER; + hash = (53 * hash) + getPeerRpcVersions().hashCode(); + } + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static io.grpc.alts.internal.Altscontext.AltsContext parseFrom( + java.nio.ByteBuffer data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Altscontext.AltsContext parseFrom( + java.nio.ByteBuffer data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Altscontext.AltsContext parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Altscontext.AltsContext parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Altscontext.AltsContext parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Altscontext.AltsContext parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Altscontext.AltsContext parseFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Altscontext.AltsContext parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + public static io.grpc.alts.internal.Altscontext.AltsContext parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Altscontext.AltsContext parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input, extensionRegistry); + } + public static io.grpc.alts.internal.Altscontext.AltsContext parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Altscontext.AltsContext parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + public static Builder newBuilder(io.grpc.alts.internal.Altscontext.AltsContext prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { + return this == DEFAULT_INSTANCE + ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + * Protobuf type {@code grpc.gcp.AltsContext} + */ + public static final class Builder extends + com.google.protobuf.GeneratedMessageV3.Builder implements + // @@protoc_insertion_point(builder_implements:grpc.gcp.AltsContext) + io.grpc.alts.internal.Altscontext.AltsContextOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return io.grpc.alts.internal.Altscontext.internal_static_grpc_gcp_AltsContext_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return io.grpc.alts.internal.Altscontext.internal_static_grpc_gcp_AltsContext_fieldAccessorTable + .ensureFieldAccessorsInitialized( + io.grpc.alts.internal.Altscontext.AltsContext.class, io.grpc.alts.internal.Altscontext.AltsContext.Builder.class); + } + + // Construct using io.grpc.alts.internal.Altscontext.AltsContext.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder( + com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3 + .alwaysUseFieldBuilders) { + } + } + public Builder clear() { + super.clear(); + applicationProtocol_ = ""; + + recordProtocol_ = ""; + + securityLevel_ = 0; + + peerServiceAccount_ = ""; + + localServiceAccount_ = ""; + + if (peerRpcVersionsBuilder_ == null) { + peerRpcVersions_ = null; + } else { + peerRpcVersions_ = null; + peerRpcVersionsBuilder_ = null; + } + return this; + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return io.grpc.alts.internal.Altscontext.internal_static_grpc_gcp_AltsContext_descriptor; + } + + public io.grpc.alts.internal.Altscontext.AltsContext getDefaultInstanceForType() { + return io.grpc.alts.internal.Altscontext.AltsContext.getDefaultInstance(); + } + + public io.grpc.alts.internal.Altscontext.AltsContext build() { + io.grpc.alts.internal.Altscontext.AltsContext result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public io.grpc.alts.internal.Altscontext.AltsContext buildPartial() { + io.grpc.alts.internal.Altscontext.AltsContext result = new io.grpc.alts.internal.Altscontext.AltsContext(this); + result.applicationProtocol_ = applicationProtocol_; + result.recordProtocol_ = recordProtocol_; + result.securityLevel_ = securityLevel_; + result.peerServiceAccount_ = peerServiceAccount_; + result.localServiceAccount_ = localServiceAccount_; + if (peerRpcVersionsBuilder_ == null) { + result.peerRpcVersions_ = peerRpcVersions_; + } else { + result.peerRpcVersions_ = peerRpcVersionsBuilder_.build(); + } + onBuilt(); + return result; + } + + public Builder clone() { + return (Builder) super.clone(); + } + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, + java.lang.Object value) { + return (Builder) super.setField(field, value); + } + public Builder clearField( + com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); + } + public Builder clearOneof( + com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); + } + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); + } + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); + } + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof io.grpc.alts.internal.Altscontext.AltsContext) { + return mergeFrom((io.grpc.alts.internal.Altscontext.AltsContext)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(io.grpc.alts.internal.Altscontext.AltsContext other) { + if (other == io.grpc.alts.internal.Altscontext.AltsContext.getDefaultInstance()) return this; + if (!other.getApplicationProtocol().isEmpty()) { + applicationProtocol_ = other.applicationProtocol_; + onChanged(); + } + if (!other.getRecordProtocol().isEmpty()) { + recordProtocol_ = other.recordProtocol_; + onChanged(); + } + if (other.securityLevel_ != 0) { + setSecurityLevelValue(other.getSecurityLevelValue()); + } + if (!other.getPeerServiceAccount().isEmpty()) { + peerServiceAccount_ = other.peerServiceAccount_; + onChanged(); + } + if (!other.getLocalServiceAccount().isEmpty()) { + localServiceAccount_ = other.localServiceAccount_; + onChanged(); + } + if (other.hasPeerRpcVersions()) { + mergePeerRpcVersions(other.getPeerRpcVersions()); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + io.grpc.alts.internal.Altscontext.AltsContext parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (io.grpc.alts.internal.Altscontext.AltsContext) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + private java.lang.Object applicationProtocol_ = ""; + /** + *
+       * The application protocol negotiated for this connection.
+       * 
+ * + * string application_protocol = 1; + */ + public java.lang.String getApplicationProtocol() { + java.lang.Object ref = applicationProtocol_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + applicationProtocol_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + /** + *
+       * The application protocol negotiated for this connection.
+       * 
+ * + * string application_protocol = 1; + */ + public com.google.protobuf.ByteString + getApplicationProtocolBytes() { + java.lang.Object ref = applicationProtocol_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (java.lang.String) ref); + applicationProtocol_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + /** + *
+       * The application protocol negotiated for this connection.
+       * 
+ * + * string application_protocol = 1; + */ + public Builder setApplicationProtocol( + java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + + applicationProtocol_ = value; + onChanged(); + return this; + } + /** + *
+       * The application protocol negotiated for this connection.
+       * 
+ * + * string application_protocol = 1; + */ + public Builder clearApplicationProtocol() { + + applicationProtocol_ = getDefaultInstance().getApplicationProtocol(); + onChanged(); + return this; + } + /** + *
+       * The application protocol negotiated for this connection.
+       * 
+ * + * string application_protocol = 1; + */ + public Builder setApplicationProtocolBytes( + com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + + applicationProtocol_ = value; + onChanged(); + return this; + } + + private java.lang.Object recordProtocol_ = ""; + /** + *
+       * The record protocol negotiated for this connection.
+       * 
+ * + * string record_protocol = 2; + */ + public java.lang.String getRecordProtocol() { + java.lang.Object ref = recordProtocol_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + recordProtocol_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + /** + *
+       * The record protocol negotiated for this connection.
+       * 
+ * + * string record_protocol = 2; + */ + public com.google.protobuf.ByteString + getRecordProtocolBytes() { + java.lang.Object ref = recordProtocol_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (java.lang.String) ref); + recordProtocol_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + /** + *
+       * The record protocol negotiated for this connection.
+       * 
+ * + * string record_protocol = 2; + */ + public Builder setRecordProtocol( + java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + + recordProtocol_ = value; + onChanged(); + return this; + } + /** + *
+       * The record protocol negotiated for this connection.
+       * 
+ * + * string record_protocol = 2; + */ + public Builder clearRecordProtocol() { + + recordProtocol_ = getDefaultInstance().getRecordProtocol(); + onChanged(); + return this; + } + /** + *
+       * The record protocol negotiated for this connection.
+       * 
+ * + * string record_protocol = 2; + */ + public Builder setRecordProtocolBytes( + com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + + recordProtocol_ = value; + onChanged(); + return this; + } + + private int securityLevel_ = 0; + /** + *
+       * The security level of the created secure channel.
+       * 
+ * + * .grpc.gcp.SecurityLevel security_level = 3; + */ + public int getSecurityLevelValue() { + return securityLevel_; + } + /** + *
+       * The security level of the created secure channel.
+       * 
+ * + * .grpc.gcp.SecurityLevel security_level = 3; + */ + public Builder setSecurityLevelValue(int value) { + securityLevel_ = value; + onChanged(); + return this; + } + /** + *
+       * The security level of the created secure channel.
+       * 
+ * + * .grpc.gcp.SecurityLevel security_level = 3; + */ + public io.grpc.alts.internal.TransportSecurityCommon.SecurityLevel getSecurityLevel() { + io.grpc.alts.internal.TransportSecurityCommon.SecurityLevel result = io.grpc.alts.internal.TransportSecurityCommon.SecurityLevel.valueOf(securityLevel_); + return result == null ? io.grpc.alts.internal.TransportSecurityCommon.SecurityLevel.UNRECOGNIZED : result; + } + /** + *
+       * The security level of the created secure channel.
+       * 
+ * + * .grpc.gcp.SecurityLevel security_level = 3; + */ + public Builder setSecurityLevel(io.grpc.alts.internal.TransportSecurityCommon.SecurityLevel value) { + if (value == null) { + throw new NullPointerException(); + } + + securityLevel_ = value.getNumber(); + onChanged(); + return this; + } + /** + *
+       * The security level of the created secure channel.
+       * 
+ * + * .grpc.gcp.SecurityLevel security_level = 3; + */ + public Builder clearSecurityLevel() { + + securityLevel_ = 0; + onChanged(); + return this; + } + + private java.lang.Object peerServiceAccount_ = ""; + /** + *
+       * The peer service account.
+       * 
+ * + * string peer_service_account = 4; + */ + public java.lang.String getPeerServiceAccount() { + java.lang.Object ref = peerServiceAccount_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + peerServiceAccount_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + /** + *
+       * The peer service account.
+       * 
+ * + * string peer_service_account = 4; + */ + public com.google.protobuf.ByteString + getPeerServiceAccountBytes() { + java.lang.Object ref = peerServiceAccount_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (java.lang.String) ref); + peerServiceAccount_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + /** + *
+       * The peer service account.
+       * 
+ * + * string peer_service_account = 4; + */ + public Builder setPeerServiceAccount( + java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + + peerServiceAccount_ = value; + onChanged(); + return this; + } + /** + *
+       * The peer service account.
+       * 
+ * + * string peer_service_account = 4; + */ + public Builder clearPeerServiceAccount() { + + peerServiceAccount_ = getDefaultInstance().getPeerServiceAccount(); + onChanged(); + return this; + } + /** + *
+       * The peer service account.
+       * 
+ * + * string peer_service_account = 4; + */ + public Builder setPeerServiceAccountBytes( + com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + + peerServiceAccount_ = value; + onChanged(); + return this; + } + + private java.lang.Object localServiceAccount_ = ""; + /** + *
+       * The local service account.
+       * 
+ * + * string local_service_account = 5; + */ + public java.lang.String getLocalServiceAccount() { + java.lang.Object ref = localServiceAccount_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + localServiceAccount_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + /** + *
+       * The local service account.
+       * 
+ * + * string local_service_account = 5; + */ + public com.google.protobuf.ByteString + getLocalServiceAccountBytes() { + java.lang.Object ref = localServiceAccount_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (java.lang.String) ref); + localServiceAccount_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + /** + *
+       * The local service account.
+       * 
+ * + * string local_service_account = 5; + */ + public Builder setLocalServiceAccount( + java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + + localServiceAccount_ = value; + onChanged(); + return this; + } + /** + *
+       * The local service account.
+       * 
+ * + * string local_service_account = 5; + */ + public Builder clearLocalServiceAccount() { + + localServiceAccount_ = getDefaultInstance().getLocalServiceAccount(); + onChanged(); + return this; + } + /** + *
+       * The local service account.
+       * 
+ * + * string local_service_account = 5; + */ + public Builder setLocalServiceAccountBytes( + com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + + localServiceAccount_ = value; + onChanged(); + return this; + } + + private io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions peerRpcVersions_ = null; + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Builder, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersionsOrBuilder> peerRpcVersionsBuilder_; + /** + *
+       * The RPC protocol versions supported by the peer.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions peer_rpc_versions = 6; + */ + public boolean hasPeerRpcVersions() { + return peerRpcVersionsBuilder_ != null || peerRpcVersions_ != null; + } + /** + *
+       * The RPC protocol versions supported by the peer.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions peer_rpc_versions = 6; + */ + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions getPeerRpcVersions() { + if (peerRpcVersionsBuilder_ == null) { + return peerRpcVersions_ == null ? io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.getDefaultInstance() : peerRpcVersions_; + } else { + return peerRpcVersionsBuilder_.getMessage(); + } + } + /** + *
+       * The RPC protocol versions supported by the peer.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions peer_rpc_versions = 6; + */ + public Builder setPeerRpcVersions(io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions value) { + if (peerRpcVersionsBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + peerRpcVersions_ = value; + onChanged(); + } else { + peerRpcVersionsBuilder_.setMessage(value); + } + + return this; + } + /** + *
+       * The RPC protocol versions supported by the peer.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions peer_rpc_versions = 6; + */ + public Builder setPeerRpcVersions( + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Builder builderForValue) { + if (peerRpcVersionsBuilder_ == null) { + peerRpcVersions_ = builderForValue.build(); + onChanged(); + } else { + peerRpcVersionsBuilder_.setMessage(builderForValue.build()); + } + + return this; + } + /** + *
+       * The RPC protocol versions supported by the peer.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions peer_rpc_versions = 6; + */ + public Builder mergePeerRpcVersions(io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions value) { + if (peerRpcVersionsBuilder_ == null) { + if (peerRpcVersions_ != null) { + peerRpcVersions_ = + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.newBuilder(peerRpcVersions_).mergeFrom(value).buildPartial(); + } else { + peerRpcVersions_ = value; + } + onChanged(); + } else { + peerRpcVersionsBuilder_.mergeFrom(value); + } + + return this; + } + /** + *
+       * The RPC protocol versions supported by the peer.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions peer_rpc_versions = 6; + */ + public Builder clearPeerRpcVersions() { + if (peerRpcVersionsBuilder_ == null) { + peerRpcVersions_ = null; + onChanged(); + } else { + peerRpcVersions_ = null; + peerRpcVersionsBuilder_ = null; + } + + return this; + } + /** + *
+       * The RPC protocol versions supported by the peer.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions peer_rpc_versions = 6; + */ + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Builder getPeerRpcVersionsBuilder() { + + onChanged(); + return getPeerRpcVersionsFieldBuilder().getBuilder(); + } + /** + *
+       * The RPC protocol versions supported by the peer.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions peer_rpc_versions = 6; + */ + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersionsOrBuilder getPeerRpcVersionsOrBuilder() { + if (peerRpcVersionsBuilder_ != null) { + return peerRpcVersionsBuilder_.getMessageOrBuilder(); + } else { + return peerRpcVersions_ == null ? + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.getDefaultInstance() : peerRpcVersions_; + } + } + /** + *
+       * The RPC protocol versions supported by the peer.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions peer_rpc_versions = 6; + */ + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Builder, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersionsOrBuilder> + getPeerRpcVersionsFieldBuilder() { + if (peerRpcVersionsBuilder_ == null) { + peerRpcVersionsBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Builder, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersionsOrBuilder>( + getPeerRpcVersions(), + getParentForChildren(), + isClean()); + peerRpcVersions_ = null; + } + return peerRpcVersionsBuilder_; + } + public final Builder setUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); + } + + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + + // @@protoc_insertion_point(builder_scope:grpc.gcp.AltsContext) + } + + // @@protoc_insertion_point(class_scope:grpc.gcp.AltsContext) + private static final io.grpc.alts.internal.Altscontext.AltsContext DEFAULT_INSTANCE; + static { + DEFAULT_INSTANCE = new io.grpc.alts.internal.Altscontext.AltsContext(); + } + + public static io.grpc.alts.internal.Altscontext.AltsContext getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + private static final com.google.protobuf.Parser + PARSER = new com.google.protobuf.AbstractParser() { + public AltsContext parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new AltsContext(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public io.grpc.alts.internal.Altscontext.AltsContext getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } + + } + + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_grpc_gcp_AltsContext_descriptor; + private static final + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_grpc_gcp_AltsContext_fieldAccessorTable; + + public static com.google.protobuf.Descriptors.FileDescriptor + getDescriptor() { + return descriptor; + } + private static com.google.protobuf.Descriptors.FileDescriptor + descriptor; + static { + java.lang.String[] descriptorData = { + "\n\032grpc/gcp/altscontext.proto\022\010grpc.gcp\032(" + + "grpc/gcp/transport_security_common.proto" + + "\"\354\001\n\013AltsContext\022\034\n\024application_protocol" + + "\030\001 \001(\t\022\027\n\017record_protocol\030\002 \001(\t\022/\n\016secur" + + "ity_level\030\003 \001(\0162\027.grpc.gcp.SecurityLevel" + + "\022\034\n\024peer_service_account\030\004 \001(\t\022\035\n\025local_" + + "service_account\030\005 \001(\t\0228\n\021peer_rpc_versio" + + "ns\030\006 \001(\0132\035.grpc.gcp.RpcProtocolVersionsB" + + "\027\n\025io.grpc.alts.internalb\006proto3" + }; + com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = + new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { + public com.google.protobuf.ExtensionRegistry assignDescriptors( + com.google.protobuf.Descriptors.FileDescriptor root) { + descriptor = root; + return null; + } + }; + com.google.protobuf.Descriptors.FileDescriptor + .internalBuildGeneratedFileFrom(descriptorData, + new com.google.protobuf.Descriptors.FileDescriptor[] { + io.grpc.alts.internal.TransportSecurityCommon.getDescriptor(), + }, assigner); + internal_static_grpc_gcp_AltsContext_descriptor = + getDescriptor().getMessageTypes().get(0); + internal_static_grpc_gcp_AltsContext_fieldAccessorTable = new + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_grpc_gcp_AltsContext_descriptor, + new java.lang.String[] { "ApplicationProtocol", "RecordProtocol", "SecurityLevel", "PeerServiceAccount", "LocalServiceAccount", "PeerRpcVersions", }); + io.grpc.alts.internal.TransportSecurityCommon.getDescriptor(); + } + + // @@protoc_insertion_point(outer_class_scope) +} diff --git a/alts/src/generated/main/java/io/grpc/alts/internal/Handshaker.java b/alts/src/generated/main/java/io/grpc/alts/internal/Handshaker.java new file mode 100644 index 0000000000000000000000000000000000000000..51dc505fb805dfb3f78384e39c0314a01ea52c26 --- /dev/null +++ b/alts/src/generated/main/java/io/grpc/alts/internal/Handshaker.java @@ -0,0 +1,13320 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: grpc/gcp/handshaker.proto + +package io.grpc.alts.internal; + +public final class Handshaker { + private Handshaker() {} + public static void registerAllExtensions( + com.google.protobuf.ExtensionRegistryLite registry) { + } + + public static void registerAllExtensions( + com.google.protobuf.ExtensionRegistry registry) { + registerAllExtensions( + (com.google.protobuf.ExtensionRegistryLite) registry); + } + /** + * Protobuf enum {@code grpc.gcp.HandshakeProtocol} + */ + public enum HandshakeProtocol + implements com.google.protobuf.ProtocolMessageEnum { + /** + *
+     * Default value.
+     * 
+ * + * HANDSHAKE_PROTOCOL_UNSPECIFIED = 0; + */ + HANDSHAKE_PROTOCOL_UNSPECIFIED(0), + /** + *
+     * TLS handshake protocol.
+     * 
+ * + * TLS = 1; + */ + TLS(1), + /** + *
+     * Application Layer Transport Security handshake protocol.
+     * 
+ * + * ALTS = 2; + */ + ALTS(2), + UNRECOGNIZED(-1), + ; + + /** + *
+     * Default value.
+     * 
+ * + * HANDSHAKE_PROTOCOL_UNSPECIFIED = 0; + */ + public static final int HANDSHAKE_PROTOCOL_UNSPECIFIED_VALUE = 0; + /** + *
+     * TLS handshake protocol.
+     * 
+ * + * TLS = 1; + */ + public static final int TLS_VALUE = 1; + /** + *
+     * Application Layer Transport Security handshake protocol.
+     * 
+ * + * ALTS = 2; + */ + public static final int ALTS_VALUE = 2; + + + public final int getNumber() { + if (this == UNRECOGNIZED) { + throw new java.lang.IllegalArgumentException( + "Can't get the number of an unknown enum value."); + } + return value; + } + + /** + * @deprecated Use {@link #forNumber(int)} instead. + */ + @java.lang.Deprecated + public static HandshakeProtocol valueOf(int value) { + return forNumber(value); + } + + public static HandshakeProtocol forNumber(int value) { + switch (value) { + case 0: return HANDSHAKE_PROTOCOL_UNSPECIFIED; + case 1: return TLS; + case 2: return ALTS; + default: return null; + } + } + + public static com.google.protobuf.Internal.EnumLiteMap + internalGetValueMap() { + return internalValueMap; + } + private static final com.google.protobuf.Internal.EnumLiteMap< + HandshakeProtocol> internalValueMap = + new com.google.protobuf.Internal.EnumLiteMap() { + public HandshakeProtocol findValueByNumber(int number) { + return HandshakeProtocol.forNumber(number); + } + }; + + public final com.google.protobuf.Descriptors.EnumValueDescriptor + getValueDescriptor() { + return getDescriptor().getValues().get(ordinal()); + } + public final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptorForType() { + return getDescriptor(); + } + public static final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptor() { + return io.grpc.alts.internal.Handshaker.getDescriptor().getEnumTypes().get(0); + } + + private static final HandshakeProtocol[] VALUES = values(); + + public static HandshakeProtocol valueOf( + com.google.protobuf.Descriptors.EnumValueDescriptor desc) { + if (desc.getType() != getDescriptor()) { + throw new java.lang.IllegalArgumentException( + "EnumValueDescriptor is not for this type."); + } + if (desc.getIndex() == -1) { + return UNRECOGNIZED; + } + return VALUES[desc.getIndex()]; + } + + private final int value; + + private HandshakeProtocol(int value) { + this.value = value; + } + + // @@protoc_insertion_point(enum_scope:grpc.gcp.HandshakeProtocol) + } + + /** + * Protobuf enum {@code grpc.gcp.NetworkProtocol} + */ + public enum NetworkProtocol + implements com.google.protobuf.ProtocolMessageEnum { + /** + * NETWORK_PROTOCOL_UNSPECIFIED = 0; + */ + NETWORK_PROTOCOL_UNSPECIFIED(0), + /** + * TCP = 1; + */ + TCP(1), + /** + * UDP = 2; + */ + UDP(2), + UNRECOGNIZED(-1), + ; + + /** + * NETWORK_PROTOCOL_UNSPECIFIED = 0; + */ + public static final int NETWORK_PROTOCOL_UNSPECIFIED_VALUE = 0; + /** + * TCP = 1; + */ + public static final int TCP_VALUE = 1; + /** + * UDP = 2; + */ + public static final int UDP_VALUE = 2; + + + public final int getNumber() { + if (this == UNRECOGNIZED) { + throw new java.lang.IllegalArgumentException( + "Can't get the number of an unknown enum value."); + } + return value; + } + + /** + * @deprecated Use {@link #forNumber(int)} instead. + */ + @java.lang.Deprecated + public static NetworkProtocol valueOf(int value) { + return forNumber(value); + } + + public static NetworkProtocol forNumber(int value) { + switch (value) { + case 0: return NETWORK_PROTOCOL_UNSPECIFIED; + case 1: return TCP; + case 2: return UDP; + default: return null; + } + } + + public static com.google.protobuf.Internal.EnumLiteMap + internalGetValueMap() { + return internalValueMap; + } + private static final com.google.protobuf.Internal.EnumLiteMap< + NetworkProtocol> internalValueMap = + new com.google.protobuf.Internal.EnumLiteMap() { + public NetworkProtocol findValueByNumber(int number) { + return NetworkProtocol.forNumber(number); + } + }; + + public final com.google.protobuf.Descriptors.EnumValueDescriptor + getValueDescriptor() { + return getDescriptor().getValues().get(ordinal()); + } + public final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptorForType() { + return getDescriptor(); + } + public static final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptor() { + return io.grpc.alts.internal.Handshaker.getDescriptor().getEnumTypes().get(1); + } + + private static final NetworkProtocol[] VALUES = values(); + + public static NetworkProtocol valueOf( + com.google.protobuf.Descriptors.EnumValueDescriptor desc) { + if (desc.getType() != getDescriptor()) { + throw new java.lang.IllegalArgumentException( + "EnumValueDescriptor is not for this type."); + } + if (desc.getIndex() == -1) { + return UNRECOGNIZED; + } + return VALUES[desc.getIndex()]; + } + + private final int value; + + private NetworkProtocol(int value) { + this.value = value; + } + + // @@protoc_insertion_point(enum_scope:grpc.gcp.NetworkProtocol) + } + + public interface EndpointOrBuilder extends + // @@protoc_insertion_point(interface_extends:grpc.gcp.Endpoint) + com.google.protobuf.MessageOrBuilder { + + /** + *
+     * IP address. It should contain an IPv4 or IPv6 string literal, e.g.
+     * "192.168.0.1" or "2001:db8::1".
+     * 
+ * + * string ip_address = 1; + */ + java.lang.String getIpAddress(); + /** + *
+     * IP address. It should contain an IPv4 or IPv6 string literal, e.g.
+     * "192.168.0.1" or "2001:db8::1".
+     * 
+ * + * string ip_address = 1; + */ + com.google.protobuf.ByteString + getIpAddressBytes(); + + /** + *
+     * Port number.
+     * 
+ * + * int32 port = 2; + */ + int getPort(); + + /** + *
+     * Network protocol (e.g., TCP, UDP) associated with this endpoint.
+     * 
+ * + * .grpc.gcp.NetworkProtocol protocol = 3; + */ + int getProtocolValue(); + /** + *
+     * Network protocol (e.g., TCP, UDP) associated with this endpoint.
+     * 
+ * + * .grpc.gcp.NetworkProtocol protocol = 3; + */ + io.grpc.alts.internal.Handshaker.NetworkProtocol getProtocol(); + } + /** + * Protobuf type {@code grpc.gcp.Endpoint} + */ + public static final class Endpoint extends + com.google.protobuf.GeneratedMessageV3 implements + // @@protoc_insertion_point(message_implements:grpc.gcp.Endpoint) + EndpointOrBuilder { + private static final long serialVersionUID = 0L; + // Use Endpoint.newBuilder() to construct. + private Endpoint(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + private Endpoint() { + ipAddress_ = ""; + port_ = 0; + protocol_ = 0; + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return this.unknownFields; + } + private Endpoint( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownFieldProto3( + input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 10: { + java.lang.String s = input.readStringRequireUtf8(); + + ipAddress_ = s; + break; + } + case 16: { + + port_ = input.readInt32(); + break; + } + case 24: { + int rawValue = input.readEnum(); + + protocol_ = rawValue; + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_Endpoint_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_Endpoint_fieldAccessorTable + .ensureFieldAccessorsInitialized( + io.grpc.alts.internal.Handshaker.Endpoint.class, io.grpc.alts.internal.Handshaker.Endpoint.Builder.class); + } + + public static final int IP_ADDRESS_FIELD_NUMBER = 1; + private volatile java.lang.Object ipAddress_; + /** + *
+     * IP address. It should contain an IPv4 or IPv6 string literal, e.g.
+     * "192.168.0.1" or "2001:db8::1".
+     * 
+ * + * string ip_address = 1; + */ + public java.lang.String getIpAddress() { + java.lang.Object ref = ipAddress_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + ipAddress_ = s; + return s; + } + } + /** + *
+     * IP address. It should contain an IPv4 or IPv6 string literal, e.g.
+     * "192.168.0.1" or "2001:db8::1".
+     * 
+ * + * string ip_address = 1; + */ + public com.google.protobuf.ByteString + getIpAddressBytes() { + java.lang.Object ref = ipAddress_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (java.lang.String) ref); + ipAddress_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int PORT_FIELD_NUMBER = 2; + private int port_; + /** + *
+     * Port number.
+     * 
+ * + * int32 port = 2; + */ + public int getPort() { + return port_; + } + + public static final int PROTOCOL_FIELD_NUMBER = 3; + private int protocol_; + /** + *
+     * Network protocol (e.g., TCP, UDP) associated with this endpoint.
+     * 
+ * + * .grpc.gcp.NetworkProtocol protocol = 3; + */ + public int getProtocolValue() { + return protocol_; + } + /** + *
+     * Network protocol (e.g., TCP, UDP) associated with this endpoint.
+     * 
+ * + * .grpc.gcp.NetworkProtocol protocol = 3; + */ + public io.grpc.alts.internal.Handshaker.NetworkProtocol getProtocol() { + io.grpc.alts.internal.Handshaker.NetworkProtocol result = io.grpc.alts.internal.Handshaker.NetworkProtocol.valueOf(protocol_); + return result == null ? io.grpc.alts.internal.Handshaker.NetworkProtocol.UNRECOGNIZED : result; + } + + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + if (!getIpAddressBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 1, ipAddress_); + } + if (port_ != 0) { + output.writeInt32(2, port_); + } + if (protocol_ != io.grpc.alts.internal.Handshaker.NetworkProtocol.NETWORK_PROTOCOL_UNSPECIFIED.getNumber()) { + output.writeEnum(3, protocol_); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (!getIpAddressBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, ipAddress_); + } + if (port_ != 0) { + size += com.google.protobuf.CodedOutputStream + .computeInt32Size(2, port_); + } + if (protocol_ != io.grpc.alts.internal.Handshaker.NetworkProtocol.NETWORK_PROTOCOL_UNSPECIFIED.getNumber()) { + size += com.google.protobuf.CodedOutputStream + .computeEnumSize(3, protocol_); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof io.grpc.alts.internal.Handshaker.Endpoint)) { + return super.equals(obj); + } + io.grpc.alts.internal.Handshaker.Endpoint other = (io.grpc.alts.internal.Handshaker.Endpoint) obj; + + boolean result = true; + result = result && getIpAddress() + .equals(other.getIpAddress()); + result = result && (getPort() + == other.getPort()); + result = result && protocol_ == other.protocol_; + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + hash = (37 * hash) + IP_ADDRESS_FIELD_NUMBER; + hash = (53 * hash) + getIpAddress().hashCode(); + hash = (37 * hash) + PORT_FIELD_NUMBER; + hash = (53 * hash) + getPort(); + hash = (37 * hash) + PROTOCOL_FIELD_NUMBER; + hash = (53 * hash) + protocol_; + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static io.grpc.alts.internal.Handshaker.Endpoint parseFrom( + java.nio.ByteBuffer data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Handshaker.Endpoint parseFrom( + java.nio.ByteBuffer data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.Endpoint parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Handshaker.Endpoint parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.Endpoint parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Handshaker.Endpoint parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.Endpoint parseFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Handshaker.Endpoint parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.Endpoint parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Handshaker.Endpoint parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.Endpoint parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Handshaker.Endpoint parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + public static Builder newBuilder(io.grpc.alts.internal.Handshaker.Endpoint prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { + return this == DEFAULT_INSTANCE + ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + * Protobuf type {@code grpc.gcp.Endpoint} + */ + public static final class Builder extends + com.google.protobuf.GeneratedMessageV3.Builder implements + // @@protoc_insertion_point(builder_implements:grpc.gcp.Endpoint) + io.grpc.alts.internal.Handshaker.EndpointOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_Endpoint_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_Endpoint_fieldAccessorTable + .ensureFieldAccessorsInitialized( + io.grpc.alts.internal.Handshaker.Endpoint.class, io.grpc.alts.internal.Handshaker.Endpoint.Builder.class); + } + + // Construct using io.grpc.alts.internal.Handshaker.Endpoint.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder( + com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3 + .alwaysUseFieldBuilders) { + } + } + public Builder clear() { + super.clear(); + ipAddress_ = ""; + + port_ = 0; + + protocol_ = 0; + + return this; + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_Endpoint_descriptor; + } + + public io.grpc.alts.internal.Handshaker.Endpoint getDefaultInstanceForType() { + return io.grpc.alts.internal.Handshaker.Endpoint.getDefaultInstance(); + } + + public io.grpc.alts.internal.Handshaker.Endpoint build() { + io.grpc.alts.internal.Handshaker.Endpoint result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public io.grpc.alts.internal.Handshaker.Endpoint buildPartial() { + io.grpc.alts.internal.Handshaker.Endpoint result = new io.grpc.alts.internal.Handshaker.Endpoint(this); + result.ipAddress_ = ipAddress_; + result.port_ = port_; + result.protocol_ = protocol_; + onBuilt(); + return result; + } + + public Builder clone() { + return (Builder) super.clone(); + } + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, + java.lang.Object value) { + return (Builder) super.setField(field, value); + } + public Builder clearField( + com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); + } + public Builder clearOneof( + com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); + } + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); + } + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); + } + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof io.grpc.alts.internal.Handshaker.Endpoint) { + return mergeFrom((io.grpc.alts.internal.Handshaker.Endpoint)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(io.grpc.alts.internal.Handshaker.Endpoint other) { + if (other == io.grpc.alts.internal.Handshaker.Endpoint.getDefaultInstance()) return this; + if (!other.getIpAddress().isEmpty()) { + ipAddress_ = other.ipAddress_; + onChanged(); + } + if (other.getPort() != 0) { + setPort(other.getPort()); + } + if (other.protocol_ != 0) { + setProtocolValue(other.getProtocolValue()); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + io.grpc.alts.internal.Handshaker.Endpoint parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (io.grpc.alts.internal.Handshaker.Endpoint) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + private java.lang.Object ipAddress_ = ""; + /** + *
+       * IP address. It should contain an IPv4 or IPv6 string literal, e.g.
+       * "192.168.0.1" or "2001:db8::1".
+       * 
+ * + * string ip_address = 1; + */ + public java.lang.String getIpAddress() { + java.lang.Object ref = ipAddress_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + ipAddress_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + /** + *
+       * IP address. It should contain an IPv4 or IPv6 string literal, e.g.
+       * "192.168.0.1" or "2001:db8::1".
+       * 
+ * + * string ip_address = 1; + */ + public com.google.protobuf.ByteString + getIpAddressBytes() { + java.lang.Object ref = ipAddress_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (java.lang.String) ref); + ipAddress_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + /** + *
+       * IP address. It should contain an IPv4 or IPv6 string literal, e.g.
+       * "192.168.0.1" or "2001:db8::1".
+       * 
+ * + * string ip_address = 1; + */ + public Builder setIpAddress( + java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + + ipAddress_ = value; + onChanged(); + return this; + } + /** + *
+       * IP address. It should contain an IPv4 or IPv6 string literal, e.g.
+       * "192.168.0.1" or "2001:db8::1".
+       * 
+ * + * string ip_address = 1; + */ + public Builder clearIpAddress() { + + ipAddress_ = getDefaultInstance().getIpAddress(); + onChanged(); + return this; + } + /** + *
+       * IP address. It should contain an IPv4 or IPv6 string literal, e.g.
+       * "192.168.0.1" or "2001:db8::1".
+       * 
+ * + * string ip_address = 1; + */ + public Builder setIpAddressBytes( + com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + + ipAddress_ = value; + onChanged(); + return this; + } + + private int port_ ; + /** + *
+       * Port number.
+       * 
+ * + * int32 port = 2; + */ + public int getPort() { + return port_; + } + /** + *
+       * Port number.
+       * 
+ * + * int32 port = 2; + */ + public Builder setPort(int value) { + + port_ = value; + onChanged(); + return this; + } + /** + *
+       * Port number.
+       * 
+ * + * int32 port = 2; + */ + public Builder clearPort() { + + port_ = 0; + onChanged(); + return this; + } + + private int protocol_ = 0; + /** + *
+       * Network protocol (e.g., TCP, UDP) associated with this endpoint.
+       * 
+ * + * .grpc.gcp.NetworkProtocol protocol = 3; + */ + public int getProtocolValue() { + return protocol_; + } + /** + *
+       * Network protocol (e.g., TCP, UDP) associated with this endpoint.
+       * 
+ * + * .grpc.gcp.NetworkProtocol protocol = 3; + */ + public Builder setProtocolValue(int value) { + protocol_ = value; + onChanged(); + return this; + } + /** + *
+       * Network protocol (e.g., TCP, UDP) associated with this endpoint.
+       * 
+ * + * .grpc.gcp.NetworkProtocol protocol = 3; + */ + public io.grpc.alts.internal.Handshaker.NetworkProtocol getProtocol() { + io.grpc.alts.internal.Handshaker.NetworkProtocol result = io.grpc.alts.internal.Handshaker.NetworkProtocol.valueOf(protocol_); + return result == null ? io.grpc.alts.internal.Handshaker.NetworkProtocol.UNRECOGNIZED : result; + } + /** + *
+       * Network protocol (e.g., TCP, UDP) associated with this endpoint.
+       * 
+ * + * .grpc.gcp.NetworkProtocol protocol = 3; + */ + public Builder setProtocol(io.grpc.alts.internal.Handshaker.NetworkProtocol value) { + if (value == null) { + throw new NullPointerException(); + } + + protocol_ = value.getNumber(); + onChanged(); + return this; + } + /** + *
+       * Network protocol (e.g., TCP, UDP) associated with this endpoint.
+       * 
+ * + * .grpc.gcp.NetworkProtocol protocol = 3; + */ + public Builder clearProtocol() { + + protocol_ = 0; + onChanged(); + return this; + } + public final Builder setUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); + } + + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + + // @@protoc_insertion_point(builder_scope:grpc.gcp.Endpoint) + } + + // @@protoc_insertion_point(class_scope:grpc.gcp.Endpoint) + private static final io.grpc.alts.internal.Handshaker.Endpoint DEFAULT_INSTANCE; + static { + DEFAULT_INSTANCE = new io.grpc.alts.internal.Handshaker.Endpoint(); + } + + public static io.grpc.alts.internal.Handshaker.Endpoint getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + private static final com.google.protobuf.Parser + PARSER = new com.google.protobuf.AbstractParser() { + public Endpoint parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new Endpoint(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public io.grpc.alts.internal.Handshaker.Endpoint getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } + + } + + public interface IdentityOrBuilder extends + // @@protoc_insertion_point(interface_extends:grpc.gcp.Identity) + com.google.protobuf.MessageOrBuilder { + + /** + *
+     * Service account of a connection endpoint.
+     * 
+ * + * string service_account = 1; + */ + java.lang.String getServiceAccount(); + /** + *
+     * Service account of a connection endpoint.
+     * 
+ * + * string service_account = 1; + */ + com.google.protobuf.ByteString + getServiceAccountBytes(); + + /** + *
+     * Hostname of a connection endpoint.
+     * 
+ * + * string hostname = 2; + */ + java.lang.String getHostname(); + /** + *
+     * Hostname of a connection endpoint.
+     * 
+ * + * string hostname = 2; + */ + com.google.protobuf.ByteString + getHostnameBytes(); + + public io.grpc.alts.internal.Handshaker.Identity.IdentityOneofCase getIdentityOneofCase(); + } + /** + * Protobuf type {@code grpc.gcp.Identity} + */ + public static final class Identity extends + com.google.protobuf.GeneratedMessageV3 implements + // @@protoc_insertion_point(message_implements:grpc.gcp.Identity) + IdentityOrBuilder { + private static final long serialVersionUID = 0L; + // Use Identity.newBuilder() to construct. + private Identity(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + private Identity() { + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return this.unknownFields; + } + private Identity( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownFieldProto3( + input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 10: { + java.lang.String s = input.readStringRequireUtf8(); + identityOneofCase_ = 1; + identityOneof_ = s; + break; + } + case 18: { + java.lang.String s = input.readStringRequireUtf8(); + identityOneofCase_ = 2; + identityOneof_ = s; + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_Identity_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_Identity_fieldAccessorTable + .ensureFieldAccessorsInitialized( + io.grpc.alts.internal.Handshaker.Identity.class, io.grpc.alts.internal.Handshaker.Identity.Builder.class); + } + + private int identityOneofCase_ = 0; + private java.lang.Object identityOneof_; + public enum IdentityOneofCase + implements com.google.protobuf.Internal.EnumLite { + SERVICE_ACCOUNT(1), + HOSTNAME(2), + IDENTITYONEOF_NOT_SET(0); + private final int value; + private IdentityOneofCase(int value) { + this.value = value; + } + /** + * @deprecated Use {@link #forNumber(int)} instead. + */ + @java.lang.Deprecated + public static IdentityOneofCase valueOf(int value) { + return forNumber(value); + } + + public static IdentityOneofCase forNumber(int value) { + switch (value) { + case 1: return SERVICE_ACCOUNT; + case 2: return HOSTNAME; + case 0: return IDENTITYONEOF_NOT_SET; + default: return null; + } + } + public int getNumber() { + return this.value; + } + }; + + public IdentityOneofCase + getIdentityOneofCase() { + return IdentityOneofCase.forNumber( + identityOneofCase_); + } + + public static final int SERVICE_ACCOUNT_FIELD_NUMBER = 1; + /** + *
+     * Service account of a connection endpoint.
+     * 
+ * + * string service_account = 1; + */ + public java.lang.String getServiceAccount() { + java.lang.Object ref = ""; + if (identityOneofCase_ == 1) { + ref = identityOneof_; + } + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + if (identityOneofCase_ == 1) { + identityOneof_ = s; + } + return s; + } + } + /** + *
+     * Service account of a connection endpoint.
+     * 
+ * + * string service_account = 1; + */ + public com.google.protobuf.ByteString + getServiceAccountBytes() { + java.lang.Object ref = ""; + if (identityOneofCase_ == 1) { + ref = identityOneof_; + } + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (java.lang.String) ref); + if (identityOneofCase_ == 1) { + identityOneof_ = b; + } + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int HOSTNAME_FIELD_NUMBER = 2; + /** + *
+     * Hostname of a connection endpoint.
+     * 
+ * + * string hostname = 2; + */ + public java.lang.String getHostname() { + java.lang.Object ref = ""; + if (identityOneofCase_ == 2) { + ref = identityOneof_; + } + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + if (identityOneofCase_ == 2) { + identityOneof_ = s; + } + return s; + } + } + /** + *
+     * Hostname of a connection endpoint.
+     * 
+ * + * string hostname = 2; + */ + public com.google.protobuf.ByteString + getHostnameBytes() { + java.lang.Object ref = ""; + if (identityOneofCase_ == 2) { + ref = identityOneof_; + } + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (java.lang.String) ref); + if (identityOneofCase_ == 2) { + identityOneof_ = b; + } + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + if (identityOneofCase_ == 1) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 1, identityOneof_); + } + if (identityOneofCase_ == 2) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 2, identityOneof_); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (identityOneofCase_ == 1) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, identityOneof_); + } + if (identityOneofCase_ == 2) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, identityOneof_); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof io.grpc.alts.internal.Handshaker.Identity)) { + return super.equals(obj); + } + io.grpc.alts.internal.Handshaker.Identity other = (io.grpc.alts.internal.Handshaker.Identity) obj; + + boolean result = true; + result = result && getIdentityOneofCase().equals( + other.getIdentityOneofCase()); + if (!result) return false; + switch (identityOneofCase_) { + case 1: + result = result && getServiceAccount() + .equals(other.getServiceAccount()); + break; + case 2: + result = result && getHostname() + .equals(other.getHostname()); + break; + case 0: + default: + } + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + switch (identityOneofCase_) { + case 1: + hash = (37 * hash) + SERVICE_ACCOUNT_FIELD_NUMBER; + hash = (53 * hash) + getServiceAccount().hashCode(); + break; + case 2: + hash = (37 * hash) + HOSTNAME_FIELD_NUMBER; + hash = (53 * hash) + getHostname().hashCode(); + break; + case 0: + default: + } + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static io.grpc.alts.internal.Handshaker.Identity parseFrom( + java.nio.ByteBuffer data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Handshaker.Identity parseFrom( + java.nio.ByteBuffer data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.Identity parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Handshaker.Identity parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.Identity parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Handshaker.Identity parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.Identity parseFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Handshaker.Identity parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.Identity parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Handshaker.Identity parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.Identity parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Handshaker.Identity parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + public static Builder newBuilder(io.grpc.alts.internal.Handshaker.Identity prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { + return this == DEFAULT_INSTANCE + ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + * Protobuf type {@code grpc.gcp.Identity} + */ + public static final class Builder extends + com.google.protobuf.GeneratedMessageV3.Builder implements + // @@protoc_insertion_point(builder_implements:grpc.gcp.Identity) + io.grpc.alts.internal.Handshaker.IdentityOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_Identity_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_Identity_fieldAccessorTable + .ensureFieldAccessorsInitialized( + io.grpc.alts.internal.Handshaker.Identity.class, io.grpc.alts.internal.Handshaker.Identity.Builder.class); + } + + // Construct using io.grpc.alts.internal.Handshaker.Identity.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder( + com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3 + .alwaysUseFieldBuilders) { + } + } + public Builder clear() { + super.clear(); + identityOneofCase_ = 0; + identityOneof_ = null; + return this; + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_Identity_descriptor; + } + + public io.grpc.alts.internal.Handshaker.Identity getDefaultInstanceForType() { + return io.grpc.alts.internal.Handshaker.Identity.getDefaultInstance(); + } + + public io.grpc.alts.internal.Handshaker.Identity build() { + io.grpc.alts.internal.Handshaker.Identity result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public io.grpc.alts.internal.Handshaker.Identity buildPartial() { + io.grpc.alts.internal.Handshaker.Identity result = new io.grpc.alts.internal.Handshaker.Identity(this); + if (identityOneofCase_ == 1) { + result.identityOneof_ = identityOneof_; + } + if (identityOneofCase_ == 2) { + result.identityOneof_ = identityOneof_; + } + result.identityOneofCase_ = identityOneofCase_; + onBuilt(); + return result; + } + + public Builder clone() { + return (Builder) super.clone(); + } + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, + java.lang.Object value) { + return (Builder) super.setField(field, value); + } + public Builder clearField( + com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); + } + public Builder clearOneof( + com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); + } + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); + } + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); + } + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof io.grpc.alts.internal.Handshaker.Identity) { + return mergeFrom((io.grpc.alts.internal.Handshaker.Identity)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(io.grpc.alts.internal.Handshaker.Identity other) { + if (other == io.grpc.alts.internal.Handshaker.Identity.getDefaultInstance()) return this; + switch (other.getIdentityOneofCase()) { + case SERVICE_ACCOUNT: { + identityOneofCase_ = 1; + identityOneof_ = other.identityOneof_; + onChanged(); + break; + } + case HOSTNAME: { + identityOneofCase_ = 2; + identityOneof_ = other.identityOneof_; + onChanged(); + break; + } + case IDENTITYONEOF_NOT_SET: { + break; + } + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + io.grpc.alts.internal.Handshaker.Identity parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (io.grpc.alts.internal.Handshaker.Identity) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + private int identityOneofCase_ = 0; + private java.lang.Object identityOneof_; + public IdentityOneofCase + getIdentityOneofCase() { + return IdentityOneofCase.forNumber( + identityOneofCase_); + } + + public Builder clearIdentityOneof() { + identityOneofCase_ = 0; + identityOneof_ = null; + onChanged(); + return this; + } + + + /** + *
+       * Service account of a connection endpoint.
+       * 
+ * + * string service_account = 1; + */ + public java.lang.String getServiceAccount() { + java.lang.Object ref = ""; + if (identityOneofCase_ == 1) { + ref = identityOneof_; + } + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + if (identityOneofCase_ == 1) { + identityOneof_ = s; + } + return s; + } else { + return (java.lang.String) ref; + } + } + /** + *
+       * Service account of a connection endpoint.
+       * 
+ * + * string service_account = 1; + */ + public com.google.protobuf.ByteString + getServiceAccountBytes() { + java.lang.Object ref = ""; + if (identityOneofCase_ == 1) { + ref = identityOneof_; + } + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (java.lang.String) ref); + if (identityOneofCase_ == 1) { + identityOneof_ = b; + } + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + /** + *
+       * Service account of a connection endpoint.
+       * 
+ * + * string service_account = 1; + */ + public Builder setServiceAccount( + java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + identityOneofCase_ = 1; + identityOneof_ = value; + onChanged(); + return this; + } + /** + *
+       * Service account of a connection endpoint.
+       * 
+ * + * string service_account = 1; + */ + public Builder clearServiceAccount() { + if (identityOneofCase_ == 1) { + identityOneofCase_ = 0; + identityOneof_ = null; + onChanged(); + } + return this; + } + /** + *
+       * Service account of a connection endpoint.
+       * 
+ * + * string service_account = 1; + */ + public Builder setServiceAccountBytes( + com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + identityOneofCase_ = 1; + identityOneof_ = value; + onChanged(); + return this; + } + + /** + *
+       * Hostname of a connection endpoint.
+       * 
+ * + * string hostname = 2; + */ + public java.lang.String getHostname() { + java.lang.Object ref = ""; + if (identityOneofCase_ == 2) { + ref = identityOneof_; + } + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + if (identityOneofCase_ == 2) { + identityOneof_ = s; + } + return s; + } else { + return (java.lang.String) ref; + } + } + /** + *
+       * Hostname of a connection endpoint.
+       * 
+ * + * string hostname = 2; + */ + public com.google.protobuf.ByteString + getHostnameBytes() { + java.lang.Object ref = ""; + if (identityOneofCase_ == 2) { + ref = identityOneof_; + } + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (java.lang.String) ref); + if (identityOneofCase_ == 2) { + identityOneof_ = b; + } + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + /** + *
+       * Hostname of a connection endpoint.
+       * 
+ * + * string hostname = 2; + */ + public Builder setHostname( + java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + identityOneofCase_ = 2; + identityOneof_ = value; + onChanged(); + return this; + } + /** + *
+       * Hostname of a connection endpoint.
+       * 
+ * + * string hostname = 2; + */ + public Builder clearHostname() { + if (identityOneofCase_ == 2) { + identityOneofCase_ = 0; + identityOneof_ = null; + onChanged(); + } + return this; + } + /** + *
+       * Hostname of a connection endpoint.
+       * 
+ * + * string hostname = 2; + */ + public Builder setHostnameBytes( + com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + identityOneofCase_ = 2; + identityOneof_ = value; + onChanged(); + return this; + } + public final Builder setUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); + } + + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + + // @@protoc_insertion_point(builder_scope:grpc.gcp.Identity) + } + + // @@protoc_insertion_point(class_scope:grpc.gcp.Identity) + private static final io.grpc.alts.internal.Handshaker.Identity DEFAULT_INSTANCE; + static { + DEFAULT_INSTANCE = new io.grpc.alts.internal.Handshaker.Identity(); + } + + public static io.grpc.alts.internal.Handshaker.Identity getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + private static final com.google.protobuf.Parser + PARSER = new com.google.protobuf.AbstractParser() { + public Identity parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new Identity(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public io.grpc.alts.internal.Handshaker.Identity getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } + + } + + public interface StartClientHandshakeReqOrBuilder extends + // @@protoc_insertion_point(interface_extends:grpc.gcp.StartClientHandshakeReq) + com.google.protobuf.MessageOrBuilder { + + /** + *
+     * Handshake security protocol requested by the client.
+     * 
+ * + * .grpc.gcp.HandshakeProtocol handshake_security_protocol = 1; + */ + int getHandshakeSecurityProtocolValue(); + /** + *
+     * Handshake security protocol requested by the client.
+     * 
+ * + * .grpc.gcp.HandshakeProtocol handshake_security_protocol = 1; + */ + io.grpc.alts.internal.Handshaker.HandshakeProtocol getHandshakeSecurityProtocol(); + + /** + *
+     * The application protocols supported by the client, e.g., "h2" (for http2),
+     * "grpc".
+     * 
+ * + * repeated string application_protocols = 2; + */ + java.util.List + getApplicationProtocolsList(); + /** + *
+     * The application protocols supported by the client, e.g., "h2" (for http2),
+     * "grpc".
+     * 
+ * + * repeated string application_protocols = 2; + */ + int getApplicationProtocolsCount(); + /** + *
+     * The application protocols supported by the client, e.g., "h2" (for http2),
+     * "grpc".
+     * 
+ * + * repeated string application_protocols = 2; + */ + java.lang.String getApplicationProtocols(int index); + /** + *
+     * The application protocols supported by the client, e.g., "h2" (for http2),
+     * "grpc".
+     * 
+ * + * repeated string application_protocols = 2; + */ + com.google.protobuf.ByteString + getApplicationProtocolsBytes(int index); + + /** + *
+     * The record protocols supported by the client, e.g.,
+     * "ALTSRP_GCM_AES128".
+     * 
+ * + * repeated string record_protocols = 3; + */ + java.util.List + getRecordProtocolsList(); + /** + *
+     * The record protocols supported by the client, e.g.,
+     * "ALTSRP_GCM_AES128".
+     * 
+ * + * repeated string record_protocols = 3; + */ + int getRecordProtocolsCount(); + /** + *
+     * The record protocols supported by the client, e.g.,
+     * "ALTSRP_GCM_AES128".
+     * 
+ * + * repeated string record_protocols = 3; + */ + java.lang.String getRecordProtocols(int index); + /** + *
+     * The record protocols supported by the client, e.g.,
+     * "ALTSRP_GCM_AES128".
+     * 
+ * + * repeated string record_protocols = 3; + */ + com.google.protobuf.ByteString + getRecordProtocolsBytes(int index); + + /** + *
+     * (Optional) Describes which server identities are acceptable by the client.
+     * If target identities are provided and none of them matches the peer
+     * identity of the server, handshake will fail.
+     * 
+ * + * repeated .grpc.gcp.Identity target_identities = 4; + */ + java.util.List + getTargetIdentitiesList(); + /** + *
+     * (Optional) Describes which server identities are acceptable by the client.
+     * If target identities are provided and none of them matches the peer
+     * identity of the server, handshake will fail.
+     * 
+ * + * repeated .grpc.gcp.Identity target_identities = 4; + */ + io.grpc.alts.internal.Handshaker.Identity getTargetIdentities(int index); + /** + *
+     * (Optional) Describes which server identities are acceptable by the client.
+     * If target identities are provided and none of them matches the peer
+     * identity of the server, handshake will fail.
+     * 
+ * + * repeated .grpc.gcp.Identity target_identities = 4; + */ + int getTargetIdentitiesCount(); + /** + *
+     * (Optional) Describes which server identities are acceptable by the client.
+     * If target identities are provided and none of them matches the peer
+     * identity of the server, handshake will fail.
+     * 
+ * + * repeated .grpc.gcp.Identity target_identities = 4; + */ + java.util.List + getTargetIdentitiesOrBuilderList(); + /** + *
+     * (Optional) Describes which server identities are acceptable by the client.
+     * If target identities are provided and none of them matches the peer
+     * identity of the server, handshake will fail.
+     * 
+ * + * repeated .grpc.gcp.Identity target_identities = 4; + */ + io.grpc.alts.internal.Handshaker.IdentityOrBuilder getTargetIdentitiesOrBuilder( + int index); + + /** + *
+     * (Optional) Application may specify a local identity. Otherwise, the
+     * handshaker chooses a default local identity.
+     * 
+ * + * .grpc.gcp.Identity local_identity = 5; + */ + boolean hasLocalIdentity(); + /** + *
+     * (Optional) Application may specify a local identity. Otherwise, the
+     * handshaker chooses a default local identity.
+     * 
+ * + * .grpc.gcp.Identity local_identity = 5; + */ + io.grpc.alts.internal.Handshaker.Identity getLocalIdentity(); + /** + *
+     * (Optional) Application may specify a local identity. Otherwise, the
+     * handshaker chooses a default local identity.
+     * 
+ * + * .grpc.gcp.Identity local_identity = 5; + */ + io.grpc.alts.internal.Handshaker.IdentityOrBuilder getLocalIdentityOrBuilder(); + + /** + *
+     * (Optional) Local endpoint information of the connection to the server,
+     * such as local IP address, port number, and network protocol.
+     * 
+ * + * .grpc.gcp.Endpoint local_endpoint = 6; + */ + boolean hasLocalEndpoint(); + /** + *
+     * (Optional) Local endpoint information of the connection to the server,
+     * such as local IP address, port number, and network protocol.
+     * 
+ * + * .grpc.gcp.Endpoint local_endpoint = 6; + */ + io.grpc.alts.internal.Handshaker.Endpoint getLocalEndpoint(); + /** + *
+     * (Optional) Local endpoint information of the connection to the server,
+     * such as local IP address, port number, and network protocol.
+     * 
+ * + * .grpc.gcp.Endpoint local_endpoint = 6; + */ + io.grpc.alts.internal.Handshaker.EndpointOrBuilder getLocalEndpointOrBuilder(); + + /** + *
+     * (Optional) Endpoint information of the remote server, such as IP address,
+     * port number, and network protocol.
+     * 
+ * + * .grpc.gcp.Endpoint remote_endpoint = 7; + */ + boolean hasRemoteEndpoint(); + /** + *
+     * (Optional) Endpoint information of the remote server, such as IP address,
+     * port number, and network protocol.
+     * 
+ * + * .grpc.gcp.Endpoint remote_endpoint = 7; + */ + io.grpc.alts.internal.Handshaker.Endpoint getRemoteEndpoint(); + /** + *
+     * (Optional) Endpoint information of the remote server, such as IP address,
+     * port number, and network protocol.
+     * 
+ * + * .grpc.gcp.Endpoint remote_endpoint = 7; + */ + io.grpc.alts.internal.Handshaker.EndpointOrBuilder getRemoteEndpointOrBuilder(); + + /** + *
+     * (Optional) If target name is provided, a secure naming check is performed
+     * to verify that the peer authenticated identity is indeed authorized to run
+     * the target name.
+     * 
+ * + * string target_name = 8; + */ + java.lang.String getTargetName(); + /** + *
+     * (Optional) If target name is provided, a secure naming check is performed
+     * to verify that the peer authenticated identity is indeed authorized to run
+     * the target name.
+     * 
+ * + * string target_name = 8; + */ + com.google.protobuf.ByteString + getTargetNameBytes(); + + /** + *
+     * (Optional) RPC protocol versions supported by the client.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions rpc_versions = 9; + */ + boolean hasRpcVersions(); + /** + *
+     * (Optional) RPC protocol versions supported by the client.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions rpc_versions = 9; + */ + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions getRpcVersions(); + /** + *
+     * (Optional) RPC protocol versions supported by the client.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions rpc_versions = 9; + */ + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersionsOrBuilder getRpcVersionsOrBuilder(); + } + /** + * Protobuf type {@code grpc.gcp.StartClientHandshakeReq} + */ + public static final class StartClientHandshakeReq extends + com.google.protobuf.GeneratedMessageV3 implements + // @@protoc_insertion_point(message_implements:grpc.gcp.StartClientHandshakeReq) + StartClientHandshakeReqOrBuilder { + private static final long serialVersionUID = 0L; + // Use StartClientHandshakeReq.newBuilder() to construct. + private StartClientHandshakeReq(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + private StartClientHandshakeReq() { + handshakeSecurityProtocol_ = 0; + applicationProtocols_ = com.google.protobuf.LazyStringArrayList.EMPTY; + recordProtocols_ = com.google.protobuf.LazyStringArrayList.EMPTY; + targetIdentities_ = java.util.Collections.emptyList(); + targetName_ = ""; + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return this.unknownFields; + } + private StartClientHandshakeReq( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownFieldProto3( + input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 8: { + int rawValue = input.readEnum(); + + handshakeSecurityProtocol_ = rawValue; + break; + } + case 18: { + java.lang.String s = input.readStringRequireUtf8(); + if (!((mutable_bitField0_ & 0x00000002) == 0x00000002)) { + applicationProtocols_ = new com.google.protobuf.LazyStringArrayList(); + mutable_bitField0_ |= 0x00000002; + } + applicationProtocols_.add(s); + break; + } + case 26: { + java.lang.String s = input.readStringRequireUtf8(); + if (!((mutable_bitField0_ & 0x00000004) == 0x00000004)) { + recordProtocols_ = new com.google.protobuf.LazyStringArrayList(); + mutable_bitField0_ |= 0x00000004; + } + recordProtocols_.add(s); + break; + } + case 34: { + if (!((mutable_bitField0_ & 0x00000008) == 0x00000008)) { + targetIdentities_ = new java.util.ArrayList(); + mutable_bitField0_ |= 0x00000008; + } + targetIdentities_.add( + input.readMessage(io.grpc.alts.internal.Handshaker.Identity.parser(), extensionRegistry)); + break; + } + case 42: { + io.grpc.alts.internal.Handshaker.Identity.Builder subBuilder = null; + if (localIdentity_ != null) { + subBuilder = localIdentity_.toBuilder(); + } + localIdentity_ = input.readMessage(io.grpc.alts.internal.Handshaker.Identity.parser(), extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(localIdentity_); + localIdentity_ = subBuilder.buildPartial(); + } + + break; + } + case 50: { + io.grpc.alts.internal.Handshaker.Endpoint.Builder subBuilder = null; + if (localEndpoint_ != null) { + subBuilder = localEndpoint_.toBuilder(); + } + localEndpoint_ = input.readMessage(io.grpc.alts.internal.Handshaker.Endpoint.parser(), extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(localEndpoint_); + localEndpoint_ = subBuilder.buildPartial(); + } + + break; + } + case 58: { + io.grpc.alts.internal.Handshaker.Endpoint.Builder subBuilder = null; + if (remoteEndpoint_ != null) { + subBuilder = remoteEndpoint_.toBuilder(); + } + remoteEndpoint_ = input.readMessage(io.grpc.alts.internal.Handshaker.Endpoint.parser(), extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(remoteEndpoint_); + remoteEndpoint_ = subBuilder.buildPartial(); + } + + break; + } + case 66: { + java.lang.String s = input.readStringRequireUtf8(); + + targetName_ = s; + break; + } + case 74: { + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Builder subBuilder = null; + if (rpcVersions_ != null) { + subBuilder = rpcVersions_.toBuilder(); + } + rpcVersions_ = input.readMessage(io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.parser(), extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(rpcVersions_); + rpcVersions_ = subBuilder.buildPartial(); + } + + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e).setUnfinishedMessage(this); + } finally { + if (((mutable_bitField0_ & 0x00000002) == 0x00000002)) { + applicationProtocols_ = applicationProtocols_.getUnmodifiableView(); + } + if (((mutable_bitField0_ & 0x00000004) == 0x00000004)) { + recordProtocols_ = recordProtocols_.getUnmodifiableView(); + } + if (((mutable_bitField0_ & 0x00000008) == 0x00000008)) { + targetIdentities_ = java.util.Collections.unmodifiableList(targetIdentities_); + } + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_StartClientHandshakeReq_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_StartClientHandshakeReq_fieldAccessorTable + .ensureFieldAccessorsInitialized( + io.grpc.alts.internal.Handshaker.StartClientHandshakeReq.class, io.grpc.alts.internal.Handshaker.StartClientHandshakeReq.Builder.class); + } + + private int bitField0_; + public static final int HANDSHAKE_SECURITY_PROTOCOL_FIELD_NUMBER = 1; + private int handshakeSecurityProtocol_; + /** + *
+     * Handshake security protocol requested by the client.
+     * 
+ * + * .grpc.gcp.HandshakeProtocol handshake_security_protocol = 1; + */ + public int getHandshakeSecurityProtocolValue() { + return handshakeSecurityProtocol_; + } + /** + *
+     * Handshake security protocol requested by the client.
+     * 
+ * + * .grpc.gcp.HandshakeProtocol handshake_security_protocol = 1; + */ + public io.grpc.alts.internal.Handshaker.HandshakeProtocol getHandshakeSecurityProtocol() { + io.grpc.alts.internal.Handshaker.HandshakeProtocol result = io.grpc.alts.internal.Handshaker.HandshakeProtocol.valueOf(handshakeSecurityProtocol_); + return result == null ? io.grpc.alts.internal.Handshaker.HandshakeProtocol.UNRECOGNIZED : result; + } + + public static final int APPLICATION_PROTOCOLS_FIELD_NUMBER = 2; + private com.google.protobuf.LazyStringList applicationProtocols_; + /** + *
+     * The application protocols supported by the client, e.g., "h2" (for http2),
+     * "grpc".
+     * 
+ * + * repeated string application_protocols = 2; + */ + public com.google.protobuf.ProtocolStringList + getApplicationProtocolsList() { + return applicationProtocols_; + } + /** + *
+     * The application protocols supported by the client, e.g., "h2" (for http2),
+     * "grpc".
+     * 
+ * + * repeated string application_protocols = 2; + */ + public int getApplicationProtocolsCount() { + return applicationProtocols_.size(); + } + /** + *
+     * The application protocols supported by the client, e.g., "h2" (for http2),
+     * "grpc".
+     * 
+ * + * repeated string application_protocols = 2; + */ + public java.lang.String getApplicationProtocols(int index) { + return applicationProtocols_.get(index); + } + /** + *
+     * The application protocols supported by the client, e.g., "h2" (for http2),
+     * "grpc".
+     * 
+ * + * repeated string application_protocols = 2; + */ + public com.google.protobuf.ByteString + getApplicationProtocolsBytes(int index) { + return applicationProtocols_.getByteString(index); + } + + public static final int RECORD_PROTOCOLS_FIELD_NUMBER = 3; + private com.google.protobuf.LazyStringList recordProtocols_; + /** + *
+     * The record protocols supported by the client, e.g.,
+     * "ALTSRP_GCM_AES128".
+     * 
+ * + * repeated string record_protocols = 3; + */ + public com.google.protobuf.ProtocolStringList + getRecordProtocolsList() { + return recordProtocols_; + } + /** + *
+     * The record protocols supported by the client, e.g.,
+     * "ALTSRP_GCM_AES128".
+     * 
+ * + * repeated string record_protocols = 3; + */ + public int getRecordProtocolsCount() { + return recordProtocols_.size(); + } + /** + *
+     * The record protocols supported by the client, e.g.,
+     * "ALTSRP_GCM_AES128".
+     * 
+ * + * repeated string record_protocols = 3; + */ + public java.lang.String getRecordProtocols(int index) { + return recordProtocols_.get(index); + } + /** + *
+     * The record protocols supported by the client, e.g.,
+     * "ALTSRP_GCM_AES128".
+     * 
+ * + * repeated string record_protocols = 3; + */ + public com.google.protobuf.ByteString + getRecordProtocolsBytes(int index) { + return recordProtocols_.getByteString(index); + } + + public static final int TARGET_IDENTITIES_FIELD_NUMBER = 4; + private java.util.List targetIdentities_; + /** + *
+     * (Optional) Describes which server identities are acceptable by the client.
+     * If target identities are provided and none of them matches the peer
+     * identity of the server, handshake will fail.
+     * 
+ * + * repeated .grpc.gcp.Identity target_identities = 4; + */ + public java.util.List getTargetIdentitiesList() { + return targetIdentities_; + } + /** + *
+     * (Optional) Describes which server identities are acceptable by the client.
+     * If target identities are provided and none of them matches the peer
+     * identity of the server, handshake will fail.
+     * 
+ * + * repeated .grpc.gcp.Identity target_identities = 4; + */ + public java.util.List + getTargetIdentitiesOrBuilderList() { + return targetIdentities_; + } + /** + *
+     * (Optional) Describes which server identities are acceptable by the client.
+     * If target identities are provided and none of them matches the peer
+     * identity of the server, handshake will fail.
+     * 
+ * + * repeated .grpc.gcp.Identity target_identities = 4; + */ + public int getTargetIdentitiesCount() { + return targetIdentities_.size(); + } + /** + *
+     * (Optional) Describes which server identities are acceptable by the client.
+     * If target identities are provided and none of them matches the peer
+     * identity of the server, handshake will fail.
+     * 
+ * + * repeated .grpc.gcp.Identity target_identities = 4; + */ + public io.grpc.alts.internal.Handshaker.Identity getTargetIdentities(int index) { + return targetIdentities_.get(index); + } + /** + *
+     * (Optional) Describes which server identities are acceptable by the client.
+     * If target identities are provided and none of them matches the peer
+     * identity of the server, handshake will fail.
+     * 
+ * + * repeated .grpc.gcp.Identity target_identities = 4; + */ + public io.grpc.alts.internal.Handshaker.IdentityOrBuilder getTargetIdentitiesOrBuilder( + int index) { + return targetIdentities_.get(index); + } + + public static final int LOCAL_IDENTITY_FIELD_NUMBER = 5; + private io.grpc.alts.internal.Handshaker.Identity localIdentity_; + /** + *
+     * (Optional) Application may specify a local identity. Otherwise, the
+     * handshaker chooses a default local identity.
+     * 
+ * + * .grpc.gcp.Identity local_identity = 5; + */ + public boolean hasLocalIdentity() { + return localIdentity_ != null; + } + /** + *
+     * (Optional) Application may specify a local identity. Otherwise, the
+     * handshaker chooses a default local identity.
+     * 
+ * + * .grpc.gcp.Identity local_identity = 5; + */ + public io.grpc.alts.internal.Handshaker.Identity getLocalIdentity() { + return localIdentity_ == null ? io.grpc.alts.internal.Handshaker.Identity.getDefaultInstance() : localIdentity_; + } + /** + *
+     * (Optional) Application may specify a local identity. Otherwise, the
+     * handshaker chooses a default local identity.
+     * 
+ * + * .grpc.gcp.Identity local_identity = 5; + */ + public io.grpc.alts.internal.Handshaker.IdentityOrBuilder getLocalIdentityOrBuilder() { + return getLocalIdentity(); + } + + public static final int LOCAL_ENDPOINT_FIELD_NUMBER = 6; + private io.grpc.alts.internal.Handshaker.Endpoint localEndpoint_; + /** + *
+     * (Optional) Local endpoint information of the connection to the server,
+     * such as local IP address, port number, and network protocol.
+     * 
+ * + * .grpc.gcp.Endpoint local_endpoint = 6; + */ + public boolean hasLocalEndpoint() { + return localEndpoint_ != null; + } + /** + *
+     * (Optional) Local endpoint information of the connection to the server,
+     * such as local IP address, port number, and network protocol.
+     * 
+ * + * .grpc.gcp.Endpoint local_endpoint = 6; + */ + public io.grpc.alts.internal.Handshaker.Endpoint getLocalEndpoint() { + return localEndpoint_ == null ? io.grpc.alts.internal.Handshaker.Endpoint.getDefaultInstance() : localEndpoint_; + } + /** + *
+     * (Optional) Local endpoint information of the connection to the server,
+     * such as local IP address, port number, and network protocol.
+     * 
+ * + * .grpc.gcp.Endpoint local_endpoint = 6; + */ + public io.grpc.alts.internal.Handshaker.EndpointOrBuilder getLocalEndpointOrBuilder() { + return getLocalEndpoint(); + } + + public static final int REMOTE_ENDPOINT_FIELD_NUMBER = 7; + private io.grpc.alts.internal.Handshaker.Endpoint remoteEndpoint_; + /** + *
+     * (Optional) Endpoint information of the remote server, such as IP address,
+     * port number, and network protocol.
+     * 
+ * + * .grpc.gcp.Endpoint remote_endpoint = 7; + */ + public boolean hasRemoteEndpoint() { + return remoteEndpoint_ != null; + } + /** + *
+     * (Optional) Endpoint information of the remote server, such as IP address,
+     * port number, and network protocol.
+     * 
+ * + * .grpc.gcp.Endpoint remote_endpoint = 7; + */ + public io.grpc.alts.internal.Handshaker.Endpoint getRemoteEndpoint() { + return remoteEndpoint_ == null ? io.grpc.alts.internal.Handshaker.Endpoint.getDefaultInstance() : remoteEndpoint_; + } + /** + *
+     * (Optional) Endpoint information of the remote server, such as IP address,
+     * port number, and network protocol.
+     * 
+ * + * .grpc.gcp.Endpoint remote_endpoint = 7; + */ + public io.grpc.alts.internal.Handshaker.EndpointOrBuilder getRemoteEndpointOrBuilder() { + return getRemoteEndpoint(); + } + + public static final int TARGET_NAME_FIELD_NUMBER = 8; + private volatile java.lang.Object targetName_; + /** + *
+     * (Optional) If target name is provided, a secure naming check is performed
+     * to verify that the peer authenticated identity is indeed authorized to run
+     * the target name.
+     * 
+ * + * string target_name = 8; + */ + public java.lang.String getTargetName() { + java.lang.Object ref = targetName_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + targetName_ = s; + return s; + } + } + /** + *
+     * (Optional) If target name is provided, a secure naming check is performed
+     * to verify that the peer authenticated identity is indeed authorized to run
+     * the target name.
+     * 
+ * + * string target_name = 8; + */ + public com.google.protobuf.ByteString + getTargetNameBytes() { + java.lang.Object ref = targetName_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (java.lang.String) ref); + targetName_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int RPC_VERSIONS_FIELD_NUMBER = 9; + private io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions rpcVersions_; + /** + *
+     * (Optional) RPC protocol versions supported by the client.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions rpc_versions = 9; + */ + public boolean hasRpcVersions() { + return rpcVersions_ != null; + } + /** + *
+     * (Optional) RPC protocol versions supported by the client.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions rpc_versions = 9; + */ + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions getRpcVersions() { + return rpcVersions_ == null ? io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.getDefaultInstance() : rpcVersions_; + } + /** + *
+     * (Optional) RPC protocol versions supported by the client.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions rpc_versions = 9; + */ + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersionsOrBuilder getRpcVersionsOrBuilder() { + return getRpcVersions(); + } + + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + if (handshakeSecurityProtocol_ != io.grpc.alts.internal.Handshaker.HandshakeProtocol.HANDSHAKE_PROTOCOL_UNSPECIFIED.getNumber()) { + output.writeEnum(1, handshakeSecurityProtocol_); + } + for (int i = 0; i < applicationProtocols_.size(); i++) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 2, applicationProtocols_.getRaw(i)); + } + for (int i = 0; i < recordProtocols_.size(); i++) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 3, recordProtocols_.getRaw(i)); + } + for (int i = 0; i < targetIdentities_.size(); i++) { + output.writeMessage(4, targetIdentities_.get(i)); + } + if (localIdentity_ != null) { + output.writeMessage(5, getLocalIdentity()); + } + if (localEndpoint_ != null) { + output.writeMessage(6, getLocalEndpoint()); + } + if (remoteEndpoint_ != null) { + output.writeMessage(7, getRemoteEndpoint()); + } + if (!getTargetNameBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 8, targetName_); + } + if (rpcVersions_ != null) { + output.writeMessage(9, getRpcVersions()); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (handshakeSecurityProtocol_ != io.grpc.alts.internal.Handshaker.HandshakeProtocol.HANDSHAKE_PROTOCOL_UNSPECIFIED.getNumber()) { + size += com.google.protobuf.CodedOutputStream + .computeEnumSize(1, handshakeSecurityProtocol_); + } + { + int dataSize = 0; + for (int i = 0; i < applicationProtocols_.size(); i++) { + dataSize += computeStringSizeNoTag(applicationProtocols_.getRaw(i)); + } + size += dataSize; + size += 1 * getApplicationProtocolsList().size(); + } + { + int dataSize = 0; + for (int i = 0; i < recordProtocols_.size(); i++) { + dataSize += computeStringSizeNoTag(recordProtocols_.getRaw(i)); + } + size += dataSize; + size += 1 * getRecordProtocolsList().size(); + } + for (int i = 0; i < targetIdentities_.size(); i++) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(4, targetIdentities_.get(i)); + } + if (localIdentity_ != null) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(5, getLocalIdentity()); + } + if (localEndpoint_ != null) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(6, getLocalEndpoint()); + } + if (remoteEndpoint_ != null) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(7, getRemoteEndpoint()); + } + if (!getTargetNameBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(8, targetName_); + } + if (rpcVersions_ != null) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(9, getRpcVersions()); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof io.grpc.alts.internal.Handshaker.StartClientHandshakeReq)) { + return super.equals(obj); + } + io.grpc.alts.internal.Handshaker.StartClientHandshakeReq other = (io.grpc.alts.internal.Handshaker.StartClientHandshakeReq) obj; + + boolean result = true; + result = result && handshakeSecurityProtocol_ == other.handshakeSecurityProtocol_; + result = result && getApplicationProtocolsList() + .equals(other.getApplicationProtocolsList()); + result = result && getRecordProtocolsList() + .equals(other.getRecordProtocolsList()); + result = result && getTargetIdentitiesList() + .equals(other.getTargetIdentitiesList()); + result = result && (hasLocalIdentity() == other.hasLocalIdentity()); + if (hasLocalIdentity()) { + result = result && getLocalIdentity() + .equals(other.getLocalIdentity()); + } + result = result && (hasLocalEndpoint() == other.hasLocalEndpoint()); + if (hasLocalEndpoint()) { + result = result && getLocalEndpoint() + .equals(other.getLocalEndpoint()); + } + result = result && (hasRemoteEndpoint() == other.hasRemoteEndpoint()); + if (hasRemoteEndpoint()) { + result = result && getRemoteEndpoint() + .equals(other.getRemoteEndpoint()); + } + result = result && getTargetName() + .equals(other.getTargetName()); + result = result && (hasRpcVersions() == other.hasRpcVersions()); + if (hasRpcVersions()) { + result = result && getRpcVersions() + .equals(other.getRpcVersions()); + } + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + hash = (37 * hash) + HANDSHAKE_SECURITY_PROTOCOL_FIELD_NUMBER; + hash = (53 * hash) + handshakeSecurityProtocol_; + if (getApplicationProtocolsCount() > 0) { + hash = (37 * hash) + APPLICATION_PROTOCOLS_FIELD_NUMBER; + hash = (53 * hash) + getApplicationProtocolsList().hashCode(); + } + if (getRecordProtocolsCount() > 0) { + hash = (37 * hash) + RECORD_PROTOCOLS_FIELD_NUMBER; + hash = (53 * hash) + getRecordProtocolsList().hashCode(); + } + if (getTargetIdentitiesCount() > 0) { + hash = (37 * hash) + TARGET_IDENTITIES_FIELD_NUMBER; + hash = (53 * hash) + getTargetIdentitiesList().hashCode(); + } + if (hasLocalIdentity()) { + hash = (37 * hash) + LOCAL_IDENTITY_FIELD_NUMBER; + hash = (53 * hash) + getLocalIdentity().hashCode(); + } + if (hasLocalEndpoint()) { + hash = (37 * hash) + LOCAL_ENDPOINT_FIELD_NUMBER; + hash = (53 * hash) + getLocalEndpoint().hashCode(); + } + if (hasRemoteEndpoint()) { + hash = (37 * hash) + REMOTE_ENDPOINT_FIELD_NUMBER; + hash = (53 * hash) + getRemoteEndpoint().hashCode(); + } + hash = (37 * hash) + TARGET_NAME_FIELD_NUMBER; + hash = (53 * hash) + getTargetName().hashCode(); + if (hasRpcVersions()) { + hash = (37 * hash) + RPC_VERSIONS_FIELD_NUMBER; + hash = (53 * hash) + getRpcVersions().hashCode(); + } + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static io.grpc.alts.internal.Handshaker.StartClientHandshakeReq parseFrom( + java.nio.ByteBuffer data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Handshaker.StartClientHandshakeReq parseFrom( + java.nio.ByteBuffer data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.StartClientHandshakeReq parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Handshaker.StartClientHandshakeReq parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.StartClientHandshakeReq parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Handshaker.StartClientHandshakeReq parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.StartClientHandshakeReq parseFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Handshaker.StartClientHandshakeReq parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.StartClientHandshakeReq parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Handshaker.StartClientHandshakeReq parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.StartClientHandshakeReq parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Handshaker.StartClientHandshakeReq parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + public static Builder newBuilder(io.grpc.alts.internal.Handshaker.StartClientHandshakeReq prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { + return this == DEFAULT_INSTANCE + ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + * Protobuf type {@code grpc.gcp.StartClientHandshakeReq} + */ + public static final class Builder extends + com.google.protobuf.GeneratedMessageV3.Builder implements + // @@protoc_insertion_point(builder_implements:grpc.gcp.StartClientHandshakeReq) + io.grpc.alts.internal.Handshaker.StartClientHandshakeReqOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_StartClientHandshakeReq_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_StartClientHandshakeReq_fieldAccessorTable + .ensureFieldAccessorsInitialized( + io.grpc.alts.internal.Handshaker.StartClientHandshakeReq.class, io.grpc.alts.internal.Handshaker.StartClientHandshakeReq.Builder.class); + } + + // Construct using io.grpc.alts.internal.Handshaker.StartClientHandshakeReq.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder( + com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3 + .alwaysUseFieldBuilders) { + getTargetIdentitiesFieldBuilder(); + } + } + public Builder clear() { + super.clear(); + handshakeSecurityProtocol_ = 0; + + applicationProtocols_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bitField0_ = (bitField0_ & ~0x00000002); + recordProtocols_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bitField0_ = (bitField0_ & ~0x00000004); + if (targetIdentitiesBuilder_ == null) { + targetIdentities_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000008); + } else { + targetIdentitiesBuilder_.clear(); + } + if (localIdentityBuilder_ == null) { + localIdentity_ = null; + } else { + localIdentity_ = null; + localIdentityBuilder_ = null; + } + if (localEndpointBuilder_ == null) { + localEndpoint_ = null; + } else { + localEndpoint_ = null; + localEndpointBuilder_ = null; + } + if (remoteEndpointBuilder_ == null) { + remoteEndpoint_ = null; + } else { + remoteEndpoint_ = null; + remoteEndpointBuilder_ = null; + } + targetName_ = ""; + + if (rpcVersionsBuilder_ == null) { + rpcVersions_ = null; + } else { + rpcVersions_ = null; + rpcVersionsBuilder_ = null; + } + return this; + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_StartClientHandshakeReq_descriptor; + } + + public io.grpc.alts.internal.Handshaker.StartClientHandshakeReq getDefaultInstanceForType() { + return io.grpc.alts.internal.Handshaker.StartClientHandshakeReq.getDefaultInstance(); + } + + public io.grpc.alts.internal.Handshaker.StartClientHandshakeReq build() { + io.grpc.alts.internal.Handshaker.StartClientHandshakeReq result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public io.grpc.alts.internal.Handshaker.StartClientHandshakeReq buildPartial() { + io.grpc.alts.internal.Handshaker.StartClientHandshakeReq result = new io.grpc.alts.internal.Handshaker.StartClientHandshakeReq(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + result.handshakeSecurityProtocol_ = handshakeSecurityProtocol_; + if (((bitField0_ & 0x00000002) == 0x00000002)) { + applicationProtocols_ = applicationProtocols_.getUnmodifiableView(); + bitField0_ = (bitField0_ & ~0x00000002); + } + result.applicationProtocols_ = applicationProtocols_; + if (((bitField0_ & 0x00000004) == 0x00000004)) { + recordProtocols_ = recordProtocols_.getUnmodifiableView(); + bitField0_ = (bitField0_ & ~0x00000004); + } + result.recordProtocols_ = recordProtocols_; + if (targetIdentitiesBuilder_ == null) { + if (((bitField0_ & 0x00000008) == 0x00000008)) { + targetIdentities_ = java.util.Collections.unmodifiableList(targetIdentities_); + bitField0_ = (bitField0_ & ~0x00000008); + } + result.targetIdentities_ = targetIdentities_; + } else { + result.targetIdentities_ = targetIdentitiesBuilder_.build(); + } + if (localIdentityBuilder_ == null) { + result.localIdentity_ = localIdentity_; + } else { + result.localIdentity_ = localIdentityBuilder_.build(); + } + if (localEndpointBuilder_ == null) { + result.localEndpoint_ = localEndpoint_; + } else { + result.localEndpoint_ = localEndpointBuilder_.build(); + } + if (remoteEndpointBuilder_ == null) { + result.remoteEndpoint_ = remoteEndpoint_; + } else { + result.remoteEndpoint_ = remoteEndpointBuilder_.build(); + } + result.targetName_ = targetName_; + if (rpcVersionsBuilder_ == null) { + result.rpcVersions_ = rpcVersions_; + } else { + result.rpcVersions_ = rpcVersionsBuilder_.build(); + } + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder clone() { + return (Builder) super.clone(); + } + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, + java.lang.Object value) { + return (Builder) super.setField(field, value); + } + public Builder clearField( + com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); + } + public Builder clearOneof( + com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); + } + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); + } + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); + } + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof io.grpc.alts.internal.Handshaker.StartClientHandshakeReq) { + return mergeFrom((io.grpc.alts.internal.Handshaker.StartClientHandshakeReq)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(io.grpc.alts.internal.Handshaker.StartClientHandshakeReq other) { + if (other == io.grpc.alts.internal.Handshaker.StartClientHandshakeReq.getDefaultInstance()) return this; + if (other.handshakeSecurityProtocol_ != 0) { + setHandshakeSecurityProtocolValue(other.getHandshakeSecurityProtocolValue()); + } + if (!other.applicationProtocols_.isEmpty()) { + if (applicationProtocols_.isEmpty()) { + applicationProtocols_ = other.applicationProtocols_; + bitField0_ = (bitField0_ & ~0x00000002); + } else { + ensureApplicationProtocolsIsMutable(); + applicationProtocols_.addAll(other.applicationProtocols_); + } + onChanged(); + } + if (!other.recordProtocols_.isEmpty()) { + if (recordProtocols_.isEmpty()) { + recordProtocols_ = other.recordProtocols_; + bitField0_ = (bitField0_ & ~0x00000004); + } else { + ensureRecordProtocolsIsMutable(); + recordProtocols_.addAll(other.recordProtocols_); + } + onChanged(); + } + if (targetIdentitiesBuilder_ == null) { + if (!other.targetIdentities_.isEmpty()) { + if (targetIdentities_.isEmpty()) { + targetIdentities_ = other.targetIdentities_; + bitField0_ = (bitField0_ & ~0x00000008); + } else { + ensureTargetIdentitiesIsMutable(); + targetIdentities_.addAll(other.targetIdentities_); + } + onChanged(); + } + } else { + if (!other.targetIdentities_.isEmpty()) { + if (targetIdentitiesBuilder_.isEmpty()) { + targetIdentitiesBuilder_.dispose(); + targetIdentitiesBuilder_ = null; + targetIdentities_ = other.targetIdentities_; + bitField0_ = (bitField0_ & ~0x00000008); + targetIdentitiesBuilder_ = + com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? + getTargetIdentitiesFieldBuilder() : null; + } else { + targetIdentitiesBuilder_.addAllMessages(other.targetIdentities_); + } + } + } + if (other.hasLocalIdentity()) { + mergeLocalIdentity(other.getLocalIdentity()); + } + if (other.hasLocalEndpoint()) { + mergeLocalEndpoint(other.getLocalEndpoint()); + } + if (other.hasRemoteEndpoint()) { + mergeRemoteEndpoint(other.getRemoteEndpoint()); + } + if (!other.getTargetName().isEmpty()) { + targetName_ = other.targetName_; + onChanged(); + } + if (other.hasRpcVersions()) { + mergeRpcVersions(other.getRpcVersions()); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + io.grpc.alts.internal.Handshaker.StartClientHandshakeReq parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (io.grpc.alts.internal.Handshaker.StartClientHandshakeReq) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + private int bitField0_; + + private int handshakeSecurityProtocol_ = 0; + /** + *
+       * Handshake security protocol requested by the client.
+       * 
+ * + * .grpc.gcp.HandshakeProtocol handshake_security_protocol = 1; + */ + public int getHandshakeSecurityProtocolValue() { + return handshakeSecurityProtocol_; + } + /** + *
+       * Handshake security protocol requested by the client.
+       * 
+ * + * .grpc.gcp.HandshakeProtocol handshake_security_protocol = 1; + */ + public Builder setHandshakeSecurityProtocolValue(int value) { + handshakeSecurityProtocol_ = value; + onChanged(); + return this; + } + /** + *
+       * Handshake security protocol requested by the client.
+       * 
+ * + * .grpc.gcp.HandshakeProtocol handshake_security_protocol = 1; + */ + public io.grpc.alts.internal.Handshaker.HandshakeProtocol getHandshakeSecurityProtocol() { + io.grpc.alts.internal.Handshaker.HandshakeProtocol result = io.grpc.alts.internal.Handshaker.HandshakeProtocol.valueOf(handshakeSecurityProtocol_); + return result == null ? io.grpc.alts.internal.Handshaker.HandshakeProtocol.UNRECOGNIZED : result; + } + /** + *
+       * Handshake security protocol requested by the client.
+       * 
+ * + * .grpc.gcp.HandshakeProtocol handshake_security_protocol = 1; + */ + public Builder setHandshakeSecurityProtocol(io.grpc.alts.internal.Handshaker.HandshakeProtocol value) { + if (value == null) { + throw new NullPointerException(); + } + + handshakeSecurityProtocol_ = value.getNumber(); + onChanged(); + return this; + } + /** + *
+       * Handshake security protocol requested by the client.
+       * 
+ * + * .grpc.gcp.HandshakeProtocol handshake_security_protocol = 1; + */ + public Builder clearHandshakeSecurityProtocol() { + + handshakeSecurityProtocol_ = 0; + onChanged(); + return this; + } + + private com.google.protobuf.LazyStringList applicationProtocols_ = com.google.protobuf.LazyStringArrayList.EMPTY; + private void ensureApplicationProtocolsIsMutable() { + if (!((bitField0_ & 0x00000002) == 0x00000002)) { + applicationProtocols_ = new com.google.protobuf.LazyStringArrayList(applicationProtocols_); + bitField0_ |= 0x00000002; + } + } + /** + *
+       * The application protocols supported by the client, e.g., "h2" (for http2),
+       * "grpc".
+       * 
+ * + * repeated string application_protocols = 2; + */ + public com.google.protobuf.ProtocolStringList + getApplicationProtocolsList() { + return applicationProtocols_.getUnmodifiableView(); + } + /** + *
+       * The application protocols supported by the client, e.g., "h2" (for http2),
+       * "grpc".
+       * 
+ * + * repeated string application_protocols = 2; + */ + public int getApplicationProtocolsCount() { + return applicationProtocols_.size(); + } + /** + *
+       * The application protocols supported by the client, e.g., "h2" (for http2),
+       * "grpc".
+       * 
+ * + * repeated string application_protocols = 2; + */ + public java.lang.String getApplicationProtocols(int index) { + return applicationProtocols_.get(index); + } + /** + *
+       * The application protocols supported by the client, e.g., "h2" (for http2),
+       * "grpc".
+       * 
+ * + * repeated string application_protocols = 2; + */ + public com.google.protobuf.ByteString + getApplicationProtocolsBytes(int index) { + return applicationProtocols_.getByteString(index); + } + /** + *
+       * The application protocols supported by the client, e.g., "h2" (for http2),
+       * "grpc".
+       * 
+ * + * repeated string application_protocols = 2; + */ + public Builder setApplicationProtocols( + int index, java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + ensureApplicationProtocolsIsMutable(); + applicationProtocols_.set(index, value); + onChanged(); + return this; + } + /** + *
+       * The application protocols supported by the client, e.g., "h2" (for http2),
+       * "grpc".
+       * 
+ * + * repeated string application_protocols = 2; + */ + public Builder addApplicationProtocols( + java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + ensureApplicationProtocolsIsMutable(); + applicationProtocols_.add(value); + onChanged(); + return this; + } + /** + *
+       * The application protocols supported by the client, e.g., "h2" (for http2),
+       * "grpc".
+       * 
+ * + * repeated string application_protocols = 2; + */ + public Builder addAllApplicationProtocols( + java.lang.Iterable values) { + ensureApplicationProtocolsIsMutable(); + com.google.protobuf.AbstractMessageLite.Builder.addAll( + values, applicationProtocols_); + onChanged(); + return this; + } + /** + *
+       * The application protocols supported by the client, e.g., "h2" (for http2),
+       * "grpc".
+       * 
+ * + * repeated string application_protocols = 2; + */ + public Builder clearApplicationProtocols() { + applicationProtocols_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bitField0_ = (bitField0_ & ~0x00000002); + onChanged(); + return this; + } + /** + *
+       * The application protocols supported by the client, e.g., "h2" (for http2),
+       * "grpc".
+       * 
+ * + * repeated string application_protocols = 2; + */ + public Builder addApplicationProtocolsBytes( + com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + ensureApplicationProtocolsIsMutable(); + applicationProtocols_.add(value); + onChanged(); + return this; + } + + private com.google.protobuf.LazyStringList recordProtocols_ = com.google.protobuf.LazyStringArrayList.EMPTY; + private void ensureRecordProtocolsIsMutable() { + if (!((bitField0_ & 0x00000004) == 0x00000004)) { + recordProtocols_ = new com.google.protobuf.LazyStringArrayList(recordProtocols_); + bitField0_ |= 0x00000004; + } + } + /** + *
+       * The record protocols supported by the client, e.g.,
+       * "ALTSRP_GCM_AES128".
+       * 
+ * + * repeated string record_protocols = 3; + */ + public com.google.protobuf.ProtocolStringList + getRecordProtocolsList() { + return recordProtocols_.getUnmodifiableView(); + } + /** + *
+       * The record protocols supported by the client, e.g.,
+       * "ALTSRP_GCM_AES128".
+       * 
+ * + * repeated string record_protocols = 3; + */ + public int getRecordProtocolsCount() { + return recordProtocols_.size(); + } + /** + *
+       * The record protocols supported by the client, e.g.,
+       * "ALTSRP_GCM_AES128".
+       * 
+ * + * repeated string record_protocols = 3; + */ + public java.lang.String getRecordProtocols(int index) { + return recordProtocols_.get(index); + } + /** + *
+       * The record protocols supported by the client, e.g.,
+       * "ALTSRP_GCM_AES128".
+       * 
+ * + * repeated string record_protocols = 3; + */ + public com.google.protobuf.ByteString + getRecordProtocolsBytes(int index) { + return recordProtocols_.getByteString(index); + } + /** + *
+       * The record protocols supported by the client, e.g.,
+       * "ALTSRP_GCM_AES128".
+       * 
+ * + * repeated string record_protocols = 3; + */ + public Builder setRecordProtocols( + int index, java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + ensureRecordProtocolsIsMutable(); + recordProtocols_.set(index, value); + onChanged(); + return this; + } + /** + *
+       * The record protocols supported by the client, e.g.,
+       * "ALTSRP_GCM_AES128".
+       * 
+ * + * repeated string record_protocols = 3; + */ + public Builder addRecordProtocols( + java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + ensureRecordProtocolsIsMutable(); + recordProtocols_.add(value); + onChanged(); + return this; + } + /** + *
+       * The record protocols supported by the client, e.g.,
+       * "ALTSRP_GCM_AES128".
+       * 
+ * + * repeated string record_protocols = 3; + */ + public Builder addAllRecordProtocols( + java.lang.Iterable values) { + ensureRecordProtocolsIsMutable(); + com.google.protobuf.AbstractMessageLite.Builder.addAll( + values, recordProtocols_); + onChanged(); + return this; + } + /** + *
+       * The record protocols supported by the client, e.g.,
+       * "ALTSRP_GCM_AES128".
+       * 
+ * + * repeated string record_protocols = 3; + */ + public Builder clearRecordProtocols() { + recordProtocols_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bitField0_ = (bitField0_ & ~0x00000004); + onChanged(); + return this; + } + /** + *
+       * The record protocols supported by the client, e.g.,
+       * "ALTSRP_GCM_AES128".
+       * 
+ * + * repeated string record_protocols = 3; + */ + public Builder addRecordProtocolsBytes( + com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + ensureRecordProtocolsIsMutable(); + recordProtocols_.add(value); + onChanged(); + return this; + } + + private java.util.List targetIdentities_ = + java.util.Collections.emptyList(); + private void ensureTargetIdentitiesIsMutable() { + if (!((bitField0_ & 0x00000008) == 0x00000008)) { + targetIdentities_ = new java.util.ArrayList(targetIdentities_); + bitField0_ |= 0x00000008; + } + } + + private com.google.protobuf.RepeatedFieldBuilderV3< + io.grpc.alts.internal.Handshaker.Identity, io.grpc.alts.internal.Handshaker.Identity.Builder, io.grpc.alts.internal.Handshaker.IdentityOrBuilder> targetIdentitiesBuilder_; + + /** + *
+       * (Optional) Describes which server identities are acceptable by the client.
+       * If target identities are provided and none of them matches the peer
+       * identity of the server, handshake will fail.
+       * 
+ * + * repeated .grpc.gcp.Identity target_identities = 4; + */ + public java.util.List getTargetIdentitiesList() { + if (targetIdentitiesBuilder_ == null) { + return java.util.Collections.unmodifiableList(targetIdentities_); + } else { + return targetIdentitiesBuilder_.getMessageList(); + } + } + /** + *
+       * (Optional) Describes which server identities are acceptable by the client.
+       * If target identities are provided and none of them matches the peer
+       * identity of the server, handshake will fail.
+       * 
+ * + * repeated .grpc.gcp.Identity target_identities = 4; + */ + public int getTargetIdentitiesCount() { + if (targetIdentitiesBuilder_ == null) { + return targetIdentities_.size(); + } else { + return targetIdentitiesBuilder_.getCount(); + } + } + /** + *
+       * (Optional) Describes which server identities are acceptable by the client.
+       * If target identities are provided and none of them matches the peer
+       * identity of the server, handshake will fail.
+       * 
+ * + * repeated .grpc.gcp.Identity target_identities = 4; + */ + public io.grpc.alts.internal.Handshaker.Identity getTargetIdentities(int index) { + if (targetIdentitiesBuilder_ == null) { + return targetIdentities_.get(index); + } else { + return targetIdentitiesBuilder_.getMessage(index); + } + } + /** + *
+       * (Optional) Describes which server identities are acceptable by the client.
+       * If target identities are provided and none of them matches the peer
+       * identity of the server, handshake will fail.
+       * 
+ * + * repeated .grpc.gcp.Identity target_identities = 4; + */ + public Builder setTargetIdentities( + int index, io.grpc.alts.internal.Handshaker.Identity value) { + if (targetIdentitiesBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureTargetIdentitiesIsMutable(); + targetIdentities_.set(index, value); + onChanged(); + } else { + targetIdentitiesBuilder_.setMessage(index, value); + } + return this; + } + /** + *
+       * (Optional) Describes which server identities are acceptable by the client.
+       * If target identities are provided and none of them matches the peer
+       * identity of the server, handshake will fail.
+       * 
+ * + * repeated .grpc.gcp.Identity target_identities = 4; + */ + public Builder setTargetIdentities( + int index, io.grpc.alts.internal.Handshaker.Identity.Builder builderForValue) { + if (targetIdentitiesBuilder_ == null) { + ensureTargetIdentitiesIsMutable(); + targetIdentities_.set(index, builderForValue.build()); + onChanged(); + } else { + targetIdentitiesBuilder_.setMessage(index, builderForValue.build()); + } + return this; + } + /** + *
+       * (Optional) Describes which server identities are acceptable by the client.
+       * If target identities are provided and none of them matches the peer
+       * identity of the server, handshake will fail.
+       * 
+ * + * repeated .grpc.gcp.Identity target_identities = 4; + */ + public Builder addTargetIdentities(io.grpc.alts.internal.Handshaker.Identity value) { + if (targetIdentitiesBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureTargetIdentitiesIsMutable(); + targetIdentities_.add(value); + onChanged(); + } else { + targetIdentitiesBuilder_.addMessage(value); + } + return this; + } + /** + *
+       * (Optional) Describes which server identities are acceptable by the client.
+       * If target identities are provided and none of them matches the peer
+       * identity of the server, handshake will fail.
+       * 
+ * + * repeated .grpc.gcp.Identity target_identities = 4; + */ + public Builder addTargetIdentities( + int index, io.grpc.alts.internal.Handshaker.Identity value) { + if (targetIdentitiesBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureTargetIdentitiesIsMutable(); + targetIdentities_.add(index, value); + onChanged(); + } else { + targetIdentitiesBuilder_.addMessage(index, value); + } + return this; + } + /** + *
+       * (Optional) Describes which server identities are acceptable by the client.
+       * If target identities are provided and none of them matches the peer
+       * identity of the server, handshake will fail.
+       * 
+ * + * repeated .grpc.gcp.Identity target_identities = 4; + */ + public Builder addTargetIdentities( + io.grpc.alts.internal.Handshaker.Identity.Builder builderForValue) { + if (targetIdentitiesBuilder_ == null) { + ensureTargetIdentitiesIsMutable(); + targetIdentities_.add(builderForValue.build()); + onChanged(); + } else { + targetIdentitiesBuilder_.addMessage(builderForValue.build()); + } + return this; + } + /** + *
+       * (Optional) Describes which server identities are acceptable by the client.
+       * If target identities are provided and none of them matches the peer
+       * identity of the server, handshake will fail.
+       * 
+ * + * repeated .grpc.gcp.Identity target_identities = 4; + */ + public Builder addTargetIdentities( + int index, io.grpc.alts.internal.Handshaker.Identity.Builder builderForValue) { + if (targetIdentitiesBuilder_ == null) { + ensureTargetIdentitiesIsMutable(); + targetIdentities_.add(index, builderForValue.build()); + onChanged(); + } else { + targetIdentitiesBuilder_.addMessage(index, builderForValue.build()); + } + return this; + } + /** + *
+       * (Optional) Describes which server identities are acceptable by the client.
+       * If target identities are provided and none of them matches the peer
+       * identity of the server, handshake will fail.
+       * 
+ * + * repeated .grpc.gcp.Identity target_identities = 4; + */ + public Builder addAllTargetIdentities( + java.lang.Iterable values) { + if (targetIdentitiesBuilder_ == null) { + ensureTargetIdentitiesIsMutable(); + com.google.protobuf.AbstractMessageLite.Builder.addAll( + values, targetIdentities_); + onChanged(); + } else { + targetIdentitiesBuilder_.addAllMessages(values); + } + return this; + } + /** + *
+       * (Optional) Describes which server identities are acceptable by the client.
+       * If target identities are provided and none of them matches the peer
+       * identity of the server, handshake will fail.
+       * 
+ * + * repeated .grpc.gcp.Identity target_identities = 4; + */ + public Builder clearTargetIdentities() { + if (targetIdentitiesBuilder_ == null) { + targetIdentities_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000008); + onChanged(); + } else { + targetIdentitiesBuilder_.clear(); + } + return this; + } + /** + *
+       * (Optional) Describes which server identities are acceptable by the client.
+       * If target identities are provided and none of them matches the peer
+       * identity of the server, handshake will fail.
+       * 
+ * + * repeated .grpc.gcp.Identity target_identities = 4; + */ + public Builder removeTargetIdentities(int index) { + if (targetIdentitiesBuilder_ == null) { + ensureTargetIdentitiesIsMutable(); + targetIdentities_.remove(index); + onChanged(); + } else { + targetIdentitiesBuilder_.remove(index); + } + return this; + } + /** + *
+       * (Optional) Describes which server identities are acceptable by the client.
+       * If target identities are provided and none of them matches the peer
+       * identity of the server, handshake will fail.
+       * 
+ * + * repeated .grpc.gcp.Identity target_identities = 4; + */ + public io.grpc.alts.internal.Handshaker.Identity.Builder getTargetIdentitiesBuilder( + int index) { + return getTargetIdentitiesFieldBuilder().getBuilder(index); + } + /** + *
+       * (Optional) Describes which server identities are acceptable by the client.
+       * If target identities are provided and none of them matches the peer
+       * identity of the server, handshake will fail.
+       * 
+ * + * repeated .grpc.gcp.Identity target_identities = 4; + */ + public io.grpc.alts.internal.Handshaker.IdentityOrBuilder getTargetIdentitiesOrBuilder( + int index) { + if (targetIdentitiesBuilder_ == null) { + return targetIdentities_.get(index); } else { + return targetIdentitiesBuilder_.getMessageOrBuilder(index); + } + } + /** + *
+       * (Optional) Describes which server identities are acceptable by the client.
+       * If target identities are provided and none of them matches the peer
+       * identity of the server, handshake will fail.
+       * 
+ * + * repeated .grpc.gcp.Identity target_identities = 4; + */ + public java.util.List + getTargetIdentitiesOrBuilderList() { + if (targetIdentitiesBuilder_ != null) { + return targetIdentitiesBuilder_.getMessageOrBuilderList(); + } else { + return java.util.Collections.unmodifiableList(targetIdentities_); + } + } + /** + *
+       * (Optional) Describes which server identities are acceptable by the client.
+       * If target identities are provided and none of them matches the peer
+       * identity of the server, handshake will fail.
+       * 
+ * + * repeated .grpc.gcp.Identity target_identities = 4; + */ + public io.grpc.alts.internal.Handshaker.Identity.Builder addTargetIdentitiesBuilder() { + return getTargetIdentitiesFieldBuilder().addBuilder( + io.grpc.alts.internal.Handshaker.Identity.getDefaultInstance()); + } + /** + *
+       * (Optional) Describes which server identities are acceptable by the client.
+       * If target identities are provided and none of them matches the peer
+       * identity of the server, handshake will fail.
+       * 
+ * + * repeated .grpc.gcp.Identity target_identities = 4; + */ + public io.grpc.alts.internal.Handshaker.Identity.Builder addTargetIdentitiesBuilder( + int index) { + return getTargetIdentitiesFieldBuilder().addBuilder( + index, io.grpc.alts.internal.Handshaker.Identity.getDefaultInstance()); + } + /** + *
+       * (Optional) Describes which server identities are acceptable by the client.
+       * If target identities are provided and none of them matches the peer
+       * identity of the server, handshake will fail.
+       * 
+ * + * repeated .grpc.gcp.Identity target_identities = 4; + */ + public java.util.List + getTargetIdentitiesBuilderList() { + return getTargetIdentitiesFieldBuilder().getBuilderList(); + } + private com.google.protobuf.RepeatedFieldBuilderV3< + io.grpc.alts.internal.Handshaker.Identity, io.grpc.alts.internal.Handshaker.Identity.Builder, io.grpc.alts.internal.Handshaker.IdentityOrBuilder> + getTargetIdentitiesFieldBuilder() { + if (targetIdentitiesBuilder_ == null) { + targetIdentitiesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< + io.grpc.alts.internal.Handshaker.Identity, io.grpc.alts.internal.Handshaker.Identity.Builder, io.grpc.alts.internal.Handshaker.IdentityOrBuilder>( + targetIdentities_, + ((bitField0_ & 0x00000008) == 0x00000008), + getParentForChildren(), + isClean()); + targetIdentities_ = null; + } + return targetIdentitiesBuilder_; + } + + private io.grpc.alts.internal.Handshaker.Identity localIdentity_ = null; + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.Identity, io.grpc.alts.internal.Handshaker.Identity.Builder, io.grpc.alts.internal.Handshaker.IdentityOrBuilder> localIdentityBuilder_; + /** + *
+       * (Optional) Application may specify a local identity. Otherwise, the
+       * handshaker chooses a default local identity.
+       * 
+ * + * .grpc.gcp.Identity local_identity = 5; + */ + public boolean hasLocalIdentity() { + return localIdentityBuilder_ != null || localIdentity_ != null; + } + /** + *
+       * (Optional) Application may specify a local identity. Otherwise, the
+       * handshaker chooses a default local identity.
+       * 
+ * + * .grpc.gcp.Identity local_identity = 5; + */ + public io.grpc.alts.internal.Handshaker.Identity getLocalIdentity() { + if (localIdentityBuilder_ == null) { + return localIdentity_ == null ? io.grpc.alts.internal.Handshaker.Identity.getDefaultInstance() : localIdentity_; + } else { + return localIdentityBuilder_.getMessage(); + } + } + /** + *
+       * (Optional) Application may specify a local identity. Otherwise, the
+       * handshaker chooses a default local identity.
+       * 
+ * + * .grpc.gcp.Identity local_identity = 5; + */ + public Builder setLocalIdentity(io.grpc.alts.internal.Handshaker.Identity value) { + if (localIdentityBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + localIdentity_ = value; + onChanged(); + } else { + localIdentityBuilder_.setMessage(value); + } + + return this; + } + /** + *
+       * (Optional) Application may specify a local identity. Otherwise, the
+       * handshaker chooses a default local identity.
+       * 
+ * + * .grpc.gcp.Identity local_identity = 5; + */ + public Builder setLocalIdentity( + io.grpc.alts.internal.Handshaker.Identity.Builder builderForValue) { + if (localIdentityBuilder_ == null) { + localIdentity_ = builderForValue.build(); + onChanged(); + } else { + localIdentityBuilder_.setMessage(builderForValue.build()); + } + + return this; + } + /** + *
+       * (Optional) Application may specify a local identity. Otherwise, the
+       * handshaker chooses a default local identity.
+       * 
+ * + * .grpc.gcp.Identity local_identity = 5; + */ + public Builder mergeLocalIdentity(io.grpc.alts.internal.Handshaker.Identity value) { + if (localIdentityBuilder_ == null) { + if (localIdentity_ != null) { + localIdentity_ = + io.grpc.alts.internal.Handshaker.Identity.newBuilder(localIdentity_).mergeFrom(value).buildPartial(); + } else { + localIdentity_ = value; + } + onChanged(); + } else { + localIdentityBuilder_.mergeFrom(value); + } + + return this; + } + /** + *
+       * (Optional) Application may specify a local identity. Otherwise, the
+       * handshaker chooses a default local identity.
+       * 
+ * + * .grpc.gcp.Identity local_identity = 5; + */ + public Builder clearLocalIdentity() { + if (localIdentityBuilder_ == null) { + localIdentity_ = null; + onChanged(); + } else { + localIdentity_ = null; + localIdentityBuilder_ = null; + } + + return this; + } + /** + *
+       * (Optional) Application may specify a local identity. Otherwise, the
+       * handshaker chooses a default local identity.
+       * 
+ * + * .grpc.gcp.Identity local_identity = 5; + */ + public io.grpc.alts.internal.Handshaker.Identity.Builder getLocalIdentityBuilder() { + + onChanged(); + return getLocalIdentityFieldBuilder().getBuilder(); + } + /** + *
+       * (Optional) Application may specify a local identity. Otherwise, the
+       * handshaker chooses a default local identity.
+       * 
+ * + * .grpc.gcp.Identity local_identity = 5; + */ + public io.grpc.alts.internal.Handshaker.IdentityOrBuilder getLocalIdentityOrBuilder() { + if (localIdentityBuilder_ != null) { + return localIdentityBuilder_.getMessageOrBuilder(); + } else { + return localIdentity_ == null ? + io.grpc.alts.internal.Handshaker.Identity.getDefaultInstance() : localIdentity_; + } + } + /** + *
+       * (Optional) Application may specify a local identity. Otherwise, the
+       * handshaker chooses a default local identity.
+       * 
+ * + * .grpc.gcp.Identity local_identity = 5; + */ + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.Identity, io.grpc.alts.internal.Handshaker.Identity.Builder, io.grpc.alts.internal.Handshaker.IdentityOrBuilder> + getLocalIdentityFieldBuilder() { + if (localIdentityBuilder_ == null) { + localIdentityBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.Identity, io.grpc.alts.internal.Handshaker.Identity.Builder, io.grpc.alts.internal.Handshaker.IdentityOrBuilder>( + getLocalIdentity(), + getParentForChildren(), + isClean()); + localIdentity_ = null; + } + return localIdentityBuilder_; + } + + private io.grpc.alts.internal.Handshaker.Endpoint localEndpoint_ = null; + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.Endpoint, io.grpc.alts.internal.Handshaker.Endpoint.Builder, io.grpc.alts.internal.Handshaker.EndpointOrBuilder> localEndpointBuilder_; + /** + *
+       * (Optional) Local endpoint information of the connection to the server,
+       * such as local IP address, port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint local_endpoint = 6; + */ + public boolean hasLocalEndpoint() { + return localEndpointBuilder_ != null || localEndpoint_ != null; + } + /** + *
+       * (Optional) Local endpoint information of the connection to the server,
+       * such as local IP address, port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint local_endpoint = 6; + */ + public io.grpc.alts.internal.Handshaker.Endpoint getLocalEndpoint() { + if (localEndpointBuilder_ == null) { + return localEndpoint_ == null ? io.grpc.alts.internal.Handshaker.Endpoint.getDefaultInstance() : localEndpoint_; + } else { + return localEndpointBuilder_.getMessage(); + } + } + /** + *
+       * (Optional) Local endpoint information of the connection to the server,
+       * such as local IP address, port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint local_endpoint = 6; + */ + public Builder setLocalEndpoint(io.grpc.alts.internal.Handshaker.Endpoint value) { + if (localEndpointBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + localEndpoint_ = value; + onChanged(); + } else { + localEndpointBuilder_.setMessage(value); + } + + return this; + } + /** + *
+       * (Optional) Local endpoint information of the connection to the server,
+       * such as local IP address, port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint local_endpoint = 6; + */ + public Builder setLocalEndpoint( + io.grpc.alts.internal.Handshaker.Endpoint.Builder builderForValue) { + if (localEndpointBuilder_ == null) { + localEndpoint_ = builderForValue.build(); + onChanged(); + } else { + localEndpointBuilder_.setMessage(builderForValue.build()); + } + + return this; + } + /** + *
+       * (Optional) Local endpoint information of the connection to the server,
+       * such as local IP address, port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint local_endpoint = 6; + */ + public Builder mergeLocalEndpoint(io.grpc.alts.internal.Handshaker.Endpoint value) { + if (localEndpointBuilder_ == null) { + if (localEndpoint_ != null) { + localEndpoint_ = + io.grpc.alts.internal.Handshaker.Endpoint.newBuilder(localEndpoint_).mergeFrom(value).buildPartial(); + } else { + localEndpoint_ = value; + } + onChanged(); + } else { + localEndpointBuilder_.mergeFrom(value); + } + + return this; + } + /** + *
+       * (Optional) Local endpoint information of the connection to the server,
+       * such as local IP address, port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint local_endpoint = 6; + */ + public Builder clearLocalEndpoint() { + if (localEndpointBuilder_ == null) { + localEndpoint_ = null; + onChanged(); + } else { + localEndpoint_ = null; + localEndpointBuilder_ = null; + } + + return this; + } + /** + *
+       * (Optional) Local endpoint information of the connection to the server,
+       * such as local IP address, port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint local_endpoint = 6; + */ + public io.grpc.alts.internal.Handshaker.Endpoint.Builder getLocalEndpointBuilder() { + + onChanged(); + return getLocalEndpointFieldBuilder().getBuilder(); + } + /** + *
+       * (Optional) Local endpoint information of the connection to the server,
+       * such as local IP address, port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint local_endpoint = 6; + */ + public io.grpc.alts.internal.Handshaker.EndpointOrBuilder getLocalEndpointOrBuilder() { + if (localEndpointBuilder_ != null) { + return localEndpointBuilder_.getMessageOrBuilder(); + } else { + return localEndpoint_ == null ? + io.grpc.alts.internal.Handshaker.Endpoint.getDefaultInstance() : localEndpoint_; + } + } + /** + *
+       * (Optional) Local endpoint information of the connection to the server,
+       * such as local IP address, port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint local_endpoint = 6; + */ + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.Endpoint, io.grpc.alts.internal.Handshaker.Endpoint.Builder, io.grpc.alts.internal.Handshaker.EndpointOrBuilder> + getLocalEndpointFieldBuilder() { + if (localEndpointBuilder_ == null) { + localEndpointBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.Endpoint, io.grpc.alts.internal.Handshaker.Endpoint.Builder, io.grpc.alts.internal.Handshaker.EndpointOrBuilder>( + getLocalEndpoint(), + getParentForChildren(), + isClean()); + localEndpoint_ = null; + } + return localEndpointBuilder_; + } + + private io.grpc.alts.internal.Handshaker.Endpoint remoteEndpoint_ = null; + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.Endpoint, io.grpc.alts.internal.Handshaker.Endpoint.Builder, io.grpc.alts.internal.Handshaker.EndpointOrBuilder> remoteEndpointBuilder_; + /** + *
+       * (Optional) Endpoint information of the remote server, such as IP address,
+       * port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint remote_endpoint = 7; + */ + public boolean hasRemoteEndpoint() { + return remoteEndpointBuilder_ != null || remoteEndpoint_ != null; + } + /** + *
+       * (Optional) Endpoint information of the remote server, such as IP address,
+       * port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint remote_endpoint = 7; + */ + public io.grpc.alts.internal.Handshaker.Endpoint getRemoteEndpoint() { + if (remoteEndpointBuilder_ == null) { + return remoteEndpoint_ == null ? io.grpc.alts.internal.Handshaker.Endpoint.getDefaultInstance() : remoteEndpoint_; + } else { + return remoteEndpointBuilder_.getMessage(); + } + } + /** + *
+       * (Optional) Endpoint information of the remote server, such as IP address,
+       * port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint remote_endpoint = 7; + */ + public Builder setRemoteEndpoint(io.grpc.alts.internal.Handshaker.Endpoint value) { + if (remoteEndpointBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + remoteEndpoint_ = value; + onChanged(); + } else { + remoteEndpointBuilder_.setMessage(value); + } + + return this; + } + /** + *
+       * (Optional) Endpoint information of the remote server, such as IP address,
+       * port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint remote_endpoint = 7; + */ + public Builder setRemoteEndpoint( + io.grpc.alts.internal.Handshaker.Endpoint.Builder builderForValue) { + if (remoteEndpointBuilder_ == null) { + remoteEndpoint_ = builderForValue.build(); + onChanged(); + } else { + remoteEndpointBuilder_.setMessage(builderForValue.build()); + } + + return this; + } + /** + *
+       * (Optional) Endpoint information of the remote server, such as IP address,
+       * port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint remote_endpoint = 7; + */ + public Builder mergeRemoteEndpoint(io.grpc.alts.internal.Handshaker.Endpoint value) { + if (remoteEndpointBuilder_ == null) { + if (remoteEndpoint_ != null) { + remoteEndpoint_ = + io.grpc.alts.internal.Handshaker.Endpoint.newBuilder(remoteEndpoint_).mergeFrom(value).buildPartial(); + } else { + remoteEndpoint_ = value; + } + onChanged(); + } else { + remoteEndpointBuilder_.mergeFrom(value); + } + + return this; + } + /** + *
+       * (Optional) Endpoint information of the remote server, such as IP address,
+       * port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint remote_endpoint = 7; + */ + public Builder clearRemoteEndpoint() { + if (remoteEndpointBuilder_ == null) { + remoteEndpoint_ = null; + onChanged(); + } else { + remoteEndpoint_ = null; + remoteEndpointBuilder_ = null; + } + + return this; + } + /** + *
+       * (Optional) Endpoint information of the remote server, such as IP address,
+       * port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint remote_endpoint = 7; + */ + public io.grpc.alts.internal.Handshaker.Endpoint.Builder getRemoteEndpointBuilder() { + + onChanged(); + return getRemoteEndpointFieldBuilder().getBuilder(); + } + /** + *
+       * (Optional) Endpoint information of the remote server, such as IP address,
+       * port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint remote_endpoint = 7; + */ + public io.grpc.alts.internal.Handshaker.EndpointOrBuilder getRemoteEndpointOrBuilder() { + if (remoteEndpointBuilder_ != null) { + return remoteEndpointBuilder_.getMessageOrBuilder(); + } else { + return remoteEndpoint_ == null ? + io.grpc.alts.internal.Handshaker.Endpoint.getDefaultInstance() : remoteEndpoint_; + } + } + /** + *
+       * (Optional) Endpoint information of the remote server, such as IP address,
+       * port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint remote_endpoint = 7; + */ + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.Endpoint, io.grpc.alts.internal.Handshaker.Endpoint.Builder, io.grpc.alts.internal.Handshaker.EndpointOrBuilder> + getRemoteEndpointFieldBuilder() { + if (remoteEndpointBuilder_ == null) { + remoteEndpointBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.Endpoint, io.grpc.alts.internal.Handshaker.Endpoint.Builder, io.grpc.alts.internal.Handshaker.EndpointOrBuilder>( + getRemoteEndpoint(), + getParentForChildren(), + isClean()); + remoteEndpoint_ = null; + } + return remoteEndpointBuilder_; + } + + private java.lang.Object targetName_ = ""; + /** + *
+       * (Optional) If target name is provided, a secure naming check is performed
+       * to verify that the peer authenticated identity is indeed authorized to run
+       * the target name.
+       * 
+ * + * string target_name = 8; + */ + public java.lang.String getTargetName() { + java.lang.Object ref = targetName_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + targetName_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + /** + *
+       * (Optional) If target name is provided, a secure naming check is performed
+       * to verify that the peer authenticated identity is indeed authorized to run
+       * the target name.
+       * 
+ * + * string target_name = 8; + */ + public com.google.protobuf.ByteString + getTargetNameBytes() { + java.lang.Object ref = targetName_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (java.lang.String) ref); + targetName_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + /** + *
+       * (Optional) If target name is provided, a secure naming check is performed
+       * to verify that the peer authenticated identity is indeed authorized to run
+       * the target name.
+       * 
+ * + * string target_name = 8; + */ + public Builder setTargetName( + java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + + targetName_ = value; + onChanged(); + return this; + } + /** + *
+       * (Optional) If target name is provided, a secure naming check is performed
+       * to verify that the peer authenticated identity is indeed authorized to run
+       * the target name.
+       * 
+ * + * string target_name = 8; + */ + public Builder clearTargetName() { + + targetName_ = getDefaultInstance().getTargetName(); + onChanged(); + return this; + } + /** + *
+       * (Optional) If target name is provided, a secure naming check is performed
+       * to verify that the peer authenticated identity is indeed authorized to run
+       * the target name.
+       * 
+ * + * string target_name = 8; + */ + public Builder setTargetNameBytes( + com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + + targetName_ = value; + onChanged(); + return this; + } + + private io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions rpcVersions_ = null; + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Builder, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersionsOrBuilder> rpcVersionsBuilder_; + /** + *
+       * (Optional) RPC protocol versions supported by the client.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions rpc_versions = 9; + */ + public boolean hasRpcVersions() { + return rpcVersionsBuilder_ != null || rpcVersions_ != null; + } + /** + *
+       * (Optional) RPC protocol versions supported by the client.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions rpc_versions = 9; + */ + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions getRpcVersions() { + if (rpcVersionsBuilder_ == null) { + return rpcVersions_ == null ? io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.getDefaultInstance() : rpcVersions_; + } else { + return rpcVersionsBuilder_.getMessage(); + } + } + /** + *
+       * (Optional) RPC protocol versions supported by the client.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions rpc_versions = 9; + */ + public Builder setRpcVersions(io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions value) { + if (rpcVersionsBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + rpcVersions_ = value; + onChanged(); + } else { + rpcVersionsBuilder_.setMessage(value); + } + + return this; + } + /** + *
+       * (Optional) RPC protocol versions supported by the client.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions rpc_versions = 9; + */ + public Builder setRpcVersions( + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Builder builderForValue) { + if (rpcVersionsBuilder_ == null) { + rpcVersions_ = builderForValue.build(); + onChanged(); + } else { + rpcVersionsBuilder_.setMessage(builderForValue.build()); + } + + return this; + } + /** + *
+       * (Optional) RPC protocol versions supported by the client.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions rpc_versions = 9; + */ + public Builder mergeRpcVersions(io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions value) { + if (rpcVersionsBuilder_ == null) { + if (rpcVersions_ != null) { + rpcVersions_ = + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.newBuilder(rpcVersions_).mergeFrom(value).buildPartial(); + } else { + rpcVersions_ = value; + } + onChanged(); + } else { + rpcVersionsBuilder_.mergeFrom(value); + } + + return this; + } + /** + *
+       * (Optional) RPC protocol versions supported by the client.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions rpc_versions = 9; + */ + public Builder clearRpcVersions() { + if (rpcVersionsBuilder_ == null) { + rpcVersions_ = null; + onChanged(); + } else { + rpcVersions_ = null; + rpcVersionsBuilder_ = null; + } + + return this; + } + /** + *
+       * (Optional) RPC protocol versions supported by the client.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions rpc_versions = 9; + */ + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Builder getRpcVersionsBuilder() { + + onChanged(); + return getRpcVersionsFieldBuilder().getBuilder(); + } + /** + *
+       * (Optional) RPC protocol versions supported by the client.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions rpc_versions = 9; + */ + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersionsOrBuilder getRpcVersionsOrBuilder() { + if (rpcVersionsBuilder_ != null) { + return rpcVersionsBuilder_.getMessageOrBuilder(); + } else { + return rpcVersions_ == null ? + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.getDefaultInstance() : rpcVersions_; + } + } + /** + *
+       * (Optional) RPC protocol versions supported by the client.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions rpc_versions = 9; + */ + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Builder, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersionsOrBuilder> + getRpcVersionsFieldBuilder() { + if (rpcVersionsBuilder_ == null) { + rpcVersionsBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Builder, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersionsOrBuilder>( + getRpcVersions(), + getParentForChildren(), + isClean()); + rpcVersions_ = null; + } + return rpcVersionsBuilder_; + } + public final Builder setUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); + } + + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + + // @@protoc_insertion_point(builder_scope:grpc.gcp.StartClientHandshakeReq) + } + + // @@protoc_insertion_point(class_scope:grpc.gcp.StartClientHandshakeReq) + private static final io.grpc.alts.internal.Handshaker.StartClientHandshakeReq DEFAULT_INSTANCE; + static { + DEFAULT_INSTANCE = new io.grpc.alts.internal.Handshaker.StartClientHandshakeReq(); + } + + public static io.grpc.alts.internal.Handshaker.StartClientHandshakeReq getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + private static final com.google.protobuf.Parser + PARSER = new com.google.protobuf.AbstractParser() { + public StartClientHandshakeReq parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new StartClientHandshakeReq(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public io.grpc.alts.internal.Handshaker.StartClientHandshakeReq getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } + + } + + public interface ServerHandshakeParametersOrBuilder extends + // @@protoc_insertion_point(interface_extends:grpc.gcp.ServerHandshakeParameters) + com.google.protobuf.MessageOrBuilder { + + /** + *
+     * The record protocols supported by the server, e.g.,
+     * "ALTSRP_GCM_AES128".
+     * 
+ * + * repeated string record_protocols = 1; + */ + java.util.List + getRecordProtocolsList(); + /** + *
+     * The record protocols supported by the server, e.g.,
+     * "ALTSRP_GCM_AES128".
+     * 
+ * + * repeated string record_protocols = 1; + */ + int getRecordProtocolsCount(); + /** + *
+     * The record protocols supported by the server, e.g.,
+     * "ALTSRP_GCM_AES128".
+     * 
+ * + * repeated string record_protocols = 1; + */ + java.lang.String getRecordProtocols(int index); + /** + *
+     * The record protocols supported by the server, e.g.,
+     * "ALTSRP_GCM_AES128".
+     * 
+ * + * repeated string record_protocols = 1; + */ + com.google.protobuf.ByteString + getRecordProtocolsBytes(int index); + + /** + *
+     * (Optional) A list of local identities supported by the server, if
+     * specified. Otherwise, the handshaker chooses a default local identity.
+     * 
+ * + * repeated .grpc.gcp.Identity local_identities = 2; + */ + java.util.List + getLocalIdentitiesList(); + /** + *
+     * (Optional) A list of local identities supported by the server, if
+     * specified. Otherwise, the handshaker chooses a default local identity.
+     * 
+ * + * repeated .grpc.gcp.Identity local_identities = 2; + */ + io.grpc.alts.internal.Handshaker.Identity getLocalIdentities(int index); + /** + *
+     * (Optional) A list of local identities supported by the server, if
+     * specified. Otherwise, the handshaker chooses a default local identity.
+     * 
+ * + * repeated .grpc.gcp.Identity local_identities = 2; + */ + int getLocalIdentitiesCount(); + /** + *
+     * (Optional) A list of local identities supported by the server, if
+     * specified. Otherwise, the handshaker chooses a default local identity.
+     * 
+ * + * repeated .grpc.gcp.Identity local_identities = 2; + */ + java.util.List + getLocalIdentitiesOrBuilderList(); + /** + *
+     * (Optional) A list of local identities supported by the server, if
+     * specified. Otherwise, the handshaker chooses a default local identity.
+     * 
+ * + * repeated .grpc.gcp.Identity local_identities = 2; + */ + io.grpc.alts.internal.Handshaker.IdentityOrBuilder getLocalIdentitiesOrBuilder( + int index); + } + /** + * Protobuf type {@code grpc.gcp.ServerHandshakeParameters} + */ + public static final class ServerHandshakeParameters extends + com.google.protobuf.GeneratedMessageV3 implements + // @@protoc_insertion_point(message_implements:grpc.gcp.ServerHandshakeParameters) + ServerHandshakeParametersOrBuilder { + private static final long serialVersionUID = 0L; + // Use ServerHandshakeParameters.newBuilder() to construct. + private ServerHandshakeParameters(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + private ServerHandshakeParameters() { + recordProtocols_ = com.google.protobuf.LazyStringArrayList.EMPTY; + localIdentities_ = java.util.Collections.emptyList(); + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return this.unknownFields; + } + private ServerHandshakeParameters( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownFieldProto3( + input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 10: { + java.lang.String s = input.readStringRequireUtf8(); + if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { + recordProtocols_ = new com.google.protobuf.LazyStringArrayList(); + mutable_bitField0_ |= 0x00000001; + } + recordProtocols_.add(s); + break; + } + case 18: { + if (!((mutable_bitField0_ & 0x00000002) == 0x00000002)) { + localIdentities_ = new java.util.ArrayList(); + mutable_bitField0_ |= 0x00000002; + } + localIdentities_.add( + input.readMessage(io.grpc.alts.internal.Handshaker.Identity.parser(), extensionRegistry)); + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e).setUnfinishedMessage(this); + } finally { + if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) { + recordProtocols_ = recordProtocols_.getUnmodifiableView(); + } + if (((mutable_bitField0_ & 0x00000002) == 0x00000002)) { + localIdentities_ = java.util.Collections.unmodifiableList(localIdentities_); + } + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_ServerHandshakeParameters_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_ServerHandshakeParameters_fieldAccessorTable + .ensureFieldAccessorsInitialized( + io.grpc.alts.internal.Handshaker.ServerHandshakeParameters.class, io.grpc.alts.internal.Handshaker.ServerHandshakeParameters.Builder.class); + } + + public static final int RECORD_PROTOCOLS_FIELD_NUMBER = 1; + private com.google.protobuf.LazyStringList recordProtocols_; + /** + *
+     * The record protocols supported by the server, e.g.,
+     * "ALTSRP_GCM_AES128".
+     * 
+ * + * repeated string record_protocols = 1; + */ + public com.google.protobuf.ProtocolStringList + getRecordProtocolsList() { + return recordProtocols_; + } + /** + *
+     * The record protocols supported by the server, e.g.,
+     * "ALTSRP_GCM_AES128".
+     * 
+ * + * repeated string record_protocols = 1; + */ + public int getRecordProtocolsCount() { + return recordProtocols_.size(); + } + /** + *
+     * The record protocols supported by the server, e.g.,
+     * "ALTSRP_GCM_AES128".
+     * 
+ * + * repeated string record_protocols = 1; + */ + public java.lang.String getRecordProtocols(int index) { + return recordProtocols_.get(index); + } + /** + *
+     * The record protocols supported by the server, e.g.,
+     * "ALTSRP_GCM_AES128".
+     * 
+ * + * repeated string record_protocols = 1; + */ + public com.google.protobuf.ByteString + getRecordProtocolsBytes(int index) { + return recordProtocols_.getByteString(index); + } + + public static final int LOCAL_IDENTITIES_FIELD_NUMBER = 2; + private java.util.List localIdentities_; + /** + *
+     * (Optional) A list of local identities supported by the server, if
+     * specified. Otherwise, the handshaker chooses a default local identity.
+     * 
+ * + * repeated .grpc.gcp.Identity local_identities = 2; + */ + public java.util.List getLocalIdentitiesList() { + return localIdentities_; + } + /** + *
+     * (Optional) A list of local identities supported by the server, if
+     * specified. Otherwise, the handshaker chooses a default local identity.
+     * 
+ * + * repeated .grpc.gcp.Identity local_identities = 2; + */ + public java.util.List + getLocalIdentitiesOrBuilderList() { + return localIdentities_; + } + /** + *
+     * (Optional) A list of local identities supported by the server, if
+     * specified. Otherwise, the handshaker chooses a default local identity.
+     * 
+ * + * repeated .grpc.gcp.Identity local_identities = 2; + */ + public int getLocalIdentitiesCount() { + return localIdentities_.size(); + } + /** + *
+     * (Optional) A list of local identities supported by the server, if
+     * specified. Otherwise, the handshaker chooses a default local identity.
+     * 
+ * + * repeated .grpc.gcp.Identity local_identities = 2; + */ + public io.grpc.alts.internal.Handshaker.Identity getLocalIdentities(int index) { + return localIdentities_.get(index); + } + /** + *
+     * (Optional) A list of local identities supported by the server, if
+     * specified. Otherwise, the handshaker chooses a default local identity.
+     * 
+ * + * repeated .grpc.gcp.Identity local_identities = 2; + */ + public io.grpc.alts.internal.Handshaker.IdentityOrBuilder getLocalIdentitiesOrBuilder( + int index) { + return localIdentities_.get(index); + } + + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + for (int i = 0; i < recordProtocols_.size(); i++) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 1, recordProtocols_.getRaw(i)); + } + for (int i = 0; i < localIdentities_.size(); i++) { + output.writeMessage(2, localIdentities_.get(i)); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + { + int dataSize = 0; + for (int i = 0; i < recordProtocols_.size(); i++) { + dataSize += computeStringSizeNoTag(recordProtocols_.getRaw(i)); + } + size += dataSize; + size += 1 * getRecordProtocolsList().size(); + } + for (int i = 0; i < localIdentities_.size(); i++) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(2, localIdentities_.get(i)); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof io.grpc.alts.internal.Handshaker.ServerHandshakeParameters)) { + return super.equals(obj); + } + io.grpc.alts.internal.Handshaker.ServerHandshakeParameters other = (io.grpc.alts.internal.Handshaker.ServerHandshakeParameters) obj; + + boolean result = true; + result = result && getRecordProtocolsList() + .equals(other.getRecordProtocolsList()); + result = result && getLocalIdentitiesList() + .equals(other.getLocalIdentitiesList()); + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + if (getRecordProtocolsCount() > 0) { + hash = (37 * hash) + RECORD_PROTOCOLS_FIELD_NUMBER; + hash = (53 * hash) + getRecordProtocolsList().hashCode(); + } + if (getLocalIdentitiesCount() > 0) { + hash = (37 * hash) + LOCAL_IDENTITIES_FIELD_NUMBER; + hash = (53 * hash) + getLocalIdentitiesList().hashCode(); + } + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static io.grpc.alts.internal.Handshaker.ServerHandshakeParameters parseFrom( + java.nio.ByteBuffer data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Handshaker.ServerHandshakeParameters parseFrom( + java.nio.ByteBuffer data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.ServerHandshakeParameters parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Handshaker.ServerHandshakeParameters parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.ServerHandshakeParameters parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Handshaker.ServerHandshakeParameters parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.ServerHandshakeParameters parseFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Handshaker.ServerHandshakeParameters parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.ServerHandshakeParameters parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Handshaker.ServerHandshakeParameters parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.ServerHandshakeParameters parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Handshaker.ServerHandshakeParameters parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + public static Builder newBuilder(io.grpc.alts.internal.Handshaker.ServerHandshakeParameters prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { + return this == DEFAULT_INSTANCE + ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + * Protobuf type {@code grpc.gcp.ServerHandshakeParameters} + */ + public static final class Builder extends + com.google.protobuf.GeneratedMessageV3.Builder implements + // @@protoc_insertion_point(builder_implements:grpc.gcp.ServerHandshakeParameters) + io.grpc.alts.internal.Handshaker.ServerHandshakeParametersOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_ServerHandshakeParameters_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_ServerHandshakeParameters_fieldAccessorTable + .ensureFieldAccessorsInitialized( + io.grpc.alts.internal.Handshaker.ServerHandshakeParameters.class, io.grpc.alts.internal.Handshaker.ServerHandshakeParameters.Builder.class); + } + + // Construct using io.grpc.alts.internal.Handshaker.ServerHandshakeParameters.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder( + com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3 + .alwaysUseFieldBuilders) { + getLocalIdentitiesFieldBuilder(); + } + } + public Builder clear() { + super.clear(); + recordProtocols_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bitField0_ = (bitField0_ & ~0x00000001); + if (localIdentitiesBuilder_ == null) { + localIdentities_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000002); + } else { + localIdentitiesBuilder_.clear(); + } + return this; + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_ServerHandshakeParameters_descriptor; + } + + public io.grpc.alts.internal.Handshaker.ServerHandshakeParameters getDefaultInstanceForType() { + return io.grpc.alts.internal.Handshaker.ServerHandshakeParameters.getDefaultInstance(); + } + + public io.grpc.alts.internal.Handshaker.ServerHandshakeParameters build() { + io.grpc.alts.internal.Handshaker.ServerHandshakeParameters result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public io.grpc.alts.internal.Handshaker.ServerHandshakeParameters buildPartial() { + io.grpc.alts.internal.Handshaker.ServerHandshakeParameters result = new io.grpc.alts.internal.Handshaker.ServerHandshakeParameters(this); + int from_bitField0_ = bitField0_; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + recordProtocols_ = recordProtocols_.getUnmodifiableView(); + bitField0_ = (bitField0_ & ~0x00000001); + } + result.recordProtocols_ = recordProtocols_; + if (localIdentitiesBuilder_ == null) { + if (((bitField0_ & 0x00000002) == 0x00000002)) { + localIdentities_ = java.util.Collections.unmodifiableList(localIdentities_); + bitField0_ = (bitField0_ & ~0x00000002); + } + result.localIdentities_ = localIdentities_; + } else { + result.localIdentities_ = localIdentitiesBuilder_.build(); + } + onBuilt(); + return result; + } + + public Builder clone() { + return (Builder) super.clone(); + } + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, + java.lang.Object value) { + return (Builder) super.setField(field, value); + } + public Builder clearField( + com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); + } + public Builder clearOneof( + com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); + } + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); + } + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); + } + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof io.grpc.alts.internal.Handshaker.ServerHandshakeParameters) { + return mergeFrom((io.grpc.alts.internal.Handshaker.ServerHandshakeParameters)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(io.grpc.alts.internal.Handshaker.ServerHandshakeParameters other) { + if (other == io.grpc.alts.internal.Handshaker.ServerHandshakeParameters.getDefaultInstance()) return this; + if (!other.recordProtocols_.isEmpty()) { + if (recordProtocols_.isEmpty()) { + recordProtocols_ = other.recordProtocols_; + bitField0_ = (bitField0_ & ~0x00000001); + } else { + ensureRecordProtocolsIsMutable(); + recordProtocols_.addAll(other.recordProtocols_); + } + onChanged(); + } + if (localIdentitiesBuilder_ == null) { + if (!other.localIdentities_.isEmpty()) { + if (localIdentities_.isEmpty()) { + localIdentities_ = other.localIdentities_; + bitField0_ = (bitField0_ & ~0x00000002); + } else { + ensureLocalIdentitiesIsMutable(); + localIdentities_.addAll(other.localIdentities_); + } + onChanged(); + } + } else { + if (!other.localIdentities_.isEmpty()) { + if (localIdentitiesBuilder_.isEmpty()) { + localIdentitiesBuilder_.dispose(); + localIdentitiesBuilder_ = null; + localIdentities_ = other.localIdentities_; + bitField0_ = (bitField0_ & ~0x00000002); + localIdentitiesBuilder_ = + com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? + getLocalIdentitiesFieldBuilder() : null; + } else { + localIdentitiesBuilder_.addAllMessages(other.localIdentities_); + } + } + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + io.grpc.alts.internal.Handshaker.ServerHandshakeParameters parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (io.grpc.alts.internal.Handshaker.ServerHandshakeParameters) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + private int bitField0_; + + private com.google.protobuf.LazyStringList recordProtocols_ = com.google.protobuf.LazyStringArrayList.EMPTY; + private void ensureRecordProtocolsIsMutable() { + if (!((bitField0_ & 0x00000001) == 0x00000001)) { + recordProtocols_ = new com.google.protobuf.LazyStringArrayList(recordProtocols_); + bitField0_ |= 0x00000001; + } + } + /** + *
+       * The record protocols supported by the server, e.g.,
+       * "ALTSRP_GCM_AES128".
+       * 
+ * + * repeated string record_protocols = 1; + */ + public com.google.protobuf.ProtocolStringList + getRecordProtocolsList() { + return recordProtocols_.getUnmodifiableView(); + } + /** + *
+       * The record protocols supported by the server, e.g.,
+       * "ALTSRP_GCM_AES128".
+       * 
+ * + * repeated string record_protocols = 1; + */ + public int getRecordProtocolsCount() { + return recordProtocols_.size(); + } + /** + *
+       * The record protocols supported by the server, e.g.,
+       * "ALTSRP_GCM_AES128".
+       * 
+ * + * repeated string record_protocols = 1; + */ + public java.lang.String getRecordProtocols(int index) { + return recordProtocols_.get(index); + } + /** + *
+       * The record protocols supported by the server, e.g.,
+       * "ALTSRP_GCM_AES128".
+       * 
+ * + * repeated string record_protocols = 1; + */ + public com.google.protobuf.ByteString + getRecordProtocolsBytes(int index) { + return recordProtocols_.getByteString(index); + } + /** + *
+       * The record protocols supported by the server, e.g.,
+       * "ALTSRP_GCM_AES128".
+       * 
+ * + * repeated string record_protocols = 1; + */ + public Builder setRecordProtocols( + int index, java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + ensureRecordProtocolsIsMutable(); + recordProtocols_.set(index, value); + onChanged(); + return this; + } + /** + *
+       * The record protocols supported by the server, e.g.,
+       * "ALTSRP_GCM_AES128".
+       * 
+ * + * repeated string record_protocols = 1; + */ + public Builder addRecordProtocols( + java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + ensureRecordProtocolsIsMutable(); + recordProtocols_.add(value); + onChanged(); + return this; + } + /** + *
+       * The record protocols supported by the server, e.g.,
+       * "ALTSRP_GCM_AES128".
+       * 
+ * + * repeated string record_protocols = 1; + */ + public Builder addAllRecordProtocols( + java.lang.Iterable values) { + ensureRecordProtocolsIsMutable(); + com.google.protobuf.AbstractMessageLite.Builder.addAll( + values, recordProtocols_); + onChanged(); + return this; + } + /** + *
+       * The record protocols supported by the server, e.g.,
+       * "ALTSRP_GCM_AES128".
+       * 
+ * + * repeated string record_protocols = 1; + */ + public Builder clearRecordProtocols() { + recordProtocols_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bitField0_ = (bitField0_ & ~0x00000001); + onChanged(); + return this; + } + /** + *
+       * The record protocols supported by the server, e.g.,
+       * "ALTSRP_GCM_AES128".
+       * 
+ * + * repeated string record_protocols = 1; + */ + public Builder addRecordProtocolsBytes( + com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + ensureRecordProtocolsIsMutable(); + recordProtocols_.add(value); + onChanged(); + return this; + } + + private java.util.List localIdentities_ = + java.util.Collections.emptyList(); + private void ensureLocalIdentitiesIsMutable() { + if (!((bitField0_ & 0x00000002) == 0x00000002)) { + localIdentities_ = new java.util.ArrayList(localIdentities_); + bitField0_ |= 0x00000002; + } + } + + private com.google.protobuf.RepeatedFieldBuilderV3< + io.grpc.alts.internal.Handshaker.Identity, io.grpc.alts.internal.Handshaker.Identity.Builder, io.grpc.alts.internal.Handshaker.IdentityOrBuilder> localIdentitiesBuilder_; + + /** + *
+       * (Optional) A list of local identities supported by the server, if
+       * specified. Otherwise, the handshaker chooses a default local identity.
+       * 
+ * + * repeated .grpc.gcp.Identity local_identities = 2; + */ + public java.util.List getLocalIdentitiesList() { + if (localIdentitiesBuilder_ == null) { + return java.util.Collections.unmodifiableList(localIdentities_); + } else { + return localIdentitiesBuilder_.getMessageList(); + } + } + /** + *
+       * (Optional) A list of local identities supported by the server, if
+       * specified. Otherwise, the handshaker chooses a default local identity.
+       * 
+ * + * repeated .grpc.gcp.Identity local_identities = 2; + */ + public int getLocalIdentitiesCount() { + if (localIdentitiesBuilder_ == null) { + return localIdentities_.size(); + } else { + return localIdentitiesBuilder_.getCount(); + } + } + /** + *
+       * (Optional) A list of local identities supported by the server, if
+       * specified. Otherwise, the handshaker chooses a default local identity.
+       * 
+ * + * repeated .grpc.gcp.Identity local_identities = 2; + */ + public io.grpc.alts.internal.Handshaker.Identity getLocalIdentities(int index) { + if (localIdentitiesBuilder_ == null) { + return localIdentities_.get(index); + } else { + return localIdentitiesBuilder_.getMessage(index); + } + } + /** + *
+       * (Optional) A list of local identities supported by the server, if
+       * specified. Otherwise, the handshaker chooses a default local identity.
+       * 
+ * + * repeated .grpc.gcp.Identity local_identities = 2; + */ + public Builder setLocalIdentities( + int index, io.grpc.alts.internal.Handshaker.Identity value) { + if (localIdentitiesBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureLocalIdentitiesIsMutable(); + localIdentities_.set(index, value); + onChanged(); + } else { + localIdentitiesBuilder_.setMessage(index, value); + } + return this; + } + /** + *
+       * (Optional) A list of local identities supported by the server, if
+       * specified. Otherwise, the handshaker chooses a default local identity.
+       * 
+ * + * repeated .grpc.gcp.Identity local_identities = 2; + */ + public Builder setLocalIdentities( + int index, io.grpc.alts.internal.Handshaker.Identity.Builder builderForValue) { + if (localIdentitiesBuilder_ == null) { + ensureLocalIdentitiesIsMutable(); + localIdentities_.set(index, builderForValue.build()); + onChanged(); + } else { + localIdentitiesBuilder_.setMessage(index, builderForValue.build()); + } + return this; + } + /** + *
+       * (Optional) A list of local identities supported by the server, if
+       * specified. Otherwise, the handshaker chooses a default local identity.
+       * 
+ * + * repeated .grpc.gcp.Identity local_identities = 2; + */ + public Builder addLocalIdentities(io.grpc.alts.internal.Handshaker.Identity value) { + if (localIdentitiesBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureLocalIdentitiesIsMutable(); + localIdentities_.add(value); + onChanged(); + } else { + localIdentitiesBuilder_.addMessage(value); + } + return this; + } + /** + *
+       * (Optional) A list of local identities supported by the server, if
+       * specified. Otherwise, the handshaker chooses a default local identity.
+       * 
+ * + * repeated .grpc.gcp.Identity local_identities = 2; + */ + public Builder addLocalIdentities( + int index, io.grpc.alts.internal.Handshaker.Identity value) { + if (localIdentitiesBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureLocalIdentitiesIsMutable(); + localIdentities_.add(index, value); + onChanged(); + } else { + localIdentitiesBuilder_.addMessage(index, value); + } + return this; + } + /** + *
+       * (Optional) A list of local identities supported by the server, if
+       * specified. Otherwise, the handshaker chooses a default local identity.
+       * 
+ * + * repeated .grpc.gcp.Identity local_identities = 2; + */ + public Builder addLocalIdentities( + io.grpc.alts.internal.Handshaker.Identity.Builder builderForValue) { + if (localIdentitiesBuilder_ == null) { + ensureLocalIdentitiesIsMutable(); + localIdentities_.add(builderForValue.build()); + onChanged(); + } else { + localIdentitiesBuilder_.addMessage(builderForValue.build()); + } + return this; + } + /** + *
+       * (Optional) A list of local identities supported by the server, if
+       * specified. Otherwise, the handshaker chooses a default local identity.
+       * 
+ * + * repeated .grpc.gcp.Identity local_identities = 2; + */ + public Builder addLocalIdentities( + int index, io.grpc.alts.internal.Handshaker.Identity.Builder builderForValue) { + if (localIdentitiesBuilder_ == null) { + ensureLocalIdentitiesIsMutable(); + localIdentities_.add(index, builderForValue.build()); + onChanged(); + } else { + localIdentitiesBuilder_.addMessage(index, builderForValue.build()); + } + return this; + } + /** + *
+       * (Optional) A list of local identities supported by the server, if
+       * specified. Otherwise, the handshaker chooses a default local identity.
+       * 
+ * + * repeated .grpc.gcp.Identity local_identities = 2; + */ + public Builder addAllLocalIdentities( + java.lang.Iterable values) { + if (localIdentitiesBuilder_ == null) { + ensureLocalIdentitiesIsMutable(); + com.google.protobuf.AbstractMessageLite.Builder.addAll( + values, localIdentities_); + onChanged(); + } else { + localIdentitiesBuilder_.addAllMessages(values); + } + return this; + } + /** + *
+       * (Optional) A list of local identities supported by the server, if
+       * specified. Otherwise, the handshaker chooses a default local identity.
+       * 
+ * + * repeated .grpc.gcp.Identity local_identities = 2; + */ + public Builder clearLocalIdentities() { + if (localIdentitiesBuilder_ == null) { + localIdentities_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000002); + onChanged(); + } else { + localIdentitiesBuilder_.clear(); + } + return this; + } + /** + *
+       * (Optional) A list of local identities supported by the server, if
+       * specified. Otherwise, the handshaker chooses a default local identity.
+       * 
+ * + * repeated .grpc.gcp.Identity local_identities = 2; + */ + public Builder removeLocalIdentities(int index) { + if (localIdentitiesBuilder_ == null) { + ensureLocalIdentitiesIsMutable(); + localIdentities_.remove(index); + onChanged(); + } else { + localIdentitiesBuilder_.remove(index); + } + return this; + } + /** + *
+       * (Optional) A list of local identities supported by the server, if
+       * specified. Otherwise, the handshaker chooses a default local identity.
+       * 
+ * + * repeated .grpc.gcp.Identity local_identities = 2; + */ + public io.grpc.alts.internal.Handshaker.Identity.Builder getLocalIdentitiesBuilder( + int index) { + return getLocalIdentitiesFieldBuilder().getBuilder(index); + } + /** + *
+       * (Optional) A list of local identities supported by the server, if
+       * specified. Otherwise, the handshaker chooses a default local identity.
+       * 
+ * + * repeated .grpc.gcp.Identity local_identities = 2; + */ + public io.grpc.alts.internal.Handshaker.IdentityOrBuilder getLocalIdentitiesOrBuilder( + int index) { + if (localIdentitiesBuilder_ == null) { + return localIdentities_.get(index); } else { + return localIdentitiesBuilder_.getMessageOrBuilder(index); + } + } + /** + *
+       * (Optional) A list of local identities supported by the server, if
+       * specified. Otherwise, the handshaker chooses a default local identity.
+       * 
+ * + * repeated .grpc.gcp.Identity local_identities = 2; + */ + public java.util.List + getLocalIdentitiesOrBuilderList() { + if (localIdentitiesBuilder_ != null) { + return localIdentitiesBuilder_.getMessageOrBuilderList(); + } else { + return java.util.Collections.unmodifiableList(localIdentities_); + } + } + /** + *
+       * (Optional) A list of local identities supported by the server, if
+       * specified. Otherwise, the handshaker chooses a default local identity.
+       * 
+ * + * repeated .grpc.gcp.Identity local_identities = 2; + */ + public io.grpc.alts.internal.Handshaker.Identity.Builder addLocalIdentitiesBuilder() { + return getLocalIdentitiesFieldBuilder().addBuilder( + io.grpc.alts.internal.Handshaker.Identity.getDefaultInstance()); + } + /** + *
+       * (Optional) A list of local identities supported by the server, if
+       * specified. Otherwise, the handshaker chooses a default local identity.
+       * 
+ * + * repeated .grpc.gcp.Identity local_identities = 2; + */ + public io.grpc.alts.internal.Handshaker.Identity.Builder addLocalIdentitiesBuilder( + int index) { + return getLocalIdentitiesFieldBuilder().addBuilder( + index, io.grpc.alts.internal.Handshaker.Identity.getDefaultInstance()); + } + /** + *
+       * (Optional) A list of local identities supported by the server, if
+       * specified. Otherwise, the handshaker chooses a default local identity.
+       * 
+ * + * repeated .grpc.gcp.Identity local_identities = 2; + */ + public java.util.List + getLocalIdentitiesBuilderList() { + return getLocalIdentitiesFieldBuilder().getBuilderList(); + } + private com.google.protobuf.RepeatedFieldBuilderV3< + io.grpc.alts.internal.Handshaker.Identity, io.grpc.alts.internal.Handshaker.Identity.Builder, io.grpc.alts.internal.Handshaker.IdentityOrBuilder> + getLocalIdentitiesFieldBuilder() { + if (localIdentitiesBuilder_ == null) { + localIdentitiesBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3< + io.grpc.alts.internal.Handshaker.Identity, io.grpc.alts.internal.Handshaker.Identity.Builder, io.grpc.alts.internal.Handshaker.IdentityOrBuilder>( + localIdentities_, + ((bitField0_ & 0x00000002) == 0x00000002), + getParentForChildren(), + isClean()); + localIdentities_ = null; + } + return localIdentitiesBuilder_; + } + public final Builder setUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); + } + + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + + // @@protoc_insertion_point(builder_scope:grpc.gcp.ServerHandshakeParameters) + } + + // @@protoc_insertion_point(class_scope:grpc.gcp.ServerHandshakeParameters) + private static final io.grpc.alts.internal.Handshaker.ServerHandshakeParameters DEFAULT_INSTANCE; + static { + DEFAULT_INSTANCE = new io.grpc.alts.internal.Handshaker.ServerHandshakeParameters(); + } + + public static io.grpc.alts.internal.Handshaker.ServerHandshakeParameters getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + private static final com.google.protobuf.Parser + PARSER = new com.google.protobuf.AbstractParser() { + public ServerHandshakeParameters parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new ServerHandshakeParameters(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public io.grpc.alts.internal.Handshaker.ServerHandshakeParameters getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } + + } + + public interface StartServerHandshakeReqOrBuilder extends + // @@protoc_insertion_point(interface_extends:grpc.gcp.StartServerHandshakeReq) + com.google.protobuf.MessageOrBuilder { + + /** + *
+     * The application protocols supported by the server, e.g., "h2" (for http2),
+     * "grpc".
+     * 
+ * + * repeated string application_protocols = 1; + */ + java.util.List + getApplicationProtocolsList(); + /** + *
+     * The application protocols supported by the server, e.g., "h2" (for http2),
+     * "grpc".
+     * 
+ * + * repeated string application_protocols = 1; + */ + int getApplicationProtocolsCount(); + /** + *
+     * The application protocols supported by the server, e.g., "h2" (for http2),
+     * "grpc".
+     * 
+ * + * repeated string application_protocols = 1; + */ + java.lang.String getApplicationProtocols(int index); + /** + *
+     * The application protocols supported by the server, e.g., "h2" (for http2),
+     * "grpc".
+     * 
+ * + * repeated string application_protocols = 1; + */ + com.google.protobuf.ByteString + getApplicationProtocolsBytes(int index); + + /** + *
+     * Handshake parameters (record protocols and local identities supported by
+     * the server) mapped by the handshake protocol. Each handshake security
+     * protocol (e.g., TLS or ALTS) has its own set of record protocols and local
+     * identities. Since protobuf does not support enum as key to the map, the key
+     * to handshake_parameters is the integer value of HandshakeProtocol enum.
+     * 
+ * + * map<int32, .grpc.gcp.ServerHandshakeParameters> handshake_parameters = 2; + */ + int getHandshakeParametersCount(); + /** + *
+     * Handshake parameters (record protocols and local identities supported by
+     * the server) mapped by the handshake protocol. Each handshake security
+     * protocol (e.g., TLS or ALTS) has its own set of record protocols and local
+     * identities. Since protobuf does not support enum as key to the map, the key
+     * to handshake_parameters is the integer value of HandshakeProtocol enum.
+     * 
+ * + * map<int32, .grpc.gcp.ServerHandshakeParameters> handshake_parameters = 2; + */ + boolean containsHandshakeParameters( + int key); + /** + * Use {@link #getHandshakeParametersMap()} instead. + */ + @java.lang.Deprecated + java.util.Map + getHandshakeParameters(); + /** + *
+     * Handshake parameters (record protocols and local identities supported by
+     * the server) mapped by the handshake protocol. Each handshake security
+     * protocol (e.g., TLS or ALTS) has its own set of record protocols and local
+     * identities. Since protobuf does not support enum as key to the map, the key
+     * to handshake_parameters is the integer value of HandshakeProtocol enum.
+     * 
+ * + * map<int32, .grpc.gcp.ServerHandshakeParameters> handshake_parameters = 2; + */ + java.util.Map + getHandshakeParametersMap(); + /** + *
+     * Handshake parameters (record protocols and local identities supported by
+     * the server) mapped by the handshake protocol. Each handshake security
+     * protocol (e.g., TLS or ALTS) has its own set of record protocols and local
+     * identities. Since protobuf does not support enum as key to the map, the key
+     * to handshake_parameters is the integer value of HandshakeProtocol enum.
+     * 
+ * + * map<int32, .grpc.gcp.ServerHandshakeParameters> handshake_parameters = 2; + */ + + io.grpc.alts.internal.Handshaker.ServerHandshakeParameters getHandshakeParametersOrDefault( + int key, + io.grpc.alts.internal.Handshaker.ServerHandshakeParameters defaultValue); + /** + *
+     * Handshake parameters (record protocols and local identities supported by
+     * the server) mapped by the handshake protocol. Each handshake security
+     * protocol (e.g., TLS or ALTS) has its own set of record protocols and local
+     * identities. Since protobuf does not support enum as key to the map, the key
+     * to handshake_parameters is the integer value of HandshakeProtocol enum.
+     * 
+ * + * map<int32, .grpc.gcp.ServerHandshakeParameters> handshake_parameters = 2; + */ + + io.grpc.alts.internal.Handshaker.ServerHandshakeParameters getHandshakeParametersOrThrow( + int key); + + /** + *
+     * Bytes in out_frames returned from the peer's HandshakerResp. It is possible
+     * that the peer's out_frames are split into multiple HandshakReq messages.
+     * 
+ * + * bytes in_bytes = 3; + */ + com.google.protobuf.ByteString getInBytes(); + + /** + *
+     * (Optional) Local endpoint information of the connection to the client,
+     * such as local IP address, port number, and network protocol.
+     * 
+ * + * .grpc.gcp.Endpoint local_endpoint = 4; + */ + boolean hasLocalEndpoint(); + /** + *
+     * (Optional) Local endpoint information of the connection to the client,
+     * such as local IP address, port number, and network protocol.
+     * 
+ * + * .grpc.gcp.Endpoint local_endpoint = 4; + */ + io.grpc.alts.internal.Handshaker.Endpoint getLocalEndpoint(); + /** + *
+     * (Optional) Local endpoint information of the connection to the client,
+     * such as local IP address, port number, and network protocol.
+     * 
+ * + * .grpc.gcp.Endpoint local_endpoint = 4; + */ + io.grpc.alts.internal.Handshaker.EndpointOrBuilder getLocalEndpointOrBuilder(); + + /** + *
+     * (Optional) Endpoint information of the remote client, such as IP address,
+     * port number, and network protocol.
+     * 
+ * + * .grpc.gcp.Endpoint remote_endpoint = 5; + */ + boolean hasRemoteEndpoint(); + /** + *
+     * (Optional) Endpoint information of the remote client, such as IP address,
+     * port number, and network protocol.
+     * 
+ * + * .grpc.gcp.Endpoint remote_endpoint = 5; + */ + io.grpc.alts.internal.Handshaker.Endpoint getRemoteEndpoint(); + /** + *
+     * (Optional) Endpoint information of the remote client, such as IP address,
+     * port number, and network protocol.
+     * 
+ * + * .grpc.gcp.Endpoint remote_endpoint = 5; + */ + io.grpc.alts.internal.Handshaker.EndpointOrBuilder getRemoteEndpointOrBuilder(); + + /** + *
+     * (Optional) RPC protocol versions supported by the server.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions rpc_versions = 6; + */ + boolean hasRpcVersions(); + /** + *
+     * (Optional) RPC protocol versions supported by the server.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions rpc_versions = 6; + */ + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions getRpcVersions(); + /** + *
+     * (Optional) RPC protocol versions supported by the server.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions rpc_versions = 6; + */ + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersionsOrBuilder getRpcVersionsOrBuilder(); + } + /** + * Protobuf type {@code grpc.gcp.StartServerHandshakeReq} + */ + public static final class StartServerHandshakeReq extends + com.google.protobuf.GeneratedMessageV3 implements + // @@protoc_insertion_point(message_implements:grpc.gcp.StartServerHandshakeReq) + StartServerHandshakeReqOrBuilder { + private static final long serialVersionUID = 0L; + // Use StartServerHandshakeReq.newBuilder() to construct. + private StartServerHandshakeReq(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + private StartServerHandshakeReq() { + applicationProtocols_ = com.google.protobuf.LazyStringArrayList.EMPTY; + inBytes_ = com.google.protobuf.ByteString.EMPTY; + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return this.unknownFields; + } + private StartServerHandshakeReq( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownFieldProto3( + input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 10: { + java.lang.String s = input.readStringRequireUtf8(); + if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { + applicationProtocols_ = new com.google.protobuf.LazyStringArrayList(); + mutable_bitField0_ |= 0x00000001; + } + applicationProtocols_.add(s); + break; + } + case 18: { + if (!((mutable_bitField0_ & 0x00000002) == 0x00000002)) { + handshakeParameters_ = com.google.protobuf.MapField.newMapField( + HandshakeParametersDefaultEntryHolder.defaultEntry); + mutable_bitField0_ |= 0x00000002; + } + com.google.protobuf.MapEntry + handshakeParameters__ = input.readMessage( + HandshakeParametersDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry); + handshakeParameters_.getMutableMap().put( + handshakeParameters__.getKey(), handshakeParameters__.getValue()); + break; + } + case 26: { + + inBytes_ = input.readBytes(); + break; + } + case 34: { + io.grpc.alts.internal.Handshaker.Endpoint.Builder subBuilder = null; + if (localEndpoint_ != null) { + subBuilder = localEndpoint_.toBuilder(); + } + localEndpoint_ = input.readMessage(io.grpc.alts.internal.Handshaker.Endpoint.parser(), extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(localEndpoint_); + localEndpoint_ = subBuilder.buildPartial(); + } + + break; + } + case 42: { + io.grpc.alts.internal.Handshaker.Endpoint.Builder subBuilder = null; + if (remoteEndpoint_ != null) { + subBuilder = remoteEndpoint_.toBuilder(); + } + remoteEndpoint_ = input.readMessage(io.grpc.alts.internal.Handshaker.Endpoint.parser(), extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(remoteEndpoint_); + remoteEndpoint_ = subBuilder.buildPartial(); + } + + break; + } + case 50: { + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Builder subBuilder = null; + if (rpcVersions_ != null) { + subBuilder = rpcVersions_.toBuilder(); + } + rpcVersions_ = input.readMessage(io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.parser(), extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(rpcVersions_); + rpcVersions_ = subBuilder.buildPartial(); + } + + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e).setUnfinishedMessage(this); + } finally { + if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) { + applicationProtocols_ = applicationProtocols_.getUnmodifiableView(); + } + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_StartServerHandshakeReq_descriptor; + } + + @SuppressWarnings({"rawtypes"}) + protected com.google.protobuf.MapField internalGetMapField( + int number) { + switch (number) { + case 2: + return internalGetHandshakeParameters(); + default: + throw new RuntimeException( + "Invalid map field number: " + number); + } + } + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_StartServerHandshakeReq_fieldAccessorTable + .ensureFieldAccessorsInitialized( + io.grpc.alts.internal.Handshaker.StartServerHandshakeReq.class, io.grpc.alts.internal.Handshaker.StartServerHandshakeReq.Builder.class); + } + + private int bitField0_; + public static final int APPLICATION_PROTOCOLS_FIELD_NUMBER = 1; + private com.google.protobuf.LazyStringList applicationProtocols_; + /** + *
+     * The application protocols supported by the server, e.g., "h2" (for http2),
+     * "grpc".
+     * 
+ * + * repeated string application_protocols = 1; + */ + public com.google.protobuf.ProtocolStringList + getApplicationProtocolsList() { + return applicationProtocols_; + } + /** + *
+     * The application protocols supported by the server, e.g., "h2" (for http2),
+     * "grpc".
+     * 
+ * + * repeated string application_protocols = 1; + */ + public int getApplicationProtocolsCount() { + return applicationProtocols_.size(); + } + /** + *
+     * The application protocols supported by the server, e.g., "h2" (for http2),
+     * "grpc".
+     * 
+ * + * repeated string application_protocols = 1; + */ + public java.lang.String getApplicationProtocols(int index) { + return applicationProtocols_.get(index); + } + /** + *
+     * The application protocols supported by the server, e.g., "h2" (for http2),
+     * "grpc".
+     * 
+ * + * repeated string application_protocols = 1; + */ + public com.google.protobuf.ByteString + getApplicationProtocolsBytes(int index) { + return applicationProtocols_.getByteString(index); + } + + public static final int HANDSHAKE_PARAMETERS_FIELD_NUMBER = 2; + private static final class HandshakeParametersDefaultEntryHolder { + static final com.google.protobuf.MapEntry< + java.lang.Integer, io.grpc.alts.internal.Handshaker.ServerHandshakeParameters> defaultEntry = + com.google.protobuf.MapEntry + .newDefaultInstance( + io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry_descriptor, + com.google.protobuf.WireFormat.FieldType.INT32, + 0, + com.google.protobuf.WireFormat.FieldType.MESSAGE, + io.grpc.alts.internal.Handshaker.ServerHandshakeParameters.getDefaultInstance()); + } + private com.google.protobuf.MapField< + java.lang.Integer, io.grpc.alts.internal.Handshaker.ServerHandshakeParameters> handshakeParameters_; + private com.google.protobuf.MapField + internalGetHandshakeParameters() { + if (handshakeParameters_ == null) { + return com.google.protobuf.MapField.emptyMapField( + HandshakeParametersDefaultEntryHolder.defaultEntry); + } + return handshakeParameters_; + } + + public int getHandshakeParametersCount() { + return internalGetHandshakeParameters().getMap().size(); + } + /** + *
+     * Handshake parameters (record protocols and local identities supported by
+     * the server) mapped by the handshake protocol. Each handshake security
+     * protocol (e.g., TLS or ALTS) has its own set of record protocols and local
+     * identities. Since protobuf does not support enum as key to the map, the key
+     * to handshake_parameters is the integer value of HandshakeProtocol enum.
+     * 
+ * + * map<int32, .grpc.gcp.ServerHandshakeParameters> handshake_parameters = 2; + */ + + public boolean containsHandshakeParameters( + int key) { + + return internalGetHandshakeParameters().getMap().containsKey(key); + } + /** + * Use {@link #getHandshakeParametersMap()} instead. + */ + @java.lang.Deprecated + public java.util.Map getHandshakeParameters() { + return getHandshakeParametersMap(); + } + /** + *
+     * Handshake parameters (record protocols and local identities supported by
+     * the server) mapped by the handshake protocol. Each handshake security
+     * protocol (e.g., TLS or ALTS) has its own set of record protocols and local
+     * identities. Since protobuf does not support enum as key to the map, the key
+     * to handshake_parameters is the integer value of HandshakeProtocol enum.
+     * 
+ * + * map<int32, .grpc.gcp.ServerHandshakeParameters> handshake_parameters = 2; + */ + + public java.util.Map getHandshakeParametersMap() { + return internalGetHandshakeParameters().getMap(); + } + /** + *
+     * Handshake parameters (record protocols and local identities supported by
+     * the server) mapped by the handshake protocol. Each handshake security
+     * protocol (e.g., TLS or ALTS) has its own set of record protocols and local
+     * identities. Since protobuf does not support enum as key to the map, the key
+     * to handshake_parameters is the integer value of HandshakeProtocol enum.
+     * 
+ * + * map<int32, .grpc.gcp.ServerHandshakeParameters> handshake_parameters = 2; + */ + + public io.grpc.alts.internal.Handshaker.ServerHandshakeParameters getHandshakeParametersOrDefault( + int key, + io.grpc.alts.internal.Handshaker.ServerHandshakeParameters defaultValue) { + + java.util.Map map = + internalGetHandshakeParameters().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; + } + /** + *
+     * Handshake parameters (record protocols and local identities supported by
+     * the server) mapped by the handshake protocol. Each handshake security
+     * protocol (e.g., TLS or ALTS) has its own set of record protocols and local
+     * identities. Since protobuf does not support enum as key to the map, the key
+     * to handshake_parameters is the integer value of HandshakeProtocol enum.
+     * 
+ * + * map<int32, .grpc.gcp.ServerHandshakeParameters> handshake_parameters = 2; + */ + + public io.grpc.alts.internal.Handshaker.ServerHandshakeParameters getHandshakeParametersOrThrow( + int key) { + + java.util.Map map = + internalGetHandshakeParameters().getMap(); + if (!map.containsKey(key)) { + throw new java.lang.IllegalArgumentException(); + } + return map.get(key); + } + + public static final int IN_BYTES_FIELD_NUMBER = 3; + private com.google.protobuf.ByteString inBytes_; + /** + *
+     * Bytes in out_frames returned from the peer's HandshakerResp. It is possible
+     * that the peer's out_frames are split into multiple HandshakReq messages.
+     * 
+ * + * bytes in_bytes = 3; + */ + public com.google.protobuf.ByteString getInBytes() { + return inBytes_; + } + + public static final int LOCAL_ENDPOINT_FIELD_NUMBER = 4; + private io.grpc.alts.internal.Handshaker.Endpoint localEndpoint_; + /** + *
+     * (Optional) Local endpoint information of the connection to the client,
+     * such as local IP address, port number, and network protocol.
+     * 
+ * + * .grpc.gcp.Endpoint local_endpoint = 4; + */ + public boolean hasLocalEndpoint() { + return localEndpoint_ != null; + } + /** + *
+     * (Optional) Local endpoint information of the connection to the client,
+     * such as local IP address, port number, and network protocol.
+     * 
+ * + * .grpc.gcp.Endpoint local_endpoint = 4; + */ + public io.grpc.alts.internal.Handshaker.Endpoint getLocalEndpoint() { + return localEndpoint_ == null ? io.grpc.alts.internal.Handshaker.Endpoint.getDefaultInstance() : localEndpoint_; + } + /** + *
+     * (Optional) Local endpoint information of the connection to the client,
+     * such as local IP address, port number, and network protocol.
+     * 
+ * + * .grpc.gcp.Endpoint local_endpoint = 4; + */ + public io.grpc.alts.internal.Handshaker.EndpointOrBuilder getLocalEndpointOrBuilder() { + return getLocalEndpoint(); + } + + public static final int REMOTE_ENDPOINT_FIELD_NUMBER = 5; + private io.grpc.alts.internal.Handshaker.Endpoint remoteEndpoint_; + /** + *
+     * (Optional) Endpoint information of the remote client, such as IP address,
+     * port number, and network protocol.
+     * 
+ * + * .grpc.gcp.Endpoint remote_endpoint = 5; + */ + public boolean hasRemoteEndpoint() { + return remoteEndpoint_ != null; + } + /** + *
+     * (Optional) Endpoint information of the remote client, such as IP address,
+     * port number, and network protocol.
+     * 
+ * + * .grpc.gcp.Endpoint remote_endpoint = 5; + */ + public io.grpc.alts.internal.Handshaker.Endpoint getRemoteEndpoint() { + return remoteEndpoint_ == null ? io.grpc.alts.internal.Handshaker.Endpoint.getDefaultInstance() : remoteEndpoint_; + } + /** + *
+     * (Optional) Endpoint information of the remote client, such as IP address,
+     * port number, and network protocol.
+     * 
+ * + * .grpc.gcp.Endpoint remote_endpoint = 5; + */ + public io.grpc.alts.internal.Handshaker.EndpointOrBuilder getRemoteEndpointOrBuilder() { + return getRemoteEndpoint(); + } + + public static final int RPC_VERSIONS_FIELD_NUMBER = 6; + private io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions rpcVersions_; + /** + *
+     * (Optional) RPC protocol versions supported by the server.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions rpc_versions = 6; + */ + public boolean hasRpcVersions() { + return rpcVersions_ != null; + } + /** + *
+     * (Optional) RPC protocol versions supported by the server.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions rpc_versions = 6; + */ + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions getRpcVersions() { + return rpcVersions_ == null ? io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.getDefaultInstance() : rpcVersions_; + } + /** + *
+     * (Optional) RPC protocol versions supported by the server.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions rpc_versions = 6; + */ + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersionsOrBuilder getRpcVersionsOrBuilder() { + return getRpcVersions(); + } + + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + for (int i = 0; i < applicationProtocols_.size(); i++) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 1, applicationProtocols_.getRaw(i)); + } + com.google.protobuf.GeneratedMessageV3 + .serializeIntegerMapTo( + output, + internalGetHandshakeParameters(), + HandshakeParametersDefaultEntryHolder.defaultEntry, + 2); + if (!inBytes_.isEmpty()) { + output.writeBytes(3, inBytes_); + } + if (localEndpoint_ != null) { + output.writeMessage(4, getLocalEndpoint()); + } + if (remoteEndpoint_ != null) { + output.writeMessage(5, getRemoteEndpoint()); + } + if (rpcVersions_ != null) { + output.writeMessage(6, getRpcVersions()); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + { + int dataSize = 0; + for (int i = 0; i < applicationProtocols_.size(); i++) { + dataSize += computeStringSizeNoTag(applicationProtocols_.getRaw(i)); + } + size += dataSize; + size += 1 * getApplicationProtocolsList().size(); + } + for (java.util.Map.Entry entry + : internalGetHandshakeParameters().getMap().entrySet()) { + com.google.protobuf.MapEntry + handshakeParameters__ = HandshakeParametersDefaultEntryHolder.defaultEntry.newBuilderForType() + .setKey(entry.getKey()) + .setValue(entry.getValue()) + .build(); + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(2, handshakeParameters__); + } + if (!inBytes_.isEmpty()) { + size += com.google.protobuf.CodedOutputStream + .computeBytesSize(3, inBytes_); + } + if (localEndpoint_ != null) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(4, getLocalEndpoint()); + } + if (remoteEndpoint_ != null) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(5, getRemoteEndpoint()); + } + if (rpcVersions_ != null) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(6, getRpcVersions()); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof io.grpc.alts.internal.Handshaker.StartServerHandshakeReq)) { + return super.equals(obj); + } + io.grpc.alts.internal.Handshaker.StartServerHandshakeReq other = (io.grpc.alts.internal.Handshaker.StartServerHandshakeReq) obj; + + boolean result = true; + result = result && getApplicationProtocolsList() + .equals(other.getApplicationProtocolsList()); + result = result && internalGetHandshakeParameters().equals( + other.internalGetHandshakeParameters()); + result = result && getInBytes() + .equals(other.getInBytes()); + result = result && (hasLocalEndpoint() == other.hasLocalEndpoint()); + if (hasLocalEndpoint()) { + result = result && getLocalEndpoint() + .equals(other.getLocalEndpoint()); + } + result = result && (hasRemoteEndpoint() == other.hasRemoteEndpoint()); + if (hasRemoteEndpoint()) { + result = result && getRemoteEndpoint() + .equals(other.getRemoteEndpoint()); + } + result = result && (hasRpcVersions() == other.hasRpcVersions()); + if (hasRpcVersions()) { + result = result && getRpcVersions() + .equals(other.getRpcVersions()); + } + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + if (getApplicationProtocolsCount() > 0) { + hash = (37 * hash) + APPLICATION_PROTOCOLS_FIELD_NUMBER; + hash = (53 * hash) + getApplicationProtocolsList().hashCode(); + } + if (!internalGetHandshakeParameters().getMap().isEmpty()) { + hash = (37 * hash) + HANDSHAKE_PARAMETERS_FIELD_NUMBER; + hash = (53 * hash) + internalGetHandshakeParameters().hashCode(); + } + hash = (37 * hash) + IN_BYTES_FIELD_NUMBER; + hash = (53 * hash) + getInBytes().hashCode(); + if (hasLocalEndpoint()) { + hash = (37 * hash) + LOCAL_ENDPOINT_FIELD_NUMBER; + hash = (53 * hash) + getLocalEndpoint().hashCode(); + } + if (hasRemoteEndpoint()) { + hash = (37 * hash) + REMOTE_ENDPOINT_FIELD_NUMBER; + hash = (53 * hash) + getRemoteEndpoint().hashCode(); + } + if (hasRpcVersions()) { + hash = (37 * hash) + RPC_VERSIONS_FIELD_NUMBER; + hash = (53 * hash) + getRpcVersions().hashCode(); + } + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static io.grpc.alts.internal.Handshaker.StartServerHandshakeReq parseFrom( + java.nio.ByteBuffer data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Handshaker.StartServerHandshakeReq parseFrom( + java.nio.ByteBuffer data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.StartServerHandshakeReq parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Handshaker.StartServerHandshakeReq parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.StartServerHandshakeReq parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Handshaker.StartServerHandshakeReq parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.StartServerHandshakeReq parseFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Handshaker.StartServerHandshakeReq parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.StartServerHandshakeReq parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Handshaker.StartServerHandshakeReq parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.StartServerHandshakeReq parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Handshaker.StartServerHandshakeReq parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + public static Builder newBuilder(io.grpc.alts.internal.Handshaker.StartServerHandshakeReq prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { + return this == DEFAULT_INSTANCE + ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + * Protobuf type {@code grpc.gcp.StartServerHandshakeReq} + */ + public static final class Builder extends + com.google.protobuf.GeneratedMessageV3.Builder implements + // @@protoc_insertion_point(builder_implements:grpc.gcp.StartServerHandshakeReq) + io.grpc.alts.internal.Handshaker.StartServerHandshakeReqOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_StartServerHandshakeReq_descriptor; + } + + @SuppressWarnings({"rawtypes"}) + protected com.google.protobuf.MapField internalGetMapField( + int number) { + switch (number) { + case 2: + return internalGetHandshakeParameters(); + default: + throw new RuntimeException( + "Invalid map field number: " + number); + } + } + @SuppressWarnings({"rawtypes"}) + protected com.google.protobuf.MapField internalGetMutableMapField( + int number) { + switch (number) { + case 2: + return internalGetMutableHandshakeParameters(); + default: + throw new RuntimeException( + "Invalid map field number: " + number); + } + } + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_StartServerHandshakeReq_fieldAccessorTable + .ensureFieldAccessorsInitialized( + io.grpc.alts.internal.Handshaker.StartServerHandshakeReq.class, io.grpc.alts.internal.Handshaker.StartServerHandshakeReq.Builder.class); + } + + // Construct using io.grpc.alts.internal.Handshaker.StartServerHandshakeReq.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder( + com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3 + .alwaysUseFieldBuilders) { + } + } + public Builder clear() { + super.clear(); + applicationProtocols_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bitField0_ = (bitField0_ & ~0x00000001); + internalGetMutableHandshakeParameters().clear(); + inBytes_ = com.google.protobuf.ByteString.EMPTY; + + if (localEndpointBuilder_ == null) { + localEndpoint_ = null; + } else { + localEndpoint_ = null; + localEndpointBuilder_ = null; + } + if (remoteEndpointBuilder_ == null) { + remoteEndpoint_ = null; + } else { + remoteEndpoint_ = null; + remoteEndpointBuilder_ = null; + } + if (rpcVersionsBuilder_ == null) { + rpcVersions_ = null; + } else { + rpcVersions_ = null; + rpcVersionsBuilder_ = null; + } + return this; + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_StartServerHandshakeReq_descriptor; + } + + public io.grpc.alts.internal.Handshaker.StartServerHandshakeReq getDefaultInstanceForType() { + return io.grpc.alts.internal.Handshaker.StartServerHandshakeReq.getDefaultInstance(); + } + + public io.grpc.alts.internal.Handshaker.StartServerHandshakeReq build() { + io.grpc.alts.internal.Handshaker.StartServerHandshakeReq result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public io.grpc.alts.internal.Handshaker.StartServerHandshakeReq buildPartial() { + io.grpc.alts.internal.Handshaker.StartServerHandshakeReq result = new io.grpc.alts.internal.Handshaker.StartServerHandshakeReq(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + applicationProtocols_ = applicationProtocols_.getUnmodifiableView(); + bitField0_ = (bitField0_ & ~0x00000001); + } + result.applicationProtocols_ = applicationProtocols_; + result.handshakeParameters_ = internalGetHandshakeParameters(); + result.handshakeParameters_.makeImmutable(); + result.inBytes_ = inBytes_; + if (localEndpointBuilder_ == null) { + result.localEndpoint_ = localEndpoint_; + } else { + result.localEndpoint_ = localEndpointBuilder_.build(); + } + if (remoteEndpointBuilder_ == null) { + result.remoteEndpoint_ = remoteEndpoint_; + } else { + result.remoteEndpoint_ = remoteEndpointBuilder_.build(); + } + if (rpcVersionsBuilder_ == null) { + result.rpcVersions_ = rpcVersions_; + } else { + result.rpcVersions_ = rpcVersionsBuilder_.build(); + } + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder clone() { + return (Builder) super.clone(); + } + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, + java.lang.Object value) { + return (Builder) super.setField(field, value); + } + public Builder clearField( + com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); + } + public Builder clearOneof( + com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); + } + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); + } + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); + } + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof io.grpc.alts.internal.Handshaker.StartServerHandshakeReq) { + return mergeFrom((io.grpc.alts.internal.Handshaker.StartServerHandshakeReq)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(io.grpc.alts.internal.Handshaker.StartServerHandshakeReq other) { + if (other == io.grpc.alts.internal.Handshaker.StartServerHandshakeReq.getDefaultInstance()) return this; + if (!other.applicationProtocols_.isEmpty()) { + if (applicationProtocols_.isEmpty()) { + applicationProtocols_ = other.applicationProtocols_; + bitField0_ = (bitField0_ & ~0x00000001); + } else { + ensureApplicationProtocolsIsMutable(); + applicationProtocols_.addAll(other.applicationProtocols_); + } + onChanged(); + } + internalGetMutableHandshakeParameters().mergeFrom( + other.internalGetHandshakeParameters()); + if (other.getInBytes() != com.google.protobuf.ByteString.EMPTY) { + setInBytes(other.getInBytes()); + } + if (other.hasLocalEndpoint()) { + mergeLocalEndpoint(other.getLocalEndpoint()); + } + if (other.hasRemoteEndpoint()) { + mergeRemoteEndpoint(other.getRemoteEndpoint()); + } + if (other.hasRpcVersions()) { + mergeRpcVersions(other.getRpcVersions()); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + io.grpc.alts.internal.Handshaker.StartServerHandshakeReq parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (io.grpc.alts.internal.Handshaker.StartServerHandshakeReq) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + private int bitField0_; + + private com.google.protobuf.LazyStringList applicationProtocols_ = com.google.protobuf.LazyStringArrayList.EMPTY; + private void ensureApplicationProtocolsIsMutable() { + if (!((bitField0_ & 0x00000001) == 0x00000001)) { + applicationProtocols_ = new com.google.protobuf.LazyStringArrayList(applicationProtocols_); + bitField0_ |= 0x00000001; + } + } + /** + *
+       * The application protocols supported by the server, e.g., "h2" (for http2),
+       * "grpc".
+       * 
+ * + * repeated string application_protocols = 1; + */ + public com.google.protobuf.ProtocolStringList + getApplicationProtocolsList() { + return applicationProtocols_.getUnmodifiableView(); + } + /** + *
+       * The application protocols supported by the server, e.g., "h2" (for http2),
+       * "grpc".
+       * 
+ * + * repeated string application_protocols = 1; + */ + public int getApplicationProtocolsCount() { + return applicationProtocols_.size(); + } + /** + *
+       * The application protocols supported by the server, e.g., "h2" (for http2),
+       * "grpc".
+       * 
+ * + * repeated string application_protocols = 1; + */ + public java.lang.String getApplicationProtocols(int index) { + return applicationProtocols_.get(index); + } + /** + *
+       * The application protocols supported by the server, e.g., "h2" (for http2),
+       * "grpc".
+       * 
+ * + * repeated string application_protocols = 1; + */ + public com.google.protobuf.ByteString + getApplicationProtocolsBytes(int index) { + return applicationProtocols_.getByteString(index); + } + /** + *
+       * The application protocols supported by the server, e.g., "h2" (for http2),
+       * "grpc".
+       * 
+ * + * repeated string application_protocols = 1; + */ + public Builder setApplicationProtocols( + int index, java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + ensureApplicationProtocolsIsMutable(); + applicationProtocols_.set(index, value); + onChanged(); + return this; + } + /** + *
+       * The application protocols supported by the server, e.g., "h2" (for http2),
+       * "grpc".
+       * 
+ * + * repeated string application_protocols = 1; + */ + public Builder addApplicationProtocols( + java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + ensureApplicationProtocolsIsMutable(); + applicationProtocols_.add(value); + onChanged(); + return this; + } + /** + *
+       * The application protocols supported by the server, e.g., "h2" (for http2),
+       * "grpc".
+       * 
+ * + * repeated string application_protocols = 1; + */ + public Builder addAllApplicationProtocols( + java.lang.Iterable values) { + ensureApplicationProtocolsIsMutable(); + com.google.protobuf.AbstractMessageLite.Builder.addAll( + values, applicationProtocols_); + onChanged(); + return this; + } + /** + *
+       * The application protocols supported by the server, e.g., "h2" (for http2),
+       * "grpc".
+       * 
+ * + * repeated string application_protocols = 1; + */ + public Builder clearApplicationProtocols() { + applicationProtocols_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bitField0_ = (bitField0_ & ~0x00000001); + onChanged(); + return this; + } + /** + *
+       * The application protocols supported by the server, e.g., "h2" (for http2),
+       * "grpc".
+       * 
+ * + * repeated string application_protocols = 1; + */ + public Builder addApplicationProtocolsBytes( + com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + ensureApplicationProtocolsIsMutable(); + applicationProtocols_.add(value); + onChanged(); + return this; + } + + private com.google.protobuf.MapField< + java.lang.Integer, io.grpc.alts.internal.Handshaker.ServerHandshakeParameters> handshakeParameters_; + private com.google.protobuf.MapField + internalGetHandshakeParameters() { + if (handshakeParameters_ == null) { + return com.google.protobuf.MapField.emptyMapField( + HandshakeParametersDefaultEntryHolder.defaultEntry); + } + return handshakeParameters_; + } + private com.google.protobuf.MapField + internalGetMutableHandshakeParameters() { + onChanged();; + if (handshakeParameters_ == null) { + handshakeParameters_ = com.google.protobuf.MapField.newMapField( + HandshakeParametersDefaultEntryHolder.defaultEntry); + } + if (!handshakeParameters_.isMutable()) { + handshakeParameters_ = handshakeParameters_.copy(); + } + return handshakeParameters_; + } + + public int getHandshakeParametersCount() { + return internalGetHandshakeParameters().getMap().size(); + } + /** + *
+       * Handshake parameters (record protocols and local identities supported by
+       * the server) mapped by the handshake protocol. Each handshake security
+       * protocol (e.g., TLS or ALTS) has its own set of record protocols and local
+       * identities. Since protobuf does not support enum as key to the map, the key
+       * to handshake_parameters is the integer value of HandshakeProtocol enum.
+       * 
+ * + * map<int32, .grpc.gcp.ServerHandshakeParameters> handshake_parameters = 2; + */ + + public boolean containsHandshakeParameters( + int key) { + + return internalGetHandshakeParameters().getMap().containsKey(key); + } + /** + * Use {@link #getHandshakeParametersMap()} instead. + */ + @java.lang.Deprecated + public java.util.Map getHandshakeParameters() { + return getHandshakeParametersMap(); + } + /** + *
+       * Handshake parameters (record protocols and local identities supported by
+       * the server) mapped by the handshake protocol. Each handshake security
+       * protocol (e.g., TLS or ALTS) has its own set of record protocols and local
+       * identities. Since protobuf does not support enum as key to the map, the key
+       * to handshake_parameters is the integer value of HandshakeProtocol enum.
+       * 
+ * + * map<int32, .grpc.gcp.ServerHandshakeParameters> handshake_parameters = 2; + */ + + public java.util.Map getHandshakeParametersMap() { + return internalGetHandshakeParameters().getMap(); + } + /** + *
+       * Handshake parameters (record protocols and local identities supported by
+       * the server) mapped by the handshake protocol. Each handshake security
+       * protocol (e.g., TLS or ALTS) has its own set of record protocols and local
+       * identities. Since protobuf does not support enum as key to the map, the key
+       * to handshake_parameters is the integer value of HandshakeProtocol enum.
+       * 
+ * + * map<int32, .grpc.gcp.ServerHandshakeParameters> handshake_parameters = 2; + */ + + public io.grpc.alts.internal.Handshaker.ServerHandshakeParameters getHandshakeParametersOrDefault( + int key, + io.grpc.alts.internal.Handshaker.ServerHandshakeParameters defaultValue) { + + java.util.Map map = + internalGetHandshakeParameters().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; + } + /** + *
+       * Handshake parameters (record protocols and local identities supported by
+       * the server) mapped by the handshake protocol. Each handshake security
+       * protocol (e.g., TLS or ALTS) has its own set of record protocols and local
+       * identities. Since protobuf does not support enum as key to the map, the key
+       * to handshake_parameters is the integer value of HandshakeProtocol enum.
+       * 
+ * + * map<int32, .grpc.gcp.ServerHandshakeParameters> handshake_parameters = 2; + */ + + public io.grpc.alts.internal.Handshaker.ServerHandshakeParameters getHandshakeParametersOrThrow( + int key) { + + java.util.Map map = + internalGetHandshakeParameters().getMap(); + if (!map.containsKey(key)) { + throw new java.lang.IllegalArgumentException(); + } + return map.get(key); + } + + public Builder clearHandshakeParameters() { + internalGetMutableHandshakeParameters().getMutableMap() + .clear(); + return this; + } + /** + *
+       * Handshake parameters (record protocols and local identities supported by
+       * the server) mapped by the handshake protocol. Each handshake security
+       * protocol (e.g., TLS or ALTS) has its own set of record protocols and local
+       * identities. Since protobuf does not support enum as key to the map, the key
+       * to handshake_parameters is the integer value of HandshakeProtocol enum.
+       * 
+ * + * map<int32, .grpc.gcp.ServerHandshakeParameters> handshake_parameters = 2; + */ + + public Builder removeHandshakeParameters( + int key) { + + internalGetMutableHandshakeParameters().getMutableMap() + .remove(key); + return this; + } + /** + * Use alternate mutation accessors instead. + */ + @java.lang.Deprecated + public java.util.Map + getMutableHandshakeParameters() { + return internalGetMutableHandshakeParameters().getMutableMap(); + } + /** + *
+       * Handshake parameters (record protocols and local identities supported by
+       * the server) mapped by the handshake protocol. Each handshake security
+       * protocol (e.g., TLS or ALTS) has its own set of record protocols and local
+       * identities. Since protobuf does not support enum as key to the map, the key
+       * to handshake_parameters is the integer value of HandshakeProtocol enum.
+       * 
+ * + * map<int32, .grpc.gcp.ServerHandshakeParameters> handshake_parameters = 2; + */ + public Builder putHandshakeParameters( + int key, + io.grpc.alts.internal.Handshaker.ServerHandshakeParameters value) { + + if (value == null) { throw new java.lang.NullPointerException(); } + internalGetMutableHandshakeParameters().getMutableMap() + .put(key, value); + return this; + } + /** + *
+       * Handshake parameters (record protocols and local identities supported by
+       * the server) mapped by the handshake protocol. Each handshake security
+       * protocol (e.g., TLS or ALTS) has its own set of record protocols and local
+       * identities. Since protobuf does not support enum as key to the map, the key
+       * to handshake_parameters is the integer value of HandshakeProtocol enum.
+       * 
+ * + * map<int32, .grpc.gcp.ServerHandshakeParameters> handshake_parameters = 2; + */ + + public Builder putAllHandshakeParameters( + java.util.Map values) { + internalGetMutableHandshakeParameters().getMutableMap() + .putAll(values); + return this; + } + + private com.google.protobuf.ByteString inBytes_ = com.google.protobuf.ByteString.EMPTY; + /** + *
+       * Bytes in out_frames returned from the peer's HandshakerResp. It is possible
+       * that the peer's out_frames are split into multiple HandshakReq messages.
+       * 
+ * + * bytes in_bytes = 3; + */ + public com.google.protobuf.ByteString getInBytes() { + return inBytes_; + } + /** + *
+       * Bytes in out_frames returned from the peer's HandshakerResp. It is possible
+       * that the peer's out_frames are split into multiple HandshakReq messages.
+       * 
+ * + * bytes in_bytes = 3; + */ + public Builder setInBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + + inBytes_ = value; + onChanged(); + return this; + } + /** + *
+       * Bytes in out_frames returned from the peer's HandshakerResp. It is possible
+       * that the peer's out_frames are split into multiple HandshakReq messages.
+       * 
+ * + * bytes in_bytes = 3; + */ + public Builder clearInBytes() { + + inBytes_ = getDefaultInstance().getInBytes(); + onChanged(); + return this; + } + + private io.grpc.alts.internal.Handshaker.Endpoint localEndpoint_ = null; + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.Endpoint, io.grpc.alts.internal.Handshaker.Endpoint.Builder, io.grpc.alts.internal.Handshaker.EndpointOrBuilder> localEndpointBuilder_; + /** + *
+       * (Optional) Local endpoint information of the connection to the client,
+       * such as local IP address, port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint local_endpoint = 4; + */ + public boolean hasLocalEndpoint() { + return localEndpointBuilder_ != null || localEndpoint_ != null; + } + /** + *
+       * (Optional) Local endpoint information of the connection to the client,
+       * such as local IP address, port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint local_endpoint = 4; + */ + public io.grpc.alts.internal.Handshaker.Endpoint getLocalEndpoint() { + if (localEndpointBuilder_ == null) { + return localEndpoint_ == null ? io.grpc.alts.internal.Handshaker.Endpoint.getDefaultInstance() : localEndpoint_; + } else { + return localEndpointBuilder_.getMessage(); + } + } + /** + *
+       * (Optional) Local endpoint information of the connection to the client,
+       * such as local IP address, port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint local_endpoint = 4; + */ + public Builder setLocalEndpoint(io.grpc.alts.internal.Handshaker.Endpoint value) { + if (localEndpointBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + localEndpoint_ = value; + onChanged(); + } else { + localEndpointBuilder_.setMessage(value); + } + + return this; + } + /** + *
+       * (Optional) Local endpoint information of the connection to the client,
+       * such as local IP address, port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint local_endpoint = 4; + */ + public Builder setLocalEndpoint( + io.grpc.alts.internal.Handshaker.Endpoint.Builder builderForValue) { + if (localEndpointBuilder_ == null) { + localEndpoint_ = builderForValue.build(); + onChanged(); + } else { + localEndpointBuilder_.setMessage(builderForValue.build()); + } + + return this; + } + /** + *
+       * (Optional) Local endpoint information of the connection to the client,
+       * such as local IP address, port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint local_endpoint = 4; + */ + public Builder mergeLocalEndpoint(io.grpc.alts.internal.Handshaker.Endpoint value) { + if (localEndpointBuilder_ == null) { + if (localEndpoint_ != null) { + localEndpoint_ = + io.grpc.alts.internal.Handshaker.Endpoint.newBuilder(localEndpoint_).mergeFrom(value).buildPartial(); + } else { + localEndpoint_ = value; + } + onChanged(); + } else { + localEndpointBuilder_.mergeFrom(value); + } + + return this; + } + /** + *
+       * (Optional) Local endpoint information of the connection to the client,
+       * such as local IP address, port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint local_endpoint = 4; + */ + public Builder clearLocalEndpoint() { + if (localEndpointBuilder_ == null) { + localEndpoint_ = null; + onChanged(); + } else { + localEndpoint_ = null; + localEndpointBuilder_ = null; + } + + return this; + } + /** + *
+       * (Optional) Local endpoint information of the connection to the client,
+       * such as local IP address, port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint local_endpoint = 4; + */ + public io.grpc.alts.internal.Handshaker.Endpoint.Builder getLocalEndpointBuilder() { + + onChanged(); + return getLocalEndpointFieldBuilder().getBuilder(); + } + /** + *
+       * (Optional) Local endpoint information of the connection to the client,
+       * such as local IP address, port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint local_endpoint = 4; + */ + public io.grpc.alts.internal.Handshaker.EndpointOrBuilder getLocalEndpointOrBuilder() { + if (localEndpointBuilder_ != null) { + return localEndpointBuilder_.getMessageOrBuilder(); + } else { + return localEndpoint_ == null ? + io.grpc.alts.internal.Handshaker.Endpoint.getDefaultInstance() : localEndpoint_; + } + } + /** + *
+       * (Optional) Local endpoint information of the connection to the client,
+       * such as local IP address, port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint local_endpoint = 4; + */ + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.Endpoint, io.grpc.alts.internal.Handshaker.Endpoint.Builder, io.grpc.alts.internal.Handshaker.EndpointOrBuilder> + getLocalEndpointFieldBuilder() { + if (localEndpointBuilder_ == null) { + localEndpointBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.Endpoint, io.grpc.alts.internal.Handshaker.Endpoint.Builder, io.grpc.alts.internal.Handshaker.EndpointOrBuilder>( + getLocalEndpoint(), + getParentForChildren(), + isClean()); + localEndpoint_ = null; + } + return localEndpointBuilder_; + } + + private io.grpc.alts.internal.Handshaker.Endpoint remoteEndpoint_ = null; + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.Endpoint, io.grpc.alts.internal.Handshaker.Endpoint.Builder, io.grpc.alts.internal.Handshaker.EndpointOrBuilder> remoteEndpointBuilder_; + /** + *
+       * (Optional) Endpoint information of the remote client, such as IP address,
+       * port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint remote_endpoint = 5; + */ + public boolean hasRemoteEndpoint() { + return remoteEndpointBuilder_ != null || remoteEndpoint_ != null; + } + /** + *
+       * (Optional) Endpoint information of the remote client, such as IP address,
+       * port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint remote_endpoint = 5; + */ + public io.grpc.alts.internal.Handshaker.Endpoint getRemoteEndpoint() { + if (remoteEndpointBuilder_ == null) { + return remoteEndpoint_ == null ? io.grpc.alts.internal.Handshaker.Endpoint.getDefaultInstance() : remoteEndpoint_; + } else { + return remoteEndpointBuilder_.getMessage(); + } + } + /** + *
+       * (Optional) Endpoint information of the remote client, such as IP address,
+       * port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint remote_endpoint = 5; + */ + public Builder setRemoteEndpoint(io.grpc.alts.internal.Handshaker.Endpoint value) { + if (remoteEndpointBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + remoteEndpoint_ = value; + onChanged(); + } else { + remoteEndpointBuilder_.setMessage(value); + } + + return this; + } + /** + *
+       * (Optional) Endpoint information of the remote client, such as IP address,
+       * port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint remote_endpoint = 5; + */ + public Builder setRemoteEndpoint( + io.grpc.alts.internal.Handshaker.Endpoint.Builder builderForValue) { + if (remoteEndpointBuilder_ == null) { + remoteEndpoint_ = builderForValue.build(); + onChanged(); + } else { + remoteEndpointBuilder_.setMessage(builderForValue.build()); + } + + return this; + } + /** + *
+       * (Optional) Endpoint information of the remote client, such as IP address,
+       * port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint remote_endpoint = 5; + */ + public Builder mergeRemoteEndpoint(io.grpc.alts.internal.Handshaker.Endpoint value) { + if (remoteEndpointBuilder_ == null) { + if (remoteEndpoint_ != null) { + remoteEndpoint_ = + io.grpc.alts.internal.Handshaker.Endpoint.newBuilder(remoteEndpoint_).mergeFrom(value).buildPartial(); + } else { + remoteEndpoint_ = value; + } + onChanged(); + } else { + remoteEndpointBuilder_.mergeFrom(value); + } + + return this; + } + /** + *
+       * (Optional) Endpoint information of the remote client, such as IP address,
+       * port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint remote_endpoint = 5; + */ + public Builder clearRemoteEndpoint() { + if (remoteEndpointBuilder_ == null) { + remoteEndpoint_ = null; + onChanged(); + } else { + remoteEndpoint_ = null; + remoteEndpointBuilder_ = null; + } + + return this; + } + /** + *
+       * (Optional) Endpoint information of the remote client, such as IP address,
+       * port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint remote_endpoint = 5; + */ + public io.grpc.alts.internal.Handshaker.Endpoint.Builder getRemoteEndpointBuilder() { + + onChanged(); + return getRemoteEndpointFieldBuilder().getBuilder(); + } + /** + *
+       * (Optional) Endpoint information of the remote client, such as IP address,
+       * port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint remote_endpoint = 5; + */ + public io.grpc.alts.internal.Handshaker.EndpointOrBuilder getRemoteEndpointOrBuilder() { + if (remoteEndpointBuilder_ != null) { + return remoteEndpointBuilder_.getMessageOrBuilder(); + } else { + return remoteEndpoint_ == null ? + io.grpc.alts.internal.Handshaker.Endpoint.getDefaultInstance() : remoteEndpoint_; + } + } + /** + *
+       * (Optional) Endpoint information of the remote client, such as IP address,
+       * port number, and network protocol.
+       * 
+ * + * .grpc.gcp.Endpoint remote_endpoint = 5; + */ + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.Endpoint, io.grpc.alts.internal.Handshaker.Endpoint.Builder, io.grpc.alts.internal.Handshaker.EndpointOrBuilder> + getRemoteEndpointFieldBuilder() { + if (remoteEndpointBuilder_ == null) { + remoteEndpointBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.Endpoint, io.grpc.alts.internal.Handshaker.Endpoint.Builder, io.grpc.alts.internal.Handshaker.EndpointOrBuilder>( + getRemoteEndpoint(), + getParentForChildren(), + isClean()); + remoteEndpoint_ = null; + } + return remoteEndpointBuilder_; + } + + private io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions rpcVersions_ = null; + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Builder, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersionsOrBuilder> rpcVersionsBuilder_; + /** + *
+       * (Optional) RPC protocol versions supported by the server.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions rpc_versions = 6; + */ + public boolean hasRpcVersions() { + return rpcVersionsBuilder_ != null || rpcVersions_ != null; + } + /** + *
+       * (Optional) RPC protocol versions supported by the server.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions rpc_versions = 6; + */ + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions getRpcVersions() { + if (rpcVersionsBuilder_ == null) { + return rpcVersions_ == null ? io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.getDefaultInstance() : rpcVersions_; + } else { + return rpcVersionsBuilder_.getMessage(); + } + } + /** + *
+       * (Optional) RPC protocol versions supported by the server.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions rpc_versions = 6; + */ + public Builder setRpcVersions(io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions value) { + if (rpcVersionsBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + rpcVersions_ = value; + onChanged(); + } else { + rpcVersionsBuilder_.setMessage(value); + } + + return this; + } + /** + *
+       * (Optional) RPC protocol versions supported by the server.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions rpc_versions = 6; + */ + public Builder setRpcVersions( + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Builder builderForValue) { + if (rpcVersionsBuilder_ == null) { + rpcVersions_ = builderForValue.build(); + onChanged(); + } else { + rpcVersionsBuilder_.setMessage(builderForValue.build()); + } + + return this; + } + /** + *
+       * (Optional) RPC protocol versions supported by the server.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions rpc_versions = 6; + */ + public Builder mergeRpcVersions(io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions value) { + if (rpcVersionsBuilder_ == null) { + if (rpcVersions_ != null) { + rpcVersions_ = + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.newBuilder(rpcVersions_).mergeFrom(value).buildPartial(); + } else { + rpcVersions_ = value; + } + onChanged(); + } else { + rpcVersionsBuilder_.mergeFrom(value); + } + + return this; + } + /** + *
+       * (Optional) RPC protocol versions supported by the server.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions rpc_versions = 6; + */ + public Builder clearRpcVersions() { + if (rpcVersionsBuilder_ == null) { + rpcVersions_ = null; + onChanged(); + } else { + rpcVersions_ = null; + rpcVersionsBuilder_ = null; + } + + return this; + } + /** + *
+       * (Optional) RPC protocol versions supported by the server.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions rpc_versions = 6; + */ + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Builder getRpcVersionsBuilder() { + + onChanged(); + return getRpcVersionsFieldBuilder().getBuilder(); + } + /** + *
+       * (Optional) RPC protocol versions supported by the server.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions rpc_versions = 6; + */ + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersionsOrBuilder getRpcVersionsOrBuilder() { + if (rpcVersionsBuilder_ != null) { + return rpcVersionsBuilder_.getMessageOrBuilder(); + } else { + return rpcVersions_ == null ? + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.getDefaultInstance() : rpcVersions_; + } + } + /** + *
+       * (Optional) RPC protocol versions supported by the server.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions rpc_versions = 6; + */ + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Builder, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersionsOrBuilder> + getRpcVersionsFieldBuilder() { + if (rpcVersionsBuilder_ == null) { + rpcVersionsBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Builder, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersionsOrBuilder>( + getRpcVersions(), + getParentForChildren(), + isClean()); + rpcVersions_ = null; + } + return rpcVersionsBuilder_; + } + public final Builder setUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); + } + + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + + // @@protoc_insertion_point(builder_scope:grpc.gcp.StartServerHandshakeReq) + } + + // @@protoc_insertion_point(class_scope:grpc.gcp.StartServerHandshakeReq) + private static final io.grpc.alts.internal.Handshaker.StartServerHandshakeReq DEFAULT_INSTANCE; + static { + DEFAULT_INSTANCE = new io.grpc.alts.internal.Handshaker.StartServerHandshakeReq(); + } + + public static io.grpc.alts.internal.Handshaker.StartServerHandshakeReq getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + private static final com.google.protobuf.Parser + PARSER = new com.google.protobuf.AbstractParser() { + public StartServerHandshakeReq parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new StartServerHandshakeReq(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public io.grpc.alts.internal.Handshaker.StartServerHandshakeReq getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } + + } + + public interface NextHandshakeMessageReqOrBuilder extends + // @@protoc_insertion_point(interface_extends:grpc.gcp.NextHandshakeMessageReq) + com.google.protobuf.MessageOrBuilder { + + /** + *
+     * Bytes in out_frames returned from the peer's HandshakerResp. It is possible
+     * that the peer's out_frames are split into multiple NextHandshakerMessageReq
+     * messages.
+     * 
+ * + * bytes in_bytes = 1; + */ + com.google.protobuf.ByteString getInBytes(); + } + /** + * Protobuf type {@code grpc.gcp.NextHandshakeMessageReq} + */ + public static final class NextHandshakeMessageReq extends + com.google.protobuf.GeneratedMessageV3 implements + // @@protoc_insertion_point(message_implements:grpc.gcp.NextHandshakeMessageReq) + NextHandshakeMessageReqOrBuilder { + private static final long serialVersionUID = 0L; + // Use NextHandshakeMessageReq.newBuilder() to construct. + private NextHandshakeMessageReq(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + private NextHandshakeMessageReq() { + inBytes_ = com.google.protobuf.ByteString.EMPTY; + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return this.unknownFields; + } + private NextHandshakeMessageReq( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownFieldProto3( + input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 10: { + + inBytes_ = input.readBytes(); + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_NextHandshakeMessageReq_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_NextHandshakeMessageReq_fieldAccessorTable + .ensureFieldAccessorsInitialized( + io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq.class, io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq.Builder.class); + } + + public static final int IN_BYTES_FIELD_NUMBER = 1; + private com.google.protobuf.ByteString inBytes_; + /** + *
+     * Bytes in out_frames returned from the peer's HandshakerResp. It is possible
+     * that the peer's out_frames are split into multiple NextHandshakerMessageReq
+     * messages.
+     * 
+ * + * bytes in_bytes = 1; + */ + public com.google.protobuf.ByteString getInBytes() { + return inBytes_; + } + + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + if (!inBytes_.isEmpty()) { + output.writeBytes(1, inBytes_); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (!inBytes_.isEmpty()) { + size += com.google.protobuf.CodedOutputStream + .computeBytesSize(1, inBytes_); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq)) { + return super.equals(obj); + } + io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq other = (io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq) obj; + + boolean result = true; + result = result && getInBytes() + .equals(other.getInBytes()); + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + hash = (37 * hash) + IN_BYTES_FIELD_NUMBER; + hash = (53 * hash) + getInBytes().hashCode(); + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq parseFrom( + java.nio.ByteBuffer data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq parseFrom( + java.nio.ByteBuffer data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq parseFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + public static Builder newBuilder(io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { + return this == DEFAULT_INSTANCE + ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + * Protobuf type {@code grpc.gcp.NextHandshakeMessageReq} + */ + public static final class Builder extends + com.google.protobuf.GeneratedMessageV3.Builder implements + // @@protoc_insertion_point(builder_implements:grpc.gcp.NextHandshakeMessageReq) + io.grpc.alts.internal.Handshaker.NextHandshakeMessageReqOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_NextHandshakeMessageReq_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_NextHandshakeMessageReq_fieldAccessorTable + .ensureFieldAccessorsInitialized( + io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq.class, io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq.Builder.class); + } + + // Construct using io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder( + com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3 + .alwaysUseFieldBuilders) { + } + } + public Builder clear() { + super.clear(); + inBytes_ = com.google.protobuf.ByteString.EMPTY; + + return this; + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_NextHandshakeMessageReq_descriptor; + } + + public io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq getDefaultInstanceForType() { + return io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq.getDefaultInstance(); + } + + public io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq build() { + io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq buildPartial() { + io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq result = new io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq(this); + result.inBytes_ = inBytes_; + onBuilt(); + return result; + } + + public Builder clone() { + return (Builder) super.clone(); + } + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, + java.lang.Object value) { + return (Builder) super.setField(field, value); + } + public Builder clearField( + com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); + } + public Builder clearOneof( + com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); + } + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); + } + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); + } + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq) { + return mergeFrom((io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq other) { + if (other == io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq.getDefaultInstance()) return this; + if (other.getInBytes() != com.google.protobuf.ByteString.EMPTY) { + setInBytes(other.getInBytes()); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + private com.google.protobuf.ByteString inBytes_ = com.google.protobuf.ByteString.EMPTY; + /** + *
+       * Bytes in out_frames returned from the peer's HandshakerResp. It is possible
+       * that the peer's out_frames are split into multiple NextHandshakerMessageReq
+       * messages.
+       * 
+ * + * bytes in_bytes = 1; + */ + public com.google.protobuf.ByteString getInBytes() { + return inBytes_; + } + /** + *
+       * Bytes in out_frames returned from the peer's HandshakerResp. It is possible
+       * that the peer's out_frames are split into multiple NextHandshakerMessageReq
+       * messages.
+       * 
+ * + * bytes in_bytes = 1; + */ + public Builder setInBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + + inBytes_ = value; + onChanged(); + return this; + } + /** + *
+       * Bytes in out_frames returned from the peer's HandshakerResp. It is possible
+       * that the peer's out_frames are split into multiple NextHandshakerMessageReq
+       * messages.
+       * 
+ * + * bytes in_bytes = 1; + */ + public Builder clearInBytes() { + + inBytes_ = getDefaultInstance().getInBytes(); + onChanged(); + return this; + } + public final Builder setUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); + } + + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + + // @@protoc_insertion_point(builder_scope:grpc.gcp.NextHandshakeMessageReq) + } + + // @@protoc_insertion_point(class_scope:grpc.gcp.NextHandshakeMessageReq) + private static final io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq DEFAULT_INSTANCE; + static { + DEFAULT_INSTANCE = new io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq(); + } + + public static io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + private static final com.google.protobuf.Parser + PARSER = new com.google.protobuf.AbstractParser() { + public NextHandshakeMessageReq parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new NextHandshakeMessageReq(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } + + } + + public interface HandshakerReqOrBuilder extends + // @@protoc_insertion_point(interface_extends:grpc.gcp.HandshakerReq) + com.google.protobuf.MessageOrBuilder { + + /** + *
+     * The start client handshake request message.
+     * 
+ * + * .grpc.gcp.StartClientHandshakeReq client_start = 1; + */ + boolean hasClientStart(); + /** + *
+     * The start client handshake request message.
+     * 
+ * + * .grpc.gcp.StartClientHandshakeReq client_start = 1; + */ + io.grpc.alts.internal.Handshaker.StartClientHandshakeReq getClientStart(); + /** + *
+     * The start client handshake request message.
+     * 
+ * + * .grpc.gcp.StartClientHandshakeReq client_start = 1; + */ + io.grpc.alts.internal.Handshaker.StartClientHandshakeReqOrBuilder getClientStartOrBuilder(); + + /** + *
+     * The start server handshake request message.
+     * 
+ * + * .grpc.gcp.StartServerHandshakeReq server_start = 2; + */ + boolean hasServerStart(); + /** + *
+     * The start server handshake request message.
+     * 
+ * + * .grpc.gcp.StartServerHandshakeReq server_start = 2; + */ + io.grpc.alts.internal.Handshaker.StartServerHandshakeReq getServerStart(); + /** + *
+     * The start server handshake request message.
+     * 
+ * + * .grpc.gcp.StartServerHandshakeReq server_start = 2; + */ + io.grpc.alts.internal.Handshaker.StartServerHandshakeReqOrBuilder getServerStartOrBuilder(); + + /** + *
+     * The next handshake request message.
+     * 
+ * + * .grpc.gcp.NextHandshakeMessageReq next = 3; + */ + boolean hasNext(); + /** + *
+     * The next handshake request message.
+     * 
+ * + * .grpc.gcp.NextHandshakeMessageReq next = 3; + */ + io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq getNext(); + /** + *
+     * The next handshake request message.
+     * 
+ * + * .grpc.gcp.NextHandshakeMessageReq next = 3; + */ + io.grpc.alts.internal.Handshaker.NextHandshakeMessageReqOrBuilder getNextOrBuilder(); + + public io.grpc.alts.internal.Handshaker.HandshakerReq.ReqOneofCase getReqOneofCase(); + } + /** + * Protobuf type {@code grpc.gcp.HandshakerReq} + */ + public static final class HandshakerReq extends + com.google.protobuf.GeneratedMessageV3 implements + // @@protoc_insertion_point(message_implements:grpc.gcp.HandshakerReq) + HandshakerReqOrBuilder { + private static final long serialVersionUID = 0L; + // Use HandshakerReq.newBuilder() to construct. + private HandshakerReq(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + private HandshakerReq() { + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return this.unknownFields; + } + private HandshakerReq( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownFieldProto3( + input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 10: { + io.grpc.alts.internal.Handshaker.StartClientHandshakeReq.Builder subBuilder = null; + if (reqOneofCase_ == 1) { + subBuilder = ((io.grpc.alts.internal.Handshaker.StartClientHandshakeReq) reqOneof_).toBuilder(); + } + reqOneof_ = + input.readMessage(io.grpc.alts.internal.Handshaker.StartClientHandshakeReq.parser(), extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom((io.grpc.alts.internal.Handshaker.StartClientHandshakeReq) reqOneof_); + reqOneof_ = subBuilder.buildPartial(); + } + reqOneofCase_ = 1; + break; + } + case 18: { + io.grpc.alts.internal.Handshaker.StartServerHandshakeReq.Builder subBuilder = null; + if (reqOneofCase_ == 2) { + subBuilder = ((io.grpc.alts.internal.Handshaker.StartServerHandshakeReq) reqOneof_).toBuilder(); + } + reqOneof_ = + input.readMessage(io.grpc.alts.internal.Handshaker.StartServerHandshakeReq.parser(), extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom((io.grpc.alts.internal.Handshaker.StartServerHandshakeReq) reqOneof_); + reqOneof_ = subBuilder.buildPartial(); + } + reqOneofCase_ = 2; + break; + } + case 26: { + io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq.Builder subBuilder = null; + if (reqOneofCase_ == 3) { + subBuilder = ((io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq) reqOneof_).toBuilder(); + } + reqOneof_ = + input.readMessage(io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq.parser(), extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom((io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq) reqOneof_); + reqOneof_ = subBuilder.buildPartial(); + } + reqOneofCase_ = 3; + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_HandshakerReq_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_HandshakerReq_fieldAccessorTable + .ensureFieldAccessorsInitialized( + io.grpc.alts.internal.Handshaker.HandshakerReq.class, io.grpc.alts.internal.Handshaker.HandshakerReq.Builder.class); + } + + private int reqOneofCase_ = 0; + private java.lang.Object reqOneof_; + public enum ReqOneofCase + implements com.google.protobuf.Internal.EnumLite { + CLIENT_START(1), + SERVER_START(2), + NEXT(3), + REQONEOF_NOT_SET(0); + private final int value; + private ReqOneofCase(int value) { + this.value = value; + } + /** + * @deprecated Use {@link #forNumber(int)} instead. + */ + @java.lang.Deprecated + public static ReqOneofCase valueOf(int value) { + return forNumber(value); + } + + public static ReqOneofCase forNumber(int value) { + switch (value) { + case 1: return CLIENT_START; + case 2: return SERVER_START; + case 3: return NEXT; + case 0: return REQONEOF_NOT_SET; + default: return null; + } + } + public int getNumber() { + return this.value; + } + }; + + public ReqOneofCase + getReqOneofCase() { + return ReqOneofCase.forNumber( + reqOneofCase_); + } + + public static final int CLIENT_START_FIELD_NUMBER = 1; + /** + *
+     * The start client handshake request message.
+     * 
+ * + * .grpc.gcp.StartClientHandshakeReq client_start = 1; + */ + public boolean hasClientStart() { + return reqOneofCase_ == 1; + } + /** + *
+     * The start client handshake request message.
+     * 
+ * + * .grpc.gcp.StartClientHandshakeReq client_start = 1; + */ + public io.grpc.alts.internal.Handshaker.StartClientHandshakeReq getClientStart() { + if (reqOneofCase_ == 1) { + return (io.grpc.alts.internal.Handshaker.StartClientHandshakeReq) reqOneof_; + } + return io.grpc.alts.internal.Handshaker.StartClientHandshakeReq.getDefaultInstance(); + } + /** + *
+     * The start client handshake request message.
+     * 
+ * + * .grpc.gcp.StartClientHandshakeReq client_start = 1; + */ + public io.grpc.alts.internal.Handshaker.StartClientHandshakeReqOrBuilder getClientStartOrBuilder() { + if (reqOneofCase_ == 1) { + return (io.grpc.alts.internal.Handshaker.StartClientHandshakeReq) reqOneof_; + } + return io.grpc.alts.internal.Handshaker.StartClientHandshakeReq.getDefaultInstance(); + } + + public static final int SERVER_START_FIELD_NUMBER = 2; + /** + *
+     * The start server handshake request message.
+     * 
+ * + * .grpc.gcp.StartServerHandshakeReq server_start = 2; + */ + public boolean hasServerStart() { + return reqOneofCase_ == 2; + } + /** + *
+     * The start server handshake request message.
+     * 
+ * + * .grpc.gcp.StartServerHandshakeReq server_start = 2; + */ + public io.grpc.alts.internal.Handshaker.StartServerHandshakeReq getServerStart() { + if (reqOneofCase_ == 2) { + return (io.grpc.alts.internal.Handshaker.StartServerHandshakeReq) reqOneof_; + } + return io.grpc.alts.internal.Handshaker.StartServerHandshakeReq.getDefaultInstance(); + } + /** + *
+     * The start server handshake request message.
+     * 
+ * + * .grpc.gcp.StartServerHandshakeReq server_start = 2; + */ + public io.grpc.alts.internal.Handshaker.StartServerHandshakeReqOrBuilder getServerStartOrBuilder() { + if (reqOneofCase_ == 2) { + return (io.grpc.alts.internal.Handshaker.StartServerHandshakeReq) reqOneof_; + } + return io.grpc.alts.internal.Handshaker.StartServerHandshakeReq.getDefaultInstance(); + } + + public static final int NEXT_FIELD_NUMBER = 3; + /** + *
+     * The next handshake request message.
+     * 
+ * + * .grpc.gcp.NextHandshakeMessageReq next = 3; + */ + public boolean hasNext() { + return reqOneofCase_ == 3; + } + /** + *
+     * The next handshake request message.
+     * 
+ * + * .grpc.gcp.NextHandshakeMessageReq next = 3; + */ + public io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq getNext() { + if (reqOneofCase_ == 3) { + return (io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq) reqOneof_; + } + return io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq.getDefaultInstance(); + } + /** + *
+     * The next handshake request message.
+     * 
+ * + * .grpc.gcp.NextHandshakeMessageReq next = 3; + */ + public io.grpc.alts.internal.Handshaker.NextHandshakeMessageReqOrBuilder getNextOrBuilder() { + if (reqOneofCase_ == 3) { + return (io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq) reqOneof_; + } + return io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq.getDefaultInstance(); + } + + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + if (reqOneofCase_ == 1) { + output.writeMessage(1, (io.grpc.alts.internal.Handshaker.StartClientHandshakeReq) reqOneof_); + } + if (reqOneofCase_ == 2) { + output.writeMessage(2, (io.grpc.alts.internal.Handshaker.StartServerHandshakeReq) reqOneof_); + } + if (reqOneofCase_ == 3) { + output.writeMessage(3, (io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq) reqOneof_); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (reqOneofCase_ == 1) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(1, (io.grpc.alts.internal.Handshaker.StartClientHandshakeReq) reqOneof_); + } + if (reqOneofCase_ == 2) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(2, (io.grpc.alts.internal.Handshaker.StartServerHandshakeReq) reqOneof_); + } + if (reqOneofCase_ == 3) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(3, (io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq) reqOneof_); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof io.grpc.alts.internal.Handshaker.HandshakerReq)) { + return super.equals(obj); + } + io.grpc.alts.internal.Handshaker.HandshakerReq other = (io.grpc.alts.internal.Handshaker.HandshakerReq) obj; + + boolean result = true; + result = result && getReqOneofCase().equals( + other.getReqOneofCase()); + if (!result) return false; + switch (reqOneofCase_) { + case 1: + result = result && getClientStart() + .equals(other.getClientStart()); + break; + case 2: + result = result && getServerStart() + .equals(other.getServerStart()); + break; + case 3: + result = result && getNext() + .equals(other.getNext()); + break; + case 0: + default: + } + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + switch (reqOneofCase_) { + case 1: + hash = (37 * hash) + CLIENT_START_FIELD_NUMBER; + hash = (53 * hash) + getClientStart().hashCode(); + break; + case 2: + hash = (37 * hash) + SERVER_START_FIELD_NUMBER; + hash = (53 * hash) + getServerStart().hashCode(); + break; + case 3: + hash = (37 * hash) + NEXT_FIELD_NUMBER; + hash = (53 * hash) + getNext().hashCode(); + break; + case 0: + default: + } + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static io.grpc.alts.internal.Handshaker.HandshakerReq parseFrom( + java.nio.ByteBuffer data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Handshaker.HandshakerReq parseFrom( + java.nio.ByteBuffer data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.HandshakerReq parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Handshaker.HandshakerReq parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.HandshakerReq parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Handshaker.HandshakerReq parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.HandshakerReq parseFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Handshaker.HandshakerReq parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.HandshakerReq parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Handshaker.HandshakerReq parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.HandshakerReq parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Handshaker.HandshakerReq parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + public static Builder newBuilder(io.grpc.alts.internal.Handshaker.HandshakerReq prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { + return this == DEFAULT_INSTANCE + ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + * Protobuf type {@code grpc.gcp.HandshakerReq} + */ + public static final class Builder extends + com.google.protobuf.GeneratedMessageV3.Builder implements + // @@protoc_insertion_point(builder_implements:grpc.gcp.HandshakerReq) + io.grpc.alts.internal.Handshaker.HandshakerReqOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_HandshakerReq_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_HandshakerReq_fieldAccessorTable + .ensureFieldAccessorsInitialized( + io.grpc.alts.internal.Handshaker.HandshakerReq.class, io.grpc.alts.internal.Handshaker.HandshakerReq.Builder.class); + } + + // Construct using io.grpc.alts.internal.Handshaker.HandshakerReq.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder( + com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3 + .alwaysUseFieldBuilders) { + } + } + public Builder clear() { + super.clear(); + reqOneofCase_ = 0; + reqOneof_ = null; + return this; + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_HandshakerReq_descriptor; + } + + public io.grpc.alts.internal.Handshaker.HandshakerReq getDefaultInstanceForType() { + return io.grpc.alts.internal.Handshaker.HandshakerReq.getDefaultInstance(); + } + + public io.grpc.alts.internal.Handshaker.HandshakerReq build() { + io.grpc.alts.internal.Handshaker.HandshakerReq result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public io.grpc.alts.internal.Handshaker.HandshakerReq buildPartial() { + io.grpc.alts.internal.Handshaker.HandshakerReq result = new io.grpc.alts.internal.Handshaker.HandshakerReq(this); + if (reqOneofCase_ == 1) { + if (clientStartBuilder_ == null) { + result.reqOneof_ = reqOneof_; + } else { + result.reqOneof_ = clientStartBuilder_.build(); + } + } + if (reqOneofCase_ == 2) { + if (serverStartBuilder_ == null) { + result.reqOneof_ = reqOneof_; + } else { + result.reqOneof_ = serverStartBuilder_.build(); + } + } + if (reqOneofCase_ == 3) { + if (nextBuilder_ == null) { + result.reqOneof_ = reqOneof_; + } else { + result.reqOneof_ = nextBuilder_.build(); + } + } + result.reqOneofCase_ = reqOneofCase_; + onBuilt(); + return result; + } + + public Builder clone() { + return (Builder) super.clone(); + } + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, + java.lang.Object value) { + return (Builder) super.setField(field, value); + } + public Builder clearField( + com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); + } + public Builder clearOneof( + com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); + } + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); + } + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); + } + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof io.grpc.alts.internal.Handshaker.HandshakerReq) { + return mergeFrom((io.grpc.alts.internal.Handshaker.HandshakerReq)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(io.grpc.alts.internal.Handshaker.HandshakerReq other) { + if (other == io.grpc.alts.internal.Handshaker.HandshakerReq.getDefaultInstance()) return this; + switch (other.getReqOneofCase()) { + case CLIENT_START: { + mergeClientStart(other.getClientStart()); + break; + } + case SERVER_START: { + mergeServerStart(other.getServerStart()); + break; + } + case NEXT: { + mergeNext(other.getNext()); + break; + } + case REQONEOF_NOT_SET: { + break; + } + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + io.grpc.alts.internal.Handshaker.HandshakerReq parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (io.grpc.alts.internal.Handshaker.HandshakerReq) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + private int reqOneofCase_ = 0; + private java.lang.Object reqOneof_; + public ReqOneofCase + getReqOneofCase() { + return ReqOneofCase.forNumber( + reqOneofCase_); + } + + public Builder clearReqOneof() { + reqOneofCase_ = 0; + reqOneof_ = null; + onChanged(); + return this; + } + + + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.StartClientHandshakeReq, io.grpc.alts.internal.Handshaker.StartClientHandshakeReq.Builder, io.grpc.alts.internal.Handshaker.StartClientHandshakeReqOrBuilder> clientStartBuilder_; + /** + *
+       * The start client handshake request message.
+       * 
+ * + * .grpc.gcp.StartClientHandshakeReq client_start = 1; + */ + public boolean hasClientStart() { + return reqOneofCase_ == 1; + } + /** + *
+       * The start client handshake request message.
+       * 
+ * + * .grpc.gcp.StartClientHandshakeReq client_start = 1; + */ + public io.grpc.alts.internal.Handshaker.StartClientHandshakeReq getClientStart() { + if (clientStartBuilder_ == null) { + if (reqOneofCase_ == 1) { + return (io.grpc.alts.internal.Handshaker.StartClientHandshakeReq) reqOneof_; + } + return io.grpc.alts.internal.Handshaker.StartClientHandshakeReq.getDefaultInstance(); + } else { + if (reqOneofCase_ == 1) { + return clientStartBuilder_.getMessage(); + } + return io.grpc.alts.internal.Handshaker.StartClientHandshakeReq.getDefaultInstance(); + } + } + /** + *
+       * The start client handshake request message.
+       * 
+ * + * .grpc.gcp.StartClientHandshakeReq client_start = 1; + */ + public Builder setClientStart(io.grpc.alts.internal.Handshaker.StartClientHandshakeReq value) { + if (clientStartBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + reqOneof_ = value; + onChanged(); + } else { + clientStartBuilder_.setMessage(value); + } + reqOneofCase_ = 1; + return this; + } + /** + *
+       * The start client handshake request message.
+       * 
+ * + * .grpc.gcp.StartClientHandshakeReq client_start = 1; + */ + public Builder setClientStart( + io.grpc.alts.internal.Handshaker.StartClientHandshakeReq.Builder builderForValue) { + if (clientStartBuilder_ == null) { + reqOneof_ = builderForValue.build(); + onChanged(); + } else { + clientStartBuilder_.setMessage(builderForValue.build()); + } + reqOneofCase_ = 1; + return this; + } + /** + *
+       * The start client handshake request message.
+       * 
+ * + * .grpc.gcp.StartClientHandshakeReq client_start = 1; + */ + public Builder mergeClientStart(io.grpc.alts.internal.Handshaker.StartClientHandshakeReq value) { + if (clientStartBuilder_ == null) { + if (reqOneofCase_ == 1 && + reqOneof_ != io.grpc.alts.internal.Handshaker.StartClientHandshakeReq.getDefaultInstance()) { + reqOneof_ = io.grpc.alts.internal.Handshaker.StartClientHandshakeReq.newBuilder((io.grpc.alts.internal.Handshaker.StartClientHandshakeReq) reqOneof_) + .mergeFrom(value).buildPartial(); + } else { + reqOneof_ = value; + } + onChanged(); + } else { + if (reqOneofCase_ == 1) { + clientStartBuilder_.mergeFrom(value); + } + clientStartBuilder_.setMessage(value); + } + reqOneofCase_ = 1; + return this; + } + /** + *
+       * The start client handshake request message.
+       * 
+ * + * .grpc.gcp.StartClientHandshakeReq client_start = 1; + */ + public Builder clearClientStart() { + if (clientStartBuilder_ == null) { + if (reqOneofCase_ == 1) { + reqOneofCase_ = 0; + reqOneof_ = null; + onChanged(); + } + } else { + if (reqOneofCase_ == 1) { + reqOneofCase_ = 0; + reqOneof_ = null; + } + clientStartBuilder_.clear(); + } + return this; + } + /** + *
+       * The start client handshake request message.
+       * 
+ * + * .grpc.gcp.StartClientHandshakeReq client_start = 1; + */ + public io.grpc.alts.internal.Handshaker.StartClientHandshakeReq.Builder getClientStartBuilder() { + return getClientStartFieldBuilder().getBuilder(); + } + /** + *
+       * The start client handshake request message.
+       * 
+ * + * .grpc.gcp.StartClientHandshakeReq client_start = 1; + */ + public io.grpc.alts.internal.Handshaker.StartClientHandshakeReqOrBuilder getClientStartOrBuilder() { + if ((reqOneofCase_ == 1) && (clientStartBuilder_ != null)) { + return clientStartBuilder_.getMessageOrBuilder(); + } else { + if (reqOneofCase_ == 1) { + return (io.grpc.alts.internal.Handshaker.StartClientHandshakeReq) reqOneof_; + } + return io.grpc.alts.internal.Handshaker.StartClientHandshakeReq.getDefaultInstance(); + } + } + /** + *
+       * The start client handshake request message.
+       * 
+ * + * .grpc.gcp.StartClientHandshakeReq client_start = 1; + */ + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.StartClientHandshakeReq, io.grpc.alts.internal.Handshaker.StartClientHandshakeReq.Builder, io.grpc.alts.internal.Handshaker.StartClientHandshakeReqOrBuilder> + getClientStartFieldBuilder() { + if (clientStartBuilder_ == null) { + if (!(reqOneofCase_ == 1)) { + reqOneof_ = io.grpc.alts.internal.Handshaker.StartClientHandshakeReq.getDefaultInstance(); + } + clientStartBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.StartClientHandshakeReq, io.grpc.alts.internal.Handshaker.StartClientHandshakeReq.Builder, io.grpc.alts.internal.Handshaker.StartClientHandshakeReqOrBuilder>( + (io.grpc.alts.internal.Handshaker.StartClientHandshakeReq) reqOneof_, + getParentForChildren(), + isClean()); + reqOneof_ = null; + } + reqOneofCase_ = 1; + onChanged();; + return clientStartBuilder_; + } + + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.StartServerHandshakeReq, io.grpc.alts.internal.Handshaker.StartServerHandshakeReq.Builder, io.grpc.alts.internal.Handshaker.StartServerHandshakeReqOrBuilder> serverStartBuilder_; + /** + *
+       * The start server handshake request message.
+       * 
+ * + * .grpc.gcp.StartServerHandshakeReq server_start = 2; + */ + public boolean hasServerStart() { + return reqOneofCase_ == 2; + } + /** + *
+       * The start server handshake request message.
+       * 
+ * + * .grpc.gcp.StartServerHandshakeReq server_start = 2; + */ + public io.grpc.alts.internal.Handshaker.StartServerHandshakeReq getServerStart() { + if (serverStartBuilder_ == null) { + if (reqOneofCase_ == 2) { + return (io.grpc.alts.internal.Handshaker.StartServerHandshakeReq) reqOneof_; + } + return io.grpc.alts.internal.Handshaker.StartServerHandshakeReq.getDefaultInstance(); + } else { + if (reqOneofCase_ == 2) { + return serverStartBuilder_.getMessage(); + } + return io.grpc.alts.internal.Handshaker.StartServerHandshakeReq.getDefaultInstance(); + } + } + /** + *
+       * The start server handshake request message.
+       * 
+ * + * .grpc.gcp.StartServerHandshakeReq server_start = 2; + */ + public Builder setServerStart(io.grpc.alts.internal.Handshaker.StartServerHandshakeReq value) { + if (serverStartBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + reqOneof_ = value; + onChanged(); + } else { + serverStartBuilder_.setMessage(value); + } + reqOneofCase_ = 2; + return this; + } + /** + *
+       * The start server handshake request message.
+       * 
+ * + * .grpc.gcp.StartServerHandshakeReq server_start = 2; + */ + public Builder setServerStart( + io.grpc.alts.internal.Handshaker.StartServerHandshakeReq.Builder builderForValue) { + if (serverStartBuilder_ == null) { + reqOneof_ = builderForValue.build(); + onChanged(); + } else { + serverStartBuilder_.setMessage(builderForValue.build()); + } + reqOneofCase_ = 2; + return this; + } + /** + *
+       * The start server handshake request message.
+       * 
+ * + * .grpc.gcp.StartServerHandshakeReq server_start = 2; + */ + public Builder mergeServerStart(io.grpc.alts.internal.Handshaker.StartServerHandshakeReq value) { + if (serverStartBuilder_ == null) { + if (reqOneofCase_ == 2 && + reqOneof_ != io.grpc.alts.internal.Handshaker.StartServerHandshakeReq.getDefaultInstance()) { + reqOneof_ = io.grpc.alts.internal.Handshaker.StartServerHandshakeReq.newBuilder((io.grpc.alts.internal.Handshaker.StartServerHandshakeReq) reqOneof_) + .mergeFrom(value).buildPartial(); + } else { + reqOneof_ = value; + } + onChanged(); + } else { + if (reqOneofCase_ == 2) { + serverStartBuilder_.mergeFrom(value); + } + serverStartBuilder_.setMessage(value); + } + reqOneofCase_ = 2; + return this; + } + /** + *
+       * The start server handshake request message.
+       * 
+ * + * .grpc.gcp.StartServerHandshakeReq server_start = 2; + */ + public Builder clearServerStart() { + if (serverStartBuilder_ == null) { + if (reqOneofCase_ == 2) { + reqOneofCase_ = 0; + reqOneof_ = null; + onChanged(); + } + } else { + if (reqOneofCase_ == 2) { + reqOneofCase_ = 0; + reqOneof_ = null; + } + serverStartBuilder_.clear(); + } + return this; + } + /** + *
+       * The start server handshake request message.
+       * 
+ * + * .grpc.gcp.StartServerHandshakeReq server_start = 2; + */ + public io.grpc.alts.internal.Handshaker.StartServerHandshakeReq.Builder getServerStartBuilder() { + return getServerStartFieldBuilder().getBuilder(); + } + /** + *
+       * The start server handshake request message.
+       * 
+ * + * .grpc.gcp.StartServerHandshakeReq server_start = 2; + */ + public io.grpc.alts.internal.Handshaker.StartServerHandshakeReqOrBuilder getServerStartOrBuilder() { + if ((reqOneofCase_ == 2) && (serverStartBuilder_ != null)) { + return serverStartBuilder_.getMessageOrBuilder(); + } else { + if (reqOneofCase_ == 2) { + return (io.grpc.alts.internal.Handshaker.StartServerHandshakeReq) reqOneof_; + } + return io.grpc.alts.internal.Handshaker.StartServerHandshakeReq.getDefaultInstance(); + } + } + /** + *
+       * The start server handshake request message.
+       * 
+ * + * .grpc.gcp.StartServerHandshakeReq server_start = 2; + */ + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.StartServerHandshakeReq, io.grpc.alts.internal.Handshaker.StartServerHandshakeReq.Builder, io.grpc.alts.internal.Handshaker.StartServerHandshakeReqOrBuilder> + getServerStartFieldBuilder() { + if (serverStartBuilder_ == null) { + if (!(reqOneofCase_ == 2)) { + reqOneof_ = io.grpc.alts.internal.Handshaker.StartServerHandshakeReq.getDefaultInstance(); + } + serverStartBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.StartServerHandshakeReq, io.grpc.alts.internal.Handshaker.StartServerHandshakeReq.Builder, io.grpc.alts.internal.Handshaker.StartServerHandshakeReqOrBuilder>( + (io.grpc.alts.internal.Handshaker.StartServerHandshakeReq) reqOneof_, + getParentForChildren(), + isClean()); + reqOneof_ = null; + } + reqOneofCase_ = 2; + onChanged();; + return serverStartBuilder_; + } + + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq, io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq.Builder, io.grpc.alts.internal.Handshaker.NextHandshakeMessageReqOrBuilder> nextBuilder_; + /** + *
+       * The next handshake request message.
+       * 
+ * + * .grpc.gcp.NextHandshakeMessageReq next = 3; + */ + public boolean hasNext() { + return reqOneofCase_ == 3; + } + /** + *
+       * The next handshake request message.
+       * 
+ * + * .grpc.gcp.NextHandshakeMessageReq next = 3; + */ + public io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq getNext() { + if (nextBuilder_ == null) { + if (reqOneofCase_ == 3) { + return (io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq) reqOneof_; + } + return io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq.getDefaultInstance(); + } else { + if (reqOneofCase_ == 3) { + return nextBuilder_.getMessage(); + } + return io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq.getDefaultInstance(); + } + } + /** + *
+       * The next handshake request message.
+       * 
+ * + * .grpc.gcp.NextHandshakeMessageReq next = 3; + */ + public Builder setNext(io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq value) { + if (nextBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + reqOneof_ = value; + onChanged(); + } else { + nextBuilder_.setMessage(value); + } + reqOneofCase_ = 3; + return this; + } + /** + *
+       * The next handshake request message.
+       * 
+ * + * .grpc.gcp.NextHandshakeMessageReq next = 3; + */ + public Builder setNext( + io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq.Builder builderForValue) { + if (nextBuilder_ == null) { + reqOneof_ = builderForValue.build(); + onChanged(); + } else { + nextBuilder_.setMessage(builderForValue.build()); + } + reqOneofCase_ = 3; + return this; + } + /** + *
+       * The next handshake request message.
+       * 
+ * + * .grpc.gcp.NextHandshakeMessageReq next = 3; + */ + public Builder mergeNext(io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq value) { + if (nextBuilder_ == null) { + if (reqOneofCase_ == 3 && + reqOneof_ != io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq.getDefaultInstance()) { + reqOneof_ = io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq.newBuilder((io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq) reqOneof_) + .mergeFrom(value).buildPartial(); + } else { + reqOneof_ = value; + } + onChanged(); + } else { + if (reqOneofCase_ == 3) { + nextBuilder_.mergeFrom(value); + } + nextBuilder_.setMessage(value); + } + reqOneofCase_ = 3; + return this; + } + /** + *
+       * The next handshake request message.
+       * 
+ * + * .grpc.gcp.NextHandshakeMessageReq next = 3; + */ + public Builder clearNext() { + if (nextBuilder_ == null) { + if (reqOneofCase_ == 3) { + reqOneofCase_ = 0; + reqOneof_ = null; + onChanged(); + } + } else { + if (reqOneofCase_ == 3) { + reqOneofCase_ = 0; + reqOneof_ = null; + } + nextBuilder_.clear(); + } + return this; + } + /** + *
+       * The next handshake request message.
+       * 
+ * + * .grpc.gcp.NextHandshakeMessageReq next = 3; + */ + public io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq.Builder getNextBuilder() { + return getNextFieldBuilder().getBuilder(); + } + /** + *
+       * The next handshake request message.
+       * 
+ * + * .grpc.gcp.NextHandshakeMessageReq next = 3; + */ + public io.grpc.alts.internal.Handshaker.NextHandshakeMessageReqOrBuilder getNextOrBuilder() { + if ((reqOneofCase_ == 3) && (nextBuilder_ != null)) { + return nextBuilder_.getMessageOrBuilder(); + } else { + if (reqOneofCase_ == 3) { + return (io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq) reqOneof_; + } + return io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq.getDefaultInstance(); + } + } + /** + *
+       * The next handshake request message.
+       * 
+ * + * .grpc.gcp.NextHandshakeMessageReq next = 3; + */ + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq, io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq.Builder, io.grpc.alts.internal.Handshaker.NextHandshakeMessageReqOrBuilder> + getNextFieldBuilder() { + if (nextBuilder_ == null) { + if (!(reqOneofCase_ == 3)) { + reqOneof_ = io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq.getDefaultInstance(); + } + nextBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq, io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq.Builder, io.grpc.alts.internal.Handshaker.NextHandshakeMessageReqOrBuilder>( + (io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq) reqOneof_, + getParentForChildren(), + isClean()); + reqOneof_ = null; + } + reqOneofCase_ = 3; + onChanged();; + return nextBuilder_; + } + public final Builder setUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); + } + + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + + // @@protoc_insertion_point(builder_scope:grpc.gcp.HandshakerReq) + } + + // @@protoc_insertion_point(class_scope:grpc.gcp.HandshakerReq) + private static final io.grpc.alts.internal.Handshaker.HandshakerReq DEFAULT_INSTANCE; + static { + DEFAULT_INSTANCE = new io.grpc.alts.internal.Handshaker.HandshakerReq(); + } + + public static io.grpc.alts.internal.Handshaker.HandshakerReq getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + private static final com.google.protobuf.Parser + PARSER = new com.google.protobuf.AbstractParser() { + public HandshakerReq parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new HandshakerReq(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public io.grpc.alts.internal.Handshaker.HandshakerReq getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } + + } + + public interface HandshakerResultOrBuilder extends + // @@protoc_insertion_point(interface_extends:grpc.gcp.HandshakerResult) + com.google.protobuf.MessageOrBuilder { + + /** + *
+     * The application protocol negotiated for this connection.
+     * 
+ * + * string application_protocol = 1; + */ + java.lang.String getApplicationProtocol(); + /** + *
+     * The application protocol negotiated for this connection.
+     * 
+ * + * string application_protocol = 1; + */ + com.google.protobuf.ByteString + getApplicationProtocolBytes(); + + /** + *
+     * The record protocol negotiated for this connection.
+     * 
+ * + * string record_protocol = 2; + */ + java.lang.String getRecordProtocol(); + /** + *
+     * The record protocol negotiated for this connection.
+     * 
+ * + * string record_protocol = 2; + */ + com.google.protobuf.ByteString + getRecordProtocolBytes(); + + /** + *
+     * Cryptographic key data. The key data may be more than the key length
+     * required for the record protocol, thus the client of the handshaker
+     * service needs to truncate the key data into the right key length.
+     * 
+ * + * bytes key_data = 3; + */ + com.google.protobuf.ByteString getKeyData(); + + /** + *
+     * The authenticated identity of the peer.
+     * 
+ * + * .grpc.gcp.Identity peer_identity = 4; + */ + boolean hasPeerIdentity(); + /** + *
+     * The authenticated identity of the peer.
+     * 
+ * + * .grpc.gcp.Identity peer_identity = 4; + */ + io.grpc.alts.internal.Handshaker.Identity getPeerIdentity(); + /** + *
+     * The authenticated identity of the peer.
+     * 
+ * + * .grpc.gcp.Identity peer_identity = 4; + */ + io.grpc.alts.internal.Handshaker.IdentityOrBuilder getPeerIdentityOrBuilder(); + + /** + *
+     * The local identity used in the handshake.
+     * 
+ * + * .grpc.gcp.Identity local_identity = 5; + */ + boolean hasLocalIdentity(); + /** + *
+     * The local identity used in the handshake.
+     * 
+ * + * .grpc.gcp.Identity local_identity = 5; + */ + io.grpc.alts.internal.Handshaker.Identity getLocalIdentity(); + /** + *
+     * The local identity used in the handshake.
+     * 
+ * + * .grpc.gcp.Identity local_identity = 5; + */ + io.grpc.alts.internal.Handshaker.IdentityOrBuilder getLocalIdentityOrBuilder(); + + /** + *
+     * Indicate whether the handshaker service client should keep the channel
+     * between the handshaker service open, e.g., in order to handle
+     * post-handshake messages in the future.
+     * 
+ * + * bool keep_channel_open = 6; + */ + boolean getKeepChannelOpen(); + + /** + *
+     * The RPC protocol versions supported by the peer.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions peer_rpc_versions = 7; + */ + boolean hasPeerRpcVersions(); + /** + *
+     * The RPC protocol versions supported by the peer.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions peer_rpc_versions = 7; + */ + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions getPeerRpcVersions(); + /** + *
+     * The RPC protocol versions supported by the peer.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions peer_rpc_versions = 7; + */ + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersionsOrBuilder getPeerRpcVersionsOrBuilder(); + } + /** + * Protobuf type {@code grpc.gcp.HandshakerResult} + */ + public static final class HandshakerResult extends + com.google.protobuf.GeneratedMessageV3 implements + // @@protoc_insertion_point(message_implements:grpc.gcp.HandshakerResult) + HandshakerResultOrBuilder { + private static final long serialVersionUID = 0L; + // Use HandshakerResult.newBuilder() to construct. + private HandshakerResult(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + private HandshakerResult() { + applicationProtocol_ = ""; + recordProtocol_ = ""; + keyData_ = com.google.protobuf.ByteString.EMPTY; + keepChannelOpen_ = false; + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return this.unknownFields; + } + private HandshakerResult( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownFieldProto3( + input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 10: { + java.lang.String s = input.readStringRequireUtf8(); + + applicationProtocol_ = s; + break; + } + case 18: { + java.lang.String s = input.readStringRequireUtf8(); + + recordProtocol_ = s; + break; + } + case 26: { + + keyData_ = input.readBytes(); + break; + } + case 34: { + io.grpc.alts.internal.Handshaker.Identity.Builder subBuilder = null; + if (peerIdentity_ != null) { + subBuilder = peerIdentity_.toBuilder(); + } + peerIdentity_ = input.readMessage(io.grpc.alts.internal.Handshaker.Identity.parser(), extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(peerIdentity_); + peerIdentity_ = subBuilder.buildPartial(); + } + + break; + } + case 42: { + io.grpc.alts.internal.Handshaker.Identity.Builder subBuilder = null; + if (localIdentity_ != null) { + subBuilder = localIdentity_.toBuilder(); + } + localIdentity_ = input.readMessage(io.grpc.alts.internal.Handshaker.Identity.parser(), extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(localIdentity_); + localIdentity_ = subBuilder.buildPartial(); + } + + break; + } + case 48: { + + keepChannelOpen_ = input.readBool(); + break; + } + case 58: { + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Builder subBuilder = null; + if (peerRpcVersions_ != null) { + subBuilder = peerRpcVersions_.toBuilder(); + } + peerRpcVersions_ = input.readMessage(io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.parser(), extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(peerRpcVersions_); + peerRpcVersions_ = subBuilder.buildPartial(); + } + + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_HandshakerResult_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_HandshakerResult_fieldAccessorTable + .ensureFieldAccessorsInitialized( + io.grpc.alts.internal.Handshaker.HandshakerResult.class, io.grpc.alts.internal.Handshaker.HandshakerResult.Builder.class); + } + + public static final int APPLICATION_PROTOCOL_FIELD_NUMBER = 1; + private volatile java.lang.Object applicationProtocol_; + /** + *
+     * The application protocol negotiated for this connection.
+     * 
+ * + * string application_protocol = 1; + */ + public java.lang.String getApplicationProtocol() { + java.lang.Object ref = applicationProtocol_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + applicationProtocol_ = s; + return s; + } + } + /** + *
+     * The application protocol negotiated for this connection.
+     * 
+ * + * string application_protocol = 1; + */ + public com.google.protobuf.ByteString + getApplicationProtocolBytes() { + java.lang.Object ref = applicationProtocol_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (java.lang.String) ref); + applicationProtocol_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int RECORD_PROTOCOL_FIELD_NUMBER = 2; + private volatile java.lang.Object recordProtocol_; + /** + *
+     * The record protocol negotiated for this connection.
+     * 
+ * + * string record_protocol = 2; + */ + public java.lang.String getRecordProtocol() { + java.lang.Object ref = recordProtocol_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + recordProtocol_ = s; + return s; + } + } + /** + *
+     * The record protocol negotiated for this connection.
+     * 
+ * + * string record_protocol = 2; + */ + public com.google.protobuf.ByteString + getRecordProtocolBytes() { + java.lang.Object ref = recordProtocol_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (java.lang.String) ref); + recordProtocol_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int KEY_DATA_FIELD_NUMBER = 3; + private com.google.protobuf.ByteString keyData_; + /** + *
+     * Cryptographic key data. The key data may be more than the key length
+     * required for the record protocol, thus the client of the handshaker
+     * service needs to truncate the key data into the right key length.
+     * 
+ * + * bytes key_data = 3; + */ + public com.google.protobuf.ByteString getKeyData() { + return keyData_; + } + + public static final int PEER_IDENTITY_FIELD_NUMBER = 4; + private io.grpc.alts.internal.Handshaker.Identity peerIdentity_; + /** + *
+     * The authenticated identity of the peer.
+     * 
+ * + * .grpc.gcp.Identity peer_identity = 4; + */ + public boolean hasPeerIdentity() { + return peerIdentity_ != null; + } + /** + *
+     * The authenticated identity of the peer.
+     * 
+ * + * .grpc.gcp.Identity peer_identity = 4; + */ + public io.grpc.alts.internal.Handshaker.Identity getPeerIdentity() { + return peerIdentity_ == null ? io.grpc.alts.internal.Handshaker.Identity.getDefaultInstance() : peerIdentity_; + } + /** + *
+     * The authenticated identity of the peer.
+     * 
+ * + * .grpc.gcp.Identity peer_identity = 4; + */ + public io.grpc.alts.internal.Handshaker.IdentityOrBuilder getPeerIdentityOrBuilder() { + return getPeerIdentity(); + } + + public static final int LOCAL_IDENTITY_FIELD_NUMBER = 5; + private io.grpc.alts.internal.Handshaker.Identity localIdentity_; + /** + *
+     * The local identity used in the handshake.
+     * 
+ * + * .grpc.gcp.Identity local_identity = 5; + */ + public boolean hasLocalIdentity() { + return localIdentity_ != null; + } + /** + *
+     * The local identity used in the handshake.
+     * 
+ * + * .grpc.gcp.Identity local_identity = 5; + */ + public io.grpc.alts.internal.Handshaker.Identity getLocalIdentity() { + return localIdentity_ == null ? io.grpc.alts.internal.Handshaker.Identity.getDefaultInstance() : localIdentity_; + } + /** + *
+     * The local identity used in the handshake.
+     * 
+ * + * .grpc.gcp.Identity local_identity = 5; + */ + public io.grpc.alts.internal.Handshaker.IdentityOrBuilder getLocalIdentityOrBuilder() { + return getLocalIdentity(); + } + + public static final int KEEP_CHANNEL_OPEN_FIELD_NUMBER = 6; + private boolean keepChannelOpen_; + /** + *
+     * Indicate whether the handshaker service client should keep the channel
+     * between the handshaker service open, e.g., in order to handle
+     * post-handshake messages in the future.
+     * 
+ * + * bool keep_channel_open = 6; + */ + public boolean getKeepChannelOpen() { + return keepChannelOpen_; + } + + public static final int PEER_RPC_VERSIONS_FIELD_NUMBER = 7; + private io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions peerRpcVersions_; + /** + *
+     * The RPC protocol versions supported by the peer.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions peer_rpc_versions = 7; + */ + public boolean hasPeerRpcVersions() { + return peerRpcVersions_ != null; + } + /** + *
+     * The RPC protocol versions supported by the peer.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions peer_rpc_versions = 7; + */ + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions getPeerRpcVersions() { + return peerRpcVersions_ == null ? io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.getDefaultInstance() : peerRpcVersions_; + } + /** + *
+     * The RPC protocol versions supported by the peer.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions peer_rpc_versions = 7; + */ + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersionsOrBuilder getPeerRpcVersionsOrBuilder() { + return getPeerRpcVersions(); + } + + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + if (!getApplicationProtocolBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 1, applicationProtocol_); + } + if (!getRecordProtocolBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 2, recordProtocol_); + } + if (!keyData_.isEmpty()) { + output.writeBytes(3, keyData_); + } + if (peerIdentity_ != null) { + output.writeMessage(4, getPeerIdentity()); + } + if (localIdentity_ != null) { + output.writeMessage(5, getLocalIdentity()); + } + if (keepChannelOpen_ != false) { + output.writeBool(6, keepChannelOpen_); + } + if (peerRpcVersions_ != null) { + output.writeMessage(7, getPeerRpcVersions()); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (!getApplicationProtocolBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, applicationProtocol_); + } + if (!getRecordProtocolBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, recordProtocol_); + } + if (!keyData_.isEmpty()) { + size += com.google.protobuf.CodedOutputStream + .computeBytesSize(3, keyData_); + } + if (peerIdentity_ != null) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(4, getPeerIdentity()); + } + if (localIdentity_ != null) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(5, getLocalIdentity()); + } + if (keepChannelOpen_ != false) { + size += com.google.protobuf.CodedOutputStream + .computeBoolSize(6, keepChannelOpen_); + } + if (peerRpcVersions_ != null) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(7, getPeerRpcVersions()); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof io.grpc.alts.internal.Handshaker.HandshakerResult)) { + return super.equals(obj); + } + io.grpc.alts.internal.Handshaker.HandshakerResult other = (io.grpc.alts.internal.Handshaker.HandshakerResult) obj; + + boolean result = true; + result = result && getApplicationProtocol() + .equals(other.getApplicationProtocol()); + result = result && getRecordProtocol() + .equals(other.getRecordProtocol()); + result = result && getKeyData() + .equals(other.getKeyData()); + result = result && (hasPeerIdentity() == other.hasPeerIdentity()); + if (hasPeerIdentity()) { + result = result && getPeerIdentity() + .equals(other.getPeerIdentity()); + } + result = result && (hasLocalIdentity() == other.hasLocalIdentity()); + if (hasLocalIdentity()) { + result = result && getLocalIdentity() + .equals(other.getLocalIdentity()); + } + result = result && (getKeepChannelOpen() + == other.getKeepChannelOpen()); + result = result && (hasPeerRpcVersions() == other.hasPeerRpcVersions()); + if (hasPeerRpcVersions()) { + result = result && getPeerRpcVersions() + .equals(other.getPeerRpcVersions()); + } + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + hash = (37 * hash) + APPLICATION_PROTOCOL_FIELD_NUMBER; + hash = (53 * hash) + getApplicationProtocol().hashCode(); + hash = (37 * hash) + RECORD_PROTOCOL_FIELD_NUMBER; + hash = (53 * hash) + getRecordProtocol().hashCode(); + hash = (37 * hash) + KEY_DATA_FIELD_NUMBER; + hash = (53 * hash) + getKeyData().hashCode(); + if (hasPeerIdentity()) { + hash = (37 * hash) + PEER_IDENTITY_FIELD_NUMBER; + hash = (53 * hash) + getPeerIdentity().hashCode(); + } + if (hasLocalIdentity()) { + hash = (37 * hash) + LOCAL_IDENTITY_FIELD_NUMBER; + hash = (53 * hash) + getLocalIdentity().hashCode(); + } + hash = (37 * hash) + KEEP_CHANNEL_OPEN_FIELD_NUMBER; + hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( + getKeepChannelOpen()); + if (hasPeerRpcVersions()) { + hash = (37 * hash) + PEER_RPC_VERSIONS_FIELD_NUMBER; + hash = (53 * hash) + getPeerRpcVersions().hashCode(); + } + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static io.grpc.alts.internal.Handshaker.HandshakerResult parseFrom( + java.nio.ByteBuffer data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Handshaker.HandshakerResult parseFrom( + java.nio.ByteBuffer data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.HandshakerResult parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Handshaker.HandshakerResult parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.HandshakerResult parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Handshaker.HandshakerResult parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.HandshakerResult parseFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Handshaker.HandshakerResult parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.HandshakerResult parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Handshaker.HandshakerResult parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.HandshakerResult parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Handshaker.HandshakerResult parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + public static Builder newBuilder(io.grpc.alts.internal.Handshaker.HandshakerResult prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { + return this == DEFAULT_INSTANCE + ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + * Protobuf type {@code grpc.gcp.HandshakerResult} + */ + public static final class Builder extends + com.google.protobuf.GeneratedMessageV3.Builder implements + // @@protoc_insertion_point(builder_implements:grpc.gcp.HandshakerResult) + io.grpc.alts.internal.Handshaker.HandshakerResultOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_HandshakerResult_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_HandshakerResult_fieldAccessorTable + .ensureFieldAccessorsInitialized( + io.grpc.alts.internal.Handshaker.HandshakerResult.class, io.grpc.alts.internal.Handshaker.HandshakerResult.Builder.class); + } + + // Construct using io.grpc.alts.internal.Handshaker.HandshakerResult.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder( + com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3 + .alwaysUseFieldBuilders) { + } + } + public Builder clear() { + super.clear(); + applicationProtocol_ = ""; + + recordProtocol_ = ""; + + keyData_ = com.google.protobuf.ByteString.EMPTY; + + if (peerIdentityBuilder_ == null) { + peerIdentity_ = null; + } else { + peerIdentity_ = null; + peerIdentityBuilder_ = null; + } + if (localIdentityBuilder_ == null) { + localIdentity_ = null; + } else { + localIdentity_ = null; + localIdentityBuilder_ = null; + } + keepChannelOpen_ = false; + + if (peerRpcVersionsBuilder_ == null) { + peerRpcVersions_ = null; + } else { + peerRpcVersions_ = null; + peerRpcVersionsBuilder_ = null; + } + return this; + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_HandshakerResult_descriptor; + } + + public io.grpc.alts.internal.Handshaker.HandshakerResult getDefaultInstanceForType() { + return io.grpc.alts.internal.Handshaker.HandshakerResult.getDefaultInstance(); + } + + public io.grpc.alts.internal.Handshaker.HandshakerResult build() { + io.grpc.alts.internal.Handshaker.HandshakerResult result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public io.grpc.alts.internal.Handshaker.HandshakerResult buildPartial() { + io.grpc.alts.internal.Handshaker.HandshakerResult result = new io.grpc.alts.internal.Handshaker.HandshakerResult(this); + result.applicationProtocol_ = applicationProtocol_; + result.recordProtocol_ = recordProtocol_; + result.keyData_ = keyData_; + if (peerIdentityBuilder_ == null) { + result.peerIdentity_ = peerIdentity_; + } else { + result.peerIdentity_ = peerIdentityBuilder_.build(); + } + if (localIdentityBuilder_ == null) { + result.localIdentity_ = localIdentity_; + } else { + result.localIdentity_ = localIdentityBuilder_.build(); + } + result.keepChannelOpen_ = keepChannelOpen_; + if (peerRpcVersionsBuilder_ == null) { + result.peerRpcVersions_ = peerRpcVersions_; + } else { + result.peerRpcVersions_ = peerRpcVersionsBuilder_.build(); + } + onBuilt(); + return result; + } + + public Builder clone() { + return (Builder) super.clone(); + } + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, + java.lang.Object value) { + return (Builder) super.setField(field, value); + } + public Builder clearField( + com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); + } + public Builder clearOneof( + com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); + } + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); + } + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); + } + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof io.grpc.alts.internal.Handshaker.HandshakerResult) { + return mergeFrom((io.grpc.alts.internal.Handshaker.HandshakerResult)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(io.grpc.alts.internal.Handshaker.HandshakerResult other) { + if (other == io.grpc.alts.internal.Handshaker.HandshakerResult.getDefaultInstance()) return this; + if (!other.getApplicationProtocol().isEmpty()) { + applicationProtocol_ = other.applicationProtocol_; + onChanged(); + } + if (!other.getRecordProtocol().isEmpty()) { + recordProtocol_ = other.recordProtocol_; + onChanged(); + } + if (other.getKeyData() != com.google.protobuf.ByteString.EMPTY) { + setKeyData(other.getKeyData()); + } + if (other.hasPeerIdentity()) { + mergePeerIdentity(other.getPeerIdentity()); + } + if (other.hasLocalIdentity()) { + mergeLocalIdentity(other.getLocalIdentity()); + } + if (other.getKeepChannelOpen() != false) { + setKeepChannelOpen(other.getKeepChannelOpen()); + } + if (other.hasPeerRpcVersions()) { + mergePeerRpcVersions(other.getPeerRpcVersions()); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + io.grpc.alts.internal.Handshaker.HandshakerResult parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (io.grpc.alts.internal.Handshaker.HandshakerResult) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + private java.lang.Object applicationProtocol_ = ""; + /** + *
+       * The application protocol negotiated for this connection.
+       * 
+ * + * string application_protocol = 1; + */ + public java.lang.String getApplicationProtocol() { + java.lang.Object ref = applicationProtocol_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + applicationProtocol_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + /** + *
+       * The application protocol negotiated for this connection.
+       * 
+ * + * string application_protocol = 1; + */ + public com.google.protobuf.ByteString + getApplicationProtocolBytes() { + java.lang.Object ref = applicationProtocol_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (java.lang.String) ref); + applicationProtocol_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + /** + *
+       * The application protocol negotiated for this connection.
+       * 
+ * + * string application_protocol = 1; + */ + public Builder setApplicationProtocol( + java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + + applicationProtocol_ = value; + onChanged(); + return this; + } + /** + *
+       * The application protocol negotiated for this connection.
+       * 
+ * + * string application_protocol = 1; + */ + public Builder clearApplicationProtocol() { + + applicationProtocol_ = getDefaultInstance().getApplicationProtocol(); + onChanged(); + return this; + } + /** + *
+       * The application protocol negotiated for this connection.
+       * 
+ * + * string application_protocol = 1; + */ + public Builder setApplicationProtocolBytes( + com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + + applicationProtocol_ = value; + onChanged(); + return this; + } + + private java.lang.Object recordProtocol_ = ""; + /** + *
+       * The record protocol negotiated for this connection.
+       * 
+ * + * string record_protocol = 2; + */ + public java.lang.String getRecordProtocol() { + java.lang.Object ref = recordProtocol_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + recordProtocol_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + /** + *
+       * The record protocol negotiated for this connection.
+       * 
+ * + * string record_protocol = 2; + */ + public com.google.protobuf.ByteString + getRecordProtocolBytes() { + java.lang.Object ref = recordProtocol_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (java.lang.String) ref); + recordProtocol_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + /** + *
+       * The record protocol negotiated for this connection.
+       * 
+ * + * string record_protocol = 2; + */ + public Builder setRecordProtocol( + java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + + recordProtocol_ = value; + onChanged(); + return this; + } + /** + *
+       * The record protocol negotiated for this connection.
+       * 
+ * + * string record_protocol = 2; + */ + public Builder clearRecordProtocol() { + + recordProtocol_ = getDefaultInstance().getRecordProtocol(); + onChanged(); + return this; + } + /** + *
+       * The record protocol negotiated for this connection.
+       * 
+ * + * string record_protocol = 2; + */ + public Builder setRecordProtocolBytes( + com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + + recordProtocol_ = value; + onChanged(); + return this; + } + + private com.google.protobuf.ByteString keyData_ = com.google.protobuf.ByteString.EMPTY; + /** + *
+       * Cryptographic key data. The key data may be more than the key length
+       * required for the record protocol, thus the client of the handshaker
+       * service needs to truncate the key data into the right key length.
+       * 
+ * + * bytes key_data = 3; + */ + public com.google.protobuf.ByteString getKeyData() { + return keyData_; + } + /** + *
+       * Cryptographic key data. The key data may be more than the key length
+       * required for the record protocol, thus the client of the handshaker
+       * service needs to truncate the key data into the right key length.
+       * 
+ * + * bytes key_data = 3; + */ + public Builder setKeyData(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + + keyData_ = value; + onChanged(); + return this; + } + /** + *
+       * Cryptographic key data. The key data may be more than the key length
+       * required for the record protocol, thus the client of the handshaker
+       * service needs to truncate the key data into the right key length.
+       * 
+ * + * bytes key_data = 3; + */ + public Builder clearKeyData() { + + keyData_ = getDefaultInstance().getKeyData(); + onChanged(); + return this; + } + + private io.grpc.alts.internal.Handshaker.Identity peerIdentity_ = null; + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.Identity, io.grpc.alts.internal.Handshaker.Identity.Builder, io.grpc.alts.internal.Handshaker.IdentityOrBuilder> peerIdentityBuilder_; + /** + *
+       * The authenticated identity of the peer.
+       * 
+ * + * .grpc.gcp.Identity peer_identity = 4; + */ + public boolean hasPeerIdentity() { + return peerIdentityBuilder_ != null || peerIdentity_ != null; + } + /** + *
+       * The authenticated identity of the peer.
+       * 
+ * + * .grpc.gcp.Identity peer_identity = 4; + */ + public io.grpc.alts.internal.Handshaker.Identity getPeerIdentity() { + if (peerIdentityBuilder_ == null) { + return peerIdentity_ == null ? io.grpc.alts.internal.Handshaker.Identity.getDefaultInstance() : peerIdentity_; + } else { + return peerIdentityBuilder_.getMessage(); + } + } + /** + *
+       * The authenticated identity of the peer.
+       * 
+ * + * .grpc.gcp.Identity peer_identity = 4; + */ + public Builder setPeerIdentity(io.grpc.alts.internal.Handshaker.Identity value) { + if (peerIdentityBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + peerIdentity_ = value; + onChanged(); + } else { + peerIdentityBuilder_.setMessage(value); + } + + return this; + } + /** + *
+       * The authenticated identity of the peer.
+       * 
+ * + * .grpc.gcp.Identity peer_identity = 4; + */ + public Builder setPeerIdentity( + io.grpc.alts.internal.Handshaker.Identity.Builder builderForValue) { + if (peerIdentityBuilder_ == null) { + peerIdentity_ = builderForValue.build(); + onChanged(); + } else { + peerIdentityBuilder_.setMessage(builderForValue.build()); + } + + return this; + } + /** + *
+       * The authenticated identity of the peer.
+       * 
+ * + * .grpc.gcp.Identity peer_identity = 4; + */ + public Builder mergePeerIdentity(io.grpc.alts.internal.Handshaker.Identity value) { + if (peerIdentityBuilder_ == null) { + if (peerIdentity_ != null) { + peerIdentity_ = + io.grpc.alts.internal.Handshaker.Identity.newBuilder(peerIdentity_).mergeFrom(value).buildPartial(); + } else { + peerIdentity_ = value; + } + onChanged(); + } else { + peerIdentityBuilder_.mergeFrom(value); + } + + return this; + } + /** + *
+       * The authenticated identity of the peer.
+       * 
+ * + * .grpc.gcp.Identity peer_identity = 4; + */ + public Builder clearPeerIdentity() { + if (peerIdentityBuilder_ == null) { + peerIdentity_ = null; + onChanged(); + } else { + peerIdentity_ = null; + peerIdentityBuilder_ = null; + } + + return this; + } + /** + *
+       * The authenticated identity of the peer.
+       * 
+ * + * .grpc.gcp.Identity peer_identity = 4; + */ + public io.grpc.alts.internal.Handshaker.Identity.Builder getPeerIdentityBuilder() { + + onChanged(); + return getPeerIdentityFieldBuilder().getBuilder(); + } + /** + *
+       * The authenticated identity of the peer.
+       * 
+ * + * .grpc.gcp.Identity peer_identity = 4; + */ + public io.grpc.alts.internal.Handshaker.IdentityOrBuilder getPeerIdentityOrBuilder() { + if (peerIdentityBuilder_ != null) { + return peerIdentityBuilder_.getMessageOrBuilder(); + } else { + return peerIdentity_ == null ? + io.grpc.alts.internal.Handshaker.Identity.getDefaultInstance() : peerIdentity_; + } + } + /** + *
+       * The authenticated identity of the peer.
+       * 
+ * + * .grpc.gcp.Identity peer_identity = 4; + */ + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.Identity, io.grpc.alts.internal.Handshaker.Identity.Builder, io.grpc.alts.internal.Handshaker.IdentityOrBuilder> + getPeerIdentityFieldBuilder() { + if (peerIdentityBuilder_ == null) { + peerIdentityBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.Identity, io.grpc.alts.internal.Handshaker.Identity.Builder, io.grpc.alts.internal.Handshaker.IdentityOrBuilder>( + getPeerIdentity(), + getParentForChildren(), + isClean()); + peerIdentity_ = null; + } + return peerIdentityBuilder_; + } + + private io.grpc.alts.internal.Handshaker.Identity localIdentity_ = null; + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.Identity, io.grpc.alts.internal.Handshaker.Identity.Builder, io.grpc.alts.internal.Handshaker.IdentityOrBuilder> localIdentityBuilder_; + /** + *
+       * The local identity used in the handshake.
+       * 
+ * + * .grpc.gcp.Identity local_identity = 5; + */ + public boolean hasLocalIdentity() { + return localIdentityBuilder_ != null || localIdentity_ != null; + } + /** + *
+       * The local identity used in the handshake.
+       * 
+ * + * .grpc.gcp.Identity local_identity = 5; + */ + public io.grpc.alts.internal.Handshaker.Identity getLocalIdentity() { + if (localIdentityBuilder_ == null) { + return localIdentity_ == null ? io.grpc.alts.internal.Handshaker.Identity.getDefaultInstance() : localIdentity_; + } else { + return localIdentityBuilder_.getMessage(); + } + } + /** + *
+       * The local identity used in the handshake.
+       * 
+ * + * .grpc.gcp.Identity local_identity = 5; + */ + public Builder setLocalIdentity(io.grpc.alts.internal.Handshaker.Identity value) { + if (localIdentityBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + localIdentity_ = value; + onChanged(); + } else { + localIdentityBuilder_.setMessage(value); + } + + return this; + } + /** + *
+       * The local identity used in the handshake.
+       * 
+ * + * .grpc.gcp.Identity local_identity = 5; + */ + public Builder setLocalIdentity( + io.grpc.alts.internal.Handshaker.Identity.Builder builderForValue) { + if (localIdentityBuilder_ == null) { + localIdentity_ = builderForValue.build(); + onChanged(); + } else { + localIdentityBuilder_.setMessage(builderForValue.build()); + } + + return this; + } + /** + *
+       * The local identity used in the handshake.
+       * 
+ * + * .grpc.gcp.Identity local_identity = 5; + */ + public Builder mergeLocalIdentity(io.grpc.alts.internal.Handshaker.Identity value) { + if (localIdentityBuilder_ == null) { + if (localIdentity_ != null) { + localIdentity_ = + io.grpc.alts.internal.Handshaker.Identity.newBuilder(localIdentity_).mergeFrom(value).buildPartial(); + } else { + localIdentity_ = value; + } + onChanged(); + } else { + localIdentityBuilder_.mergeFrom(value); + } + + return this; + } + /** + *
+       * The local identity used in the handshake.
+       * 
+ * + * .grpc.gcp.Identity local_identity = 5; + */ + public Builder clearLocalIdentity() { + if (localIdentityBuilder_ == null) { + localIdentity_ = null; + onChanged(); + } else { + localIdentity_ = null; + localIdentityBuilder_ = null; + } + + return this; + } + /** + *
+       * The local identity used in the handshake.
+       * 
+ * + * .grpc.gcp.Identity local_identity = 5; + */ + public io.grpc.alts.internal.Handshaker.Identity.Builder getLocalIdentityBuilder() { + + onChanged(); + return getLocalIdentityFieldBuilder().getBuilder(); + } + /** + *
+       * The local identity used in the handshake.
+       * 
+ * + * .grpc.gcp.Identity local_identity = 5; + */ + public io.grpc.alts.internal.Handshaker.IdentityOrBuilder getLocalIdentityOrBuilder() { + if (localIdentityBuilder_ != null) { + return localIdentityBuilder_.getMessageOrBuilder(); + } else { + return localIdentity_ == null ? + io.grpc.alts.internal.Handshaker.Identity.getDefaultInstance() : localIdentity_; + } + } + /** + *
+       * The local identity used in the handshake.
+       * 
+ * + * .grpc.gcp.Identity local_identity = 5; + */ + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.Identity, io.grpc.alts.internal.Handshaker.Identity.Builder, io.grpc.alts.internal.Handshaker.IdentityOrBuilder> + getLocalIdentityFieldBuilder() { + if (localIdentityBuilder_ == null) { + localIdentityBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.Identity, io.grpc.alts.internal.Handshaker.Identity.Builder, io.grpc.alts.internal.Handshaker.IdentityOrBuilder>( + getLocalIdentity(), + getParentForChildren(), + isClean()); + localIdentity_ = null; + } + return localIdentityBuilder_; + } + + private boolean keepChannelOpen_ ; + /** + *
+       * Indicate whether the handshaker service client should keep the channel
+       * between the handshaker service open, e.g., in order to handle
+       * post-handshake messages in the future.
+       * 
+ * + * bool keep_channel_open = 6; + */ + public boolean getKeepChannelOpen() { + return keepChannelOpen_; + } + /** + *
+       * Indicate whether the handshaker service client should keep the channel
+       * between the handshaker service open, e.g., in order to handle
+       * post-handshake messages in the future.
+       * 
+ * + * bool keep_channel_open = 6; + */ + public Builder setKeepChannelOpen(boolean value) { + + keepChannelOpen_ = value; + onChanged(); + return this; + } + /** + *
+       * Indicate whether the handshaker service client should keep the channel
+       * between the handshaker service open, e.g., in order to handle
+       * post-handshake messages in the future.
+       * 
+ * + * bool keep_channel_open = 6; + */ + public Builder clearKeepChannelOpen() { + + keepChannelOpen_ = false; + onChanged(); + return this; + } + + private io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions peerRpcVersions_ = null; + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Builder, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersionsOrBuilder> peerRpcVersionsBuilder_; + /** + *
+       * The RPC protocol versions supported by the peer.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions peer_rpc_versions = 7; + */ + public boolean hasPeerRpcVersions() { + return peerRpcVersionsBuilder_ != null || peerRpcVersions_ != null; + } + /** + *
+       * The RPC protocol versions supported by the peer.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions peer_rpc_versions = 7; + */ + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions getPeerRpcVersions() { + if (peerRpcVersionsBuilder_ == null) { + return peerRpcVersions_ == null ? io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.getDefaultInstance() : peerRpcVersions_; + } else { + return peerRpcVersionsBuilder_.getMessage(); + } + } + /** + *
+       * The RPC protocol versions supported by the peer.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions peer_rpc_versions = 7; + */ + public Builder setPeerRpcVersions(io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions value) { + if (peerRpcVersionsBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + peerRpcVersions_ = value; + onChanged(); + } else { + peerRpcVersionsBuilder_.setMessage(value); + } + + return this; + } + /** + *
+       * The RPC protocol versions supported by the peer.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions peer_rpc_versions = 7; + */ + public Builder setPeerRpcVersions( + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Builder builderForValue) { + if (peerRpcVersionsBuilder_ == null) { + peerRpcVersions_ = builderForValue.build(); + onChanged(); + } else { + peerRpcVersionsBuilder_.setMessage(builderForValue.build()); + } + + return this; + } + /** + *
+       * The RPC protocol versions supported by the peer.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions peer_rpc_versions = 7; + */ + public Builder mergePeerRpcVersions(io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions value) { + if (peerRpcVersionsBuilder_ == null) { + if (peerRpcVersions_ != null) { + peerRpcVersions_ = + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.newBuilder(peerRpcVersions_).mergeFrom(value).buildPartial(); + } else { + peerRpcVersions_ = value; + } + onChanged(); + } else { + peerRpcVersionsBuilder_.mergeFrom(value); + } + + return this; + } + /** + *
+       * The RPC protocol versions supported by the peer.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions peer_rpc_versions = 7; + */ + public Builder clearPeerRpcVersions() { + if (peerRpcVersionsBuilder_ == null) { + peerRpcVersions_ = null; + onChanged(); + } else { + peerRpcVersions_ = null; + peerRpcVersionsBuilder_ = null; + } + + return this; + } + /** + *
+       * The RPC protocol versions supported by the peer.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions peer_rpc_versions = 7; + */ + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Builder getPeerRpcVersionsBuilder() { + + onChanged(); + return getPeerRpcVersionsFieldBuilder().getBuilder(); + } + /** + *
+       * The RPC protocol versions supported by the peer.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions peer_rpc_versions = 7; + */ + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersionsOrBuilder getPeerRpcVersionsOrBuilder() { + if (peerRpcVersionsBuilder_ != null) { + return peerRpcVersionsBuilder_.getMessageOrBuilder(); + } else { + return peerRpcVersions_ == null ? + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.getDefaultInstance() : peerRpcVersions_; + } + } + /** + *
+       * The RPC protocol versions supported by the peer.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions peer_rpc_versions = 7; + */ + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Builder, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersionsOrBuilder> + getPeerRpcVersionsFieldBuilder() { + if (peerRpcVersionsBuilder_ == null) { + peerRpcVersionsBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Builder, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersionsOrBuilder>( + getPeerRpcVersions(), + getParentForChildren(), + isClean()); + peerRpcVersions_ = null; + } + return peerRpcVersionsBuilder_; + } + public final Builder setUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); + } + + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + + // @@protoc_insertion_point(builder_scope:grpc.gcp.HandshakerResult) + } + + // @@protoc_insertion_point(class_scope:grpc.gcp.HandshakerResult) + private static final io.grpc.alts.internal.Handshaker.HandshakerResult DEFAULT_INSTANCE; + static { + DEFAULT_INSTANCE = new io.grpc.alts.internal.Handshaker.HandshakerResult(); + } + + public static io.grpc.alts.internal.Handshaker.HandshakerResult getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + private static final com.google.protobuf.Parser + PARSER = new com.google.protobuf.AbstractParser() { + public HandshakerResult parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new HandshakerResult(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public io.grpc.alts.internal.Handshaker.HandshakerResult getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } + + } + + public interface HandshakerStatusOrBuilder extends + // @@protoc_insertion_point(interface_extends:grpc.gcp.HandshakerStatus) + com.google.protobuf.MessageOrBuilder { + + /** + *
+     * The status code. This could be the gRPC status code.
+     * 
+ * + * uint32 code = 1; + */ + int getCode(); + + /** + *
+     * The status details.
+     * 
+ * + * string details = 2; + */ + java.lang.String getDetails(); + /** + *
+     * The status details.
+     * 
+ * + * string details = 2; + */ + com.google.protobuf.ByteString + getDetailsBytes(); + } + /** + * Protobuf type {@code grpc.gcp.HandshakerStatus} + */ + public static final class HandshakerStatus extends + com.google.protobuf.GeneratedMessageV3 implements + // @@protoc_insertion_point(message_implements:grpc.gcp.HandshakerStatus) + HandshakerStatusOrBuilder { + private static final long serialVersionUID = 0L; + // Use HandshakerStatus.newBuilder() to construct. + private HandshakerStatus(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + private HandshakerStatus() { + code_ = 0; + details_ = ""; + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return this.unknownFields; + } + private HandshakerStatus( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownFieldProto3( + input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 8: { + + code_ = input.readUInt32(); + break; + } + case 18: { + java.lang.String s = input.readStringRequireUtf8(); + + details_ = s; + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_HandshakerStatus_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_HandshakerStatus_fieldAccessorTable + .ensureFieldAccessorsInitialized( + io.grpc.alts.internal.Handshaker.HandshakerStatus.class, io.grpc.alts.internal.Handshaker.HandshakerStatus.Builder.class); + } + + public static final int CODE_FIELD_NUMBER = 1; + private int code_; + /** + *
+     * The status code. This could be the gRPC status code.
+     * 
+ * + * uint32 code = 1; + */ + public int getCode() { + return code_; + } + + public static final int DETAILS_FIELD_NUMBER = 2; + private volatile java.lang.Object details_; + /** + *
+     * The status details.
+     * 
+ * + * string details = 2; + */ + public java.lang.String getDetails() { + java.lang.Object ref = details_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + details_ = s; + return s; + } + } + /** + *
+     * The status details.
+     * 
+ * + * string details = 2; + */ + public com.google.protobuf.ByteString + getDetailsBytes() { + java.lang.Object ref = details_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (java.lang.String) ref); + details_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + if (code_ != 0) { + output.writeUInt32(1, code_); + } + if (!getDetailsBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 2, details_); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (code_ != 0) { + size += com.google.protobuf.CodedOutputStream + .computeUInt32Size(1, code_); + } + if (!getDetailsBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, details_); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof io.grpc.alts.internal.Handshaker.HandshakerStatus)) { + return super.equals(obj); + } + io.grpc.alts.internal.Handshaker.HandshakerStatus other = (io.grpc.alts.internal.Handshaker.HandshakerStatus) obj; + + boolean result = true; + result = result && (getCode() + == other.getCode()); + result = result && getDetails() + .equals(other.getDetails()); + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + hash = (37 * hash) + CODE_FIELD_NUMBER; + hash = (53 * hash) + getCode(); + hash = (37 * hash) + DETAILS_FIELD_NUMBER; + hash = (53 * hash) + getDetails().hashCode(); + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static io.grpc.alts.internal.Handshaker.HandshakerStatus parseFrom( + java.nio.ByteBuffer data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Handshaker.HandshakerStatus parseFrom( + java.nio.ByteBuffer data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.HandshakerStatus parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Handshaker.HandshakerStatus parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.HandshakerStatus parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Handshaker.HandshakerStatus parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.HandshakerStatus parseFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Handshaker.HandshakerStatus parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.HandshakerStatus parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Handshaker.HandshakerStatus parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.HandshakerStatus parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Handshaker.HandshakerStatus parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + public static Builder newBuilder(io.grpc.alts.internal.Handshaker.HandshakerStatus prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { + return this == DEFAULT_INSTANCE + ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + * Protobuf type {@code grpc.gcp.HandshakerStatus} + */ + public static final class Builder extends + com.google.protobuf.GeneratedMessageV3.Builder implements + // @@protoc_insertion_point(builder_implements:grpc.gcp.HandshakerStatus) + io.grpc.alts.internal.Handshaker.HandshakerStatusOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_HandshakerStatus_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_HandshakerStatus_fieldAccessorTable + .ensureFieldAccessorsInitialized( + io.grpc.alts.internal.Handshaker.HandshakerStatus.class, io.grpc.alts.internal.Handshaker.HandshakerStatus.Builder.class); + } + + // Construct using io.grpc.alts.internal.Handshaker.HandshakerStatus.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder( + com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3 + .alwaysUseFieldBuilders) { + } + } + public Builder clear() { + super.clear(); + code_ = 0; + + details_ = ""; + + return this; + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_HandshakerStatus_descriptor; + } + + public io.grpc.alts.internal.Handshaker.HandshakerStatus getDefaultInstanceForType() { + return io.grpc.alts.internal.Handshaker.HandshakerStatus.getDefaultInstance(); + } + + public io.grpc.alts.internal.Handshaker.HandshakerStatus build() { + io.grpc.alts.internal.Handshaker.HandshakerStatus result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public io.grpc.alts.internal.Handshaker.HandshakerStatus buildPartial() { + io.grpc.alts.internal.Handshaker.HandshakerStatus result = new io.grpc.alts.internal.Handshaker.HandshakerStatus(this); + result.code_ = code_; + result.details_ = details_; + onBuilt(); + return result; + } + + public Builder clone() { + return (Builder) super.clone(); + } + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, + java.lang.Object value) { + return (Builder) super.setField(field, value); + } + public Builder clearField( + com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); + } + public Builder clearOneof( + com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); + } + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); + } + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); + } + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof io.grpc.alts.internal.Handshaker.HandshakerStatus) { + return mergeFrom((io.grpc.alts.internal.Handshaker.HandshakerStatus)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(io.grpc.alts.internal.Handshaker.HandshakerStatus other) { + if (other == io.grpc.alts.internal.Handshaker.HandshakerStatus.getDefaultInstance()) return this; + if (other.getCode() != 0) { + setCode(other.getCode()); + } + if (!other.getDetails().isEmpty()) { + details_ = other.details_; + onChanged(); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + io.grpc.alts.internal.Handshaker.HandshakerStatus parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (io.grpc.alts.internal.Handshaker.HandshakerStatus) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + private int code_ ; + /** + *
+       * The status code. This could be the gRPC status code.
+       * 
+ * + * uint32 code = 1; + */ + public int getCode() { + return code_; + } + /** + *
+       * The status code. This could be the gRPC status code.
+       * 
+ * + * uint32 code = 1; + */ + public Builder setCode(int value) { + + code_ = value; + onChanged(); + return this; + } + /** + *
+       * The status code. This could be the gRPC status code.
+       * 
+ * + * uint32 code = 1; + */ + public Builder clearCode() { + + code_ = 0; + onChanged(); + return this; + } + + private java.lang.Object details_ = ""; + /** + *
+       * The status details.
+       * 
+ * + * string details = 2; + */ + public java.lang.String getDetails() { + java.lang.Object ref = details_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = + (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + details_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + /** + *
+       * The status details.
+       * 
+ * + * string details = 2; + */ + public com.google.protobuf.ByteString + getDetailsBytes() { + java.lang.Object ref = details_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8( + (java.lang.String) ref); + details_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + /** + *
+       * The status details.
+       * 
+ * + * string details = 2; + */ + public Builder setDetails( + java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + + details_ = value; + onChanged(); + return this; + } + /** + *
+       * The status details.
+       * 
+ * + * string details = 2; + */ + public Builder clearDetails() { + + details_ = getDefaultInstance().getDetails(); + onChanged(); + return this; + } + /** + *
+       * The status details.
+       * 
+ * + * string details = 2; + */ + public Builder setDetailsBytes( + com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + + details_ = value; + onChanged(); + return this; + } + public final Builder setUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); + } + + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + + // @@protoc_insertion_point(builder_scope:grpc.gcp.HandshakerStatus) + } + + // @@protoc_insertion_point(class_scope:grpc.gcp.HandshakerStatus) + private static final io.grpc.alts.internal.Handshaker.HandshakerStatus DEFAULT_INSTANCE; + static { + DEFAULT_INSTANCE = new io.grpc.alts.internal.Handshaker.HandshakerStatus(); + } + + public static io.grpc.alts.internal.Handshaker.HandshakerStatus getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + private static final com.google.protobuf.Parser + PARSER = new com.google.protobuf.AbstractParser() { + public HandshakerStatus parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new HandshakerStatus(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public io.grpc.alts.internal.Handshaker.HandshakerStatus getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } + + } + + public interface HandshakerRespOrBuilder extends + // @@protoc_insertion_point(interface_extends:grpc.gcp.HandshakerResp) + com.google.protobuf.MessageOrBuilder { + + /** + *
+     * Frames to be given to the peer for the NextHandshakeMessageReq. May be
+     * empty if no out_frames have to be sent to the peer or if in_bytes in the
+     * HandshakerReq are incomplete. All the non-empty out frames must be sent to
+     * the peer even if the handshaker status is not OK as these frames may
+     * contain the alert frames.
+     * 
+ * + * bytes out_frames = 1; + */ + com.google.protobuf.ByteString getOutFrames(); + + /** + *
+     * Number of bytes in the in_bytes consumed by the handshaker. It is possible
+     * that part of in_bytes in HandshakerReq was unrelated to the handshake
+     * process.
+     * 
+ * + * uint32 bytes_consumed = 2; + */ + int getBytesConsumed(); + + /** + *
+     * This is set iff the handshake was successful. out_frames may still be set
+     * to frames that needs to be forwarded to the peer.
+     * 
+ * + * .grpc.gcp.HandshakerResult result = 3; + */ + boolean hasResult(); + /** + *
+     * This is set iff the handshake was successful. out_frames may still be set
+     * to frames that needs to be forwarded to the peer.
+     * 
+ * + * .grpc.gcp.HandshakerResult result = 3; + */ + io.grpc.alts.internal.Handshaker.HandshakerResult getResult(); + /** + *
+     * This is set iff the handshake was successful. out_frames may still be set
+     * to frames that needs to be forwarded to the peer.
+     * 
+ * + * .grpc.gcp.HandshakerResult result = 3; + */ + io.grpc.alts.internal.Handshaker.HandshakerResultOrBuilder getResultOrBuilder(); + + /** + *
+     * Status of the handshaker.
+     * 
+ * + * .grpc.gcp.HandshakerStatus status = 4; + */ + boolean hasStatus(); + /** + *
+     * Status of the handshaker.
+     * 
+ * + * .grpc.gcp.HandshakerStatus status = 4; + */ + io.grpc.alts.internal.Handshaker.HandshakerStatus getStatus(); + /** + *
+     * Status of the handshaker.
+     * 
+ * + * .grpc.gcp.HandshakerStatus status = 4; + */ + io.grpc.alts.internal.Handshaker.HandshakerStatusOrBuilder getStatusOrBuilder(); + } + /** + * Protobuf type {@code grpc.gcp.HandshakerResp} + */ + public static final class HandshakerResp extends + com.google.protobuf.GeneratedMessageV3 implements + // @@protoc_insertion_point(message_implements:grpc.gcp.HandshakerResp) + HandshakerRespOrBuilder { + private static final long serialVersionUID = 0L; + // Use HandshakerResp.newBuilder() to construct. + private HandshakerResp(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + private HandshakerResp() { + outFrames_ = com.google.protobuf.ByteString.EMPTY; + bytesConsumed_ = 0; + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return this.unknownFields; + } + private HandshakerResp( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownFieldProto3( + input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 10: { + + outFrames_ = input.readBytes(); + break; + } + case 16: { + + bytesConsumed_ = input.readUInt32(); + break; + } + case 26: { + io.grpc.alts.internal.Handshaker.HandshakerResult.Builder subBuilder = null; + if (result_ != null) { + subBuilder = result_.toBuilder(); + } + result_ = input.readMessage(io.grpc.alts.internal.Handshaker.HandshakerResult.parser(), extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(result_); + result_ = subBuilder.buildPartial(); + } + + break; + } + case 34: { + io.grpc.alts.internal.Handshaker.HandshakerStatus.Builder subBuilder = null; + if (status_ != null) { + subBuilder = status_.toBuilder(); + } + status_ = input.readMessage(io.grpc.alts.internal.Handshaker.HandshakerStatus.parser(), extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(status_); + status_ = subBuilder.buildPartial(); + } + + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_HandshakerResp_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_HandshakerResp_fieldAccessorTable + .ensureFieldAccessorsInitialized( + io.grpc.alts.internal.Handshaker.HandshakerResp.class, io.grpc.alts.internal.Handshaker.HandshakerResp.Builder.class); + } + + public static final int OUT_FRAMES_FIELD_NUMBER = 1; + private com.google.protobuf.ByteString outFrames_; + /** + *
+     * Frames to be given to the peer for the NextHandshakeMessageReq. May be
+     * empty if no out_frames have to be sent to the peer or if in_bytes in the
+     * HandshakerReq are incomplete. All the non-empty out frames must be sent to
+     * the peer even if the handshaker status is not OK as these frames may
+     * contain the alert frames.
+     * 
+ * + * bytes out_frames = 1; + */ + public com.google.protobuf.ByteString getOutFrames() { + return outFrames_; + } + + public static final int BYTES_CONSUMED_FIELD_NUMBER = 2; + private int bytesConsumed_; + /** + *
+     * Number of bytes in the in_bytes consumed by the handshaker. It is possible
+     * that part of in_bytes in HandshakerReq was unrelated to the handshake
+     * process.
+     * 
+ * + * uint32 bytes_consumed = 2; + */ + public int getBytesConsumed() { + return bytesConsumed_; + } + + public static final int RESULT_FIELD_NUMBER = 3; + private io.grpc.alts.internal.Handshaker.HandshakerResult result_; + /** + *
+     * This is set iff the handshake was successful. out_frames may still be set
+     * to frames that needs to be forwarded to the peer.
+     * 
+ * + * .grpc.gcp.HandshakerResult result = 3; + */ + public boolean hasResult() { + return result_ != null; + } + /** + *
+     * This is set iff the handshake was successful. out_frames may still be set
+     * to frames that needs to be forwarded to the peer.
+     * 
+ * + * .grpc.gcp.HandshakerResult result = 3; + */ + public io.grpc.alts.internal.Handshaker.HandshakerResult getResult() { + return result_ == null ? io.grpc.alts.internal.Handshaker.HandshakerResult.getDefaultInstance() : result_; + } + /** + *
+     * This is set iff the handshake was successful. out_frames may still be set
+     * to frames that needs to be forwarded to the peer.
+     * 
+ * + * .grpc.gcp.HandshakerResult result = 3; + */ + public io.grpc.alts.internal.Handshaker.HandshakerResultOrBuilder getResultOrBuilder() { + return getResult(); + } + + public static final int STATUS_FIELD_NUMBER = 4; + private io.grpc.alts.internal.Handshaker.HandshakerStatus status_; + /** + *
+     * Status of the handshaker.
+     * 
+ * + * .grpc.gcp.HandshakerStatus status = 4; + */ + public boolean hasStatus() { + return status_ != null; + } + /** + *
+     * Status of the handshaker.
+     * 
+ * + * .grpc.gcp.HandshakerStatus status = 4; + */ + public io.grpc.alts.internal.Handshaker.HandshakerStatus getStatus() { + return status_ == null ? io.grpc.alts.internal.Handshaker.HandshakerStatus.getDefaultInstance() : status_; + } + /** + *
+     * Status of the handshaker.
+     * 
+ * + * .grpc.gcp.HandshakerStatus status = 4; + */ + public io.grpc.alts.internal.Handshaker.HandshakerStatusOrBuilder getStatusOrBuilder() { + return getStatus(); + } + + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + if (!outFrames_.isEmpty()) { + output.writeBytes(1, outFrames_); + } + if (bytesConsumed_ != 0) { + output.writeUInt32(2, bytesConsumed_); + } + if (result_ != null) { + output.writeMessage(3, getResult()); + } + if (status_ != null) { + output.writeMessage(4, getStatus()); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (!outFrames_.isEmpty()) { + size += com.google.protobuf.CodedOutputStream + .computeBytesSize(1, outFrames_); + } + if (bytesConsumed_ != 0) { + size += com.google.protobuf.CodedOutputStream + .computeUInt32Size(2, bytesConsumed_); + } + if (result_ != null) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(3, getResult()); + } + if (status_ != null) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(4, getStatus()); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof io.grpc.alts.internal.Handshaker.HandshakerResp)) { + return super.equals(obj); + } + io.grpc.alts.internal.Handshaker.HandshakerResp other = (io.grpc.alts.internal.Handshaker.HandshakerResp) obj; + + boolean result = true; + result = result && getOutFrames() + .equals(other.getOutFrames()); + result = result && (getBytesConsumed() + == other.getBytesConsumed()); + result = result && (hasResult() == other.hasResult()); + if (hasResult()) { + result = result && getResult() + .equals(other.getResult()); + } + result = result && (hasStatus() == other.hasStatus()); + if (hasStatus()) { + result = result && getStatus() + .equals(other.getStatus()); + } + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + hash = (37 * hash) + OUT_FRAMES_FIELD_NUMBER; + hash = (53 * hash) + getOutFrames().hashCode(); + hash = (37 * hash) + BYTES_CONSUMED_FIELD_NUMBER; + hash = (53 * hash) + getBytesConsumed(); + if (hasResult()) { + hash = (37 * hash) + RESULT_FIELD_NUMBER; + hash = (53 * hash) + getResult().hashCode(); + } + if (hasStatus()) { + hash = (37 * hash) + STATUS_FIELD_NUMBER; + hash = (53 * hash) + getStatus().hashCode(); + } + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static io.grpc.alts.internal.Handshaker.HandshakerResp parseFrom( + java.nio.ByteBuffer data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Handshaker.HandshakerResp parseFrom( + java.nio.ByteBuffer data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.HandshakerResp parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Handshaker.HandshakerResp parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.HandshakerResp parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.Handshaker.HandshakerResp parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.HandshakerResp parseFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Handshaker.HandshakerResp parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.HandshakerResp parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Handshaker.HandshakerResp parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input, extensionRegistry); + } + public static io.grpc.alts.internal.Handshaker.HandshakerResp parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.Handshaker.HandshakerResp parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + public static Builder newBuilder(io.grpc.alts.internal.Handshaker.HandshakerResp prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { + return this == DEFAULT_INSTANCE + ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + * Protobuf type {@code grpc.gcp.HandshakerResp} + */ + public static final class Builder extends + com.google.protobuf.GeneratedMessageV3.Builder implements + // @@protoc_insertion_point(builder_implements:grpc.gcp.HandshakerResp) + io.grpc.alts.internal.Handshaker.HandshakerRespOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_HandshakerResp_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_HandshakerResp_fieldAccessorTable + .ensureFieldAccessorsInitialized( + io.grpc.alts.internal.Handshaker.HandshakerResp.class, io.grpc.alts.internal.Handshaker.HandshakerResp.Builder.class); + } + + // Construct using io.grpc.alts.internal.Handshaker.HandshakerResp.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder( + com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3 + .alwaysUseFieldBuilders) { + } + } + public Builder clear() { + super.clear(); + outFrames_ = com.google.protobuf.ByteString.EMPTY; + + bytesConsumed_ = 0; + + if (resultBuilder_ == null) { + result_ = null; + } else { + result_ = null; + resultBuilder_ = null; + } + if (statusBuilder_ == null) { + status_ = null; + } else { + status_ = null; + statusBuilder_ = null; + } + return this; + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return io.grpc.alts.internal.Handshaker.internal_static_grpc_gcp_HandshakerResp_descriptor; + } + + public io.grpc.alts.internal.Handshaker.HandshakerResp getDefaultInstanceForType() { + return io.grpc.alts.internal.Handshaker.HandshakerResp.getDefaultInstance(); + } + + public io.grpc.alts.internal.Handshaker.HandshakerResp build() { + io.grpc.alts.internal.Handshaker.HandshakerResp result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public io.grpc.alts.internal.Handshaker.HandshakerResp buildPartial() { + io.grpc.alts.internal.Handshaker.HandshakerResp result = new io.grpc.alts.internal.Handshaker.HandshakerResp(this); + result.outFrames_ = outFrames_; + result.bytesConsumed_ = bytesConsumed_; + if (resultBuilder_ == null) { + result.result_ = result_; + } else { + result.result_ = resultBuilder_.build(); + } + if (statusBuilder_ == null) { + result.status_ = status_; + } else { + result.status_ = statusBuilder_.build(); + } + onBuilt(); + return result; + } + + public Builder clone() { + return (Builder) super.clone(); + } + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, + java.lang.Object value) { + return (Builder) super.setField(field, value); + } + public Builder clearField( + com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); + } + public Builder clearOneof( + com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); + } + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); + } + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); + } + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof io.grpc.alts.internal.Handshaker.HandshakerResp) { + return mergeFrom((io.grpc.alts.internal.Handshaker.HandshakerResp)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(io.grpc.alts.internal.Handshaker.HandshakerResp other) { + if (other == io.grpc.alts.internal.Handshaker.HandshakerResp.getDefaultInstance()) return this; + if (other.getOutFrames() != com.google.protobuf.ByteString.EMPTY) { + setOutFrames(other.getOutFrames()); + } + if (other.getBytesConsumed() != 0) { + setBytesConsumed(other.getBytesConsumed()); + } + if (other.hasResult()) { + mergeResult(other.getResult()); + } + if (other.hasStatus()) { + mergeStatus(other.getStatus()); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + io.grpc.alts.internal.Handshaker.HandshakerResp parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (io.grpc.alts.internal.Handshaker.HandshakerResp) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + private com.google.protobuf.ByteString outFrames_ = com.google.protobuf.ByteString.EMPTY; + /** + *
+       * Frames to be given to the peer for the NextHandshakeMessageReq. May be
+       * empty if no out_frames have to be sent to the peer or if in_bytes in the
+       * HandshakerReq are incomplete. All the non-empty out frames must be sent to
+       * the peer even if the handshaker status is not OK as these frames may
+       * contain the alert frames.
+       * 
+ * + * bytes out_frames = 1; + */ + public com.google.protobuf.ByteString getOutFrames() { + return outFrames_; + } + /** + *
+       * Frames to be given to the peer for the NextHandshakeMessageReq. May be
+       * empty if no out_frames have to be sent to the peer or if in_bytes in the
+       * HandshakerReq are incomplete. All the non-empty out frames must be sent to
+       * the peer even if the handshaker status is not OK as these frames may
+       * contain the alert frames.
+       * 
+ * + * bytes out_frames = 1; + */ + public Builder setOutFrames(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + + outFrames_ = value; + onChanged(); + return this; + } + /** + *
+       * Frames to be given to the peer for the NextHandshakeMessageReq. May be
+       * empty if no out_frames have to be sent to the peer or if in_bytes in the
+       * HandshakerReq are incomplete. All the non-empty out frames must be sent to
+       * the peer even if the handshaker status is not OK as these frames may
+       * contain the alert frames.
+       * 
+ * + * bytes out_frames = 1; + */ + public Builder clearOutFrames() { + + outFrames_ = getDefaultInstance().getOutFrames(); + onChanged(); + return this; + } + + private int bytesConsumed_ ; + /** + *
+       * Number of bytes in the in_bytes consumed by the handshaker. It is possible
+       * that part of in_bytes in HandshakerReq was unrelated to the handshake
+       * process.
+       * 
+ * + * uint32 bytes_consumed = 2; + */ + public int getBytesConsumed() { + return bytesConsumed_; + } + /** + *
+       * Number of bytes in the in_bytes consumed by the handshaker. It is possible
+       * that part of in_bytes in HandshakerReq was unrelated to the handshake
+       * process.
+       * 
+ * + * uint32 bytes_consumed = 2; + */ + public Builder setBytesConsumed(int value) { + + bytesConsumed_ = value; + onChanged(); + return this; + } + /** + *
+       * Number of bytes in the in_bytes consumed by the handshaker. It is possible
+       * that part of in_bytes in HandshakerReq was unrelated to the handshake
+       * process.
+       * 
+ * + * uint32 bytes_consumed = 2; + */ + public Builder clearBytesConsumed() { + + bytesConsumed_ = 0; + onChanged(); + return this; + } + + private io.grpc.alts.internal.Handshaker.HandshakerResult result_ = null; + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.HandshakerResult, io.grpc.alts.internal.Handshaker.HandshakerResult.Builder, io.grpc.alts.internal.Handshaker.HandshakerResultOrBuilder> resultBuilder_; + /** + *
+       * This is set iff the handshake was successful. out_frames may still be set
+       * to frames that needs to be forwarded to the peer.
+       * 
+ * + * .grpc.gcp.HandshakerResult result = 3; + */ + public boolean hasResult() { + return resultBuilder_ != null || result_ != null; + } + /** + *
+       * This is set iff the handshake was successful. out_frames may still be set
+       * to frames that needs to be forwarded to the peer.
+       * 
+ * + * .grpc.gcp.HandshakerResult result = 3; + */ + public io.grpc.alts.internal.Handshaker.HandshakerResult getResult() { + if (resultBuilder_ == null) { + return result_ == null ? io.grpc.alts.internal.Handshaker.HandshakerResult.getDefaultInstance() : result_; + } else { + return resultBuilder_.getMessage(); + } + } + /** + *
+       * This is set iff the handshake was successful. out_frames may still be set
+       * to frames that needs to be forwarded to the peer.
+       * 
+ * + * .grpc.gcp.HandshakerResult result = 3; + */ + public Builder setResult(io.grpc.alts.internal.Handshaker.HandshakerResult value) { + if (resultBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + result_ = value; + onChanged(); + } else { + resultBuilder_.setMessage(value); + } + + return this; + } + /** + *
+       * This is set iff the handshake was successful. out_frames may still be set
+       * to frames that needs to be forwarded to the peer.
+       * 
+ * + * .grpc.gcp.HandshakerResult result = 3; + */ + public Builder setResult( + io.grpc.alts.internal.Handshaker.HandshakerResult.Builder builderForValue) { + if (resultBuilder_ == null) { + result_ = builderForValue.build(); + onChanged(); + } else { + resultBuilder_.setMessage(builderForValue.build()); + } + + return this; + } + /** + *
+       * This is set iff the handshake was successful. out_frames may still be set
+       * to frames that needs to be forwarded to the peer.
+       * 
+ * + * .grpc.gcp.HandshakerResult result = 3; + */ + public Builder mergeResult(io.grpc.alts.internal.Handshaker.HandshakerResult value) { + if (resultBuilder_ == null) { + if (result_ != null) { + result_ = + io.grpc.alts.internal.Handshaker.HandshakerResult.newBuilder(result_).mergeFrom(value).buildPartial(); + } else { + result_ = value; + } + onChanged(); + } else { + resultBuilder_.mergeFrom(value); + } + + return this; + } + /** + *
+       * This is set iff the handshake was successful. out_frames may still be set
+       * to frames that needs to be forwarded to the peer.
+       * 
+ * + * .grpc.gcp.HandshakerResult result = 3; + */ + public Builder clearResult() { + if (resultBuilder_ == null) { + result_ = null; + onChanged(); + } else { + result_ = null; + resultBuilder_ = null; + } + + return this; + } + /** + *
+       * This is set iff the handshake was successful. out_frames may still be set
+       * to frames that needs to be forwarded to the peer.
+       * 
+ * + * .grpc.gcp.HandshakerResult result = 3; + */ + public io.grpc.alts.internal.Handshaker.HandshakerResult.Builder getResultBuilder() { + + onChanged(); + return getResultFieldBuilder().getBuilder(); + } + /** + *
+       * This is set iff the handshake was successful. out_frames may still be set
+       * to frames that needs to be forwarded to the peer.
+       * 
+ * + * .grpc.gcp.HandshakerResult result = 3; + */ + public io.grpc.alts.internal.Handshaker.HandshakerResultOrBuilder getResultOrBuilder() { + if (resultBuilder_ != null) { + return resultBuilder_.getMessageOrBuilder(); + } else { + return result_ == null ? + io.grpc.alts.internal.Handshaker.HandshakerResult.getDefaultInstance() : result_; + } + } + /** + *
+       * This is set iff the handshake was successful. out_frames may still be set
+       * to frames that needs to be forwarded to the peer.
+       * 
+ * + * .grpc.gcp.HandshakerResult result = 3; + */ + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.HandshakerResult, io.grpc.alts.internal.Handshaker.HandshakerResult.Builder, io.grpc.alts.internal.Handshaker.HandshakerResultOrBuilder> + getResultFieldBuilder() { + if (resultBuilder_ == null) { + resultBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.HandshakerResult, io.grpc.alts.internal.Handshaker.HandshakerResult.Builder, io.grpc.alts.internal.Handshaker.HandshakerResultOrBuilder>( + getResult(), + getParentForChildren(), + isClean()); + result_ = null; + } + return resultBuilder_; + } + + private io.grpc.alts.internal.Handshaker.HandshakerStatus status_ = null; + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.HandshakerStatus, io.grpc.alts.internal.Handshaker.HandshakerStatus.Builder, io.grpc.alts.internal.Handshaker.HandshakerStatusOrBuilder> statusBuilder_; + /** + *
+       * Status of the handshaker.
+       * 
+ * + * .grpc.gcp.HandshakerStatus status = 4; + */ + public boolean hasStatus() { + return statusBuilder_ != null || status_ != null; + } + /** + *
+       * Status of the handshaker.
+       * 
+ * + * .grpc.gcp.HandshakerStatus status = 4; + */ + public io.grpc.alts.internal.Handshaker.HandshakerStatus getStatus() { + if (statusBuilder_ == null) { + return status_ == null ? io.grpc.alts.internal.Handshaker.HandshakerStatus.getDefaultInstance() : status_; + } else { + return statusBuilder_.getMessage(); + } + } + /** + *
+       * Status of the handshaker.
+       * 
+ * + * .grpc.gcp.HandshakerStatus status = 4; + */ + public Builder setStatus(io.grpc.alts.internal.Handshaker.HandshakerStatus value) { + if (statusBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + status_ = value; + onChanged(); + } else { + statusBuilder_.setMessage(value); + } + + return this; + } + /** + *
+       * Status of the handshaker.
+       * 
+ * + * .grpc.gcp.HandshakerStatus status = 4; + */ + public Builder setStatus( + io.grpc.alts.internal.Handshaker.HandshakerStatus.Builder builderForValue) { + if (statusBuilder_ == null) { + status_ = builderForValue.build(); + onChanged(); + } else { + statusBuilder_.setMessage(builderForValue.build()); + } + + return this; + } + /** + *
+       * Status of the handshaker.
+       * 
+ * + * .grpc.gcp.HandshakerStatus status = 4; + */ + public Builder mergeStatus(io.grpc.alts.internal.Handshaker.HandshakerStatus value) { + if (statusBuilder_ == null) { + if (status_ != null) { + status_ = + io.grpc.alts.internal.Handshaker.HandshakerStatus.newBuilder(status_).mergeFrom(value).buildPartial(); + } else { + status_ = value; + } + onChanged(); + } else { + statusBuilder_.mergeFrom(value); + } + + return this; + } + /** + *
+       * Status of the handshaker.
+       * 
+ * + * .grpc.gcp.HandshakerStatus status = 4; + */ + public Builder clearStatus() { + if (statusBuilder_ == null) { + status_ = null; + onChanged(); + } else { + status_ = null; + statusBuilder_ = null; + } + + return this; + } + /** + *
+       * Status of the handshaker.
+       * 
+ * + * .grpc.gcp.HandshakerStatus status = 4; + */ + public io.grpc.alts.internal.Handshaker.HandshakerStatus.Builder getStatusBuilder() { + + onChanged(); + return getStatusFieldBuilder().getBuilder(); + } + /** + *
+       * Status of the handshaker.
+       * 
+ * + * .grpc.gcp.HandshakerStatus status = 4; + */ + public io.grpc.alts.internal.Handshaker.HandshakerStatusOrBuilder getStatusOrBuilder() { + if (statusBuilder_ != null) { + return statusBuilder_.getMessageOrBuilder(); + } else { + return status_ == null ? + io.grpc.alts.internal.Handshaker.HandshakerStatus.getDefaultInstance() : status_; + } + } + /** + *
+       * Status of the handshaker.
+       * 
+ * + * .grpc.gcp.HandshakerStatus status = 4; + */ + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.HandshakerStatus, io.grpc.alts.internal.Handshaker.HandshakerStatus.Builder, io.grpc.alts.internal.Handshaker.HandshakerStatusOrBuilder> + getStatusFieldBuilder() { + if (statusBuilder_ == null) { + statusBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.Handshaker.HandshakerStatus, io.grpc.alts.internal.Handshaker.HandshakerStatus.Builder, io.grpc.alts.internal.Handshaker.HandshakerStatusOrBuilder>( + getStatus(), + getParentForChildren(), + isClean()); + status_ = null; + } + return statusBuilder_; + } + public final Builder setUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); + } + + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + + // @@protoc_insertion_point(builder_scope:grpc.gcp.HandshakerResp) + } + + // @@protoc_insertion_point(class_scope:grpc.gcp.HandshakerResp) + private static final io.grpc.alts.internal.Handshaker.HandshakerResp DEFAULT_INSTANCE; + static { + DEFAULT_INSTANCE = new io.grpc.alts.internal.Handshaker.HandshakerResp(); + } + + public static io.grpc.alts.internal.Handshaker.HandshakerResp getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + private static final com.google.protobuf.Parser + PARSER = new com.google.protobuf.AbstractParser() { + public HandshakerResp parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new HandshakerResp(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public io.grpc.alts.internal.Handshaker.HandshakerResp getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } + + } + + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_grpc_gcp_Endpoint_descriptor; + private static final + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_grpc_gcp_Endpoint_fieldAccessorTable; + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_grpc_gcp_Identity_descriptor; + private static final + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_grpc_gcp_Identity_fieldAccessorTable; + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_grpc_gcp_StartClientHandshakeReq_descriptor; + private static final + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_grpc_gcp_StartClientHandshakeReq_fieldAccessorTable; + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_grpc_gcp_ServerHandshakeParameters_descriptor; + private static final + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_grpc_gcp_ServerHandshakeParameters_fieldAccessorTable; + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_grpc_gcp_StartServerHandshakeReq_descriptor; + private static final + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_grpc_gcp_StartServerHandshakeReq_fieldAccessorTable; + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry_descriptor; + private static final + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry_fieldAccessorTable; + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_grpc_gcp_NextHandshakeMessageReq_descriptor; + private static final + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_grpc_gcp_NextHandshakeMessageReq_fieldAccessorTable; + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_grpc_gcp_HandshakerReq_descriptor; + private static final + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_grpc_gcp_HandshakerReq_fieldAccessorTable; + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_grpc_gcp_HandshakerResult_descriptor; + private static final + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_grpc_gcp_HandshakerResult_fieldAccessorTable; + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_grpc_gcp_HandshakerStatus_descriptor; + private static final + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_grpc_gcp_HandshakerStatus_fieldAccessorTable; + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_grpc_gcp_HandshakerResp_descriptor; + private static final + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_grpc_gcp_HandshakerResp_fieldAccessorTable; + + public static com.google.protobuf.Descriptors.FileDescriptor + getDescriptor() { + return descriptor; + } + private static com.google.protobuf.Descriptors.FileDescriptor + descriptor; + static { + java.lang.String[] descriptorData = { + "\n\031grpc/gcp/handshaker.proto\022\010grpc.gcp\032(g" + + "rpc/gcp/transport_security_common.proto\"" + + "Y\n\010Endpoint\022\022\n\nip_address\030\001 \001(\t\022\014\n\004port\030" + + "\002 \001(\005\022+\n\010protocol\030\003 \001(\0162\031.grpc.gcp.Netwo" + + "rkProtocol\"K\n\010Identity\022\031\n\017service_accoun" + + "t\030\001 \001(\tH\000\022\022\n\010hostname\030\002 \001(\tH\000B\020\n\016identit" + + "y_oneof\"\222\003\n\027StartClientHandshakeReq\022@\n\033h" + + "andshake_security_protocol\030\001 \001(\0162\033.grpc." + + "gcp.HandshakeProtocol\022\035\n\025application_pro" + + "tocols\030\002 \003(\t\022\030\n\020record_protocols\030\003 \003(\t\022-" + + "\n\021target_identities\030\004 \003(\0132\022.grpc.gcp.Ide" + + "ntity\022*\n\016local_identity\030\005 \001(\0132\022.grpc.gcp" + + ".Identity\022*\n\016local_endpoint\030\006 \001(\0132\022.grpc" + + ".gcp.Endpoint\022+\n\017remote_endpoint\030\007 \001(\0132\022" + + ".grpc.gcp.Endpoint\022\023\n\013target_name\030\010 \001(\t\022" + + "3\n\014rpc_versions\030\t \001(\0132\035.grpc.gcp.RpcProt" + + "ocolVersions\"c\n\031ServerHandshakeParameter" + + "s\022\030\n\020record_protocols\030\001 \003(\t\022,\n\020local_ide" + + "ntities\030\002 \003(\0132\022.grpc.gcp.Identity\"\223\003\n\027St" + + "artServerHandshakeReq\022\035\n\025application_pro" + + "tocols\030\001 \003(\t\022X\n\024handshake_parameters\030\002 \003" + + "(\0132:.grpc.gcp.StartServerHandshakeReq.Ha" + + "ndshakeParametersEntry\022\020\n\010in_bytes\030\003 \001(\014" + + "\022*\n\016local_endpoint\030\004 \001(\0132\022.grpc.gcp.Endp" + + "oint\022+\n\017remote_endpoint\030\005 \001(\0132\022.grpc.gcp" + + ".Endpoint\0223\n\014rpc_versions\030\006 \001(\0132\035.grpc.g" + + "cp.RpcProtocolVersions\032_\n\030HandshakeParam" + + "etersEntry\022\013\n\003key\030\001 \001(\005\0222\n\005value\030\002 \001(\0132#" + + ".grpc.gcp.ServerHandshakeParameters:\0028\001\"" + + "+\n\027NextHandshakeMessageReq\022\020\n\010in_bytes\030\001" + + " \001(\014\"\305\001\n\rHandshakerReq\0229\n\014client_start\030\001" + + " \001(\0132!.grpc.gcp.StartClientHandshakeReqH" + + "\000\0229\n\014server_start\030\002 \001(\0132!.grpc.gcp.Start" + + "ServerHandshakeReqH\000\0221\n\004next\030\003 \001(\0132!.grp" + + "c.gcp.NextHandshakeMessageReqH\000B\013\n\treq_o" + + "neof\"\207\002\n\020HandshakerResult\022\034\n\024application" + + "_protocol\030\001 \001(\t\022\027\n\017record_protocol\030\002 \001(\t" + + "\022\020\n\010key_data\030\003 \001(\014\022)\n\rpeer_identity\030\004 \001(" + + "\0132\022.grpc.gcp.Identity\022*\n\016local_identity\030" + + "\005 \001(\0132\022.grpc.gcp.Identity\022\031\n\021keep_channe" + + "l_open\030\006 \001(\010\0228\n\021peer_rpc_versions\030\007 \001(\0132" + + "\035.grpc.gcp.RpcProtocolVersions\"1\n\020Handsh" + + "akerStatus\022\014\n\004code\030\001 \001(\r\022\017\n\007details\030\002 \001(" + + "\t\"\224\001\n\016HandshakerResp\022\022\n\nout_frames\030\001 \001(\014" + + "\022\026\n\016bytes_consumed\030\002 \001(\r\022*\n\006result\030\003 \001(\013" + + "2\032.grpc.gcp.HandshakerResult\022*\n\006status\030\004" + + " \001(\0132\032.grpc.gcp.HandshakerStatus*J\n\021Hand" + + "shakeProtocol\022\"\n\036HANDSHAKE_PROTOCOL_UNSP" + + "ECIFIED\020\000\022\007\n\003TLS\020\001\022\010\n\004ALTS\020\002*E\n\017NetworkP" + + "rotocol\022 \n\034NETWORK_PROTOCOL_UNSPECIFIED\020" + + "\000\022\007\n\003TCP\020\001\022\007\n\003UDP\020\0022[\n\021HandshakerService" + + "\022F\n\013DoHandshake\022\027.grpc.gcp.HandshakerReq" + + "\032\030.grpc.gcp.HandshakerResp\"\000(\0010\001B\027\n\025io.g" + + "rpc.alts.internalb\006proto3" + }; + com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = + new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { + public com.google.protobuf.ExtensionRegistry assignDescriptors( + com.google.protobuf.Descriptors.FileDescriptor root) { + descriptor = root; + return null; + } + }; + com.google.protobuf.Descriptors.FileDescriptor + .internalBuildGeneratedFileFrom(descriptorData, + new com.google.protobuf.Descriptors.FileDescriptor[] { + io.grpc.alts.internal.TransportSecurityCommon.getDescriptor(), + }, assigner); + internal_static_grpc_gcp_Endpoint_descriptor = + getDescriptor().getMessageTypes().get(0); + internal_static_grpc_gcp_Endpoint_fieldAccessorTable = new + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_grpc_gcp_Endpoint_descriptor, + new java.lang.String[] { "IpAddress", "Port", "Protocol", }); + internal_static_grpc_gcp_Identity_descriptor = + getDescriptor().getMessageTypes().get(1); + internal_static_grpc_gcp_Identity_fieldAccessorTable = new + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_grpc_gcp_Identity_descriptor, + new java.lang.String[] { "ServiceAccount", "Hostname", "IdentityOneof", }); + internal_static_grpc_gcp_StartClientHandshakeReq_descriptor = + getDescriptor().getMessageTypes().get(2); + internal_static_grpc_gcp_StartClientHandshakeReq_fieldAccessorTable = new + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_grpc_gcp_StartClientHandshakeReq_descriptor, + new java.lang.String[] { "HandshakeSecurityProtocol", "ApplicationProtocols", "RecordProtocols", "TargetIdentities", "LocalIdentity", "LocalEndpoint", "RemoteEndpoint", "TargetName", "RpcVersions", }); + internal_static_grpc_gcp_ServerHandshakeParameters_descriptor = + getDescriptor().getMessageTypes().get(3); + internal_static_grpc_gcp_ServerHandshakeParameters_fieldAccessorTable = new + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_grpc_gcp_ServerHandshakeParameters_descriptor, + new java.lang.String[] { "RecordProtocols", "LocalIdentities", }); + internal_static_grpc_gcp_StartServerHandshakeReq_descriptor = + getDescriptor().getMessageTypes().get(4); + internal_static_grpc_gcp_StartServerHandshakeReq_fieldAccessorTable = new + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_grpc_gcp_StartServerHandshakeReq_descriptor, + new java.lang.String[] { "ApplicationProtocols", "HandshakeParameters", "InBytes", "LocalEndpoint", "RemoteEndpoint", "RpcVersions", }); + internal_static_grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry_descriptor = + internal_static_grpc_gcp_StartServerHandshakeReq_descriptor.getNestedTypes().get(0); + internal_static_grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry_fieldAccessorTable = new + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_grpc_gcp_StartServerHandshakeReq_HandshakeParametersEntry_descriptor, + new java.lang.String[] { "Key", "Value", }); + internal_static_grpc_gcp_NextHandshakeMessageReq_descriptor = + getDescriptor().getMessageTypes().get(5); + internal_static_grpc_gcp_NextHandshakeMessageReq_fieldAccessorTable = new + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_grpc_gcp_NextHandshakeMessageReq_descriptor, + new java.lang.String[] { "InBytes", }); + internal_static_grpc_gcp_HandshakerReq_descriptor = + getDescriptor().getMessageTypes().get(6); + internal_static_grpc_gcp_HandshakerReq_fieldAccessorTable = new + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_grpc_gcp_HandshakerReq_descriptor, + new java.lang.String[] { "ClientStart", "ServerStart", "Next", "ReqOneof", }); + internal_static_grpc_gcp_HandshakerResult_descriptor = + getDescriptor().getMessageTypes().get(7); + internal_static_grpc_gcp_HandshakerResult_fieldAccessorTable = new + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_grpc_gcp_HandshakerResult_descriptor, + new java.lang.String[] { "ApplicationProtocol", "RecordProtocol", "KeyData", "PeerIdentity", "LocalIdentity", "KeepChannelOpen", "PeerRpcVersions", }); + internal_static_grpc_gcp_HandshakerStatus_descriptor = + getDescriptor().getMessageTypes().get(8); + internal_static_grpc_gcp_HandshakerStatus_fieldAccessorTable = new + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_grpc_gcp_HandshakerStatus_descriptor, + new java.lang.String[] { "Code", "Details", }); + internal_static_grpc_gcp_HandshakerResp_descriptor = + getDescriptor().getMessageTypes().get(9); + internal_static_grpc_gcp_HandshakerResp_fieldAccessorTable = new + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_grpc_gcp_HandshakerResp_descriptor, + new java.lang.String[] { "OutFrames", "BytesConsumed", "Result", "Status", }); + io.grpc.alts.internal.TransportSecurityCommon.getDescriptor(); + } + + // @@protoc_insertion_point(outer_class_scope) +} diff --git a/alts/src/generated/main/java/io/grpc/alts/internal/TransportSecurityCommon.java b/alts/src/generated/main/java/io/grpc/alts/internal/TransportSecurityCommon.java new file mode 100644 index 0000000000000000000000000000000000000000..beb3839837cd6c2969daf5d22a1deb45ac1a66cd --- /dev/null +++ b/alts/src/generated/main/java/io/grpc/alts/internal/TransportSecurityCommon.java @@ -0,0 +1,1612 @@ +// Generated by the protocol buffer compiler. DO NOT EDIT! +// source: grpc/gcp/transport_security_common.proto + +package io.grpc.alts.internal; + +public final class TransportSecurityCommon { + private TransportSecurityCommon() {} + public static void registerAllExtensions( + com.google.protobuf.ExtensionRegistryLite registry) { + } + + public static void registerAllExtensions( + com.google.protobuf.ExtensionRegistry registry) { + registerAllExtensions( + (com.google.protobuf.ExtensionRegistryLite) registry); + } + /** + *
+   * The security level of the created channel. The list is sorted in increasing
+   * level of security. This order must always be maintained.
+   * 
+ * + * Protobuf enum {@code grpc.gcp.SecurityLevel} + */ + public enum SecurityLevel + implements com.google.protobuf.ProtocolMessageEnum { + /** + * SECURITY_NONE = 0; + */ + SECURITY_NONE(0), + /** + * INTEGRITY_ONLY = 1; + */ + INTEGRITY_ONLY(1), + /** + * INTEGRITY_AND_PRIVACY = 2; + */ + INTEGRITY_AND_PRIVACY(2), + UNRECOGNIZED(-1), + ; + + /** + * SECURITY_NONE = 0; + */ + public static final int SECURITY_NONE_VALUE = 0; + /** + * INTEGRITY_ONLY = 1; + */ + public static final int INTEGRITY_ONLY_VALUE = 1; + /** + * INTEGRITY_AND_PRIVACY = 2; + */ + public static final int INTEGRITY_AND_PRIVACY_VALUE = 2; + + + public final int getNumber() { + if (this == UNRECOGNIZED) { + throw new java.lang.IllegalArgumentException( + "Can't get the number of an unknown enum value."); + } + return value; + } + + /** + * @deprecated Use {@link #forNumber(int)} instead. + */ + @java.lang.Deprecated + public static SecurityLevel valueOf(int value) { + return forNumber(value); + } + + public static SecurityLevel forNumber(int value) { + switch (value) { + case 0: return SECURITY_NONE; + case 1: return INTEGRITY_ONLY; + case 2: return INTEGRITY_AND_PRIVACY; + default: return null; + } + } + + public static com.google.protobuf.Internal.EnumLiteMap + internalGetValueMap() { + return internalValueMap; + } + private static final com.google.protobuf.Internal.EnumLiteMap< + SecurityLevel> internalValueMap = + new com.google.protobuf.Internal.EnumLiteMap() { + public SecurityLevel findValueByNumber(int number) { + return SecurityLevel.forNumber(number); + } + }; + + public final com.google.protobuf.Descriptors.EnumValueDescriptor + getValueDescriptor() { + return getDescriptor().getValues().get(ordinal()); + } + public final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptorForType() { + return getDescriptor(); + } + public static final com.google.protobuf.Descriptors.EnumDescriptor + getDescriptor() { + return io.grpc.alts.internal.TransportSecurityCommon.getDescriptor().getEnumTypes().get(0); + } + + private static final SecurityLevel[] VALUES = values(); + + public static SecurityLevel valueOf( + com.google.protobuf.Descriptors.EnumValueDescriptor desc) { + if (desc.getType() != getDescriptor()) { + throw new java.lang.IllegalArgumentException( + "EnumValueDescriptor is not for this type."); + } + if (desc.getIndex() == -1) { + return UNRECOGNIZED; + } + return VALUES[desc.getIndex()]; + } + + private final int value; + + private SecurityLevel(int value) { + this.value = value; + } + + // @@protoc_insertion_point(enum_scope:grpc.gcp.SecurityLevel) + } + + public interface RpcProtocolVersionsOrBuilder extends + // @@protoc_insertion_point(interface_extends:grpc.gcp.RpcProtocolVersions) + com.google.protobuf.MessageOrBuilder { + + /** + *
+     * Maximum supported RPC version.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions.Version max_rpc_version = 1; + */ + boolean hasMaxRpcVersion(); + /** + *
+     * Maximum supported RPC version.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions.Version max_rpc_version = 1; + */ + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version getMaxRpcVersion(); + /** + *
+     * Maximum supported RPC version.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions.Version max_rpc_version = 1; + */ + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.VersionOrBuilder getMaxRpcVersionOrBuilder(); + + /** + *
+     * Minimum supported RPC version.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions.Version min_rpc_version = 2; + */ + boolean hasMinRpcVersion(); + /** + *
+     * Minimum supported RPC version.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions.Version min_rpc_version = 2; + */ + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version getMinRpcVersion(); + /** + *
+     * Minimum supported RPC version.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions.Version min_rpc_version = 2; + */ + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.VersionOrBuilder getMinRpcVersionOrBuilder(); + } + /** + *
+   * Max and min supported RPC protocol versions.
+   * 
+ * + * Protobuf type {@code grpc.gcp.RpcProtocolVersions} + */ + public static final class RpcProtocolVersions extends + com.google.protobuf.GeneratedMessageV3 implements + // @@protoc_insertion_point(message_implements:grpc.gcp.RpcProtocolVersions) + RpcProtocolVersionsOrBuilder { + private static final long serialVersionUID = 0L; + // Use RpcProtocolVersions.newBuilder() to construct. + private RpcProtocolVersions(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + private RpcProtocolVersions() { + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return this.unknownFields; + } + private RpcProtocolVersions( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownFieldProto3( + input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 10: { + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version.Builder subBuilder = null; + if (maxRpcVersion_ != null) { + subBuilder = maxRpcVersion_.toBuilder(); + } + maxRpcVersion_ = input.readMessage(io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version.parser(), extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(maxRpcVersion_); + maxRpcVersion_ = subBuilder.buildPartial(); + } + + break; + } + case 18: { + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version.Builder subBuilder = null; + if (minRpcVersion_ != null) { + subBuilder = minRpcVersion_.toBuilder(); + } + minRpcVersion_ = input.readMessage(io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version.parser(), extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(minRpcVersion_); + minRpcVersion_ = subBuilder.buildPartial(); + } + + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return io.grpc.alts.internal.TransportSecurityCommon.internal_static_grpc_gcp_RpcProtocolVersions_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return io.grpc.alts.internal.TransportSecurityCommon.internal_static_grpc_gcp_RpcProtocolVersions_fieldAccessorTable + .ensureFieldAccessorsInitialized( + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.class, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Builder.class); + } + + public interface VersionOrBuilder extends + // @@protoc_insertion_point(interface_extends:grpc.gcp.RpcProtocolVersions.Version) + com.google.protobuf.MessageOrBuilder { + + /** + * uint32 major = 1; + */ + int getMajor(); + + /** + * uint32 minor = 2; + */ + int getMinor(); + } + /** + *
+     * RPC version contains a major version and a minor version.
+     * 
+ * + * Protobuf type {@code grpc.gcp.RpcProtocolVersions.Version} + */ + public static final class Version extends + com.google.protobuf.GeneratedMessageV3 implements + // @@protoc_insertion_point(message_implements:grpc.gcp.RpcProtocolVersions.Version) + VersionOrBuilder { + private static final long serialVersionUID = 0L; + // Use Version.newBuilder() to construct. + private Version(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + private Version() { + major_ = 0; + minor_ = 0; + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet + getUnknownFields() { + return this.unknownFields; + } + private Version( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: { + if (!parseUnknownFieldProto3( + input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 8: { + + major_ = input.readUInt32(); + break; + } + case 16: { + + minor_ = input.readUInt32(); + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException( + e).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return io.grpc.alts.internal.TransportSecurityCommon.internal_static_grpc_gcp_RpcProtocolVersions_Version_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return io.grpc.alts.internal.TransportSecurityCommon.internal_static_grpc_gcp_RpcProtocolVersions_Version_fieldAccessorTable + .ensureFieldAccessorsInitialized( + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version.class, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version.Builder.class); + } + + public static final int MAJOR_FIELD_NUMBER = 1; + private int major_; + /** + * uint32 major = 1; + */ + public int getMajor() { + return major_; + } + + public static final int MINOR_FIELD_NUMBER = 2; + private int minor_; + /** + * uint32 minor = 2; + */ + public int getMinor() { + return minor_; + } + + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + if (major_ != 0) { + output.writeUInt32(1, major_); + } + if (minor_ != 0) { + output.writeUInt32(2, minor_); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (major_ != 0) { + size += com.google.protobuf.CodedOutputStream + .computeUInt32Size(1, major_); + } + if (minor_ != 0) { + size += com.google.protobuf.CodedOutputStream + .computeUInt32Size(2, minor_); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version)) { + return super.equals(obj); + } + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version other = (io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version) obj; + + boolean result = true; + result = result && (getMajor() + == other.getMajor()); + result = result && (getMinor() + == other.getMinor()); + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + hash = (37 * hash) + MAJOR_FIELD_NUMBER; + hash = (53 * hash) + getMajor(); + hash = (37 * hash) + MINOR_FIELD_NUMBER; + hash = (53 * hash) + getMinor(); + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version parseFrom( + java.nio.ByteBuffer data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version parseFrom( + java.nio.ByteBuffer data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version parseFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + public static io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input, extensionRegistry); + } + public static io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + public static Builder newBuilder(io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { + return this == DEFAULT_INSTANCE + ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + *
+       * RPC version contains a major version and a minor version.
+       * 
+ * + * Protobuf type {@code grpc.gcp.RpcProtocolVersions.Version} + */ + public static final class Builder extends + com.google.protobuf.GeneratedMessageV3.Builder implements + // @@protoc_insertion_point(builder_implements:grpc.gcp.RpcProtocolVersions.Version) + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.VersionOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return io.grpc.alts.internal.TransportSecurityCommon.internal_static_grpc_gcp_RpcProtocolVersions_Version_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return io.grpc.alts.internal.TransportSecurityCommon.internal_static_grpc_gcp_RpcProtocolVersions_Version_fieldAccessorTable + .ensureFieldAccessorsInitialized( + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version.class, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version.Builder.class); + } + + // Construct using io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder( + com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3 + .alwaysUseFieldBuilders) { + } + } + public Builder clear() { + super.clear(); + major_ = 0; + + minor_ = 0; + + return this; + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return io.grpc.alts.internal.TransportSecurityCommon.internal_static_grpc_gcp_RpcProtocolVersions_Version_descriptor; + } + + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version getDefaultInstanceForType() { + return io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version.getDefaultInstance(); + } + + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version build() { + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version buildPartial() { + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version result = new io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version(this); + result.major_ = major_; + result.minor_ = minor_; + onBuilt(); + return result; + } + + public Builder clone() { + return (Builder) super.clone(); + } + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, + java.lang.Object value) { + return (Builder) super.setField(field, value); + } + public Builder clearField( + com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); + } + public Builder clearOneof( + com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); + } + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); + } + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); + } + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version) { + return mergeFrom((io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version other) { + if (other == io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version.getDefaultInstance()) return this; + if (other.getMajor() != 0) { + setMajor(other.getMajor()); + } + if (other.getMinor() != 0) { + setMinor(other.getMinor()); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + private int major_ ; + /** + * uint32 major = 1; + */ + public int getMajor() { + return major_; + } + /** + * uint32 major = 1; + */ + public Builder setMajor(int value) { + + major_ = value; + onChanged(); + return this; + } + /** + * uint32 major = 1; + */ + public Builder clearMajor() { + + major_ = 0; + onChanged(); + return this; + } + + private int minor_ ; + /** + * uint32 minor = 2; + */ + public int getMinor() { + return minor_; + } + /** + * uint32 minor = 2; + */ + public Builder setMinor(int value) { + + minor_ = value; + onChanged(); + return this; + } + /** + * uint32 minor = 2; + */ + public Builder clearMinor() { + + minor_ = 0; + onChanged(); + return this; + } + public final Builder setUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); + } + + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + + // @@protoc_insertion_point(builder_scope:grpc.gcp.RpcProtocolVersions.Version) + } + + // @@protoc_insertion_point(class_scope:grpc.gcp.RpcProtocolVersions.Version) + private static final io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version DEFAULT_INSTANCE; + static { + DEFAULT_INSTANCE = new io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version(); + } + + public static io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + private static final com.google.protobuf.Parser + PARSER = new com.google.protobuf.AbstractParser() { + public Version parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new Version(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } + + } + + public static final int MAX_RPC_VERSION_FIELD_NUMBER = 1; + private io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version maxRpcVersion_; + /** + *
+     * Maximum supported RPC version.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions.Version max_rpc_version = 1; + */ + public boolean hasMaxRpcVersion() { + return maxRpcVersion_ != null; + } + /** + *
+     * Maximum supported RPC version.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions.Version max_rpc_version = 1; + */ + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version getMaxRpcVersion() { + return maxRpcVersion_ == null ? io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version.getDefaultInstance() : maxRpcVersion_; + } + /** + *
+     * Maximum supported RPC version.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions.Version max_rpc_version = 1; + */ + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.VersionOrBuilder getMaxRpcVersionOrBuilder() { + return getMaxRpcVersion(); + } + + public static final int MIN_RPC_VERSION_FIELD_NUMBER = 2; + private io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version minRpcVersion_; + /** + *
+     * Minimum supported RPC version.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions.Version min_rpc_version = 2; + */ + public boolean hasMinRpcVersion() { + return minRpcVersion_ != null; + } + /** + *
+     * Minimum supported RPC version.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions.Version min_rpc_version = 2; + */ + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version getMinRpcVersion() { + return minRpcVersion_ == null ? io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version.getDefaultInstance() : minRpcVersion_; + } + /** + *
+     * Minimum supported RPC version.
+     * 
+ * + * .grpc.gcp.RpcProtocolVersions.Version min_rpc_version = 2; + */ + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.VersionOrBuilder getMinRpcVersionOrBuilder() { + return getMinRpcVersion(); + } + + private byte memoizedIsInitialized = -1; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) + throws java.io.IOException { + if (maxRpcVersion_ != null) { + output.writeMessage(1, getMaxRpcVersion()); + } + if (minRpcVersion_ != null) { + output.writeMessage(2, getMinRpcVersion()); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (maxRpcVersion_ != null) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(1, getMaxRpcVersion()); + } + if (minRpcVersion_ != null) { + size += com.google.protobuf.CodedOutputStream + .computeMessageSize(2, getMinRpcVersion()); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions)) { + return super.equals(obj); + } + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions other = (io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions) obj; + + boolean result = true; + result = result && (hasMaxRpcVersion() == other.hasMaxRpcVersion()); + if (hasMaxRpcVersion()) { + result = result && getMaxRpcVersion() + .equals(other.getMaxRpcVersion()); + } + result = result && (hasMinRpcVersion() == other.hasMinRpcVersion()); + if (hasMinRpcVersion()) { + result = result && getMinRpcVersion() + .equals(other.getMinRpcVersion()); + } + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + if (hasMaxRpcVersion()) { + hash = (37 * hash) + MAX_RPC_VERSION_FIELD_NUMBER; + hash = (53 * hash) + getMaxRpcVersion().hashCode(); + } + if (hasMinRpcVersion()) { + hash = (37 * hash) + MIN_RPC_VERSION_FIELD_NUMBER; + hash = (53 * hash) + getMinRpcVersion().hashCode(); + } + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions parseFrom( + java.nio.ByteBuffer data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions parseFrom( + java.nio.ByteBuffer data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + public static io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions parseFrom( + byte[] data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + public static io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions parseFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions parseFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + public static io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions parseDelimitedFrom(java.io.InputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions parseDelimitedFrom( + java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseDelimitedWithIOException(PARSER, input, extensionRegistry); + } + public static io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions parseFrom( + com.google.protobuf.CodedInputStream input) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input); + } + public static io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3 + .parseWithIOException(PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { return newBuilder(); } + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + public static Builder newBuilder(io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + public Builder toBuilder() { + return this == DEFAULT_INSTANCE + ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType( + com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + /** + *
+     * Max and min supported RPC protocol versions.
+     * 
+ * + * Protobuf type {@code grpc.gcp.RpcProtocolVersions} + */ + public static final class Builder extends + com.google.protobuf.GeneratedMessageV3.Builder implements + // @@protoc_insertion_point(builder_implements:grpc.gcp.RpcProtocolVersions) + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersionsOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor + getDescriptor() { + return io.grpc.alts.internal.TransportSecurityCommon.internal_static_grpc_gcp_RpcProtocolVersions_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return io.grpc.alts.internal.TransportSecurityCommon.internal_static_grpc_gcp_RpcProtocolVersions_fieldAccessorTable + .ensureFieldAccessorsInitialized( + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.class, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Builder.class); + } + + // Construct using io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder( + com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3 + .alwaysUseFieldBuilders) { + } + } + public Builder clear() { + super.clear(); + if (maxRpcVersionBuilder_ == null) { + maxRpcVersion_ = null; + } else { + maxRpcVersion_ = null; + maxRpcVersionBuilder_ = null; + } + if (minRpcVersionBuilder_ == null) { + minRpcVersion_ = null; + } else { + minRpcVersion_ = null; + minRpcVersionBuilder_ = null; + } + return this; + } + + public com.google.protobuf.Descriptors.Descriptor + getDescriptorForType() { + return io.grpc.alts.internal.TransportSecurityCommon.internal_static_grpc_gcp_RpcProtocolVersions_descriptor; + } + + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions getDefaultInstanceForType() { + return io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.getDefaultInstance(); + } + + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions build() { + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions buildPartial() { + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions result = new io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions(this); + if (maxRpcVersionBuilder_ == null) { + result.maxRpcVersion_ = maxRpcVersion_; + } else { + result.maxRpcVersion_ = maxRpcVersionBuilder_.build(); + } + if (minRpcVersionBuilder_ == null) { + result.minRpcVersion_ = minRpcVersion_; + } else { + result.minRpcVersion_ = minRpcVersionBuilder_.build(); + } + onBuilt(); + return result; + } + + public Builder clone() { + return (Builder) super.clone(); + } + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, + java.lang.Object value) { + return (Builder) super.setField(field, value); + } + public Builder clearField( + com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); + } + public Builder clearOneof( + com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); + } + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); + } + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, + java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); + } + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions) { + return mergeFrom((io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions)other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions other) { + if (other == io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.getDefaultInstance()) return this; + if (other.hasMaxRpcVersion()) { + mergeMaxRpcVersion(other.getMaxRpcVersion()); + } + if (other.hasMinRpcVersion()) { + mergeMinRpcVersion(other.getMinRpcVersion()); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } + + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + private io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version maxRpcVersion_ = null; + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version.Builder, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.VersionOrBuilder> maxRpcVersionBuilder_; + /** + *
+       * Maximum supported RPC version.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions.Version max_rpc_version = 1; + */ + public boolean hasMaxRpcVersion() { + return maxRpcVersionBuilder_ != null || maxRpcVersion_ != null; + } + /** + *
+       * Maximum supported RPC version.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions.Version max_rpc_version = 1; + */ + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version getMaxRpcVersion() { + if (maxRpcVersionBuilder_ == null) { + return maxRpcVersion_ == null ? io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version.getDefaultInstance() : maxRpcVersion_; + } else { + return maxRpcVersionBuilder_.getMessage(); + } + } + /** + *
+       * Maximum supported RPC version.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions.Version max_rpc_version = 1; + */ + public Builder setMaxRpcVersion(io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version value) { + if (maxRpcVersionBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + maxRpcVersion_ = value; + onChanged(); + } else { + maxRpcVersionBuilder_.setMessage(value); + } + + return this; + } + /** + *
+       * Maximum supported RPC version.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions.Version max_rpc_version = 1; + */ + public Builder setMaxRpcVersion( + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version.Builder builderForValue) { + if (maxRpcVersionBuilder_ == null) { + maxRpcVersion_ = builderForValue.build(); + onChanged(); + } else { + maxRpcVersionBuilder_.setMessage(builderForValue.build()); + } + + return this; + } + /** + *
+       * Maximum supported RPC version.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions.Version max_rpc_version = 1; + */ + public Builder mergeMaxRpcVersion(io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version value) { + if (maxRpcVersionBuilder_ == null) { + if (maxRpcVersion_ != null) { + maxRpcVersion_ = + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version.newBuilder(maxRpcVersion_).mergeFrom(value).buildPartial(); + } else { + maxRpcVersion_ = value; + } + onChanged(); + } else { + maxRpcVersionBuilder_.mergeFrom(value); + } + + return this; + } + /** + *
+       * Maximum supported RPC version.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions.Version max_rpc_version = 1; + */ + public Builder clearMaxRpcVersion() { + if (maxRpcVersionBuilder_ == null) { + maxRpcVersion_ = null; + onChanged(); + } else { + maxRpcVersion_ = null; + maxRpcVersionBuilder_ = null; + } + + return this; + } + /** + *
+       * Maximum supported RPC version.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions.Version max_rpc_version = 1; + */ + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version.Builder getMaxRpcVersionBuilder() { + + onChanged(); + return getMaxRpcVersionFieldBuilder().getBuilder(); + } + /** + *
+       * Maximum supported RPC version.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions.Version max_rpc_version = 1; + */ + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.VersionOrBuilder getMaxRpcVersionOrBuilder() { + if (maxRpcVersionBuilder_ != null) { + return maxRpcVersionBuilder_.getMessageOrBuilder(); + } else { + return maxRpcVersion_ == null ? + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version.getDefaultInstance() : maxRpcVersion_; + } + } + /** + *
+       * Maximum supported RPC version.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions.Version max_rpc_version = 1; + */ + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version.Builder, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.VersionOrBuilder> + getMaxRpcVersionFieldBuilder() { + if (maxRpcVersionBuilder_ == null) { + maxRpcVersionBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version.Builder, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.VersionOrBuilder>( + getMaxRpcVersion(), + getParentForChildren(), + isClean()); + maxRpcVersion_ = null; + } + return maxRpcVersionBuilder_; + } + + private io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version minRpcVersion_ = null; + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version.Builder, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.VersionOrBuilder> minRpcVersionBuilder_; + /** + *
+       * Minimum supported RPC version.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions.Version min_rpc_version = 2; + */ + public boolean hasMinRpcVersion() { + return minRpcVersionBuilder_ != null || minRpcVersion_ != null; + } + /** + *
+       * Minimum supported RPC version.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions.Version min_rpc_version = 2; + */ + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version getMinRpcVersion() { + if (minRpcVersionBuilder_ == null) { + return minRpcVersion_ == null ? io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version.getDefaultInstance() : minRpcVersion_; + } else { + return minRpcVersionBuilder_.getMessage(); + } + } + /** + *
+       * Minimum supported RPC version.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions.Version min_rpc_version = 2; + */ + public Builder setMinRpcVersion(io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version value) { + if (minRpcVersionBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + minRpcVersion_ = value; + onChanged(); + } else { + minRpcVersionBuilder_.setMessage(value); + } + + return this; + } + /** + *
+       * Minimum supported RPC version.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions.Version min_rpc_version = 2; + */ + public Builder setMinRpcVersion( + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version.Builder builderForValue) { + if (minRpcVersionBuilder_ == null) { + minRpcVersion_ = builderForValue.build(); + onChanged(); + } else { + minRpcVersionBuilder_.setMessage(builderForValue.build()); + } + + return this; + } + /** + *
+       * Minimum supported RPC version.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions.Version min_rpc_version = 2; + */ + public Builder mergeMinRpcVersion(io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version value) { + if (minRpcVersionBuilder_ == null) { + if (minRpcVersion_ != null) { + minRpcVersion_ = + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version.newBuilder(minRpcVersion_).mergeFrom(value).buildPartial(); + } else { + minRpcVersion_ = value; + } + onChanged(); + } else { + minRpcVersionBuilder_.mergeFrom(value); + } + + return this; + } + /** + *
+       * Minimum supported RPC version.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions.Version min_rpc_version = 2; + */ + public Builder clearMinRpcVersion() { + if (minRpcVersionBuilder_ == null) { + minRpcVersion_ = null; + onChanged(); + } else { + minRpcVersion_ = null; + minRpcVersionBuilder_ = null; + } + + return this; + } + /** + *
+       * Minimum supported RPC version.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions.Version min_rpc_version = 2; + */ + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version.Builder getMinRpcVersionBuilder() { + + onChanged(); + return getMinRpcVersionFieldBuilder().getBuilder(); + } + /** + *
+       * Minimum supported RPC version.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions.Version min_rpc_version = 2; + */ + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.VersionOrBuilder getMinRpcVersionOrBuilder() { + if (minRpcVersionBuilder_ != null) { + return minRpcVersionBuilder_.getMessageOrBuilder(); + } else { + return minRpcVersion_ == null ? + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version.getDefaultInstance() : minRpcVersion_; + } + } + /** + *
+       * Minimum supported RPC version.
+       * 
+ * + * .grpc.gcp.RpcProtocolVersions.Version min_rpc_version = 2; + */ + private com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version.Builder, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.VersionOrBuilder> + getMinRpcVersionFieldBuilder() { + if (minRpcVersionBuilder_ == null) { + minRpcVersionBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< + io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version.Builder, io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.VersionOrBuilder>( + getMinRpcVersion(), + getParentForChildren(), + isClean()); + minRpcVersion_ = null; + } + return minRpcVersionBuilder_; + } + public final Builder setUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); + } + + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + + // @@protoc_insertion_point(builder_scope:grpc.gcp.RpcProtocolVersions) + } + + // @@protoc_insertion_point(class_scope:grpc.gcp.RpcProtocolVersions) + private static final io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions DEFAULT_INSTANCE; + static { + DEFAULT_INSTANCE = new io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions(); + } + + public static io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + private static final com.google.protobuf.Parser + PARSER = new com.google.protobuf.AbstractParser() { + public RpcProtocolVersions parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new RpcProtocolVersions(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } + + } + + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_grpc_gcp_RpcProtocolVersions_descriptor; + private static final + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_grpc_gcp_RpcProtocolVersions_fieldAccessorTable; + private static final com.google.protobuf.Descriptors.Descriptor + internal_static_grpc_gcp_RpcProtocolVersions_Version_descriptor; + private static final + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_grpc_gcp_RpcProtocolVersions_Version_fieldAccessorTable; + + public static com.google.protobuf.Descriptors.FileDescriptor + getDescriptor() { + return descriptor; + } + private static com.google.protobuf.Descriptors.FileDescriptor + descriptor; + static { + java.lang.String[] descriptorData = { + "\n(grpc/gcp/transport_security_common.pro" + + "to\022\010grpc.gcp\"\276\001\n\023RpcProtocolVersions\022>\n\017" + + "max_rpc_version\030\001 \001(\0132%.grpc.gcp.RpcProt" + + "ocolVersions.Version\022>\n\017min_rpc_version\030" + + "\002 \001(\0132%.grpc.gcp.RpcProtocolVersions.Ver" + + "sion\032\'\n\007Version\022\r\n\005major\030\001 \001(\r\022\r\n\005minor\030" + + "\002 \001(\r*Q\n\rSecurityLevel\022\021\n\rSECURITY_NONE\020" + + "\000\022\022\n\016INTEGRITY_ONLY\020\001\022\031\n\025INTEGRITY_AND_P" + + "RIVACY\020\002B\027\n\025io.grpc.alts.internalb\006proto" + + "3" + }; + com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = + new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { + public com.google.protobuf.ExtensionRegistry assignDescriptors( + com.google.protobuf.Descriptors.FileDescriptor root) { + descriptor = root; + return null; + } + }; + com.google.protobuf.Descriptors.FileDescriptor + .internalBuildGeneratedFileFrom(descriptorData, + new com.google.protobuf.Descriptors.FileDescriptor[] { + }, assigner); + internal_static_grpc_gcp_RpcProtocolVersions_descriptor = + getDescriptor().getMessageTypes().get(0); + internal_static_grpc_gcp_RpcProtocolVersions_fieldAccessorTable = new + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_grpc_gcp_RpcProtocolVersions_descriptor, + new java.lang.String[] { "MaxRpcVersion", "MinRpcVersion", }); + internal_static_grpc_gcp_RpcProtocolVersions_Version_descriptor = + internal_static_grpc_gcp_RpcProtocolVersions_descriptor.getNestedTypes().get(0); + internal_static_grpc_gcp_RpcProtocolVersions_Version_fieldAccessorTable = new + com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_grpc_gcp_RpcProtocolVersions_Version_descriptor, + new java.lang.String[] { "Major", "Minor", }); + } + + // @@protoc_insertion_point(outer_class_scope) +} diff --git a/alts/src/main/java/io/grpc/alts/AltsChannelBuilder.java b/alts/src/main/java/io/grpc/alts/AltsChannelBuilder.java new file mode 100644 index 0000000000000000000000000000000000000000..ce24861b890367f1751901d3a611fd2743497b8e --- /dev/null +++ b/alts/src/main/java/io/grpc/alts/AltsChannelBuilder.java @@ -0,0 +1,239 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts; + +import static com.google.common.base.Preconditions.checkArgument; + +import com.google.common.annotations.VisibleForTesting; +import io.grpc.CallOptions; +import io.grpc.Channel; +import io.grpc.ClientCall; +import io.grpc.ClientInterceptor; +import io.grpc.ExperimentalApi; +import io.grpc.ForwardingChannelBuilder; +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; +import io.grpc.MethodDescriptor; +import io.grpc.Status; +import io.grpc.alts.internal.AltsClientOptions; +import io.grpc.alts.internal.AltsProtocolNegotiator; +import io.grpc.alts.internal.AltsTsiHandshaker; +import io.grpc.alts.internal.HandshakerServiceGrpc; +import io.grpc.alts.internal.RpcProtocolVersionsUtil; +import io.grpc.alts.internal.TsiHandshaker; +import io.grpc.alts.internal.TsiHandshakerFactory; +import io.grpc.internal.GrpcUtil; +import io.grpc.internal.ObjectPool; +import io.grpc.internal.ProxyParameters; +import io.grpc.internal.SharedResourcePool; +import io.grpc.netty.InternalNettyChannelBuilder; +import io.grpc.netty.InternalNettyChannelBuilder.TransportCreationParamsFilter; +import io.grpc.netty.InternalNettyChannelBuilder.TransportCreationParamsFilterFactory; +import io.grpc.netty.NettyChannelBuilder; +import java.net.InetSocketAddress; +import java.net.SocketAddress; +import java.util.concurrent.TimeUnit; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.annotation.Nullable; + +/** + * ALTS version of {@code ManagedChannelBuilder}. This class sets up a secure and authenticated + * commmunication between two cloud VMs using ALTS. + */ +@ExperimentalApi("https://github.com/grpc/grpc-java/issues/4151") +public final class AltsChannelBuilder extends ForwardingChannelBuilder { + + private static final Logger logger = Logger.getLogger(AltsChannelBuilder.class.getName()); + private final NettyChannelBuilder delegate; + private final AltsClientOptions.Builder handshakerOptionsBuilder = + new AltsClientOptions.Builder(); + private ObjectPool handshakerChannelPool = + SharedResourcePool.forResource(HandshakerServiceChannel.SHARED_HANDSHAKER_CHANNEL); + private TcpfFactory tcpfFactoryForTest; + private boolean enableUntrustedAlts; + + /** "Overrides" the static method in {@link ManagedChannelBuilder}. */ + public static final AltsChannelBuilder forTarget(String target) { + return new AltsChannelBuilder(target); + } + + /** "Overrides" the static method in {@link ManagedChannelBuilder}. */ + public static AltsChannelBuilder forAddress(String name, int port) { + return forTarget(GrpcUtil.authorityFromHostAndPort(name, port)); + } + + private AltsChannelBuilder(String target) { + delegate = + NettyChannelBuilder.forTarget(target) + .keepAliveTime(20, TimeUnit.SECONDS) + .keepAliveTimeout(10, TimeUnit.SECONDS) + .keepAliveWithoutCalls(true); + handshakerOptionsBuilder.setRpcProtocolVersions( + RpcProtocolVersionsUtil.getRpcProtocolVersions()); + } + + /** The server service account name for secure name checking. */ + public AltsChannelBuilder withSecureNamingTarget(String targetName) { + handshakerOptionsBuilder.setTargetName(targetName); + return this; + } + + /** + * Adds an expected target service accounts. One of the added service accounts should match peer + * service account in the handshaker result. Otherwise, the handshake fails. + */ + public AltsChannelBuilder addTargetServiceAccount(String targetServiceAccount) { + handshakerOptionsBuilder.addTargetServiceAccount(targetServiceAccount); + return this; + } + + /** + * Enables untrusted ALTS for testing. If this function is called, we will not check whether ALTS + * is running on Google Cloud Platform. + */ + public AltsChannelBuilder enableUntrustedAltsForTesting() { + enableUntrustedAlts = true; + return this; + } + + /** Sets a new handshaker service address for testing. */ + public AltsChannelBuilder setHandshakerAddressForTesting(String handshakerAddress) { + // Instead of using the default shared channel to the handshaker service, create a fix object + // pool of handshaker service channel for testing. + handshakerChannelPool = + HandshakerServiceChannel.getHandshakerChannelPoolForTesting(handshakerAddress); + return this; + } + + @Override + protected NettyChannelBuilder delegate() { + return delegate; + } + + @Override + public ManagedChannel build() { + if (!CheckGcpEnvironment.isOnGcp()) { + if (enableUntrustedAlts) { + logger.log( + Level.WARNING, + "Untrusted ALTS mode is enabled and we cannot guarantee the trustworthiness of the " + + "ALTS handshaker service"); + } else { + Status status = + Status.INTERNAL.withDescription("ALTS is only allowed to run on Google Cloud Platform"); + delegate().intercept(new FailingClientInterceptor(status)); + } + } + + final AltsClientOptions handshakerOptions = handshakerOptionsBuilder.build(); + TsiHandshakerFactory altsHandshakerFactory = + new TsiHandshakerFactory() { + @Override + public TsiHandshaker newHandshaker() { + // Used the shared grpc channel to connecting to the ALTS handshaker service. + // TODO: Release the channel if it is not used. + // https://github.com/grpc/grpc-java/issues/4755. + return AltsTsiHandshaker.newClient( + HandshakerServiceGrpc.newStub(handshakerChannelPool.getObject()), + handshakerOptions); + } + }; + AltsProtocolNegotiator negotiator = AltsProtocolNegotiator.create(altsHandshakerFactory); + + TcpfFactory tcpfFactory = new TcpfFactory(handshakerOptions, negotiator); + InternalNettyChannelBuilder.setDynamicTransportParamsFactory(delegate(), tcpfFactory); + tcpfFactoryForTest = tcpfFactory; + + return delegate().build(); + } + + @VisibleForTesting + @Nullable + TransportCreationParamsFilterFactory getTcpfFactoryForTest() { + return tcpfFactoryForTest; + } + + @VisibleForTesting + @Nullable + AltsClientOptions getAltsClientOptionsForTest() { + if (tcpfFactoryForTest == null) { + return null; + } + return tcpfFactoryForTest.handshakerOptions; + } + + private static final class TcpfFactory implements TransportCreationParamsFilterFactory { + + final AltsClientOptions handshakerOptions; + private final AltsProtocolNegotiator negotiator; + + public TcpfFactory(AltsClientOptions handshakerOptions, AltsProtocolNegotiator negotiator) { + this.handshakerOptions = handshakerOptions; + this.negotiator = negotiator; + } + + @Override + public TransportCreationParamsFilter create( + final SocketAddress serverAddress, + final String authority, + final String userAgent, + final ProxyParameters proxy) { + checkArgument( + serverAddress instanceof InetSocketAddress, + "%s must be a InetSocketAddress", + serverAddress); + return new TransportCreationParamsFilter() { + @Override + public SocketAddress getTargetServerAddress() { + return serverAddress; + } + + @Override + public String getAuthority() { + return authority; + } + + @Override + public String getUserAgent() { + return userAgent; + } + + @Override + public AltsProtocolNegotiator getProtocolNegotiator() { + return negotiator; + } + }; + } + } + + /** An implementation of {@link ClientInterceptor} that fails each call. */ + static final class FailingClientInterceptor implements ClientInterceptor { + + private final Status status; + + public FailingClientInterceptor(Status status) { + this.status = status; + } + + @Override + public ClientCall interceptCall( + MethodDescriptor method, CallOptions callOptions, Channel next) { + return new FailingClientCall<>(status); + } + } +} diff --git a/alts/src/main/java/io/grpc/alts/AltsServerBuilder.java b/alts/src/main/java/io/grpc/alts/AltsServerBuilder.java new file mode 100644 index 0000000000000000000000000000000000000000..a26443178e75a3bdbe3cd58c418a7e023c4f0aeb --- /dev/null +++ b/alts/src/main/java/io/grpc/alts/AltsServerBuilder.java @@ -0,0 +1,233 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts; + +import io.grpc.BindableService; +import io.grpc.CompressorRegistry; +import io.grpc.DecompressorRegistry; +import io.grpc.ExperimentalApi; +import io.grpc.HandlerRegistry; +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerBuilder; +import io.grpc.ServerCall; +import io.grpc.ServerCall.Listener; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerServiceDefinition; +import io.grpc.ServerStreamTracer.Factory; +import io.grpc.ServerTransportFilter; +import io.grpc.Status; +import io.grpc.alts.internal.AltsHandshakerOptions; +import io.grpc.alts.internal.AltsProtocolNegotiator; +import io.grpc.alts.internal.AltsTsiHandshaker; +import io.grpc.alts.internal.HandshakerServiceGrpc; +import io.grpc.alts.internal.RpcProtocolVersionsUtil; +import io.grpc.alts.internal.TsiHandshaker; +import io.grpc.alts.internal.TsiHandshakerFactory; +import io.grpc.internal.ObjectPool; +import io.grpc.internal.SharedResourcePool; +import io.grpc.netty.NettyServerBuilder; +import java.io.File; +import java.net.InetSocketAddress; +import java.util.concurrent.Executor; +import java.util.concurrent.TimeUnit; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * gRPC secure server builder used for ALTS. This class adds on the necessary ALTS support to create + * a production server on Google Cloud Platform. + */ +@ExperimentalApi("https://github.com/grpc/grpc-java/issues/4151") +public final class AltsServerBuilder extends ServerBuilder { + + private static final Logger logger = Logger.getLogger(AltsServerBuilder.class.getName()); + private final NettyServerBuilder delegate; + private ObjectPool handshakerChannelPool = + SharedResourcePool.forResource(HandshakerServiceChannel.SHARED_HANDSHAKER_CHANNEL); + private boolean enableUntrustedAlts; + + private AltsServerBuilder(NettyServerBuilder nettyDelegate) { + this.delegate = nettyDelegate; + } + + /** Creates a gRPC server builder for the given port. */ + public static AltsServerBuilder forPort(int port) { + NettyServerBuilder nettyDelegate = + NettyServerBuilder.forAddress(new InetSocketAddress(port)) + .maxConnectionIdle(1, TimeUnit.HOURS) + .keepAliveTime(270, TimeUnit.SECONDS) + .keepAliveTimeout(20, TimeUnit.SECONDS) + .permitKeepAliveTime(10, TimeUnit.SECONDS) + .permitKeepAliveWithoutCalls(true); + return new AltsServerBuilder(nettyDelegate); + } + + /** + * Enables untrusted ALTS for testing. If this function is called, we will not check whether ALTS + * is running on Google Cloud Platform. + */ + public AltsServerBuilder enableUntrustedAltsForTesting() { + enableUntrustedAlts = true; + return this; + } + + /** Sets a new handshaker service address for testing. */ + public AltsServerBuilder setHandshakerAddressForTesting(String handshakerAddress) { + // Instead of using the default shared channel to the handshaker service, create a fix object + // pool of handshaker service channel for testing. + handshakerChannelPool = + HandshakerServiceChannel.getHandshakerChannelPoolForTesting(handshakerAddress); + return this; + } + + /** {@inheritDoc} */ + @Override + public AltsServerBuilder handshakeTimeout(long timeout, TimeUnit unit) { + delegate.handshakeTimeout(timeout, unit); + return this; + } + + /** {@inheritDoc} */ + @Override + public AltsServerBuilder directExecutor() { + delegate.directExecutor(); + return this; + } + + /** {@inheritDoc} */ + @Override + public AltsServerBuilder addStreamTracerFactory(Factory factory) { + delegate.addStreamTracerFactory(factory); + return this; + } + + /** {@inheritDoc} */ + @Override + public AltsServerBuilder addTransportFilter(ServerTransportFilter filter) { + delegate.addTransportFilter(filter); + return this; + } + + /** {@inheritDoc} */ + @Override + public AltsServerBuilder executor(Executor executor) { + delegate.executor(executor); + return this; + } + + /** {@inheritDoc} */ + @Override + public AltsServerBuilder addService(ServerServiceDefinition service) { + delegate.addService(service); + return this; + } + + /** {@inheritDoc} */ + @Override + public AltsServerBuilder addService(BindableService bindableService) { + delegate.addService(bindableService); + return this; + } + + /** {@inheritDoc} */ + @Override + public AltsServerBuilder fallbackHandlerRegistry(HandlerRegistry fallbackRegistry) { + delegate.fallbackHandlerRegistry(fallbackRegistry); + return this; + } + + /** {@inheritDoc} */ + @Override + public AltsServerBuilder useTransportSecurity(File certChain, File privateKey) { + throw new UnsupportedOperationException("Can't set TLS settings for ALTS"); + } + + /** {@inheritDoc} */ + @Override + public AltsServerBuilder decompressorRegistry(DecompressorRegistry registry) { + delegate.decompressorRegistry(registry); + return this; + } + + /** {@inheritDoc} */ + @Override + public AltsServerBuilder compressorRegistry(CompressorRegistry registry) { + delegate.compressorRegistry(registry); + return this; + } + + /** {@inheritDoc} */ + @Override + public AltsServerBuilder intercept(ServerInterceptor interceptor) { + delegate.intercept(interceptor); + return this; + } + + /** {@inheritDoc} */ + @Override + public Server build() { + if (!CheckGcpEnvironment.isOnGcp()) { + if (enableUntrustedAlts) { + logger.log( + Level.WARNING, + "Untrusted ALTS mode is enabled and we cannot guarantee the trustworthiness of the " + + "ALTS handshaker service"); + } else { + Status status = + Status.INTERNAL.withDescription("ALTS is only allowed to run on Google Cloud Platform"); + delegate.intercept(new FailingServerInterceptor(status)); + } + } + + delegate.protocolNegotiator( + AltsProtocolNegotiator.create( + new TsiHandshakerFactory() { + @Override + public TsiHandshaker newHandshaker() { + // Used the shared grpc channel to connecting to the ALTS handshaker service. + // TODO: Release the channel if it is not used. + // https://github.com/grpc/grpc-java/issues/4755. + return AltsTsiHandshaker.newServer( + HandshakerServiceGrpc.newStub(handshakerChannelPool.getObject()), + new AltsHandshakerOptions(RpcProtocolVersionsUtil.getRpcProtocolVersions())); + } + })); + return delegate.build(); + } + + /** An implementation of {@link ServerInterceptor} that fails each call. */ + static final class FailingServerInterceptor implements ServerInterceptor { + + private final Status status; + + public FailingServerInterceptor(Status status) { + this.status = status; + } + + @Override + public Listener interceptCall( + ServerCall serverCall, + Metadata metadata, + ServerCallHandler nextHandler) { + serverCall.close(status, new Metadata()); + return new Listener() {}; + } + } +} diff --git a/alts/src/main/java/io/grpc/alts/CheckGcpEnvironment.java b/alts/src/main/java/io/grpc/alts/CheckGcpEnvironment.java new file mode 100644 index 0000000000000000000000000000000000000000..1533415f6b0ab51dde78eaa445e1ef352fd5a44c --- /dev/null +++ b/alts/src/main/java/io/grpc/alts/CheckGcpEnvironment.java @@ -0,0 +1,88 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts; + +import static java.nio.charset.StandardCharsets.UTF_8; + +import com.google.common.annotations.VisibleForTesting; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.apache.commons.lang3.SystemUtils; + +/** Class for checking if the system is running on Google Cloud Platform (GCP). */ +final class CheckGcpEnvironment { + + private static final Logger logger = Logger.getLogger(CheckGcpEnvironment.class.getName()); + private static final String DMI_PRODUCT_NAME = "/sys/class/dmi/id/product_name"; + private static final String WINDOWS_COMMAND = "powershell.exe"; + private static Boolean cachedResult = null; + + // Construct me not! + private CheckGcpEnvironment() {} + + static synchronized boolean isOnGcp() { + if (cachedResult == null) { + cachedResult = isRunningOnGcp(); + } + return cachedResult; + } + + @VisibleForTesting + static boolean checkProductNameOnLinux(BufferedReader reader) throws IOException { + String name = reader.readLine().trim(); + return name.equals("Google") || name.equals("Google Compute Engine"); + } + + @VisibleForTesting + static boolean checkBiosDataOnWindows(BufferedReader reader) throws IOException { + String line; + while ((line = reader.readLine()) != null) { + if (line.startsWith("Manufacturer")) { + String name = line.substring(line.indexOf(':') + 1).trim(); + return name.equals("Google"); + } + } + return false; + } + + private static boolean isRunningOnGcp() { + try { + if (SystemUtils.IS_OS_LINUX) { + // Checks GCE residency on Linux platform. + return checkProductNameOnLinux(Files.newBufferedReader(Paths.get(DMI_PRODUCT_NAME), UTF_8)); + } else if (SystemUtils.IS_OS_WINDOWS) { + // Checks GCE residency on Windows platform. + Process p = + new ProcessBuilder() + .command(WINDOWS_COMMAND, "Get-WmiObject", "-Class", "Win32_BIOS") + .start(); + return checkBiosDataOnWindows( + new BufferedReader(new InputStreamReader(p.getInputStream(), UTF_8))); + } + } catch (IOException e) { + logger.log(Level.WARNING, "Fail to read platform information: ", e); + return false; + } + // Platforms other than Linux and Windows are not supported. + return false; + } +} diff --git a/alts/src/main/java/io/grpc/alts/FailingClientCall.java b/alts/src/main/java/io/grpc/alts/FailingClientCall.java new file mode 100644 index 0000000000000000000000000000000000000000..ab674364ee64f69761fdc3850f846117c8101547 --- /dev/null +++ b/alts/src/main/java/io/grpc/alts/FailingClientCall.java @@ -0,0 +1,48 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts; + +import io.grpc.ClientCall; +import io.grpc.Metadata; +import io.grpc.Status; + +/** An implementation of {@link ClientCall} that fails when started. */ +final class FailingClientCall extends ClientCall { + + private final Status error; + + public FailingClientCall(Status error) { + this.error = error; + } + + @Override + public void start(ClientCall.Listener listener, Metadata headers) { + listener.onClose(error, new Metadata()); + } + + @Override + public void request(int numMessages) {} + + @Override + public void cancel(String message, Throwable cause) {} + + @Override + public void halfClose() {} + + @Override + public void sendMessage(ReqT message) {} +} diff --git a/alts/src/main/java/io/grpc/alts/GoogleDefaultChannelBuilder.java b/alts/src/main/java/io/grpc/alts/GoogleDefaultChannelBuilder.java new file mode 100644 index 0000000000000000000000000000000000000000..619ce04c7471a47ae145bf925b9583799df0ff94 --- /dev/null +++ b/alts/src/main/java/io/grpc/alts/GoogleDefaultChannelBuilder.java @@ -0,0 +1,195 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts; + +import static com.google.common.base.Preconditions.checkArgument; + +import com.google.auth.oauth2.GoogleCredentials; +import com.google.common.annotations.VisibleForTesting; +import io.grpc.CallCredentials; +import io.grpc.CallOptions; +import io.grpc.Channel; +import io.grpc.ClientCall; +import io.grpc.ClientInterceptor; +import io.grpc.ForwardingChannelBuilder; +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; +import io.grpc.MethodDescriptor; +import io.grpc.Status; +import io.grpc.alts.internal.AltsClientOptions; +import io.grpc.alts.internal.AltsTsiHandshaker; +import io.grpc.alts.internal.GoogleDefaultProtocolNegotiator; +import io.grpc.alts.internal.HandshakerServiceGrpc; +import io.grpc.alts.internal.RpcProtocolVersionsUtil; +import io.grpc.alts.internal.TsiHandshaker; +import io.grpc.alts.internal.TsiHandshakerFactory; +import io.grpc.auth.MoreCallCredentials; +import io.grpc.internal.GrpcUtil; +import io.grpc.internal.ProxyParameters; +import io.grpc.internal.SharedResourceHolder; +import io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.InternalNettyChannelBuilder; +import io.grpc.netty.InternalNettyChannelBuilder.TransportCreationParamsFilter; +import io.grpc.netty.InternalNettyChannelBuilder.TransportCreationParamsFilterFactory; +import io.grpc.netty.NettyChannelBuilder; +import io.netty.handler.ssl.SslContext; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.SocketAddress; +import javax.annotation.Nullable; +import javax.net.ssl.SSLException; + +/** + * Google default version of {@code ManagedChannelBuilder}. This class sets up a secure channel + * using ALTS if applicable and using TLS as fallback. + */ +public final class GoogleDefaultChannelBuilder + extends ForwardingChannelBuilder { + + private final NettyChannelBuilder delegate; + private final TcpfFactory tcpfFactory; + + private GoogleDefaultChannelBuilder(String target) { + delegate = NettyChannelBuilder.forTarget(target); + + final AltsClientOptions handshakerOptions = + new AltsClientOptions.Builder() + .setRpcProtocolVersions(RpcProtocolVersionsUtil.getRpcProtocolVersions()) + .build(); + TsiHandshakerFactory altsHandshakerFactory = + new TsiHandshakerFactory() { + @Override + public TsiHandshaker newHandshaker() { + // Used the shared grpc channel to connecting to the ALTS handshaker service. + // TODO: Release the channel if it is not used. + // https://github.com/grpc/grpc-java/issues/4755. + ManagedChannel channel = + SharedResourceHolder.get(HandshakerServiceChannel.SHARED_HANDSHAKER_CHANNEL); + return AltsTsiHandshaker.newClient( + HandshakerServiceGrpc.newStub(channel), handshakerOptions); + } + }; + SslContext sslContext; + try { + sslContext = GrpcSslContexts.forClient().build(); + } catch (SSLException ex) { + throw new RuntimeException(ex); + } + tcpfFactory = new TcpfFactory( + new GoogleDefaultProtocolNegotiator(altsHandshakerFactory, sslContext)); + InternalNettyChannelBuilder.setDynamicTransportParamsFactory(delegate(), tcpfFactory); + } + + /** "Overrides" the static method in {@link ManagedChannelBuilder}. */ + public static final GoogleDefaultChannelBuilder forTarget(String target) { + return new GoogleDefaultChannelBuilder(target); + } + + /** "Overrides" the static method in {@link ManagedChannelBuilder}. */ + public static GoogleDefaultChannelBuilder forAddress(String name, int port) { + return forTarget(GrpcUtil.authorityFromHostAndPort(name, port)); + } + + @Override + protected NettyChannelBuilder delegate() { + return delegate; + } + + @Override + public ManagedChannel build() { + @Nullable CallCredentials credentials = null; + Status status = Status.OK; + try { + credentials = MoreCallCredentials.from(GoogleCredentials.getApplicationDefault()); + } catch (IOException e) { + status = + Status.UNAUTHENTICATED + .withDescription("Failed to get Google default credentials") + .withCause(e); + } + return delegate().intercept(new GoogleDefaultInterceptor(credentials, status)).build(); + } + + @VisibleForTesting + TransportCreationParamsFilterFactory getTcpfFactoryForTest() { + return tcpfFactory; + } + + private static final class TcpfFactory implements TransportCreationParamsFilterFactory { + private final GoogleDefaultProtocolNegotiator negotiator; + + private TcpfFactory(GoogleDefaultProtocolNegotiator negotiator) { + this.negotiator = negotiator; + } + + @Override + public TransportCreationParamsFilter create( + final SocketAddress serverAddress, + final String authority, + final String userAgent, + final ProxyParameters proxy) { + checkArgument( + serverAddress instanceof InetSocketAddress, + "%s must be a InetSocketAddress", + serverAddress); + return new TransportCreationParamsFilter() { + @Override + public SocketAddress getTargetServerAddress() { + return serverAddress; + } + + @Override + public String getAuthority() { + return authority; + } + + @Override + public String getUserAgent() { + return userAgent; + } + + @Override + public GoogleDefaultProtocolNegotiator getProtocolNegotiator() { + return negotiator; + } + }; + } + } + + /** + * An implementation of {@link ClientInterceptor} that adds Google call credentials on each call. + */ + static final class GoogleDefaultInterceptor implements ClientInterceptor { + + @Nullable private final CallCredentials credentials; + private final Status status; + + public GoogleDefaultInterceptor(@Nullable CallCredentials credentials, Status status) { + this.credentials = credentials; + this.status = status; + } + + @Override + public ClientCall interceptCall( + MethodDescriptor method, CallOptions callOptions, Channel next) { + if (!status.isOk()) { + return new FailingClientCall<>(status); + } + return next.newCall(method, callOptions.withCallCredentials(credentials)); + } + } +} diff --git a/alts/src/main/java/io/grpc/alts/HandshakerServiceChannel.java b/alts/src/main/java/io/grpc/alts/HandshakerServiceChannel.java new file mode 100644 index 0000000000000000000000000000000000000000..7472112e38ee2f368af134e80693960fee4d8b72 --- /dev/null +++ b/alts/src/main/java/io/grpc/alts/HandshakerServiceChannel.java @@ -0,0 +1,81 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts; + +import io.grpc.ManagedChannel; +import io.grpc.internal.FixedObjectPool; +import io.grpc.internal.SharedResourceHolder.Resource; +import io.grpc.netty.NettyChannelBuilder; +import io.netty.channel.EventLoopGroup; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.util.concurrent.DefaultThreadFactory; +import java.util.concurrent.ThreadFactory; + +/** + * Class for creating a single shared gRPC channel to the ALTS Handshaker Service using + * SharedResourceHolder. The channel to the handshaker service is local and is over plaintext. Each + * application will have at most one connection to the handshaker service. + */ +final class HandshakerServiceChannel { + + static final Resource SHARED_HANDSHAKER_CHANNEL = + new Resource() { + + private EventLoopGroup eventGroup = null; + + @Override + public ManagedChannel create() { + /* Use its own event loop thread pool to avoid blocking. */ + if (eventGroup == null) { + eventGroup = + new NioEventLoopGroup(1, new DefaultThreadFactory("handshaker pool", true)); + } + return NettyChannelBuilder.forTarget("metadata.google.internal:8080") + .directExecutor() + .eventLoopGroup(eventGroup) + .usePlaintext() + .build(); + } + + @Override + @SuppressWarnings("FutureReturnValueIgnored") // netty ChannelFuture + public void close(ManagedChannel instance) { + instance.shutdownNow(); + if (eventGroup != null) { + eventGroup.shutdownGracefully(); + } + } + + @Override + public String toString() { + return "grpc-alts-handshaker-service-channel"; + } + }; + + /** Returns a fixed object pool of handshaker service channel for testing only. */ + static FixedObjectPool getHandshakerChannelPoolForTesting( + String handshakerAddress) { + ThreadFactory clientThreadFactory = new DefaultThreadFactory("handshaker pool", true); + ManagedChannel channel = + NettyChannelBuilder.forTarget(handshakerAddress) + .directExecutor() + .eventLoopGroup(new NioEventLoopGroup(1, clientThreadFactory)) + .usePlaintext() + .build(); + return new FixedObjectPool(channel); + } +} diff --git a/alts/src/main/java/io/grpc/alts/internal/AeadCrypter.java b/alts/src/main/java/io/grpc/alts/internal/AeadCrypter.java new file mode 100644 index 0000000000000000000000000000000000000000..4d99187c33deb91bce98cd8e68bd8789b45eea04 --- /dev/null +++ b/alts/src/main/java/io/grpc/alts/internal/AeadCrypter.java @@ -0,0 +1,76 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import java.nio.ByteBuffer; +import java.security.GeneralSecurityException; + +/** + * {@code AeadCrypter} performs authenticated encryption and decryption for a fixed key given unique + * nonces. Authenticated additional data is supported. + */ +interface AeadCrypter { + /** + * Encrypt plaintext into ciphertext buffer using the given nonce. + * + * @param ciphertext the encrypted plaintext and the tag will be written into this buffer. + * @param plaintext the input that should be encrypted. + * @param nonce the unique nonce used for the encryption. + * @throws GeneralSecurityException if ciphertext buffer is short or the nonce does not have the + * expected size. + */ + void encrypt(ByteBuffer ciphertext, ByteBuffer plaintext, byte[] nonce) + throws GeneralSecurityException; + + /** + * Encrypt plaintext into ciphertext buffer using the given nonce with authenticated data. + * + * @param ciphertext the encrypted plaintext and the tag will be written into this buffer. + * @param plaintext the input that should be encrypted. + * @param aad additional data that should be authenticated, but not encrypted. + * @param nonce the unique nonce used for the encryption. + * @throws GeneralSecurityException if ciphertext buffer is short or the nonce does not have the + * expected size. + */ + void encrypt(ByteBuffer ciphertext, ByteBuffer plaintext, ByteBuffer aad, byte[] nonce) + throws GeneralSecurityException; + + /** + * Decrypt ciphertext into plaintext buffer using the given nonce. + * + * @param plaintext the decrypted plaintext will be written into this buffer. + * @param ciphertext the ciphertext and tag that should be decrypted. + * @param nonce the nonce that was used for the encryption. + * @throws GeneralSecurityException if the tag is invalid or any of the inputs do not have the + * expected size. + */ + void decrypt(ByteBuffer plaintext, ByteBuffer ciphertext, byte[] nonce) + throws GeneralSecurityException; + + /** + * Decrypt ciphertext into plaintext buffer using the given nonce. + * + * @param plaintext the decrypted plaintext will be written into this buffer. + * @param ciphertext the ciphertext and tag that should be decrypted. + * @param aad additional data that is checked for authenticity. + * @param nonce the nonce that was used for the encryption. + * @throws GeneralSecurityException if the tag is invalid or any of the inputs do not have the + * expected size. + */ + void decrypt(ByteBuffer plaintext, ByteBuffer ciphertext, ByteBuffer aad, byte[] nonce) + throws GeneralSecurityException; +} diff --git a/alts/src/main/java/io/grpc/alts/internal/AesGcmAeadCrypter.java b/alts/src/main/java/io/grpc/alts/internal/AesGcmAeadCrypter.java new file mode 100644 index 0000000000000000000000000000000000000000..f3b968f1312e5e11bb654b1be4bd9bc8b04c5f27 --- /dev/null +++ b/alts/src/main/java/io/grpc/alts/internal/AesGcmAeadCrypter.java @@ -0,0 +1,101 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import static com.google.common.base.Preconditions.checkArgument; + +import java.nio.ByteBuffer; +import java.security.GeneralSecurityException; +import javax.annotation.Nullable; +import javax.crypto.Cipher; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +/** AES128-GCM implementation of {@link AeadCrypter} that uses default JCE provider. */ +final class AesGcmAeadCrypter implements AeadCrypter { + private static final int KEY_LENGTH = 16; + private static final int TAG_LENGTH = 16; + static final int NONCE_LENGTH = 12; + + private static final String AES = "AES"; + private static final String AES_GCM = AES + "/GCM/NoPadding"; + + private final byte[] key; + private final Cipher cipher; + + AesGcmAeadCrypter(byte[] key) throws GeneralSecurityException { + checkArgument(key.length == KEY_LENGTH); + this.key = key; + cipher = Cipher.getInstance(AES_GCM); + } + + private int encryptAad( + ByteBuffer ciphertext, ByteBuffer plaintext, @Nullable ByteBuffer aad, byte[] nonce) + throws GeneralSecurityException { + checkArgument(nonce.length == NONCE_LENGTH); + cipher.init( + Cipher.ENCRYPT_MODE, + new SecretKeySpec(this.key, AES), + new GCMParameterSpec(TAG_LENGTH * 8, nonce)); + if (aad != null) { + cipher.updateAAD(aad); + } + return cipher.doFinal(plaintext, ciphertext); + } + + private void decryptAad( + ByteBuffer plaintext, ByteBuffer ciphertext, @Nullable ByteBuffer aad, byte[] nonce) + throws GeneralSecurityException { + checkArgument(nonce.length == NONCE_LENGTH); + cipher.init( + Cipher.DECRYPT_MODE, + new SecretKeySpec(this.key, AES), + new GCMParameterSpec(TAG_LENGTH * 8, nonce)); + if (aad != null) { + cipher.updateAAD(aad); + } + cipher.doFinal(ciphertext, plaintext); + } + + @Override + public void encrypt(ByteBuffer ciphertext, ByteBuffer plaintext, byte[] nonce) + throws GeneralSecurityException { + encryptAad(ciphertext, plaintext, null, nonce); + } + + @Override + public void encrypt(ByteBuffer ciphertext, ByteBuffer plaintext, ByteBuffer aad, byte[] nonce) + throws GeneralSecurityException { + encryptAad(ciphertext, plaintext, aad, nonce); + } + + @Override + public void decrypt(ByteBuffer plaintext, ByteBuffer ciphertext, byte[] nonce) + throws GeneralSecurityException { + decryptAad(plaintext, ciphertext, null, nonce); + } + + @Override + public void decrypt(ByteBuffer plaintext, ByteBuffer ciphertext, ByteBuffer aad, byte[] nonce) + throws GeneralSecurityException { + decryptAad(plaintext, ciphertext, aad, nonce); + } + + static int getKeyLength() { + return KEY_LENGTH; + } +} diff --git a/alts/src/main/java/io/grpc/alts/internal/AesGcmHkdfAeadCrypter.java b/alts/src/main/java/io/grpc/alts/internal/AesGcmHkdfAeadCrypter.java new file mode 100644 index 0000000000000000000000000000000000000000..b0f7535d35a3047836b883085049ad40c813635c --- /dev/null +++ b/alts/src/main/java/io/grpc/alts/internal/AesGcmHkdfAeadCrypter.java @@ -0,0 +1,127 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import static com.google.common.base.Preconditions.checkArgument; + +import java.nio.ByteBuffer; +import java.security.GeneralSecurityException; +import java.util.Arrays; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; + +/** + * {@link AeadCrypter} implementation based on {@link AesGcmAeadCrypter} with nonce-based rekeying + * using HKDF-expand and random nonce-mask that is XORed with the given nonce/counter. The AES-GCM + * key is computed as HKDF-expand(kdfKey, nonce[2..7]), i.e., the first 2 bytes are ignored to + * require rekeying only after 2^16 operations and the last 4 bytes (including the direction bit) + * are ignored to allow for optimizations (use same AEAD context for both directions, store counter + * as unsigned long and boolean for direction). + */ +final class AesGcmHkdfAeadCrypter implements AeadCrypter { + private static final int KDF_KEY_LENGTH = 32; + // Rekey after 2^(2*8) = 2^16 operations by ignoring the first 2 nonce bytes for key derivation. + private static final int KDF_COUNTER_OFFSET = 2; + // Use remaining bytes of 64-bit counter included in nonce for key derivation. + private static final int KDF_COUNTER_LENGTH = 6; + private static final int NONCE_LENGTH = AesGcmAeadCrypter.NONCE_LENGTH; + private static final int KEY_LENGTH = KDF_KEY_LENGTH + NONCE_LENGTH; + + private final byte[] kdfKey; + private final byte[] kdfCounter = new byte[KDF_COUNTER_LENGTH]; + private final byte[] nonceMask; + private final byte[] nonceBuffer = new byte[NONCE_LENGTH]; + + private AeadCrypter aeadCrypter; + + AesGcmHkdfAeadCrypter(byte[] key) { + checkArgument(key.length == KEY_LENGTH); + this.kdfKey = Arrays.copyOf(key, KDF_KEY_LENGTH); + this.nonceMask = Arrays.copyOfRange(key, KDF_KEY_LENGTH, KDF_KEY_LENGTH + NONCE_LENGTH); + } + + @Override + public void encrypt(ByteBuffer ciphertext, ByteBuffer plaintext, byte[] nonce) + throws GeneralSecurityException { + maybeRekey(nonce); + maskNonce(nonceBuffer, nonceMask, nonce); + aeadCrypter.encrypt(ciphertext, plaintext, nonceBuffer); + } + + @Override + public void encrypt(ByteBuffer ciphertext, ByteBuffer plaintext, ByteBuffer aad, byte[] nonce) + throws GeneralSecurityException { + maybeRekey(nonce); + maskNonce(nonceBuffer, nonceMask, nonce); + aeadCrypter.encrypt(ciphertext, plaintext, aad, nonceBuffer); + } + + @Override + public void decrypt(ByteBuffer plaintext, ByteBuffer ciphertext, byte[] nonce) + throws GeneralSecurityException { + maybeRekey(nonce); + maskNonce(nonceBuffer, nonceMask, nonce); + aeadCrypter.decrypt(plaintext, ciphertext, nonceBuffer); + } + + @Override + public void decrypt(ByteBuffer plaintext, ByteBuffer ciphertext, ByteBuffer aad, byte[] nonce) + throws GeneralSecurityException { + maybeRekey(nonce); + maskNonce(nonceBuffer, nonceMask, nonce); + aeadCrypter.decrypt(plaintext, ciphertext, aad, nonceBuffer); + } + + private void maybeRekey(byte[] nonce) throws GeneralSecurityException { + if (aeadCrypter != null + && arrayEqualOn(nonce, KDF_COUNTER_OFFSET, kdfCounter, 0, KDF_COUNTER_LENGTH)) { + return; + } + System.arraycopy(nonce, KDF_COUNTER_OFFSET, kdfCounter, 0, KDF_COUNTER_LENGTH); + int aeKeyLen = AesGcmAeadCrypter.getKeyLength(); + byte[] aeKey = Arrays.copyOf(hkdfExpandSha256(kdfKey, kdfCounter), aeKeyLen); + aeadCrypter = new AesGcmAeadCrypter(aeKey); + } + + private static void maskNonce(byte[] nonceBuffer, byte[] nonceMask, byte[] nonce) { + checkArgument(nonce.length == NONCE_LENGTH); + for (int i = 0; i < NONCE_LENGTH; i++) { + nonceBuffer[i] = (byte) (nonceMask[i] ^ nonce[i]); + } + } + + private static byte[] hkdfExpandSha256(byte[] key, byte[] info) throws GeneralSecurityException { + Mac mac = Mac.getInstance("HMACSHA256"); + mac.init(new SecretKeySpec(key, mac.getAlgorithm())); + mac.update(info); + mac.update((byte) 0x01); + return mac.doFinal(); + } + + private static boolean arrayEqualOn(byte[] a, int aPos, byte[] b, int bPos, int length) { + for (int i = 0; i < length; i++) { + if (a[aPos + i] != b[bPos + i]) { + return false; + } + } + return true; + } + + static int getKeyLength() { + return KEY_LENGTH; + } +} diff --git a/alts/src/main/java/io/grpc/alts/internal/AltsAuthContext.java b/alts/src/main/java/io/grpc/alts/internal/AltsAuthContext.java new file mode 100644 index 0000000000000000000000000000000000000000..cc335fe96d70ee3c33044045be5c2ec5283eb8c6 --- /dev/null +++ b/alts/src/main/java/io/grpc/alts/internal/AltsAuthContext.java @@ -0,0 +1,101 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import com.google.common.annotations.VisibleForTesting; +import io.grpc.alts.internal.Altscontext.AltsContext; +import io.grpc.alts.internal.Handshaker.HandshakerResult; +import io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions; +import io.grpc.alts.internal.TransportSecurityCommon.SecurityLevel; + +/** AltsAuthContext contains security-related context information about an ALTs connection. */ +public final class AltsAuthContext { + final AltsContext context; + + /** Create a new AltsAuthContext. */ + public AltsAuthContext(HandshakerResult result) { + context = + AltsContext.newBuilder() + .setApplicationProtocol(result.getApplicationProtocol()) + .setRecordProtocol(result.getRecordProtocol()) + // TODO: Set security level based on the handshaker result. + .setSecurityLevel(SecurityLevel.INTEGRITY_AND_PRIVACY) + .setPeerServiceAccount(result.getPeerIdentity().getServiceAccount()) + .setLocalServiceAccount(result.getLocalIdentity().getServiceAccount()) + .setPeerRpcVersions(result.getPeerRpcVersions()) + .build(); + } + + @VisibleForTesting + public static AltsAuthContext getDefaultInstance() { + return new AltsAuthContext(HandshakerResult.newBuilder().build()); + } + + /** + * Get application protocol. + * + * @return the context's application protocol. + */ + public String getApplicationProtocol() { + return context.getApplicationProtocol(); + } + + /** + * Get negotiated record protocol. + * + * @return the context's negotiated record protocol. + */ + public String getRecordProtocol() { + return context.getRecordProtocol(); + } + + /** + * Get security level. + * + * @return the context's security level. + */ + public SecurityLevel getSecurityLevel() { + return context.getSecurityLevel(); + } + + /** + * Get peer service account. + * + * @return the context's peer service account. + */ + public String getPeerServiceAccount() { + return context.getPeerServiceAccount(); + } + + /** + * Get local service account. + * + * @return the context's local service account. + */ + public String getLocalServiceAccount() { + return context.getLocalServiceAccount(); + } + + /** + * Get peer RPC versions. + * + * @return the context's peer RPC versions. + */ + public RpcProtocolVersions getPeerRpcVersions() { + return context.getPeerRpcVersions(); + } +} diff --git a/alts/src/main/java/io/grpc/alts/internal/AltsChannelCrypter.java b/alts/src/main/java/io/grpc/alts/internal/AltsChannelCrypter.java new file mode 100644 index 0000000000000000000000000000000000000000..3e999fa63b45566eb1d3ba1aa0e08f1be5f500b6 --- /dev/null +++ b/alts/src/main/java/io/grpc/alts/internal/AltsChannelCrypter.java @@ -0,0 +1,171 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Verify.verify; + +import com.google.common.annotations.VisibleForTesting; +import io.netty.buffer.ByteBuf; +import java.nio.ByteBuffer; +import java.security.GeneralSecurityException; +import java.util.List; + +/** Performs encryption and decryption with AES-GCM using JCE. All methods are thread-compatible. */ +final class AltsChannelCrypter implements ChannelCrypterNetty { + private static final int KEY_LENGTH = AesGcmHkdfAeadCrypter.getKeyLength(); + private static final int COUNTER_LENGTH = 12; + // The counter will overflow after 2^64 operations and encryption/decryption will stop working. + private static final int COUNTER_OVERFLOW_LENGTH = 8; + private static final int TAG_LENGTH = 16; + + private final AeadCrypter aeadCrypter; + + private final byte[] outCounter = new byte[COUNTER_LENGTH]; + private final byte[] inCounter = new byte[COUNTER_LENGTH]; + private final byte[] oldCounter = new byte[COUNTER_LENGTH]; + + AltsChannelCrypter(byte[] key, boolean isClient) { + checkArgument(key.length == KEY_LENGTH); + byte[] counter = isClient ? inCounter : outCounter; + counter[counter.length - 1] = (byte) 0x80; + this.aeadCrypter = new AesGcmHkdfAeadCrypter(key); + } + + static int getKeyLength() { + return KEY_LENGTH; + } + + static int getCounterLength() { + return COUNTER_LENGTH; + } + + @SuppressWarnings("BetaApi") // verify is stable in Guava + @Override + public void encrypt(ByteBuf outBuf, List plainBufs) throws GeneralSecurityException { + checkArgument(outBuf.nioBufferCount() == 1); + // Copy plaintext buffers into outBuf for in-place encryption on single direct buffer. + ByteBuf plainBuf = outBuf.slice(outBuf.writerIndex(), outBuf.writableBytes()); + plainBuf.writerIndex(0); + for (ByteBuf inBuf : plainBufs) { + plainBuf.writeBytes(inBuf); + } + + verify(outBuf.writableBytes() == plainBuf.readableBytes() + TAG_LENGTH); + ByteBuffer out = outBuf.internalNioBuffer(outBuf.writerIndex(), outBuf.writableBytes()); + ByteBuffer plain = out.duplicate(); + plain.limit(out.limit() - TAG_LENGTH); + + byte[] counter = incrementOutCounter(); + int outPosition = out.position(); + aeadCrypter.encrypt(out, plain, counter); + int bytesWritten = out.position() - outPosition; + outBuf.writerIndex(outBuf.writerIndex() + bytesWritten); + verify(!outBuf.isWritable()); + } + + @Override + public void decrypt(ByteBuf out, ByteBuf tag, List ciphertextBufs) + throws GeneralSecurityException { + + ByteBuf cipherTextAndTag = out.slice(out.writerIndex(), out.writableBytes()); + cipherTextAndTag.writerIndex(0); + + for (ByteBuf inBuf : ciphertextBufs) { + cipherTextAndTag.writeBytes(inBuf); + } + cipherTextAndTag.writeBytes(tag); + + decrypt(out, cipherTextAndTag); + } + + @SuppressWarnings("BetaApi") // verify is stable in Guava + @Override + public void decrypt(ByteBuf out, ByteBuf ciphertextAndTag) throws GeneralSecurityException { + int bytesRead = ciphertextAndTag.readableBytes(); + checkArgument(bytesRead == out.writableBytes()); + + checkArgument(out.nioBufferCount() == 1); + ByteBuffer outBuffer = out.internalNioBuffer(out.writerIndex(), out.writableBytes()); + + checkArgument(ciphertextAndTag.nioBufferCount() == 1); + ByteBuffer ciphertextAndTagBuffer = + ciphertextAndTag.nioBuffer(ciphertextAndTag.readerIndex(), bytesRead); + + byte[] counter = incrementInCounter(); + int outPosition = outBuffer.position(); + aeadCrypter.decrypt(outBuffer, ciphertextAndTagBuffer, counter); + int bytesWritten = outBuffer.position() - outPosition; + out.writerIndex(out.writerIndex() + bytesWritten); + ciphertextAndTag.readerIndex(out.readerIndex() + bytesRead); + verify(out.writableBytes() == TAG_LENGTH); + } + + @Override + public int getSuffixLength() { + return TAG_LENGTH; + } + + @Override + public void destroy() { + // no destroy required + } + + /** Increments {@code counter}, store the unincremented value in {@code oldCounter}. */ + static void incrementCounter(byte[] counter, byte[] oldCounter) throws GeneralSecurityException { + System.arraycopy(counter, 0, oldCounter, 0, counter.length); + int i = 0; + for (; i < COUNTER_OVERFLOW_LENGTH; i++) { + counter[i]++; + if (counter[i] != (byte) 0x00) { + break; + } + } + + if (i == COUNTER_OVERFLOW_LENGTH) { + // Restore old counter value to ensure that encrypt and decrypt keep failing. + System.arraycopy(oldCounter, 0, counter, 0, counter.length); + throw new GeneralSecurityException("Counter has overflowed."); + } + } + + /** Increments the input counter, returning the previous (unincremented) value. */ + private byte[] incrementInCounter() throws GeneralSecurityException { + incrementCounter(inCounter, oldCounter); + return oldCounter; + } + + /** Increments the output counter, returning the previous (unincremented) value. */ + private byte[] incrementOutCounter() throws GeneralSecurityException { + incrementCounter(outCounter, oldCounter); + return oldCounter; + } + + @VisibleForTesting + void incrementInCounterForTesting(int n) throws GeneralSecurityException { + for (int i = 0; i < n; i++) { + incrementInCounter(); + } + } + + @VisibleForTesting + void incrementOutCounterForTesting(int n) throws GeneralSecurityException { + for (int i = 0; i < n; i++) { + incrementOutCounter(); + } + } +} diff --git a/alts/src/main/java/io/grpc/alts/internal/AltsClientOptions.java b/alts/src/main/java/io/grpc/alts/internal/AltsClientOptions.java new file mode 100644 index 0000000000000000000000000000000000000000..e0e506a08c5f53e17a14baa6885160f95207c251 --- /dev/null +++ b/alts/src/main/java/io/grpc/alts/internal/AltsClientOptions.java @@ -0,0 +1,75 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import javax.annotation.Nullable; + +/** Handshaker options for creating ALTS client channel. */ +public final class AltsClientOptions extends AltsHandshakerOptions { + // targetName is the server service account name for secure name checking. This field is not yet + // supported. + @Nullable private final String targetName; + // targetServiceAccounts contains a list of expected target service accounts. One of these service + // accounts should match peer service account in the handshaker result. Otherwise, the handshake + // fails. + private final List targetServiceAccounts; + + private AltsClientOptions(Builder builder) { + super(builder.rpcProtocolVersions); + targetName = builder.targetName; + targetServiceAccounts = + Collections.unmodifiableList(new ArrayList<>(builder.targetServiceAccounts)); + } + + public String getTargetName() { + return targetName; + } + + public List getTargetServiceAccounts() { + return targetServiceAccounts; + } + + /** Builder for AltsClientOptions. */ + public static final class Builder { + @Nullable private String targetName; + @Nullable private RpcProtocolVersions rpcProtocolVersions; + private ArrayList targetServiceAccounts = new ArrayList<>(); + + public Builder setTargetName(String targetName) { + this.targetName = targetName; + return this; + } + + public Builder setRpcProtocolVersions(RpcProtocolVersions rpcProtocolVersions) { + this.rpcProtocolVersions = rpcProtocolVersions; + return this; + } + + public Builder addTargetServiceAccount(String targetServiceAccount) { + targetServiceAccounts.add(targetServiceAccount); + return this; + } + + public AltsClientOptions build() { + return new AltsClientOptions(this); + } + } +} diff --git a/alts/src/main/java/io/grpc/alts/internal/AltsFraming.java b/alts/src/main/java/io/grpc/alts/internal/AltsFraming.java new file mode 100644 index 0000000000000000000000000000000000000000..d243d95f4ab351e16cdc7b7a2dea51435ba40d75 --- /dev/null +++ b/alts/src/main/java/io/grpc/alts/internal/AltsFraming.java @@ -0,0 +1,365 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import com.google.common.base.Preconditions; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.security.GeneralSecurityException; + +/** Framing and deframing methods and classes used by handshaker. */ +public final class AltsFraming { + // The size of the frame field. Must correspond to the size of int, 4 bytes. + // Left package-private for testing. + private static final int FRAME_LENGTH_HEADER_SIZE = 4; + private static final int FRAME_MESSAGE_TYPE_HEADER_SIZE = 4; + private static final int MAX_DATA_LENGTH = 1024 * 1024; + private static final int INITIAL_BUFFER_CAPACITY = 1024 * 64; + + // TODO: Make this the responsibility of the caller. + private static final int MESSAGE_TYPE = 6; + + private AltsFraming() {} + + static int getFrameLengthHeaderSize() { + return FRAME_LENGTH_HEADER_SIZE; + } + + static int getFrameMessageTypeHeaderSize() { + return FRAME_MESSAGE_TYPE_HEADER_SIZE; + } + + static int getMaxDataLength() { + return MAX_DATA_LENGTH; + } + + static int getFramingOverhead() { + return FRAME_LENGTH_HEADER_SIZE + FRAME_MESSAGE_TYPE_HEADER_SIZE; + } + + /** + * Creates a frame of length dataSize + FRAME_HEADER_SIZE using the input bytes, if dataSize <= + * input.remaining(). Otherwise, a frame of length input.remaining() + FRAME_HEADER_SIZE is + * created. + */ + static ByteBuffer toFrame(ByteBuffer input, int dataSize) throws GeneralSecurityException { + Preconditions.checkNotNull(input); + if (dataSize > input.remaining()) { + dataSize = input.remaining(); + } + Producer producer = new Producer(); + ByteBuffer inputAlias = input.duplicate(); + inputAlias.limit(input.position() + dataSize); + producer.readBytes(inputAlias); + producer.flush(); + input.position(inputAlias.position()); + ByteBuffer output = producer.getRawFrame(); + return output; + } + + /** + * A helper class to write a frame. + * + *

This class guarantees that one of the following is true: + * + *

    + *
  • readBytes will read from the input + *
  • writeBytes will write to the output + *
+ * + *

Sample usage: + * + *

{@code
+   * Producer producer = new Producer();
+   * ByteBuffer inputBuffer = readBytesFromMyStream();
+   * ByteBuffer outputBuffer = writeBytesToMyStream();
+   * while (inputBuffer.hasRemaining() || outputBuffer.hasRemaining()) {
+   *   producer.readBytes(inputBuffer);
+   *   producer.writeBytes(outputBuffer);
+   * }
+   * }
+ * + *

Alternatively, this class guarantees that one of the following is true: + * + *

    + *
  • readBytes will read from the input + *
  • {@code isComplete()} returns true and {@code getByteBuffer()} returns the contents of a + * processed frame. + *
+ * + *

Sample usage: + * + *

{@code
+   * Producer producer = new Producer();
+   * while (!producer.isComplete()) {
+   *   ByteBuffer inputBuffer = readBytesFromMyStream();
+   *   producer.readBytes(inputBuffer);
+   * }
+   * producer.flush();
+   * ByteBuffer outputBuffer = producer.getRawFrame();
+   * }
+ */ + static final class Producer { + private ByteBuffer buffer; + private boolean isComplete; + + Producer(int maxFrameSize) { + buffer = ByteBuffer.allocate(maxFrameSize); + reset(); + Preconditions.checkArgument(maxFrameSize > getFramePrefixLength() + getFrameSuffixLength()); + } + + Producer() { + this(INITIAL_BUFFER_CAPACITY); + } + + /** The length of the frame prefix data, including the message length/type fields. */ + int getFramePrefixLength() { + int result = FRAME_LENGTH_HEADER_SIZE + FRAME_MESSAGE_TYPE_HEADER_SIZE; + return result; + } + + int getFrameSuffixLength() { + return 0; + } + + /** + * Reads bytes from input, parsing them into a frame. Returns false if and only if more data is + * needed. To obtain a full frame this method must be called repeatedly until it returns true. + */ + boolean readBytes(ByteBuffer input) throws GeneralSecurityException { + Preconditions.checkNotNull(input); + if (isComplete) { + return true; + } + copy(buffer, input); + if (!buffer.hasRemaining()) { + flush(); + } + return isComplete; + } + + /** + * Completes the current frame, signaling that no further data is available to be passed to + * readBytes and that the client requires writeBytes to start returning data. isComplete() is + * guaranteed to return true after this call. + */ + void flush() throws GeneralSecurityException { + if (isComplete) { + return; + } + // Get the length of the complete frame. + int frameLength = buffer.position() + getFrameSuffixLength(); + + // Set the limit and move to the start. + buffer.flip(); + + // Advance the limit to allow a crypto suffix. + buffer.limit(buffer.limit() + getFrameSuffixLength()); + + // Write the data length and the message type. + int dataLength = frameLength - FRAME_LENGTH_HEADER_SIZE; + buffer.order(ByteOrder.LITTLE_ENDIAN); + buffer.putInt(dataLength); + buffer.putInt(MESSAGE_TYPE); + + // Move the position back to 0, the frame is ready. + buffer.position(0); + isComplete = true; + } + + /** Resets the state, preparing to construct a new frame. Must be called between frames. */ + private void reset() { + buffer.clear(); + + // Save some space for framing, we'll fill that in later. + buffer.position(getFramePrefixLength()); + buffer.limit(buffer.limit() - getFrameSuffixLength()); + + isComplete = false; + } + + /** + * Returns a ByteBuffer containing a complete raw frame, if it's available. Should only be + * called when isComplete() returns true, otherwise null is returned. The returned object + * aliases the internal buffer, that is, it shares memory with the internal buffer. No further + * operations are permitted on this object until the caller has processed the data it needs from + * the returned byte buffer. + */ + ByteBuffer getRawFrame() { + if (!isComplete) { + return null; + } + ByteBuffer result = buffer.duplicate(); + reset(); + return result; + } + } + + /** + * A helper class to read a frame. + * + *

This class guarantees that one of the following is true: + * + *

    + *
  • readBytes will read from the input + *
  • writeBytes will write to the output + *
+ * + *

Sample usage: + * + *

{@code
+   * Parser parser = new Parser();
+   * ByteBuffer inputBuffer = readBytesFromMyStream();
+   * ByteBuffer outputBuffer = writeBytesToMyStream();
+   * while (inputBuffer.hasRemaining() || outputBuffer.hasRemaining()) {
+   *   parser.readBytes(inputBuffer);
+   *   parser.writeBytes(outputBuffer); }
+   * }
+ * + *

Alternatively, this class guarantees that one of the following is true: + * + *

    + *
  • readBytes will read from the input + *
  • {@code isComplete()} returns true and {@code getByteBuffer()} returns the contents of a + * processed frame. + *
+ * + *

Sample usage: + * + *

{@code
+   * Parser parser = new Parser();
+   * while (!parser.isComplete()) {
+   *   ByteBuffer inputBuffer = readBytesFromMyStream();
+   *   parser.readBytes(inputBuffer);
+   * }
+   * ByteBuffer outputBuffer = parser.getRawFrame();
+   * }
+ */ + public static final class Parser { + private ByteBuffer buffer = ByteBuffer.allocate(INITIAL_BUFFER_CAPACITY); + private boolean isComplete = false; + + public Parser() { + Preconditions.checkArgument( + INITIAL_BUFFER_CAPACITY > getFramePrefixLength() + getFrameSuffixLength()); + } + + /** + * Reads bytes from input, parsing them into a frame. Returns false if and only if more data is + * needed. To obtain a full frame this method must be called repeatedly until it returns true. + */ + public boolean readBytes(ByteBuffer input) throws GeneralSecurityException { + Preconditions.checkNotNull(input); + + if (isComplete) { + return true; + } + + // Read enough bytes to determine the length + while (buffer.position() < FRAME_LENGTH_HEADER_SIZE && input.hasRemaining()) { + buffer.put(input.get()); + } + + // If we have enough bytes to determine the length, read the length and ensure that our + // internal buffer is large enough. + if (buffer.position() == FRAME_LENGTH_HEADER_SIZE && input.hasRemaining()) { + ByteBuffer bufferAlias = buffer.duplicate(); + bufferAlias.flip(); + bufferAlias.order(ByteOrder.LITTLE_ENDIAN); + int dataLength = bufferAlias.getInt(); + if (dataLength < FRAME_MESSAGE_TYPE_HEADER_SIZE || dataLength > MAX_DATA_LENGTH) { + throw new IllegalArgumentException("Invalid frame length " + dataLength); + } + // Maybe resize the buffer + int frameLength = dataLength + FRAME_LENGTH_HEADER_SIZE; + if (buffer.capacity() < frameLength) { + buffer = ByteBuffer.allocate(frameLength); + buffer.order(ByteOrder.LITTLE_ENDIAN); + buffer.putInt(dataLength); + } + buffer.limit(frameLength); + } + + // TODO: Similarly extract and check message type. + + // Read the remaining data into the internal buffer. + copy(buffer, input); + if (!buffer.hasRemaining()) { + buffer.flip(); + isComplete = true; + } + return isComplete; + } + + /** The length of the frame prefix data, including the message length/type fields. */ + int getFramePrefixLength() { + int result = FRAME_LENGTH_HEADER_SIZE + FRAME_MESSAGE_TYPE_HEADER_SIZE; + return result; + } + + int getFrameSuffixLength() { + return 0; + } + + /** Returns true if we've parsed a complete frame. */ + public boolean isComplete() { + return isComplete; + } + + /** Resets the state, preparing to parse a new frame. Must be called between frames. */ + private void reset() { + buffer.clear(); + isComplete = false; + } + + /** + * Returns a ByteBuffer containing a complete raw frame, if it's available. Should only be + * called when isComplete() returns true, otherwise null is returned. The returned object + * aliases the internal buffer, that is, it shares memory with the internal buffer. No further + * operations are permitted on this object until the caller has processed the data it needs from + * the returned byte buffer. + */ + public ByteBuffer getRawFrame() { + if (!isComplete) { + return null; + } + ByteBuffer result = buffer.duplicate(); + reset(); + return result; + } + } + + /** + * Copy as much as possible to dst from src. Unlike {@link ByteBuffer#put(ByteBuffer)}, this stops + * early if there is no room left in dst. + */ + private static void copy(ByteBuffer dst, ByteBuffer src) { + if (dst.hasRemaining() && src.hasRemaining()) { + // Avoid an allocation if possible. + if (dst.remaining() >= src.remaining()) { + dst.put(src); + } else { + int count = Math.min(dst.remaining(), src.remaining()); + ByteBuffer slice = src.slice(); + slice.limit(count); + dst.put(slice); + src.position(src.position() + count); + } + } + } +} diff --git a/alts/src/main/java/io/grpc/alts/internal/AltsHandshakerClient.java b/alts/src/main/java/io/grpc/alts/internal/AltsHandshakerClient.java new file mode 100644 index 0000000000000000000000000000000000000000..8f1d79bf0a89be022f3db1760a915214cc7822d5 --- /dev/null +++ b/alts/src/main/java/io/grpc/alts/internal/AltsHandshakerClient.java @@ -0,0 +1,245 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Preconditions; +import com.google.common.base.Strings; +import com.google.protobuf.ByteString; +import io.grpc.Status; +import io.grpc.alts.internal.Handshaker.HandshakeProtocol; +import io.grpc.alts.internal.Handshaker.HandshakerReq; +import io.grpc.alts.internal.Handshaker.HandshakerResp; +import io.grpc.alts.internal.Handshaker.HandshakerResult; +import io.grpc.alts.internal.Handshaker.HandshakerStatus; +import io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq; +import io.grpc.alts.internal.Handshaker.ServerHandshakeParameters; +import io.grpc.alts.internal.Handshaker.StartClientHandshakeReq; +import io.grpc.alts.internal.Handshaker.StartServerHandshakeReq; +import io.grpc.alts.internal.HandshakerServiceGrpc.HandshakerServiceStub; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.security.GeneralSecurityException; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** An API for conducting handshakes via ALTS handshaker service. */ +class AltsHandshakerClient { + private static final Logger logger = Logger.getLogger(AltsHandshakerClient.class.getName()); + + private static final String APPLICATION_PROTOCOL = "grpc"; + private static final String RECORD_PROTOCOL = "ALTSRP_GCM_AES128_REKEY"; + private static final int KEY_LENGTH = AltsChannelCrypter.getKeyLength(); + + private final AltsHandshakerStub handshakerStub; + private final AltsHandshakerOptions handshakerOptions; + private HandshakerResult result; + private HandshakerStatus status; + + /** Starts a new handshake interacting with the handshaker service. */ + AltsHandshakerClient(HandshakerServiceStub stub, AltsHandshakerOptions options) { + handshakerStub = new AltsHandshakerStub(stub); + handshakerOptions = options; + } + + @VisibleForTesting + AltsHandshakerClient(AltsHandshakerStub handshakerStub, AltsHandshakerOptions options) { + this.handshakerStub = handshakerStub; + handshakerOptions = options; + } + + static String getApplicationProtocol() { + return APPLICATION_PROTOCOL; + } + + static String getRecordProtocol() { + return RECORD_PROTOCOL; + } + + /** Sets the start client fields for the passed handshake request. */ + private void setStartClientFields(HandshakerReq.Builder req) { + // Sets the default values. + StartClientHandshakeReq.Builder startClientReq = + StartClientHandshakeReq.newBuilder() + .setHandshakeSecurityProtocol(HandshakeProtocol.ALTS) + .addApplicationProtocols(APPLICATION_PROTOCOL) + .addRecordProtocols(RECORD_PROTOCOL); + // Sets handshaker options. + if (handshakerOptions.getRpcProtocolVersions() != null) { + startClientReq.setRpcVersions(handshakerOptions.getRpcProtocolVersions()); + } + if (handshakerOptions instanceof AltsClientOptions) { + AltsClientOptions clientOptions = (AltsClientOptions) handshakerOptions; + if (!Strings.isNullOrEmpty(clientOptions.getTargetName())) { + startClientReq.setTargetName(clientOptions.getTargetName()); + } + for (String serviceAccount : clientOptions.getTargetServiceAccounts()) { + startClientReq.addTargetIdentitiesBuilder().setServiceAccount(serviceAccount); + } + } + req.setClientStart(startClientReq); + } + + /** Sets the start server fields for the passed handshake request. */ + private void setStartServerFields(HandshakerReq.Builder req, ByteBuffer inBytes) { + ServerHandshakeParameters serverParameters = + ServerHandshakeParameters.newBuilder().addRecordProtocols(RECORD_PROTOCOL).build(); + StartServerHandshakeReq.Builder startServerReq = + StartServerHandshakeReq.newBuilder() + .addApplicationProtocols(APPLICATION_PROTOCOL) + .putHandshakeParameters(HandshakeProtocol.ALTS.getNumber(), serverParameters) + .setInBytes(ByteString.copyFrom(inBytes.duplicate())); + if (handshakerOptions.getRpcProtocolVersions() != null) { + startServerReq.setRpcVersions(handshakerOptions.getRpcProtocolVersions()); + } + req.setServerStart(startServerReq); + } + + /** Returns true if the handshake is complete. */ + public boolean isFinished() { + // If we have a HandshakeResult, we are done. + if (result != null) { + return true; + } + // If we have an error status, we are done. + if (status != null && status.getCode() != Status.Code.OK.value()) { + return true; + } + return false; + } + + /** Returns the handshake status. */ + public HandshakerStatus getStatus() { + return status; + } + + /** Returns the result data of the handshake, if the handshake is completed. */ + public HandshakerResult getResult() { + return result; + } + + /** + * Returns the resulting key of the handshake, if the handshake is completed. Note that the key + * data returned from the handshake may be more than the key length required for the record + * protocol, thus we need to truncate to the right size. + */ + public byte[] getKey() { + if (result == null) { + return null; + } + if (result.getKeyData().size() < KEY_LENGTH) { + throw new IllegalStateException("Could not get enough key data from the handshake."); + } + byte[] key = new byte[KEY_LENGTH]; + result.getKeyData().copyTo(key, 0, 0, KEY_LENGTH); + return key; + } + + /** + * Parses a handshake response, setting the status, result, and closing the handshaker, as needed. + */ + private void handleResponse(HandshakerResp resp) throws GeneralSecurityException { + status = resp.getStatus(); + if (resp.hasResult()) { + result = resp.getResult(); + close(); + } + if (status.getCode() != Status.Code.OK.value()) { + String error = "Handshaker service error: " + status.getDetails(); + logger.log(Level.INFO, error); + close(); + throw new GeneralSecurityException(error); + } + } + + /** + * Starts a client handshake. A GeneralSecurityException is thrown if the handshaker service is + * interrupted or fails. Note that isFinished() must be false before this function is called. + * + * @return the frame to give to the peer. + * @throws GeneralSecurityException or IllegalStateException + */ + public ByteBuffer startClientHandshake() throws GeneralSecurityException { + Preconditions.checkState(!isFinished(), "Handshake has already finished."); + HandshakerReq.Builder req = HandshakerReq.newBuilder(); + setStartClientFields(req); + HandshakerResp resp; + try { + resp = handshakerStub.send(req.build()); + } catch (IOException | InterruptedException e) { + throw new GeneralSecurityException(e); + } + handleResponse(resp); + return resp.getOutFrames().asReadOnlyByteBuffer(); + } + + /** + * Starts a server handshake. A GeneralSecurityException is thrown if the handshaker service is + * interrupted or fails. Note that isFinished() must be false before this function is called. + * + * @param inBytes the bytes received from the peer. + * @return the frame to give to the peer. + * @throws GeneralSecurityException or IllegalStateException + */ + public ByteBuffer startServerHandshake(ByteBuffer inBytes) throws GeneralSecurityException { + Preconditions.checkState(!isFinished(), "Handshake has already finished."); + HandshakerReq.Builder req = HandshakerReq.newBuilder(); + setStartServerFields(req, inBytes); + HandshakerResp resp; + try { + resp = handshakerStub.send(req.build()); + } catch (IOException | InterruptedException e) { + throw new GeneralSecurityException(e); + } + handleResponse(resp); + inBytes.position(inBytes.position() + resp.getBytesConsumed()); + return resp.getOutFrames().asReadOnlyByteBuffer(); + } + + /** + * Processes the next bytes in a handshake. A GeneralSecurityException is thrown if the handshaker + * service is interrupted or fails. Note that isFinished() must be false before this function is + * called. + * + * @param inBytes the bytes received from the peer. + * @return the frame to give to the peer. + * @throws GeneralSecurityException or IllegalStateException + */ + public ByteBuffer next(ByteBuffer inBytes) throws GeneralSecurityException { + Preconditions.checkState(!isFinished(), "Handshake has already finished."); + HandshakerReq.Builder req = + HandshakerReq.newBuilder() + .setNext( + NextHandshakeMessageReq.newBuilder() + .setInBytes(ByteString.copyFrom(inBytes.duplicate())) + .build()); + HandshakerResp resp; + try { + resp = handshakerStub.send(req.build()); + } catch (IOException | InterruptedException e) { + throw new GeneralSecurityException(e); + } + handleResponse(resp); + inBytes.position(inBytes.position() + resp.getBytesConsumed()); + return resp.getOutFrames().asReadOnlyByteBuffer(); + } + + /** Closes the connection. */ + public void close() { + handshakerStub.close(); + } +} diff --git a/alts/src/main/java/io/grpc/alts/internal/AltsHandshakerOptions.java b/alts/src/main/java/io/grpc/alts/internal/AltsHandshakerOptions.java new file mode 100644 index 0000000000000000000000000000000000000000..5e0dbdbe29e232cef9dde289c089cd6497200e5e --- /dev/null +++ b/alts/src/main/java/io/grpc/alts/internal/AltsHandshakerOptions.java @@ -0,0 +1,33 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions; +import javax.annotation.Nullable; + +/** Handshaker options for creating ALTS channel. */ +public class AltsHandshakerOptions { + @Nullable private final RpcProtocolVersions rpcProtocolVersions; + + public AltsHandshakerOptions(RpcProtocolVersions rpcProtocolVersions) { + this.rpcProtocolVersions = rpcProtocolVersions; + } + + public RpcProtocolVersions getRpcProtocolVersions() { + return rpcProtocolVersions; + } +} diff --git a/alts/src/main/java/io/grpc/alts/internal/AltsHandshakerStub.java b/alts/src/main/java/io/grpc/alts/internal/AltsHandshakerStub.java new file mode 100644 index 0000000000000000000000000000000000000000..ee979aa433127dcb56863e27d4220c6df783b5e3 --- /dev/null +++ b/alts/src/main/java/io/grpc/alts/internal/AltsHandshakerStub.java @@ -0,0 +1,114 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Optional; +import io.grpc.alts.internal.Handshaker.HandshakerReq; +import io.grpc.alts.internal.Handshaker.HandshakerResp; +import io.grpc.alts.internal.HandshakerServiceGrpc.HandshakerServiceStub; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.atomic.AtomicReference; + +/** An interface to the ALTS handshaker service. */ +class AltsHandshakerStub { + private final StreamObserver reader = new Reader(); + private final StreamObserver writer; + private final ArrayBlockingQueue> responseQueue = + new ArrayBlockingQueue>(1); + private final AtomicReference exceptionMessage = new AtomicReference<>(); + + AltsHandshakerStub(HandshakerServiceStub serviceStub) { + this.writer = serviceStub.doHandshake(this.reader); + } + + @VisibleForTesting + AltsHandshakerStub() { + writer = null; + } + + @VisibleForTesting + AltsHandshakerStub(StreamObserver writer) { + this.writer = writer; + } + + @VisibleForTesting + StreamObserver getReaderForTest() { + return reader; + } + + /** Send a handshaker request and return the handshaker response. */ + public HandshakerResp send(HandshakerReq req) throws InterruptedException, IOException { + maybeThrowIoException(); + if (!responseQueue.isEmpty()) { + throw new IOException("Received an unexpected response."); + } + writer.onNext(req); + Optional result = responseQueue.take(); + if (!result.isPresent()) { + maybeThrowIoException(); + } + return result.get(); + } + + /** Throw exception if there is an outstanding exception. */ + private void maybeThrowIoException() throws IOException { + if (exceptionMessage.get() != null) { + throw new IOException(exceptionMessage.get()); + } + } + + /** Close the connection. */ + public void close() { + writer.onCompleted(); + } + + private class Reader implements StreamObserver { + /** Receive a handshaker response from the server. */ + @Override + public void onNext(HandshakerResp resp) { + try { + AltsHandshakerStub.this.responseQueue.add(Optional.of(resp)); + } catch (IllegalStateException e) { + AltsHandshakerStub.this.exceptionMessage.compareAndSet( + null, "Received an unexpected response."); + AltsHandshakerStub.this.close(); + } + } + + /** Receive an error from the server. */ + @Override + public void onError(Throwable t) { + AltsHandshakerStub.this.exceptionMessage.compareAndSet( + null, "Received a terminating error: " + t.toString()); + // Trigger the release of any blocked send. + Optional result = Optional.absent(); + AltsHandshakerStub.this.responseQueue.offer(result); + } + + /** Receive the closing message from the server. */ + @Override + public void onCompleted() { + AltsHandshakerStub.this.exceptionMessage.compareAndSet(null, "Response stream closed."); + // Trigger the release of any blocked send. + Optional result = Optional.absent(); + AltsHandshakerStub.this.responseQueue.offer(result); + } + } +} diff --git a/alts/src/main/java/io/grpc/alts/internal/AltsProtocolNegotiator.java b/alts/src/main/java/io/grpc/alts/internal/AltsProtocolNegotiator.java new file mode 100644 index 0000000000000000000000000000000000000000..f146dbc4c8a66c6897cd9c1fd304bfeada9ead08 --- /dev/null +++ b/alts/src/main/java/io/grpc/alts/internal/AltsProtocolNegotiator.java @@ -0,0 +1,145 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Preconditions; +import com.google.protobuf.Any; +import io.grpc.Attributes; +import io.grpc.CallCredentials; +import io.grpc.Grpc; +import io.grpc.InternalChannelz.OtherSecurity; +import io.grpc.InternalChannelz.Security; +import io.grpc.SecurityLevel; +import io.grpc.Status; +import io.grpc.alts.internal.RpcProtocolVersionsUtil.RpcVersionsCheckResult; +import io.grpc.alts.internal.TsiHandshakeHandler.TsiHandshakeCompletionEvent; +import io.grpc.netty.GrpcHttp2ConnectionHandler; +import io.grpc.netty.ProtocolNegotiator; +import io.grpc.netty.ProtocolNegotiators.AbstractBufferingHandler; +import io.netty.channel.ChannelHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.util.AsciiString; + +/** + * A client-side GRPC {@link ProtocolNegotiator} for ALTS. This class creates a Netty handler that + * provides ALTS security on the wire, similar to Netty's {@code SslHandler}. + */ +public abstract class AltsProtocolNegotiator implements ProtocolNegotiator { + + private static final Attributes.Key TSI_PEER_KEY = Attributes.Key.create("TSI_PEER"); + private static final Attributes.Key ALTS_CONTEXT_KEY = + Attributes.Key.create("ALTS_CONTEXT_KEY"); + private static final AsciiString scheme = AsciiString.of("https"); + + public static Attributes.Key getTsiPeerAttributeKey() { + return TSI_PEER_KEY; + } + + public static Attributes.Key getAltsAuthContextAttributeKey() { + return ALTS_CONTEXT_KEY; + } + + /** Creates a negotiator used for ALTS. */ + public static AltsProtocolNegotiator create(final TsiHandshakerFactory handshakerFactory) { + return new AltsProtocolNegotiator() { + @Override + public Handler newHandler(GrpcHttp2ConnectionHandler grpcHandler) { + return new BufferUntilAltsNegotiatedHandler( + grpcHandler, + new TsiHandshakeHandler(new NettyTsiHandshaker(handshakerFactory.newHandshaker())), + new TsiFrameHandler()); + } + }; + } + + /** Buffers all writes until the ALTS handshake is complete. */ + @VisibleForTesting + static class BufferUntilAltsNegotiatedHandler extends AbstractBufferingHandler + implements ProtocolNegotiator.Handler { + + private final GrpcHttp2ConnectionHandler grpcHandler; + + BufferUntilAltsNegotiatedHandler( + GrpcHttp2ConnectionHandler grpcHandler, ChannelHandler... negotiationhandlers) { + super(negotiationhandlers); + // Save the gRPC handler. The ALTS handler doesn't support buffering before the handshake + // completes, so we wait until the handshake was successful before adding the grpc handler. + this.grpcHandler = grpcHandler; + } + + // TODO: Remove this once https://github.com/grpc/grpc-java/pull/3715 is in. + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + fail(ctx, cause); + ctx.fireExceptionCaught(cause); + } + + @Override + public AsciiString scheme() { + return scheme; + } + + @Override + public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { + if (evt instanceof TsiHandshakeCompletionEvent) { + TsiHandshakeCompletionEvent altsEvt = (TsiHandshakeCompletionEvent) evt; + if (altsEvt.isSuccess()) { + // Add the gRPC handler just before this handler. We only allow the grpcHandler to be + // null to support testing. In production, a grpc handler will always be provided. + if (grpcHandler != null) { + ctx.pipeline().addBefore(ctx.name(), null, grpcHandler); + AltsAuthContext altsContext = (AltsAuthContext) altsEvt.context(); + Preconditions.checkNotNull(altsContext); + // Checks peer Rpc Protocol Versions in the ALTS auth context. Fails the connection if + // Rpc Protocol Versions mismatch. + RpcVersionsCheckResult checkResult = + RpcProtocolVersionsUtil.checkRpcProtocolVersions( + RpcProtocolVersionsUtil.getRpcProtocolVersions(), + altsContext.getPeerRpcVersions()); + if (!checkResult.getResult()) { + String errorMessage = + "Local Rpc Protocol Versions " + + RpcProtocolVersionsUtil.getRpcProtocolVersions().toString() + + "are not compatible with peer Rpc Protocol Versions " + + altsContext.getPeerRpcVersions().toString(); + fail(ctx, Status.UNAVAILABLE.withDescription(errorMessage).asRuntimeException()); + } + grpcHandler.handleProtocolNegotiationCompleted( + Attributes.newBuilder() + .set(TSI_PEER_KEY, altsEvt.peer()) + .set(ALTS_CONTEXT_KEY, altsContext) + .set(Grpc.TRANSPORT_ATTR_REMOTE_ADDR, ctx.channel().remoteAddress()) + .set(CallCredentials.ATTR_SECURITY_LEVEL, SecurityLevel.PRIVACY_AND_INTEGRITY) + .build(), + new Security(new OtherSecurity("alts", Any.pack(altsContext.context)))); + } + + // Now write any buffered data and remove this handler. + writeBufferedAndRemove(ctx); + } else { + fail(ctx, unavailableException("ALTS handshake failed", altsEvt.cause())); + } + } + super.userEventTriggered(ctx, evt); + } + + private static RuntimeException unavailableException(String msg, Throwable cause) { + return Status.UNAVAILABLE.withCause(cause).withDescription(msg).asRuntimeException(); + } + } +} diff --git a/alts/src/main/java/io/grpc/alts/internal/AltsTsiFrameProtector.java b/alts/src/main/java/io/grpc/alts/internal/AltsTsiFrameProtector.java new file mode 100644 index 0000000000000000000000000000000000000000..c112c319b8c59ef92f82b499c6d92c1af3c440e1 --- /dev/null +++ b/alts/src/main/java/io/grpc/alts/internal/AltsTsiFrameProtector.java @@ -0,0 +1,405 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkState; +import static com.google.common.base.Verify.verify; + +import com.google.common.primitives.Ints; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufAllocator; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.List; + +/** Frame protector that uses the ALTS framing. */ +public final class AltsTsiFrameProtector implements TsiFrameProtector { + private static final int HEADER_LEN_FIELD_BYTES = 4; + private static final int HEADER_TYPE_FIELD_BYTES = 4; + private static final int HEADER_BYTES = HEADER_LEN_FIELD_BYTES + HEADER_TYPE_FIELD_BYTES; + private static final int HEADER_TYPE_DEFAULT = 6; + // Total frame size including full header and tag. + private static final int MAX_ALLOWED_FRAME_BYTES = 16 * 1024; + private static final int LIMIT_MAX_ALLOWED_FRAME_BYTES = 1024 * 1024; + + private final Protector protector; + private final Unprotector unprotector; + + /** Create a new AltsTsiFrameProtector. */ + public AltsTsiFrameProtector( + int maxProtectedFrameBytes, ChannelCrypterNetty crypter, ByteBufAllocator alloc) { + checkArgument(maxProtectedFrameBytes > HEADER_BYTES + crypter.getSuffixLength()); + maxProtectedFrameBytes = Math.min(LIMIT_MAX_ALLOWED_FRAME_BYTES, maxProtectedFrameBytes); + protector = new Protector(maxProtectedFrameBytes, crypter); + unprotector = new Unprotector(crypter, alloc); + } + + static int getHeaderLenFieldBytes() { + return HEADER_LEN_FIELD_BYTES; + } + + static int getHeaderTypeFieldBytes() { + return HEADER_TYPE_FIELD_BYTES; + } + + public static int getHeaderBytes() { + return HEADER_BYTES; + } + + static int getHeaderTypeDefault() { + return HEADER_TYPE_DEFAULT; + } + + public static int getMaxAllowedFrameBytes() { + return MAX_ALLOWED_FRAME_BYTES; + } + + static int getLimitMaxAllowedFrameBytes() { + return LIMIT_MAX_ALLOWED_FRAME_BYTES; + } + + @Override + public void protectFlush( + List unprotectedBufs, Consumer ctxWrite, ByteBufAllocator alloc) + throws GeneralSecurityException { + protector.protectFlush(unprotectedBufs, ctxWrite, alloc); + } + + @Override + public void unprotect(ByteBuf in, List out, ByteBufAllocator alloc) + throws GeneralSecurityException { + unprotector.unprotect(in, out, alloc); + } + + @Override + public void destroy() { + try { + unprotector.destroy(); + } finally { + protector.destroy(); + } + } + + static final class Protector { + private final int maxUnprotectedBytesPerFrame; + private final int suffixBytes; + private ChannelCrypterNetty crypter; + + Protector(int maxProtectedFrameBytes, ChannelCrypterNetty crypter) { + this.suffixBytes = crypter.getSuffixLength(); + this.maxUnprotectedBytesPerFrame = maxProtectedFrameBytes - HEADER_BYTES - suffixBytes; + this.crypter = crypter; + } + + void destroy() { + // Shared with Unprotector and destroyed there. + crypter = null; + } + + void protectFlush( + List unprotectedBufs, Consumer ctxWrite, ByteBufAllocator alloc) + throws GeneralSecurityException { + checkState(crypter != null, "Cannot protectFlush after destroy."); + ByteBuf protectedBuf; + try { + protectedBuf = handleUnprotected(unprotectedBufs, alloc); + } finally { + for (ByteBuf buf : unprotectedBufs) { + buf.release(); + } + } + if (protectedBuf != null) { + ctxWrite.accept(protectedBuf); + } + } + + @SuppressWarnings("BetaApi") // verify is stable in Guava + private ByteBuf handleUnprotected(List unprotectedBufs, ByteBufAllocator alloc) + throws GeneralSecurityException { + long unprotectedBytes = 0; + for (ByteBuf buf : unprotectedBufs) { + unprotectedBytes += buf.readableBytes(); + } + // Empty plaintext not allowed since this should be handled as no-op in layer above. + checkArgument(unprotectedBytes > 0); + + // Compute number of frames and allocate a single buffer for all frames. + long frameNum = unprotectedBytes / maxUnprotectedBytesPerFrame + 1; + int lastFrameUnprotectedBytes = (int) (unprotectedBytes % maxUnprotectedBytesPerFrame); + if (lastFrameUnprotectedBytes == 0) { + frameNum--; + lastFrameUnprotectedBytes = maxUnprotectedBytesPerFrame; + } + long protectedBytes = frameNum * (HEADER_BYTES + suffixBytes) + unprotectedBytes; + + ByteBuf protectedBuf = alloc.directBuffer(Ints.checkedCast(protectedBytes)); + try { + int bufferIdx = 0; + for (int frameIdx = 0; frameIdx < frameNum; ++frameIdx) { + int unprotectedBytesLeft = + (frameIdx == frameNum - 1) ? lastFrameUnprotectedBytes : maxUnprotectedBytesPerFrame; + // Write header (at most LIMIT_MAX_ALLOWED_FRAME_BYTES). + protectedBuf.writeIntLE(unprotectedBytesLeft + HEADER_TYPE_FIELD_BYTES + suffixBytes); + protectedBuf.writeIntLE(HEADER_TYPE_DEFAULT); + + // Ownership of the backing buffer remains with protectedBuf. + ByteBuf frameOut = writeSlice(protectedBuf, unprotectedBytesLeft + suffixBytes); + List framePlain = new ArrayList<>(); + while (unprotectedBytesLeft > 0) { + // Ownership of the buffer backing in remains with unprotectedBufs. + ByteBuf in = unprotectedBufs.get(bufferIdx); + if (in.readableBytes() <= unprotectedBytesLeft) { + // The complete buffer belongs to this frame. + framePlain.add(in); + unprotectedBytesLeft -= in.readableBytes(); + bufferIdx++; + } else { + // The remainder of in will be part of the next frame. + framePlain.add(in.readSlice(unprotectedBytesLeft)); + unprotectedBytesLeft = 0; + } + } + crypter.encrypt(frameOut, framePlain); + verify(!frameOut.isWritable()); + } + protectedBuf.readerIndex(0); + protectedBuf.writerIndex(protectedBuf.capacity()); + return protectedBuf.retain(); + } finally { + protectedBuf.release(); + } + } + } + + static final class Unprotector { + private final int suffixBytes; + private final ChannelCrypterNetty crypter; + + private DeframerState state = DeframerState.READ_HEADER; + private int requiredProtectedBytes; + private ByteBuf header; + private ByteBuf firstFrameTag; + private int unhandledIdx = 0; + private long unhandledBytes = 0; + private List unhandledBufs = new ArrayList<>(16); + + Unprotector(ChannelCrypterNetty crypter, ByteBufAllocator alloc) { + this.crypter = crypter; + this.suffixBytes = crypter.getSuffixLength(); + this.header = alloc.directBuffer(HEADER_BYTES); + this.firstFrameTag = alloc.directBuffer(suffixBytes); + } + + private void addUnhandled(ByteBuf in) { + if (in.isReadable()) { + ByteBuf buf = in.readRetainedSlice(in.readableBytes()); + unhandledBufs.add(buf); + unhandledBytes += buf.readableBytes(); + } + } + + void unprotect(ByteBuf in, List out, ByteBufAllocator alloc) + throws GeneralSecurityException { + checkState(header != null, "Cannot unprotect after destroy."); + addUnhandled(in); + decodeFrame(alloc, out); + } + + @SuppressWarnings("fallthrough") + private void decodeFrame(ByteBufAllocator alloc, List out) + throws GeneralSecurityException { + switch (state) { + case READ_HEADER: + if (unhandledBytes < HEADER_BYTES) { + return; + } + handleHeader(); + // fall through + case READ_PROTECTED_PAYLOAD: + if (unhandledBytes < requiredProtectedBytes) { + return; + } + ByteBuf unprotectedBuf; + try { + unprotectedBuf = handlePayload(alloc); + } finally { + clearState(); + } + if (unprotectedBuf != null) { + out.add(unprotectedBuf); + } + break; + default: + throw new AssertionError("impossible enum value"); + } + } + + private void handleHeader() { + while (header.isWritable()) { + ByteBuf in = unhandledBufs.get(unhandledIdx); + int headerBytesToRead = Math.min(in.readableBytes(), header.writableBytes()); + header.writeBytes(in, headerBytesToRead); + unhandledBytes -= headerBytesToRead; + if (!in.isReadable()) { + unhandledIdx++; + } + } + requiredProtectedBytes = header.readIntLE() - HEADER_TYPE_FIELD_BYTES; + checkArgument( + requiredProtectedBytes >= suffixBytes, "Invalid header field: frame size too small"); + checkArgument( + requiredProtectedBytes <= LIMIT_MAX_ALLOWED_FRAME_BYTES - HEADER_BYTES, + "Invalid header field: frame size too large"); + int frameType = header.readIntLE(); + checkArgument(frameType == HEADER_TYPE_DEFAULT, "Invalid header field: frame type"); + state = DeframerState.READ_PROTECTED_PAYLOAD; + } + + @SuppressWarnings("BetaApi") // verify is stable in Guava + private ByteBuf handlePayload(ByteBufAllocator alloc) throws GeneralSecurityException { + int requiredCiphertextBytes = requiredProtectedBytes - suffixBytes; + int firstFrameUnprotectedLen = requiredCiphertextBytes; + + // We get the ciphertexts of the first frame and copy over the tag into a single buffer. + List firstFrameCiphertext = new ArrayList<>(); + while (requiredCiphertextBytes > 0) { + ByteBuf buf = unhandledBufs.get(unhandledIdx); + if (buf.readableBytes() <= requiredCiphertextBytes) { + // We use the whole buffer. + firstFrameCiphertext.add(buf); + requiredCiphertextBytes -= buf.readableBytes(); + unhandledIdx++; + } else { + firstFrameCiphertext.add(buf.readSlice(requiredCiphertextBytes)); + requiredCiphertextBytes = 0; + } + } + int requiredSuffixBytes = suffixBytes; + while (true) { + ByteBuf buf = unhandledBufs.get(unhandledIdx); + if (buf.readableBytes() <= requiredSuffixBytes) { + // We use the whole buffer. + requiredSuffixBytes -= buf.readableBytes(); + firstFrameTag.writeBytes(buf); + if (requiredSuffixBytes == 0) { + break; + } + unhandledIdx++; + } else { + firstFrameTag.writeBytes(buf, requiredSuffixBytes); + break; + } + } + verify(unhandledIdx == unhandledBufs.size() - 1); + ByteBuf lastBuf = unhandledBufs.get(unhandledIdx); + + // We get the remaining ciphertexts and tags contained in the last buffer. + List ciphertextsAndTags = new ArrayList<>(); + List unprotectedLens = new ArrayList<>(); + long requiredUnprotectedBytesCompleteFrames = firstFrameUnprotectedLen; + while (lastBuf.readableBytes() >= HEADER_BYTES + suffixBytes) { + // Read frame size. + int frameSize = lastBuf.readIntLE(); + int payloadSize = frameSize - HEADER_TYPE_FIELD_BYTES - suffixBytes; + // Break and undo read if we don't have the complete frame yet. + if (lastBuf.readableBytes() < frameSize) { + lastBuf.readerIndex(lastBuf.readerIndex() - HEADER_LEN_FIELD_BYTES); + break; + } + // Check the type header. + checkArgument(lastBuf.readIntLE() == 6); + // Create a new frame (except for out buffer). + ciphertextsAndTags.add(lastBuf.readSlice(payloadSize + suffixBytes)); + // Update sizes for frame. + requiredUnprotectedBytesCompleteFrames += payloadSize; + unprotectedLens.add(payloadSize); + } + + // We leave space for suffixBytes to allow for in-place encryption. This allows for calling + // doFinal in the JCE implementation which can be optimized better than update and doFinal. + ByteBuf unprotectedBuf = + alloc.directBuffer( + Ints.checkedCast(requiredUnprotectedBytesCompleteFrames + suffixBytes)); + try { + + ByteBuf out = writeSlice(unprotectedBuf, firstFrameUnprotectedLen + suffixBytes); + crypter.decrypt(out, firstFrameTag, firstFrameCiphertext); + verify(out.writableBytes() == suffixBytes); + unprotectedBuf.writerIndex(unprotectedBuf.writerIndex() - suffixBytes); + + for (int frameIdx = 0; frameIdx < ciphertextsAndTags.size(); ++frameIdx) { + out = writeSlice(unprotectedBuf, unprotectedLens.get(frameIdx) + suffixBytes); + crypter.decrypt(out, ciphertextsAndTags.get(frameIdx)); + verify(out.writableBytes() == suffixBytes); + unprotectedBuf.writerIndex(unprotectedBuf.writerIndex() - suffixBytes); + } + return unprotectedBuf.retain(); + } finally { + unprotectedBuf.release(); + } + } + + private void clearState() { + int bufsSize = unhandledBufs.size(); + ByteBuf lastBuf = unhandledBufs.get(bufsSize - 1); + boolean keepLast = lastBuf.isReadable(); + for (int bufIdx = 0; bufIdx < (keepLast ? bufsSize - 1 : bufsSize); ++bufIdx) { + unhandledBufs.get(bufIdx).release(); + } + unhandledBufs.clear(); + unhandledBytes = 0; + unhandledIdx = 0; + if (keepLast) { + unhandledBufs.add(lastBuf); + unhandledBytes = lastBuf.readableBytes(); + } + state = DeframerState.READ_HEADER; + requiredProtectedBytes = 0; + header.clear(); + firstFrameTag.clear(); + } + + void destroy() { + for (ByteBuf unhandledBuf : unhandledBufs) { + unhandledBuf.release(); + } + unhandledBufs.clear(); + if (header != null) { + header.release(); + header = null; + } + if (firstFrameTag != null) { + firstFrameTag.release(); + firstFrameTag = null; + } + crypter.destroy(); + } + } + + private enum DeframerState { + READ_HEADER, + READ_PROTECTED_PAYLOAD + } + + private static ByteBuf writeSlice(ByteBuf in, int len) { + checkArgument(len <= in.writableBytes()); + ByteBuf out = in.slice(in.writerIndex(), len); + in.writerIndex(in.writerIndex() + len); + return out.writerIndex(0); + } +} diff --git a/alts/src/main/java/io/grpc/alts/internal/AltsTsiHandshaker.java b/alts/src/main/java/io/grpc/alts/internal/AltsTsiHandshaker.java new file mode 100644 index 0000000000000000000000000000000000000000..3699abb8d5ef8a583258e7000c90b21815d63c5d --- /dev/null +++ b/alts/src/main/java/io/grpc/alts/internal/AltsTsiHandshaker.java @@ -0,0 +1,195 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import static com.google.common.base.Preconditions.checkState; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Preconditions; +import io.grpc.alts.internal.HandshakerServiceGrpc.HandshakerServiceStub; +import io.netty.buffer.ByteBufAllocator; +import java.nio.ByteBuffer; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.List; + +/** + * Negotiates a grpc channel key to be used by the TsiFrameProtector, using ALTs handshaker service. + */ +public final class AltsTsiHandshaker implements TsiHandshaker { + public static final String TSI_SERVICE_ACCOUNT_PEER_PROPERTY = "service_account"; + + private final boolean isClient; + private final AltsHandshakerClient handshaker; + + private ByteBuffer outputFrame; + + /** Starts a new TSI handshaker with client options. */ + private AltsTsiHandshaker( + boolean isClient, HandshakerServiceStub stub, AltsHandshakerOptions options) { + this.isClient = isClient; + handshaker = new AltsHandshakerClient(stub, options); + } + + @VisibleForTesting + AltsTsiHandshaker(boolean isClient, AltsHandshakerClient handshaker) { + this.isClient = isClient; + this.handshaker = handshaker; + } + + /** + * Process the bytes received from the peer. + * + * @param bytes The buffer containing the handshake bytes from the peer. + * @return true, if the handshake has all the data it needs to process and false, if the method + * must be called again to complete processing. + */ + @Override + public boolean processBytesFromPeer(ByteBuffer bytes) throws GeneralSecurityException { + // If we're the client and we haven't given an output frame, we shouldn't be processing any + // bytes. + if (outputFrame == null && isClient) { + return true; + } + // If we already have bytes to write, just return. + if (outputFrame != null && outputFrame.hasRemaining()) { + return true; + } + int remaining = bytes.remaining(); + // Call handshaker service to proceess the bytes. + if (outputFrame == null) { + checkState(!isClient, "Client handshaker should not process any frame at the beginning."); + outputFrame = handshaker.startServerHandshake(bytes); + } else { + outputFrame = handshaker.next(bytes); + } + // If handshake has finished or we already have bytes to write, just return true. + if (handshaker.isFinished() || outputFrame.hasRemaining()) { + return true; + } + // We have done processing input bytes, but no bytes to write. Thus we need more data. + if (!bytes.hasRemaining()) { + return false; + } + // There are still remaining bytes. Thus we need to continue processing the bytes. + // Prevent infinite loop by checking some bytes are consumed by handshaker. + checkState(bytes.remaining() < remaining, "Handshaker did not consume any bytes."); + return processBytesFromPeer(bytes); + } + + /** + * Returns the peer extracted from a completed handshake. + * + * @return the extracted peer. + */ + @Override + public TsiPeer extractPeer() throws GeneralSecurityException { + Preconditions.checkState(!isInProgress(), "Handshake is not complete."); + List> peerProperties = new ArrayList>(); + peerProperties.add( + new TsiPeer.StringProperty( + TSI_SERVICE_ACCOUNT_PEER_PROPERTY, + handshaker.getResult().getPeerIdentity().getServiceAccount())); + return new TsiPeer(peerProperties); + } + + /** + * Returns the peer extracted from a completed handshake. + * + * @return the extracted peer. + */ + @Override + public Object extractPeerObject() throws GeneralSecurityException { + Preconditions.checkState(!isInProgress(), "Handshake is not complete."); + return new AltsAuthContext(handshaker.getResult()); + } + + /** Creates a new TsiHandshaker for use by the client. */ + public static TsiHandshaker newClient(HandshakerServiceStub stub, AltsHandshakerOptions options) { + return new AltsTsiHandshaker(true, stub, options); + } + + /** Creates a new TsiHandshaker for use by the server. */ + public static TsiHandshaker newServer(HandshakerServiceStub stub, AltsHandshakerOptions options) { + return new AltsTsiHandshaker(false, stub, options); + } + + /** + * Gets bytes that need to be sent to the peer. + * + * @param bytes The buffer to put handshake bytes. + */ + @Override + public void getBytesToSendToPeer(ByteBuffer bytes) throws GeneralSecurityException { + if (outputFrame == null) { // A null outputFrame indicates we haven't started the handshake. + if (isClient) { + outputFrame = handshaker.startClientHandshake(); + } else { + // The server needs bytes to process before it can start the handshake. + return; + } + } + // Write as many bytes as we are able. + ByteBuffer outputFrameAlias = outputFrame; + if (outputFrame.remaining() > bytes.remaining()) { + outputFrameAlias = outputFrame.duplicate(); + outputFrameAlias.limit(outputFrameAlias.position() + bytes.remaining()); + } + bytes.put(outputFrameAlias); + outputFrame.position(outputFrameAlias.position()); + } + + /** + * Returns true if and only if the handshake is still in progress + * + * @return true, if the handshake is still in progress, false otherwise. + */ + @Override + public boolean isInProgress() { + return !handshaker.isFinished() || outputFrame.hasRemaining(); + } + + /** + * Creates a frame protector from a completed handshake. No other methods may be called after the + * frame protector is created. + * + * @param maxFrameSize the requested max frame size, the callee is free to ignore. + * @param alloc used for allocating ByteBufs. + * @return a new TsiFrameProtector. + */ + @Override + public TsiFrameProtector createFrameProtector(int maxFrameSize, ByteBufAllocator alloc) { + Preconditions.checkState(!isInProgress(), "Handshake is not complete."); + + byte[] key = handshaker.getKey(); + Preconditions.checkState(key.length == AltsChannelCrypter.getKeyLength(), "Bad key length."); + + return new AltsTsiFrameProtector(maxFrameSize, new AltsChannelCrypter(key, isClient), alloc); + } + + /** + * Creates a frame protector from a completed handshake. No other methods may be called after the + * frame protector is created. + * + * @param alloc used for allocating ByteBufs. + * @return a new TsiFrameProtector. + */ + @Override + public TsiFrameProtector createFrameProtector(ByteBufAllocator alloc) { + return createFrameProtector(AltsTsiFrameProtector.getMaxAllowedFrameBytes(), alloc); + } +} diff --git a/alts/src/main/java/io/grpc/alts/internal/BufUnwrapper.java b/alts/src/main/java/io/grpc/alts/internal/BufUnwrapper.java new file mode 100644 index 0000000000000000000000000000000000000000..9934dd2ff55681124fcafb35e397365a033d27ae --- /dev/null +++ b/alts/src/main/java/io/grpc/alts/internal/BufUnwrapper.java @@ -0,0 +1,84 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.CompositeByteBuf; +import java.nio.ByteBuffer; + +/** Unwraps {@link ByteBuf}s into {@link ByteBuffer}s. */ +final class BufUnwrapper implements AutoCloseable { + + private final ByteBuffer[] singleReadBuffer = new ByteBuffer[1]; + private final ByteBuffer[] singleWriteBuffer = new ByteBuffer[1]; + + /** + * Called to get access to the underlying NIO buffers for a {@link ByteBuf} that will be used for + * writing. + */ + ByteBuffer[] writableNioBuffers(ByteBuf buf) { + // Set the writer index to the capacity to guarantee that the returned NIO buffers will have + // the capacity available. + int readerIndex = buf.readerIndex(); + int writerIndex = buf.writerIndex(); + buf.readerIndex(writerIndex); + buf.writerIndex(buf.capacity()); + + try { + return nioBuffers(buf, singleWriteBuffer); + } finally { + // Restore the writer index before returning. + buf.readerIndex(readerIndex); + buf.writerIndex(writerIndex); + } + } + + /** + * Called to get access to the underlying NIO buffers for a {@link ByteBuf} that will be used for + * reading. + */ + ByteBuffer[] readableNioBuffers(ByteBuf buf) { + return nioBuffers(buf, singleReadBuffer); + } + + @Override + public void close() { + singleReadBuffer[0] = null; + singleWriteBuffer[0] = null; + } + + /** + * Optimized accessor for obtaining the underlying NIO buffers for a Netty {@link ByteBuf}. Based + * on code from Netty's {@code SslHandler}. This method returns NIO buffers that span the readable + * region of the {@link ByteBuf}. + */ + private static ByteBuffer[] nioBuffers(ByteBuf buf, ByteBuffer[] singleBuffer) { + // As CompositeByteBuf.nioBufferCount() can be expensive (as it needs to check all composed + // ByteBuf to calculate the count) we will just assume a CompositeByteBuf contains more than 1 + // ByteBuf. The worst that can happen is that we allocate an extra ByteBuffer[] in + // CompositeByteBuf.nioBuffers() which is better than walking the composed ByteBuf in most + // cases. + if (!(buf instanceof CompositeByteBuf) && buf.nioBufferCount() == 1) { + // We know its only backed by 1 ByteBuffer so use internalNioBuffer to keep object + // allocation to a minimum. + singleBuffer[0] = buf.internalNioBuffer(buf.readerIndex(), buf.readableBytes()); + return singleBuffer; + } + + return buf.nioBuffers(); + } +} diff --git a/alts/src/main/java/io/grpc/alts/internal/ChannelCrypterNetty.java b/alts/src/main/java/io/grpc/alts/internal/ChannelCrypterNetty.java new file mode 100644 index 0000000000000000000000000000000000000000..4164560e7a07af8a4b2e2c872d8e7c8c4f307793 --- /dev/null +++ b/alts/src/main/java/io/grpc/alts/internal/ChannelCrypterNetty.java @@ -0,0 +1,76 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import io.netty.buffer.ByteBuf; +import java.security.GeneralSecurityException; +import java.util.List; + +/** + * A @{code ChannelCrypterNetty} performs stateful encryption and decryption of independent input + * and output streams. Both decrypt and encrypt gather their input from a list of Netty @{link + * ByteBuf} instances. + * + *

Note that we provide implementations of this interface that provide integrity only and + * implementations that provide privacy and integrity. All methods should be thread-compatible. + */ +public interface ChannelCrypterNetty { + + /** + * Encrypt plaintext into output buffer. + * + * @param out the protected input will be written into this buffer. The buffer must be direct and + * have enough space to hold all input buffers and the tag. Encrypt does not take ownership of + * this buffer. + * @param plain the input buffers that should be protected. Encrypt does not modify or take + * ownership of these buffers. + */ + void encrypt(ByteBuf out, List plain) throws GeneralSecurityException; + + /** + * Decrypt ciphertext into the given output buffer and check tag. + * + * @param out the unprotected input will be written into this buffer. The buffer must be direct + * and have enough space to hold all ciphertext buffers and the tag, i.e., it must have + * additional space for the tag, even though this space will be unused in the final result. + * Decrypt does not take ownership of this buffer. + * @param tag the tag appended to the ciphertext. Decrypt does not modify or take ownership of + * this buffer. + * @param ciphertext the buffers that should be unprotected (excluding the tag). Decrypt does not + * modify or take ownership of these buffers. + */ + void decrypt(ByteBuf out, ByteBuf tag, List ciphertext) throws GeneralSecurityException; + + /** + * Decrypt ciphertext into the given output buffer and check tag. + * + * @param out the unprotected input will be written into this buffer. The buffer must be direct + * and have enough space to hold all ciphertext buffers and the tag, i.e., it must have + * additional space for the tag, even though this space will be unused in the final result. + * Decrypt does not take ownership of this buffer. + * @param ciphertextAndTag single buffer containing ciphertext and tag that should be unprotected. + * The buffer must be direct and either completely overlap with {@code out} or not overlap at + * all. + */ + void decrypt(ByteBuf out, ByteBuf ciphertextAndTag) throws GeneralSecurityException; + + /** Returns the length of the tag in bytes. */ + int getSuffixLength(); + + /** Must be called to release all associated resources (instance cannot be used afterwards). */ + void destroy(); +} diff --git a/alts/src/main/java/io/grpc/alts/internal/GoogleDefaultProtocolNegotiator.java b/alts/src/main/java/io/grpc/alts/internal/GoogleDefaultProtocolNegotiator.java new file mode 100644 index 0000000000000000000000000000000000000000..84288945f36e85c1d4d49fbacfa130cd83fb9164 --- /dev/null +++ b/alts/src/main/java/io/grpc/alts/internal/GoogleDefaultProtocolNegotiator.java @@ -0,0 +1,52 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import com.google.common.annotations.VisibleForTesting; +import io.grpc.internal.GrpcAttributes; +import io.grpc.netty.GrpcHttp2ConnectionHandler; +import io.grpc.netty.ProtocolNegotiator; +import io.grpc.netty.ProtocolNegotiators; +import io.netty.handler.ssl.SslContext; + +/** A client-side GPRC {@link ProtocolNegotiator} for Google Default Channel. */ +public final class GoogleDefaultProtocolNegotiator implements ProtocolNegotiator { + private final ProtocolNegotiator altsProtocolNegotiator; + private final ProtocolNegotiator tlsProtocolNegotiator; + + public GoogleDefaultProtocolNegotiator(TsiHandshakerFactory altsFactory, SslContext sslContext) { + altsProtocolNegotiator = AltsProtocolNegotiator.create(altsFactory); + tlsProtocolNegotiator = ProtocolNegotiators.tls(sslContext); + } + + @VisibleForTesting + GoogleDefaultProtocolNegotiator( + ProtocolNegotiator altsProtocolNegotiator, ProtocolNegotiator tlsProtocolNegotiator) { + this.altsProtocolNegotiator = altsProtocolNegotiator; + this.tlsProtocolNegotiator = tlsProtocolNegotiator; + } + + @Override + public Handler newHandler(GrpcHttp2ConnectionHandler grpcHandler) { + if (grpcHandler.getEagAttributes().get(GrpcAttributes.ATTR_LB_ADDR_AUTHORITY) != null + || grpcHandler.getEagAttributes().get(GrpcAttributes.ATTR_LB_PROVIDED_BACKEND) != null) { + return altsProtocolNegotiator.newHandler(grpcHandler); + } else { + return tlsProtocolNegotiator.newHandler(grpcHandler); + } + } +} diff --git a/alts/src/main/java/io/grpc/alts/internal/NettyTsiHandshaker.java b/alts/src/main/java/io/grpc/alts/internal/NettyTsiHandshaker.java new file mode 100644 index 0000000000000000000000000000000000000000..8d4bbd1a21e0c42f695b24530faa851d6e15f61e --- /dev/null +++ b/alts/src/main/java/io/grpc/alts/internal/NettyTsiHandshaker.java @@ -0,0 +1,152 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkState; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufAllocator; +import java.nio.ByteBuffer; +import java.security.GeneralSecurityException; + +/** + * A wrapper for a {@link io.grpc.alts.internal.TsiHandshaker} that accepts netty {@link ByteBuf}s. + */ +public final class NettyTsiHandshaker { + + private BufUnwrapper unwrapper = new BufUnwrapper(); + private final TsiHandshaker internalHandshaker; + + public NettyTsiHandshaker(TsiHandshaker handshaker) { + internalHandshaker = checkNotNull(handshaker); + } + + /** + * Gets data that is ready to be sent to the to the remote peer. This should be called in a loop + * until no bytes are written to the output buffer. + * + * @param out the buffer to receive the bytes. + */ + void getBytesToSendToPeer(ByteBuf out) throws GeneralSecurityException { + checkState(unwrapper != null, "protector already created"); + try (BufUnwrapper unwrapper = this.unwrapper) { + // Write as many bytes as possible into the buffer. + int bytesWritten = 0; + for (ByteBuffer nioBuffer : unwrapper.writableNioBuffers(out)) { + if (!nioBuffer.hasRemaining()) { + // This buffer doesn't have any more space to write, go to the next buffer. + continue; + } + + int prevPos = nioBuffer.position(); + internalHandshaker.getBytesToSendToPeer(nioBuffer); + bytesWritten += nioBuffer.position() - prevPos; + + // If the buffer position was not changed, the frame has been completely read into the + // buffers. + if (nioBuffer.position() == prevPos) { + break; + } + } + + out.writerIndex(out.writerIndex() + bytesWritten); + } + } + + /** + * Process handshake data received from the remote peer. + * + * @return {@code true}, if the handshake has all the data it needs to process and {@code false}, + * if the method must be called again to complete processing. + */ + boolean processBytesFromPeer(ByteBuf data) throws GeneralSecurityException { + checkState(unwrapper != null, "protector already created"); + try (BufUnwrapper unwrapper = this.unwrapper) { + int bytesRead = 0; + boolean done = false; + for (ByteBuffer nioBuffer : unwrapper.readableNioBuffers(data)) { + if (!nioBuffer.hasRemaining()) { + // This buffer has been fully read, continue to the next buffer. + continue; + } + + int prevPos = nioBuffer.position(); + done = internalHandshaker.processBytesFromPeer(nioBuffer); + bytesRead += nioBuffer.position() - prevPos; + if (done) { + break; + } + } + + data.readerIndex(data.readerIndex() + bytesRead); + return done; + } + } + + /** + * Returns true if and only if the handshake is still in progress + * + * @return true, if the handshake is still in progress, false otherwise. + */ + boolean isInProgress() { + return internalHandshaker.isInProgress(); + } + + /** + * Returns the peer extracted from a completed handshake. + * + * @return the extracted peer. + */ + TsiPeer extractPeer() throws GeneralSecurityException { + checkState(!internalHandshaker.isInProgress()); + return internalHandshaker.extractPeer(); + } + + /** + * Returns the peer extracted from a completed handshake. + * + * @return the extracted peer. + */ + Object extractPeerObject() throws GeneralSecurityException { + checkState(!internalHandshaker.isInProgress()); + return internalHandshaker.extractPeerObject(); + } + + /** + * Creates a frame protector from a completed handshake. No other methods may be called after the + * frame protector is created. + * + * @param maxFrameSize the requested max frame size, the callee is free to ignore. + * @return a new {@link io.grpc.alts.internal.TsiFrameProtector}. + */ + TsiFrameProtector createFrameProtector(int maxFrameSize, ByteBufAllocator alloc) { + unwrapper = null; + return internalHandshaker.createFrameProtector(maxFrameSize, alloc); + } + + /** + * Creates a frame protector from a completed handshake. No other methods may be called after the + * frame protector is created. + * + * @return a new {@link io.grpc.alts.internal.TsiFrameProtector}. + */ + TsiFrameProtector createFrameProtector(ByteBufAllocator alloc) { + unwrapper = null; + return internalHandshaker.createFrameProtector(alloc); + } +} diff --git a/alts/src/main/java/io/grpc/alts/internal/ProtectedPromise.java b/alts/src/main/java/io/grpc/alts/internal/ProtectedPromise.java new file mode 100644 index 0000000000000000000000000000000000000000..a19a8160f58760fb9fd7b5bd0bbd58df6611986b --- /dev/null +++ b/alts/src/main/java/io/grpc/alts/internal/ProtectedPromise.java @@ -0,0 +1,149 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import static com.google.common.base.Preconditions.checkState; + +import io.netty.channel.Channel; +import io.netty.channel.ChannelPromise; +import io.netty.channel.DefaultChannelPromise; +import io.netty.util.concurrent.EventExecutor; +import java.util.ArrayList; +import java.util.List; + +/** + * Promise used when flushing the {@code pendingUnprotectedWrites} queue. It manages the many-to + * many relationship between pending unprotected messages and the individual writes. Each protected + * frame will be written using the same instance of this promise and it will accumulate the results. + * Once all frames have been successfully written (or any failed), all of the promises for the + * pending unprotected writes are notified. + * + *

NOTE: this code is based on code in Netty's {@code Http2CodecUtil}. + */ +final class ProtectedPromise extends DefaultChannelPromise { + private final List unprotectedPromises; + private int expectedCount; + private int successfulCount; + private int failureCount; + private boolean doneAllocating; + + ProtectedPromise(Channel channel, EventExecutor executor, int numUnprotectedPromises) { + super(channel, executor); + unprotectedPromises = new ArrayList<>(numUnprotectedPromises); + } + + /** + * Adds a promise for a pending unprotected write. This will be notified after all of the writes + * complete. + */ + void addUnprotectedPromise(ChannelPromise promise) { + unprotectedPromises.add(promise); + } + + /** + * Allocate a new promise for the write of a protected frame. This will be used to aggregate the + * overall success of the unprotected promises. + * + * @return {@code this} promise. + */ + ChannelPromise newPromise() { + checkState(!doneAllocating, "Done allocating. No more promises can be allocated."); + expectedCount++; + return this; + } + + /** + * Signify that no more {@link #newPromise()} allocations will be made. The aggregation can not be + * successful until this method is called. + * + * @return {@code this} promise. + */ + ChannelPromise doneAllocatingPromises() { + if (!doneAllocating) { + doneAllocating = true; + if (successfulCount == expectedCount) { + trySuccessInternal(null); + return super.setSuccess(null); + } + } + return this; + } + + @Override + public boolean tryFailure(Throwable cause) { + if (awaitingPromises()) { + ++failureCount; + if (failureCount == 1) { + tryFailureInternal(cause); + return super.tryFailure(cause); + } + // TODO: We break the interface a bit here. + // Multiple failure events can be processed without issue because this is an aggregation. + return true; + } + return false; + } + + /** + * Fail this object if it has not already been failed. + * + *

This method will NOT throw an {@link IllegalStateException} if called multiple times because + * that may be expected. + */ + @Override + public ChannelPromise setFailure(Throwable cause) { + tryFailure(cause); + return this; + } + + private boolean awaitingPromises() { + return successfulCount + failureCount < expectedCount; + } + + @Override + public ChannelPromise setSuccess(Void result) { + trySuccess(result); + return this; + } + + @Override + public boolean trySuccess(Void result) { + if (awaitingPromises()) { + ++successfulCount; + if (successfulCount == expectedCount && doneAllocating) { + trySuccessInternal(result); + return super.trySuccess(result); + } + // TODO: We break the interface a bit here. + // Multiple success events can be processed without issue because this is an aggregation. + return true; + } + return false; + } + + private void trySuccessInternal(Void result) { + for (int i = 0; i < unprotectedPromises.size(); ++i) { + unprotectedPromises.get(i).trySuccess(result); + } + } + + private void tryFailureInternal(Throwable cause) { + for (int i = 0; i < unprotectedPromises.size(); ++i) { + unprotectedPromises.get(i).tryFailure(cause); + } + } +} diff --git a/alts/src/main/java/io/grpc/alts/internal/RpcProtocolVersionsUtil.java b/alts/src/main/java/io/grpc/alts/internal/RpcProtocolVersionsUtil.java new file mode 100644 index 0000000000000000000000000000000000000000..b685b6b2d3feda680d144d3427a68c2edfea3b82 --- /dev/null +++ b/alts/src/main/java/io/grpc/alts/internal/RpcProtocolVersionsUtil.java @@ -0,0 +1,130 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import com.google.common.annotations.VisibleForTesting; +import io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions; +import io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version; +import javax.annotation.Nullable; + +/** Utility class for Rpc Protocol Versions. */ +public final class RpcProtocolVersionsUtil { + + private static final int MAX_RPC_VERSION_MAJOR = 2; + private static final int MAX_RPC_VERSION_MINOR = 1; + private static final int MIN_RPC_VERSION_MAJOR = 2; + private static final int MIN_RPC_VERSION_MINOR = 1; + private static final RpcProtocolVersions RPC_PROTOCOL_VERSIONS = + RpcProtocolVersions.newBuilder() + .setMaxRpcVersion( + RpcProtocolVersions.Version.newBuilder() + .setMajor(MAX_RPC_VERSION_MAJOR) + .setMinor(MAX_RPC_VERSION_MINOR) + .build()) + .setMinRpcVersion( + RpcProtocolVersions.Version.newBuilder() + .setMajor(MIN_RPC_VERSION_MAJOR) + .setMinor(MIN_RPC_VERSION_MINOR) + .build()) + .build(); + + /** Returns default Rpc Protocol Versions. */ + public static RpcProtocolVersions getRpcProtocolVersions() { + return RPC_PROTOCOL_VERSIONS; + } + + /** + * Returns true if first Rpc Protocol Version is greater than or equal to the second one. Returns + * false otherwise. + */ + @VisibleForTesting + static boolean isGreaterThanOrEqualTo(Version first, Version second) { + if ((first.getMajor() > second.getMajor()) + || (first.getMajor() == second.getMajor() && first.getMinor() >= second.getMinor())) { + return true; + } + return false; + } + + /** + * Performs check between local and peer Rpc Protocol Versions. This function returns true and the + * highest common version if there exists a common Rpc Protocol Version to use, and returns false + * and null otherwise. + */ + static RpcVersionsCheckResult checkRpcProtocolVersions( + RpcProtocolVersions localVersions, RpcProtocolVersions peerVersions) { + Version maxCommonVersion; + Version minCommonVersion; + // maxCommonVersion is MIN(local.max, peer.max) + if (isGreaterThanOrEqualTo(localVersions.getMaxRpcVersion(), peerVersions.getMaxRpcVersion())) { + maxCommonVersion = peerVersions.getMaxRpcVersion(); + } else { + maxCommonVersion = localVersions.getMaxRpcVersion(); + } + // minCommonVersion is MAX(local.min, peer.min) + if (isGreaterThanOrEqualTo(localVersions.getMinRpcVersion(), peerVersions.getMinRpcVersion())) { + minCommonVersion = localVersions.getMinRpcVersion(); + } else { + minCommonVersion = peerVersions.getMinRpcVersion(); + } + if (isGreaterThanOrEqualTo(maxCommonVersion, minCommonVersion)) { + return new RpcVersionsCheckResult.Builder() + .setResult(true) + .setHighestCommonVersion(maxCommonVersion) + .build(); + } + return new RpcVersionsCheckResult.Builder().setResult(false).build(); + } + + /** Wrapper class that stores results of Rpc Protocol Versions check. */ + static final class RpcVersionsCheckResult { + private final boolean result; + @Nullable private final Version highestCommonVersion; + + private RpcVersionsCheckResult(Builder builder) { + result = builder.result; + highestCommonVersion = builder.highestCommonVersion; + } + + boolean getResult() { + return result; + } + + Version getHighestCommonVersion() { + return highestCommonVersion; + } + + static final class Builder { + private boolean result; + @Nullable private Version highestCommonVersion = null; + + public Builder setResult(boolean result) { + this.result = result; + return this; + } + + public Builder setHighestCommonVersion(Version highestCommonVersion) { + this.highestCommonVersion = highestCommonVersion; + return this; + } + + public RpcVersionsCheckResult build() { + return new RpcVersionsCheckResult(this); + } + } + } +} diff --git a/alts/src/main/java/io/grpc/alts/internal/TsiFrameHandler.java b/alts/src/main/java/io/grpc/alts/internal/TsiFrameHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..60ce859a9544d0fe55e9801d27d898162f9ec13e --- /dev/null +++ b/alts/src/main/java/io/grpc/alts/internal/TsiFrameHandler.java @@ -0,0 +1,181 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkState; + +import com.google.common.annotations.VisibleForTesting; +import io.grpc.alts.internal.TsiFrameProtector.Consumer; +import io.grpc.alts.internal.TsiHandshakeHandler.TsiHandshakeCompletionEvent; +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelException; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelOutboundHandler; +import io.netty.channel.ChannelPromise; +import io.netty.channel.PendingWriteQueue; +import io.netty.handler.codec.ByteToMessageDecoder; +import java.net.SocketAddress; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Future; + +/** + * Encrypts and decrypts TSI Frames. Writes are buffered here until {@link #flush} is called. Writes + * must not be made before the TSI handshake is complete. + */ +public final class TsiFrameHandler extends ByteToMessageDecoder implements ChannelOutboundHandler { + + private TsiFrameProtector protector; + private PendingWriteQueue pendingUnprotectedWrites; + + public TsiFrameHandler() {} + + @Override + public void handlerAdded(ChannelHandlerContext ctx) throws Exception { + super.handlerAdded(ctx); + assert pendingUnprotectedWrites == null; + pendingUnprotectedWrites = new PendingWriteQueue(checkNotNull(ctx)); + } + + @Override + public void userEventTriggered(ChannelHandlerContext ctx, Object event) throws Exception { + if (event instanceof TsiHandshakeCompletionEvent) { + TsiHandshakeCompletionEvent tsiEvent = (TsiHandshakeCompletionEvent) event; + if (tsiEvent.isSuccess()) { + setProtector(tsiEvent.protector()); + } + // Ignore errors. Another handler in the pipeline must handle TSI Errors. + } + // Keep propagating the message, as others may want to read it. + super.userEventTriggered(ctx, event); + } + + @VisibleForTesting + void setProtector(TsiFrameProtector protector) { + checkState(this.protector == null); + this.protector = checkNotNull(protector); + } + + @Override + protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception { + checkState(protector != null, "Cannot read frames while the TSI handshake is in progress"); + protector.unprotect(in, out, ctx.alloc()); + } + + @Override + public void write(ChannelHandlerContext ctx, Object message, ChannelPromise promise) + throws Exception { + checkState(protector != null, "Cannot write frames while the TSI handshake is in progress"); + ByteBuf msg = (ByteBuf) message; + if (!msg.isReadable()) { + // Nothing to encode. + @SuppressWarnings("unused") // go/futurereturn-lsc + Future possiblyIgnoredError = promise.setSuccess(); + return; + } + + // Just add the message to the pending queue. We'll write it on the next flush. + pendingUnprotectedWrites.add(msg, promise); + } + + @Override + public void handlerRemoved0(ChannelHandlerContext ctx) throws Exception { + if (!pendingUnprotectedWrites.isEmpty()) { + pendingUnprotectedWrites.removeAndFailAll( + new ChannelException("Pending write on removal of TSI handler")); + } + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + pendingUnprotectedWrites.removeAndFailAll(cause); + super.exceptionCaught(ctx, cause); + } + + @Override + public void bind(ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise) { + ctx.bind(localAddress, promise); + } + + @Override + public void connect( + ChannelHandlerContext ctx, + SocketAddress remoteAddress, + SocketAddress localAddress, + ChannelPromise promise) { + ctx.connect(remoteAddress, localAddress, promise); + } + + @Override + public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) { + ctx.disconnect(promise); + } + + @Override + public void close(ChannelHandlerContext ctx, ChannelPromise promise) { + ctx.close(promise); + } + + @Override + public void deregister(ChannelHandlerContext ctx, ChannelPromise promise) { + ctx.deregister(promise); + } + + @Override + public void read(ChannelHandlerContext ctx) { + ctx.read(); + } + + @Override + public void flush(final ChannelHandlerContext ctx) throws GeneralSecurityException { + checkState(protector != null, "Cannot write frames while the TSI handshake is in progress"); + final ProtectedPromise aggregatePromise = + new ProtectedPromise(ctx.channel(), ctx.executor(), pendingUnprotectedWrites.size()); + + List bufs = new ArrayList<>(pendingUnprotectedWrites.size()); + + if (pendingUnprotectedWrites.isEmpty()) { + // Return early if there's nothing to write. Otherwise protector.protectFlush() below may + // not check for "no-data" and go on writing the 0-byte "data" to the socket with the + // protection framing. + return; + } + // Drain the unprotected writes. + while (!pendingUnprotectedWrites.isEmpty()) { + ByteBuf in = (ByteBuf) pendingUnprotectedWrites.current(); + bufs.add(in.retain()); + // Remove and release the buffer and add its promise to the aggregate. + aggregatePromise.addUnprotectedPromise(pendingUnprotectedWrites.remove()); + } + + protector.protectFlush( + bufs, + new Consumer() { + @Override + public void accept(ByteBuf b) { + ctx.writeAndFlush(b, aggregatePromise.newPromise()); + } + }, + ctx.alloc()); + + // We're done writing, start the flow of promise events. + @SuppressWarnings("unused") // go/futurereturn-lsc + Future possiblyIgnoredError = aggregatePromise.doneAllocatingPromises(); + } +} diff --git a/alts/src/main/java/io/grpc/alts/internal/TsiFrameProtector.java b/alts/src/main/java/io/grpc/alts/internal/TsiFrameProtector.java new file mode 100644 index 0000000000000000000000000000000000000000..b4227989ef2f0c3b238ec0d7107bab33539459c3 --- /dev/null +++ b/alts/src/main/java/io/grpc/alts/internal/TsiFrameProtector.java @@ -0,0 +1,60 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufAllocator; +import java.security.GeneralSecurityException; +import java.util.List; + +/** + * This object protects and unprotects netty buffers once the handshake is done. + * + *

Implementations of this object must be thread compatible. + */ +public interface TsiFrameProtector { + + /** + * Protects the buffers by performing framing and encrypting/appending MACs. + * + * @param unprotectedBufs contain the payload that will be protected + * @param ctxWrite is called with buffers containing protected frames and must release the given + * buffers + * @param alloc is used to allocate new buffers for the protected frames + */ + void protectFlush( + List unprotectedBufs, Consumer ctxWrite, ByteBufAllocator alloc) + throws GeneralSecurityException; + + /** + * Unprotects the buffers by removing the framing and decrypting/checking MACs. + * + * @param in contains (partial) protected frames + * @param out is only used to append unprotected payload buffers + * @param alloc is used to allocate new buffers for the unprotected frames + */ + void unprotect(ByteBuf in, List out, ByteBufAllocator alloc) + throws GeneralSecurityException; + + /** Must be called to release all associated resources (instance cannot be used afterwards). */ + void destroy(); + + /** A mirror of java.util.function.Consumer without the Java 8 dependency. */ + interface Consumer { + void accept(T t); + } +} diff --git a/alts/src/main/java/io/grpc/alts/internal/TsiHandshakeHandler.java b/alts/src/main/java/io/grpc/alts/internal/TsiHandshakeHandler.java new file mode 100644 index 0000000000000000000000000000000000000000..2cc66b06fd886bd2a9f7ba589d63419da385f1ed --- /dev/null +++ b/alts/src/main/java/io/grpc/alts/internal/TsiHandshakeHandler.java @@ -0,0 +1,212 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import static com.google.common.base.Preconditions.checkNotNull; + +import com.google.common.annotations.VisibleForTesting; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufAllocator; +import io.netty.channel.ChannelHandlerContext; +import io.netty.handler.codec.ByteToMessageDecoder; +import io.netty.util.ReferenceCountUtil; +import java.security.GeneralSecurityException; +import java.util.List; +import java.util.concurrent.Future; +import javax.annotation.Nullable; + +/** + * Performs The TSI Handshake. When the handshake is complete, it fires a user event with a {@link + * TsiHandshakeCompletionEvent} indicating the result of the handshake. + */ +public final class TsiHandshakeHandler extends ByteToMessageDecoder { + private static final int HANDSHAKE_FRAME_SIZE = 1024; + + private final NettyTsiHandshaker handshaker; + private boolean started; + + /** + * This buffer doesn't store any state. We just hold onto it in case we end up allocating a buffer + * that ends up being unused. + */ + private ByteBuf buffer; + + public TsiHandshakeHandler(NettyTsiHandshaker handshaker) { + this.handshaker = checkNotNull(handshaker); + } + + /** + * Event that is fired once the TSI handshake is complete, which may be because it was successful + * or there was an error. + */ + public static final class TsiHandshakeCompletionEvent { + + private final Throwable cause; + private final TsiPeer peer; + private final Object context; + private final TsiFrameProtector protector; + + /** Creates a new event that indicates a successful handshake. */ + @VisibleForTesting + TsiHandshakeCompletionEvent( + TsiFrameProtector protector, TsiPeer peer, @Nullable Object peerObject) { + this.cause = null; + this.peer = checkNotNull(peer); + this.protector = checkNotNull(protector); + this.context = peerObject; + } + + /** Creates a new event that indicates an unsuccessful handshake/. */ + TsiHandshakeCompletionEvent(Throwable cause) { + this.cause = checkNotNull(cause); + this.peer = null; + this.protector = null; + this.context = null; + } + + /** Return {@code true} if the handshake was successful. */ + public boolean isSuccess() { + return cause == null; + } + + /** + * Return the {@link Throwable} if {@link #isSuccess()} returns {@code false} and so the + * handshake failed. + */ + @Nullable + public Throwable cause() { + return cause; + } + + @Nullable + public TsiPeer peer() { + return peer; + } + + @Nullable + public Object context() { + return context; + } + + @Nullable + TsiFrameProtector protector() { + return protector; + } + } + + @Override + public void handlerAdded(ChannelHandlerContext ctx) throws Exception { + maybeStart(ctx); + super.handlerAdded(ctx); + } + + @Override + public void channelActive(ChannelHandlerContext ctx) throws Exception { + maybeStart(ctx); + super.channelActive(ctx); + } + + @Override + public void handlerRemoved0(ChannelHandlerContext ctx) throws Exception { + close(); + super.handlerRemoved0(ctx); + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + ctx.fireUserEventTriggered(new TsiHandshakeCompletionEvent(cause)); + super.exceptionCaught(ctx, cause); + } + + @Override + protected void decodeLast(ChannelHandlerContext ctx, ByteBuf in, List out) + throws Exception { + // TODO: Not sure why override is needed. Investigate if it can be removed. + decode(ctx, in, out); + } + + @Override + protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception { + // Process the data. If we need to send more data, do so now. + if (handshaker.processBytesFromPeer(in) && handshaker.isInProgress()) { + sendHandshake(ctx); + } + + // If the handshake is complete, transition to the framing state. + if (!handshaker.isInProgress()) { + try { + ctx.pipeline().remove(this); + ctx.fireUserEventTriggered( + new TsiHandshakeCompletionEvent( + handshaker.createFrameProtector(ctx.alloc()), + handshaker.extractPeer(), + handshaker.extractPeerObject())); + // No need to do anything with the in buffer, it will be re added to the pipeline when this + // handler is removed. + } finally { + close(); + } + } + } + + private void maybeStart(ChannelHandlerContext ctx) { + if (!started && ctx.channel().isActive()) { + started = true; + sendHandshake(ctx); + } + } + + /** Sends as many bytes as are available from the handshaker to the remote peer. */ + private void sendHandshake(ChannelHandlerContext ctx) { + boolean needToFlush = false; + + // Iterate until there is nothing left to write. + while (true) { + buffer = getOrCreateBuffer(ctx.alloc()); + try { + handshaker.getBytesToSendToPeer(buffer); + } catch (GeneralSecurityException e) { + throw new RuntimeException(e); + } + if (!buffer.isReadable()) { + break; + } + + needToFlush = true; + @SuppressWarnings("unused") // go/futurereturn-lsc + Future possiblyIgnoredError = ctx.write(buffer); + buffer = null; + } + + // If something was written, flush. + if (needToFlush) { + ctx.flush(); + } + } + + private ByteBuf getOrCreateBuffer(ByteBufAllocator alloc) { + if (buffer == null) { + buffer = alloc.buffer(HANDSHAKE_FRAME_SIZE); + } + return buffer; + } + + private void close() { + ReferenceCountUtil.safeRelease(buffer); + buffer = null; + } +} diff --git a/alts/src/main/java/io/grpc/alts/internal/TsiHandshaker.java b/alts/src/main/java/io/grpc/alts/internal/TsiHandshaker.java new file mode 100644 index 0000000000000000000000000000000000000000..967582aa811f8e615bf7b6c43c85ecc90a1339c7 --- /dev/null +++ b/alts/src/main/java/io/grpc/alts/internal/TsiHandshaker.java @@ -0,0 +1,109 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import io.netty.buffer.ByteBufAllocator; +import java.nio.ByteBuffer; +import java.security.GeneralSecurityException; + +/** + * This object protects and unprotects buffers once the handshake is done. + * + *

A typical usage of this object would be: + * + *

{@code
+ * ByteBuffer buffer = allocateDirect(ALLOCATE_SIZE);
+ * while (true) {
+ *   while (true) {
+ *     tsiHandshaker.getBytesToSendToPeer(buffer.clear());
+ *     if (!buffer.hasRemaining()) break;
+ *     yourTransportSendMethod(buffer.flip());
+ *     assert(!buffer.hasRemaining());  // Guaranteed by yourTransportReceiveMethod(...)
+ *   }
+ *   if (!tsiHandshaker.isInProgress()) break;
+ *   while (true) {
+ *     assert(!buffer.hasRemaining());
+ *     yourTransportReceiveMethod(buffer.clear());
+ *     if (tsiHandshaker.processBytesFromPeer(buffer.flip())) break;
+ *   }
+ *   if (!tsiHandshaker.isInProgress()) break;
+ *   assert(!buffer.hasRemaining());
+ * }
+ * yourCheckPeerMethod(tsiHandshaker.extractPeer());
+ * TsiFrameProtector tsiFrameProtector = tsiHandshaker.createFrameProtector(MAX_FRAME_SIZE);
+ * if (buffer.hasRemaining()) tsiFrameProtector.unprotect(buffer, messageBuffer);
+ * }
+ * + *

Implementations of this object must be thread compatible. + */ +public interface TsiHandshaker { + /** + * Gets bytes that need to be sent to the peer. + * + * @param bytes The buffer to put handshake bytes. + */ + void getBytesToSendToPeer(ByteBuffer bytes) throws GeneralSecurityException; + + /** + * Process the bytes received from the peer. + * + * @param bytes The buffer containing the handshake bytes from the peer. + * @return true, if the handshake has all the data it needs to process and false, if the method + * must be called again to complete processing. + */ + boolean processBytesFromPeer(ByteBuffer bytes) throws GeneralSecurityException; + + /** + * Returns true if and only if the handshake is still in progress + * + * @return true, if the handshake is still in progress, false otherwise. + */ + boolean isInProgress(); + + /** + * Returns the peer extracted from a completed handshake. + * + * @return the extracted peer. + */ + TsiPeer extractPeer() throws GeneralSecurityException; + + /** + * Returns the peer extracted from a completed handshake. + * + * @return the extracted peer. + */ + public Object extractPeerObject() throws GeneralSecurityException; + + /** + * Creates a frame protector from a completed handshake. No other methods may be called after the + * frame protector is created. + * + * @param maxFrameSize the requested max frame size, the callee is free to ignore. + * @param alloc used for allocating ByteBufs. + * @return a new TsiFrameProtector. + */ + TsiFrameProtector createFrameProtector(int maxFrameSize, ByteBufAllocator alloc); + + /** + * Creates a frame protector from a completed handshake. No other methods may be called after the + * frame protector is created. + * + * @param alloc used for allocating ByteBufs. + * @return a new TsiFrameProtector. + */ + TsiFrameProtector createFrameProtector(ByteBufAllocator alloc); +} diff --git a/alts/src/main/java/io/grpc/alts/internal/TsiHandshakerFactory.java b/alts/src/main/java/io/grpc/alts/internal/TsiHandshakerFactory.java new file mode 100644 index 0000000000000000000000000000000000000000..58e3726cbd3a91e7c3248f939ae26eeb3ffbeae1 --- /dev/null +++ b/alts/src/main/java/io/grpc/alts/internal/TsiHandshakerFactory.java @@ -0,0 +1,24 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +/** Factory that manufactures instances of {@link TsiHandshaker}. */ +public interface TsiHandshakerFactory { + + /** Creates a new handshaker. */ + TsiHandshaker newHandshaker(); +} diff --git a/alts/src/main/java/io/grpc/alts/internal/TsiPeer.java b/alts/src/main/java/io/grpc/alts/internal/TsiPeer.java new file mode 100644 index 0000000000000000000000000000000000000000..990cf0b9c03971dc866ce6645261bdd2cf82cf55 --- /dev/null +++ b/alts/src/main/java/io/grpc/alts/internal/TsiPeer.java @@ -0,0 +1,110 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import javax.annotation.Nonnull; + +/** A set of peer properties. */ +public final class TsiPeer { + private final List> properties; + + public TsiPeer(List> properties) { + this.properties = Collections.unmodifiableList(properties); + } + + public List> getProperties() { + return properties; + } + + /** Get peer property. */ + public Property getProperty(String name) { + for (Property property : properties) { + if (property.getName().equals(name)) { + return property; + } + } + return null; + } + + @Override + public String toString() { + return new ArrayList<>(properties).toString(); + } + + /** A peer property. */ + public abstract static class Property { + private final String name; + private final T value; + + public Property(@Nonnull String name, @Nonnull T value) { + this.name = name; + this.value = value; + } + + public final T getValue() { + return value; + } + + public final String getName() { + return name; + } + + @Override + public String toString() { + return String.format("%s=%s", name, value); + } + } + + /** A peer property corresponding to a signed 64-bit integer. */ + public static final class SignedInt64Property extends Property { + public SignedInt64Property(@Nonnull String name, @Nonnull Long value) { + super(name, value); + } + } + + /** A peer property corresponding to an unsigned 64-bit integer. */ + public static final class UnsignedInt64Property extends Property { + public UnsignedInt64Property(@Nonnull String name, @Nonnull BigInteger value) { + super(name, value); + } + } + + /** A peer property corresponding to a double. */ + public static final class DoubleProperty extends Property { + public DoubleProperty(@Nonnull String name, @Nonnull Double value) { + super(name, value); + } + } + + /** A peer property corresponding to a string. */ + public static final class StringProperty extends Property { + public StringProperty(@Nonnull String name, @Nonnull String value) { + super(name, value); + } + } + + /** A peer property corresponding to a list of peer properties. */ + public static final class PropertyList extends Property>> { + public PropertyList(@Nonnull String name, @Nonnull List> value) { + super(name, value); + } + } +} diff --git a/alts/src/main/proto/grpc/gcp/altscontext.proto b/alts/src/main/proto/grpc/gcp/altscontext.proto new file mode 100644 index 0000000000000000000000000000000000000000..9568c0718718860e785fc59f06ba04879c5bec8d --- /dev/null +++ b/alts/src/main/proto/grpc/gcp/altscontext.proto @@ -0,0 +1,41 @@ +// Copyright 2018 The gRPC Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package grpc.gcp; + +import "grpc/gcp/transport_security_common.proto"; + +option java_package = "io.grpc.alts.internal"; + +message AltsContext { + // The application protocol negotiated for this connection. + string application_protocol = 1; + + // The record protocol negotiated for this connection. + string record_protocol = 2; + + // The security level of the created secure channel. + SecurityLevel security_level = 3; + + // The peer service account. + string peer_service_account = 4; + + // The local service account. + string local_service_account = 5; + + // The RPC protocol versions supported by the peer. + RpcProtocolVersions peer_rpc_versions = 6; +} diff --git a/alts/src/main/proto/grpc/gcp/handshaker.proto b/alts/src/main/proto/grpc/gcp/handshaker.proto new file mode 100644 index 0000000000000000000000000000000000000000..3a1fd717cfa9b162bfc8c13668aa65f08ae0dbb6 --- /dev/null +++ b/alts/src/main/proto/grpc/gcp/handshaker.proto @@ -0,0 +1,224 @@ +// Copyright 2018 The gRPC Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package grpc.gcp; + +import "grpc/gcp/transport_security_common.proto"; + +option java_package = "io.grpc.alts.internal"; + +enum HandshakeProtocol { + // Default value. + HANDSHAKE_PROTOCOL_UNSPECIFIED = 0; + + // TLS handshake protocol. + TLS = 1; + + // Application Layer Transport Security handshake protocol. + ALTS = 2; +} + +enum NetworkProtocol { + NETWORK_PROTOCOL_UNSPECIFIED = 0; + TCP = 1; + UDP = 2; +} + +message Endpoint { + // IP address. It should contain an IPv4 or IPv6 string literal, e.g. + // "192.168.0.1" or "2001:db8::1". + string ip_address = 1; + + // Port number. + int32 port = 2; + + // Network protocol (e.g., TCP, UDP) associated with this endpoint. + NetworkProtocol protocol = 3; +} + +message Identity { + oneof identity_oneof { + // Service account of a connection endpoint. + string service_account = 1; + + // Hostname of a connection endpoint. + string hostname = 2; + } +} + +message StartClientHandshakeReq { + // Handshake security protocol requested by the client. + HandshakeProtocol handshake_security_protocol = 1; + + // The application protocols supported by the client, e.g., "h2" (for http2), + // "grpc". + repeated string application_protocols = 2; + + // The record protocols supported by the client, e.g., + // "ALTSRP_GCM_AES128". + repeated string record_protocols = 3; + + // (Optional) Describes which server identities are acceptable by the client. + // If target identities are provided and none of them matches the peer + // identity of the server, handshake will fail. + repeated Identity target_identities = 4; + + // (Optional) Application may specify a local identity. Otherwise, the + // handshaker chooses a default local identity. + Identity local_identity = 5; + + // (Optional) Local endpoint information of the connection to the server, + // such as local IP address, port number, and network protocol. + Endpoint local_endpoint = 6; + + // (Optional) Endpoint information of the remote server, such as IP address, + // port number, and network protocol. + Endpoint remote_endpoint = 7; + + // (Optional) If target name is provided, a secure naming check is performed + // to verify that the peer authenticated identity is indeed authorized to run + // the target name. + string target_name = 8; + + // (Optional) RPC protocol versions supported by the client. + RpcProtocolVersions rpc_versions = 9; +} + +message ServerHandshakeParameters { + // The record protocols supported by the server, e.g., + // "ALTSRP_GCM_AES128". + repeated string record_protocols = 1; + + // (Optional) A list of local identities supported by the server, if + // specified. Otherwise, the handshaker chooses a default local identity. + repeated Identity local_identities = 2; +} + +message StartServerHandshakeReq { + // The application protocols supported by the server, e.g., "h2" (for http2), + // "grpc". + repeated string application_protocols = 1; + + // Handshake parameters (record protocols and local identities supported by + // the server) mapped by the handshake protocol. Each handshake security + // protocol (e.g., TLS or ALTS) has its own set of record protocols and local + // identities. Since protobuf does not support enum as key to the map, the key + // to handshake_parameters is the integer value of HandshakeProtocol enum. + map handshake_parameters = 2; + + // Bytes in out_frames returned from the peer's HandshakerResp. It is possible + // that the peer's out_frames are split into multiple HandshakReq messages. + bytes in_bytes = 3; + + // (Optional) Local endpoint information of the connection to the client, + // such as local IP address, port number, and network protocol. + Endpoint local_endpoint = 4; + + // (Optional) Endpoint information of the remote client, such as IP address, + // port number, and network protocol. + Endpoint remote_endpoint = 5; + + // (Optional) RPC protocol versions supported by the server. + RpcProtocolVersions rpc_versions = 6; +} + +message NextHandshakeMessageReq { + // Bytes in out_frames returned from the peer's HandshakerResp. It is possible + // that the peer's out_frames are split into multiple NextHandshakerMessageReq + // messages. + bytes in_bytes = 1; +} + +message HandshakerReq { + oneof req_oneof { + // The start client handshake request message. + StartClientHandshakeReq client_start = 1; + + // The start server handshake request message. + StartServerHandshakeReq server_start = 2; + + // The next handshake request message. + NextHandshakeMessageReq next = 3; + } +} + +message HandshakerResult { + // The application protocol negotiated for this connection. + string application_protocol = 1; + + // The record protocol negotiated for this connection. + string record_protocol = 2; + + // Cryptographic key data. The key data may be more than the key length + // required for the record protocol, thus the client of the handshaker + // service needs to truncate the key data into the right key length. + bytes key_data = 3; + + // The authenticated identity of the peer. + Identity peer_identity = 4; + + // The local identity used in the handshake. + Identity local_identity = 5; + + // Indicate whether the handshaker service client should keep the channel + // between the handshaker service open, e.g., in order to handle + // post-handshake messages in the future. + bool keep_channel_open = 6; + + // The RPC protocol versions supported by the peer. + RpcProtocolVersions peer_rpc_versions = 7; +} + +message HandshakerStatus { + // The status code. This could be the gRPC status code. + uint32 code = 1; + + // The status details. + string details = 2; +} + +message HandshakerResp { + // Frames to be given to the peer for the NextHandshakeMessageReq. May be + // empty if no out_frames have to be sent to the peer or if in_bytes in the + // HandshakerReq are incomplete. All the non-empty out frames must be sent to + // the peer even if the handshaker status is not OK as these frames may + // contain the alert frames. + bytes out_frames = 1; + + // Number of bytes in the in_bytes consumed by the handshaker. It is possible + // that part of in_bytes in HandshakerReq was unrelated to the handshake + // process. + uint32 bytes_consumed = 2; + + // This is set iff the handshake was successful. out_frames may still be set + // to frames that needs to be forwarded to the peer. + HandshakerResult result = 3; + + // Status of the handshaker. + HandshakerStatus status = 4; +} + +service HandshakerService { + // Handshaker service accepts a stream of handshaker request, returning a + // stream of handshaker response. Client is expected to send exactly one + // message with either client_start or server_start followed by one or more + // messages with next. Each time client sends a request, the handshaker + // service expects to respond. Client does not have to wait for service's + // response before sending next request. + rpc DoHandshake(stream HandshakerReq) + returns (stream HandshakerResp) { + } +} diff --git a/alts/src/main/proto/grpc/gcp/transport_security_common.proto b/alts/src/main/proto/grpc/gcp/transport_security_common.proto new file mode 100644 index 0000000000000000000000000000000000000000..e10197159e099a70f03e6f23060d1fc38a4469a0 --- /dev/null +++ b/alts/src/main/proto/grpc/gcp/transport_security_common.proto @@ -0,0 +1,40 @@ +// Copyright 2018 The gRPC Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +syntax = "proto3"; + +package grpc.gcp; + +option java_package = "io.grpc.alts.internal"; + +// The security level of the created channel. The list is sorted in increasing +// level of security. This order must always be maintained. +enum SecurityLevel { + SECURITY_NONE = 0; + INTEGRITY_ONLY = 1; + INTEGRITY_AND_PRIVACY = 2; +} + +// Max and min supported RPC protocol versions. +message RpcProtocolVersions { + // RPC version contains a major version and a minor version. + message Version { + uint32 major = 1; + uint32 minor = 2; + } + // Maximum supported RPC version. + Version max_rpc_version = 1; + // Minimum supported RPC version. + Version min_rpc_version = 2; +} diff --git a/alts/src/test/java/io/grpc/alts/AltsChannelBuilderTest.java b/alts/src/test/java/io/grpc/alts/AltsChannelBuilderTest.java new file mode 100644 index 0000000000000000000000000000000000000000..747992ab633f49edfa100f556d51827f5ba659d6 --- /dev/null +++ b/alts/src/test/java/io/grpc/alts/AltsChannelBuilderTest.java @@ -0,0 +1,67 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts; + +import static com.google.common.truth.Truth.assertThat; + +import io.grpc.alts.internal.AltsClientOptions; +import io.grpc.alts.internal.AltsProtocolNegotiator; +import io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions; +import io.grpc.netty.InternalNettyChannelBuilder.TransportCreationParamsFilterFactory; +import io.grpc.netty.ProtocolNegotiator; +import java.net.InetSocketAddress; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public final class AltsChannelBuilderTest { + + @Test + public void buildsNettyChannel() throws Exception { + AltsChannelBuilder builder = + AltsChannelBuilder.forTarget("localhost:8080").enableUntrustedAltsForTesting(); + + TransportCreationParamsFilterFactory tcpfFactory = builder.getTcpfFactoryForTest(); + AltsClientOptions altsClientOptions = builder.getAltsClientOptionsForTest(); + + assertThat(tcpfFactory).isNull(); + assertThat(altsClientOptions).isNull(); + + builder.build(); + + tcpfFactory = builder.getTcpfFactoryForTest(); + altsClientOptions = builder.getAltsClientOptionsForTest(); + + assertThat(tcpfFactory).isNotNull(); + ProtocolNegotiator protocolNegotiator = + tcpfFactory + .create(new InetSocketAddress(8080), "fakeAuthority", "fakeUserAgent", null) + .getProtocolNegotiator(); + assertThat(protocolNegotiator).isInstanceOf(AltsProtocolNegotiator.class); + + assertThat(altsClientOptions).isNotNull(); + RpcProtocolVersions expectedVersions = + RpcProtocolVersions.newBuilder() + .setMaxRpcVersion( + RpcProtocolVersions.Version.newBuilder().setMajor(2).setMinor(1).build()) + .setMinRpcVersion( + RpcProtocolVersions.Version.newBuilder().setMajor(2).setMinor(1).build()) + .build(); + assertThat(altsClientOptions.getRpcProtocolVersions()).isEqualTo(expectedVersions); + } +} diff --git a/alts/src/test/java/io/grpc/alts/AltsServerBuilderTest.java b/alts/src/test/java/io/grpc/alts/AltsServerBuilderTest.java new file mode 100644 index 0000000000000000000000000000000000000000..f729a8be2b3726fd4440a83c8c984c95023ad06f --- /dev/null +++ b/alts/src/test/java/io/grpc/alts/AltsServerBuilderTest.java @@ -0,0 +1,30 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public final class AltsServerBuilderTest { + + @Test + public void buildsNettyServer() throws Exception { + AltsServerBuilder.forPort(1234).enableUntrustedAltsForTesting().build(); + } +} diff --git a/alts/src/test/java/io/grpc/alts/CheckGcpEnvironmentTest.java b/alts/src/test/java/io/grpc/alts/CheckGcpEnvironmentTest.java new file mode 100644 index 0000000000000000000000000000000000000000..bef16f7776c2c731a2f36b054b0d91b97bbe5452 --- /dev/null +++ b/alts/src/test/java/io/grpc/alts/CheckGcpEnvironmentTest.java @@ -0,0 +1,62 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.BufferedReader; +import java.io.StringReader; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public final class CheckGcpEnvironmentTest { + + @Test + public void checkGcpLinuxPlatformData() throws Exception { + BufferedReader reader; + reader = new BufferedReader(new StringReader("HP Z440 Workstation")); + assertFalse(CheckGcpEnvironment.checkProductNameOnLinux(reader)); + reader = new BufferedReader(new StringReader("Google")); + assertTrue(CheckGcpEnvironment.checkProductNameOnLinux(reader)); + reader = new BufferedReader(new StringReader("Google Compute Engine")); + assertTrue(CheckGcpEnvironment.checkProductNameOnLinux(reader)); + reader = new BufferedReader(new StringReader("Google Compute Engine ")); + assertTrue(CheckGcpEnvironment.checkProductNameOnLinux(reader)); + } + + @Test + public void checkGcpWindowsPlatformData() throws Exception { + BufferedReader reader; + reader = new BufferedReader(new StringReader("Product : Google")); + assertFalse(CheckGcpEnvironment.checkBiosDataOnWindows(reader)); + reader = new BufferedReader(new StringReader("Manufacturer : LENOVO")); + assertFalse(CheckGcpEnvironment.checkBiosDataOnWindows(reader)); + reader = new BufferedReader(new StringReader("Manufacturer : Google Compute Engine")); + assertFalse(CheckGcpEnvironment.checkBiosDataOnWindows(reader)); + reader = new BufferedReader(new StringReader("Manufacturer : Google")); + assertTrue(CheckGcpEnvironment.checkBiosDataOnWindows(reader)); + reader = new BufferedReader(new StringReader("Manufacturer:Google")); + assertTrue(CheckGcpEnvironment.checkBiosDataOnWindows(reader)); + reader = new BufferedReader(new StringReader("Manufacturer : Google ")); + assertTrue(CheckGcpEnvironment.checkBiosDataOnWindows(reader)); + reader = new BufferedReader(new StringReader("BIOSVersion : 1.0\nManufacturer : Google\n")); + assertTrue(CheckGcpEnvironment.checkBiosDataOnWindows(reader)); + } +} diff --git a/alts/src/test/java/io/grpc/alts/GoogleDefaultChannelBuilderTest.java b/alts/src/test/java/io/grpc/alts/GoogleDefaultChannelBuilderTest.java new file mode 100644 index 0000000000000000000000000000000000000000..b681c733b4206d74d35c61efa98bef0a17a51170 --- /dev/null +++ b/alts/src/test/java/io/grpc/alts/GoogleDefaultChannelBuilderTest.java @@ -0,0 +1,44 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts; + +import static com.google.common.truth.Truth.assertThat; + +import io.grpc.alts.internal.GoogleDefaultProtocolNegotiator; +import io.grpc.netty.InternalNettyChannelBuilder.TransportCreationParamsFilterFactory; +import io.grpc.netty.ProtocolNegotiator; +import java.net.InetSocketAddress; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public final class GoogleDefaultChannelBuilderTest { + + @Test + public void buildsNettyChannel() throws Exception { + GoogleDefaultChannelBuilder builder = GoogleDefaultChannelBuilder.forTarget("localhost:8080"); + + TransportCreationParamsFilterFactory tcpfFactory = builder.getTcpfFactoryForTest(); + assertThat(tcpfFactory).isNotNull(); + ProtocolNegotiator protocolNegotiator = + tcpfFactory + .create(new InetSocketAddress(8080), "fakeAuthority", "fakeUserAgent", null) + .getProtocolNegotiator(); + assertThat(protocolNegotiator).isInstanceOf(GoogleDefaultProtocolNegotiator.class); + } +} diff --git a/alts/src/test/java/io/grpc/alts/internal/AesGcmHkdfAeadCrypterTest.java b/alts/src/test/java/io/grpc/alts/internal/AesGcmHkdfAeadCrypterTest.java new file mode 100644 index 0000000000000000000000000000000000000000..d655a6e8358d0d6c63cb7c31e5d853eb9d00dc22 --- /dev/null +++ b/alts/src/test/java/io/grpc/alts/internal/AesGcmHkdfAeadCrypterTest.java @@ -0,0 +1,494 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import static com.google.common.truth.Truth.assertWithMessage; + +import com.google.common.io.BaseEncoding; +import java.nio.ByteBuffer; +import java.security.GeneralSecurityException; +import java.util.Arrays; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Unit tests for {@link AesGcmHkdfAeadCrypter}. */ +@RunWith(JUnit4.class) +public final class AesGcmHkdfAeadCrypterTest { + + private static class TestVector { + final String comment; + final byte[] key; + final byte[] nonce; + final byte[] aad; + final byte[] plaintext; + final byte[] ciphertext; + + TestVector(TestVectorBuilder builder) { + comment = builder.comment; + key = builder.key; + nonce = builder.nonce; + aad = builder.aad; + plaintext = builder.plaintext; + ciphertext = builder.ciphertext; + } + + static TestVectorBuilder builder() { + return new TestVectorBuilder(); + } + } + + private static class TestVectorBuilder { + String comment; + byte[] key; + byte[] nonce; + byte[] aad; + byte[] plaintext; + byte[] ciphertext; + + TestVector build() { + if (comment == null + && key == null + && nonce == null + && aad == null + && plaintext == null + && ciphertext == null) { + throw new IllegalStateException("All fields must be set before calling build()."); + } + return new TestVector(this); + } + + TestVectorBuilder withComment(String comment) { + this.comment = comment; + return this; + } + + TestVectorBuilder withKey(String key) { + this.key = BaseEncoding.base16().lowerCase().decode(key); + return this; + } + + TestVectorBuilder withNonce(String nonce) { + this.nonce = BaseEncoding.base16().lowerCase().decode(nonce); + return this; + } + + TestVectorBuilder withAad(String aad) { + this.aad = BaseEncoding.base16().lowerCase().decode(aad); + return this; + } + + TestVectorBuilder withPlaintext(String plaintext) { + this.plaintext = BaseEncoding.base16().lowerCase().decode(plaintext); + return this; + } + + TestVectorBuilder withCiphertext(String ciphertext) { + this.ciphertext = BaseEncoding.base16().lowerCase().decode(ciphertext); + return this; + } + } + + @Test + public void testVectorEncrypt() throws GeneralSecurityException { + int i = 0; + for (TestVector testVector : testVectors) { + int bufferSize = testVector.ciphertext.length; + byte[] ciphertext = new byte[bufferSize]; + ByteBuffer ciphertextBuffer = ByteBuffer.wrap(ciphertext); + + AesGcmHkdfAeadCrypter aeadCrypter = new AesGcmHkdfAeadCrypter(testVector.key); + aeadCrypter.encrypt( + ciphertextBuffer, + ByteBuffer.wrap(testVector.plaintext), + ByteBuffer.wrap(testVector.aad), + testVector.nonce); + String msg = "Failure for test vector " + i; + assertWithMessage(msg) + .that(ciphertextBuffer.remaining()) + .isEqualTo(bufferSize - testVector.ciphertext.length); + byte[] exactCiphertext = Arrays.copyOf(ciphertext, testVector.ciphertext.length); + assertWithMessage(msg).that(exactCiphertext).isEqualTo(testVector.ciphertext); + i++; + } + } + + @Test + public void testVectorDecrypt() throws GeneralSecurityException { + int i = 0; + for (TestVector testVector : testVectors) { + // The plaintext buffer might require space for the tag to decrypt (e.g., for conscrypt). + int bufferSize = testVector.ciphertext.length; + byte[] plaintext = new byte[bufferSize]; + ByteBuffer plaintextBuffer = ByteBuffer.wrap(plaintext); + + AesGcmHkdfAeadCrypter aeadCrypter = new AesGcmHkdfAeadCrypter(testVector.key); + aeadCrypter.decrypt( + plaintextBuffer, + ByteBuffer.wrap(testVector.ciphertext), + ByteBuffer.wrap(testVector.aad), + testVector.nonce); + String msg = "Failure for test vector " + i; + assertWithMessage(msg) + .that(plaintextBuffer.remaining()) + .isEqualTo(bufferSize - testVector.plaintext.length); + byte[] exactPlaintext = Arrays.copyOf(plaintext, testVector.plaintext.length); + assertWithMessage(msg).that(exactPlaintext).isEqualTo(testVector.plaintext); + i++; + } + } + + /* + * NIST vectors from: + * http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/gcm/gcm-revised-spec.pdf + * + * IEEE vectors from: + * http://www.ieee802.org/1/files/public/docs2011/bn-randall-test-vectors-0511-v1.pdf + * Key expanded by setting + * expandedKey = (key||(key ^ {0x01, .., 0x01})||key ^ {0x02,..,0x02}))[0:44]. + */ + private static final TestVector[] testVectors = + new TestVector[] { + TestVector.builder() + .withComment("Derived from NIST test vector 1") + .withKey( + "0000000000000000000000000000000001010101010101010101010101010101020202020202020202" + + "020202") + .withNonce("000000000000000000000000") + .withAad("") + .withPlaintext("") + .withCiphertext("85e873e002f6ebdc4060954eb8675508") + .build(), + TestVector.builder() + .withComment("Derived from NIST test vector 2") + .withKey( + "0000000000000000000000000000000001010101010101010101010101010101020202020202020202" + + "020202") + .withNonce("000000000000000000000000") + .withAad("") + .withPlaintext("00000000000000000000000000000000") + .withCiphertext("51e9a8cb23ca2512c8256afff8e72d681aca19a1148ac115e83df4888cc00d11") + .build(), + TestVector.builder() + .withComment("Derived from NIST test vector 3") + .withKey( + "feffe9928665731c6d6a8f9467308308fffee8938764721d6c6b8e9566318209fcfdeb908467711e6f" + + "688d96") + .withNonce("cafebabefacedbaddecaf888") + .withAad("") + .withPlaintext( + "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532f" + + "cf0e2449a6b525b16aedf5aa0de657ba637b391aafd255") + .withCiphertext( + "1018ed5a1402a86516d6576d70b2ffccca261b94df88b58f53b64dfba435d18b2f6e3b7869f9353d4a" + + "c8cf09afb1663daa7b4017e6fc2c177c0c087c0df1162129952213cee1bc6e9c8495dd705e1f" + + "3d") + .build(), + TestVector.builder() + .withComment("Derived from NIST test vector 4") + .withKey( + "feffe9928665731c6d6a8f9467308308fffee8938764721d6c6b8e9566318209fcfdeb908467711e6f" + + "688d96") + .withNonce("cafebabefacedbaddecaf888") + .withAad("feedfacedeadbeeffeedfacedeadbeefabaddad2") + .withPlaintext( + "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532f" + + "cf0e2449a6b525b16aedf5aa0de657ba637b39") + .withCiphertext( + "1018ed5a1402a86516d6576d70b2ffccca261b94df88b58f53b64dfba435d18b2f6e3b7869f9353d4a" + + "c8cf09afb1663daa7b4017e6fc2c177c0c087c4764565d077e9124001ddb27fc0848c5") + .build(), + TestVector.builder() + .withComment( + "Derived from adapted NIST test vector 4" + + " for KDF counter boundary (flip nonce bit 15)") + .withKey( + "feffe9928665731c6d6a8f9467308308fffee8938764721d6c6b8e9566318209fcfdeb908467711e6f" + + "688d96") + .withNonce("ca7ebabefacedbaddecaf888") + .withAad("feedfacedeadbeeffeedfacedeadbeefabaddad2") + .withPlaintext( + "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532f" + + "cf0e2449a6b525b16aedf5aa0de657ba637b39") + .withCiphertext( + "e650d3c0fb879327f2d03287fa93cd07342b136215adbca00c3bd5099ec41832b1d18e0423ed26bb12" + + "c6cd09debb29230a94c0cee15903656f85edb6fc509b1b28216382172ecbcc31e1e9b1") + .build(), + TestVector.builder() + .withComment( + "Derived from adapted NIST test vector 4" + + " for KDF counter boundary (flip nonce bit 16)") + .withKey( + "feffe9928665731c6d6a8f9467308308fffee8938764721d6c6b8e9566318209fcfdeb908467711e6f" + + "688d96") + .withNonce("cafebbbefacedbaddecaf888") + .withAad("feedfacedeadbeeffeedfacedeadbeefabaddad2") + .withPlaintext( + "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532f" + + "cf0e2449a6b525b16aedf5aa0de657ba637b39") + .withCiphertext( + "c0121e6c954d0767f96630c33450999791b2da2ad05c4190169ccad9ac86ff1c721e3d82f2ad22ab46" + + "3bab4a0754b7dd68ca4de7ea2531b625eda01f89312b2ab957d5c7f8568dd95fcdcd1f") + .build(), + TestVector.builder() + .withComment( + "Derived from adapted NIST test vector 4" + + " for KDF counter boundary (flip nonce bit 63)") + .withKey( + "feffe9928665731c6d6a8f9467308308fffee8938764721d6c6b8e9566318209fcfdeb908467711e6f" + + "688d96") + .withNonce("cafebabefacedb2ddecaf888") + .withAad("feedfacedeadbeeffeedfacedeadbeefabaddad2") + .withPlaintext( + "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532f" + + "cf0e2449a6b525b16aedf5aa0de657ba637b39") + .withCiphertext( + "8af37ea5684a4d81d4fd817261fd9743099e7e6a025eaacf8e54b124fb5743149e05cb89f4a49467fe" + + "2e5e5965f29a19f99416b0016b54585d12553783ba59e9f782e82e097c336bf7989f08") + .build(), + TestVector.builder() + .withComment( + "Derived from adapted NIST test vector 4" + + " for KDF counter boundary (flip nonce bit 64)") + .withKey( + "feffe9928665731c6d6a8f9467308308fffee8938764721d6c6b8e9566318209fcfdeb908467711e6f" + + "688d96") + .withNonce("cafebabefacedbaddfcaf888") + .withAad("feedfacedeadbeeffeedfacedeadbeefabaddad2") + .withPlaintext( + "d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532f" + + "cf0e2449a6b525b16aedf5aa0de657ba637b39") + .withCiphertext( + "fbd528448d0346bfa878634864d407a35a039de9db2f1feb8e965b3ae9356ce6289441d77f8f0df294" + + "891f37ea438b223e3bf2bdc53d4c5a74fb680bb312a8dec6f7252cbcd7f5799750ad78") + .build(), + TestVector.builder() + .withComment("Derived from IEEE 2.1.1 54-byte auth") + .withKey( + "ad7a2bd03eac835a6f620fdcb506b345ac7b2ad13fad825b6e630eddb407b244af7829d23cae81586d" + + "600dde") + .withNonce("12153524c0895e81b2c28465") + .withAad( + "d609b1f056637a0d46df998d88e5222ab2c2846512153524c0895e8108000f10111213141516171819" + + "1a1b1c1d1e1f202122232425262728292a2b2c2d2e2f30313233340001") + .withPlaintext("") + .withCiphertext("3ea0b584f3c85e93f9320ea591699efb") + .build(), + TestVector.builder() + .withComment("Derived from IEEE 2.1.2 54-byte auth") + .withKey( + "e3c08a8f06c6e3ad95a70557b23f75483ce33021a9c72b7025666204c69c0b72e1c2888d04c4e1af97" + + "a50755") + .withNonce("12153524c0895e81b2c28465") + .withAad( + "d609b1f056637a0d46df998d88e5222ab2c2846512153524c0895e8108000f10111213141516171819" + + "1a1b1c1d1e1f202122232425262728292a2b2c2d2e2f30313233340001") + .withPlaintext("") + .withCiphertext("294e028bf1fe6f14c4e8f7305c933eb5") + .build(), + TestVector.builder() + .withComment("Derived from IEEE 2.2.1 60-byte crypt") + .withKey( + "ad7a2bd03eac835a6f620fdcb506b345ac7b2ad13fad825b6e630eddb407b244af7829d23cae81586d" + + "600dde") + .withNonce("12153524c0895e81b2c28465") + .withAad("d609b1f056637a0d46df998d88e52e00b2c2846512153524c0895e81") + .withPlaintext( + "08000f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435" + + "363738393a0002") + .withCiphertext( + "db3d25719c6b0a3ca6145c159d5c6ed9aff9c6e0b79f17019ea923b8665ddf52137ad611f0d1bf417a" + + "7ca85e45afe106ff9c7569d335d086ae6c03f00987ccd6") + .build(), + TestVector.builder() + .withComment("Derived from IEEE 2.2.2 60-byte crypt") + .withKey( + "e3c08a8f06c6e3ad95a70557b23f75483ce33021a9c72b7025666204c69c0b72e1c2888d04c4e1af97" + + "a50755") + .withNonce("12153524c0895e81b2c28465") + .withAad("d609b1f056637a0d46df998d88e52e00b2c2846512153524c0895e81") + .withPlaintext( + "08000f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435" + + "363738393a0002") + .withCiphertext( + "1641f28ec13afcc8f7903389787201051644914933e9202bb9d06aa020c2a67ef51dfe7bc00a856c55" + + "b8f8133e77f659132502bad63f5713d57d0c11e0f871ed") + .build(), + TestVector.builder() + .withComment("Derived from IEEE 2.3.1 60-byte auth") + .withKey( + "071b113b0ca743fecccf3d051f737382061a103a0da642ffcdce3c041e727283051913390ea541fcce" + + "cd3f07") + .withNonce("f0761e8dcd3d000176d457ed") + .withAad( + "e20106d7cd0df0761e8dcd3d88e5400076d457ed08000f101112131415161718191a1b1c1d1e1f2021" + + "22232425262728292a2b2c2d2e2f303132333435363738393a0003") + .withPlaintext("") + .withCiphertext("58837a10562b0f1f8edbe58ca55811d3") + .build(), + TestVector.builder() + .withComment("Derived from IEEE 2.3.2 60-byte auth") + .withKey( + "691d3ee909d7f54167fd1ca0b5d769081f2bde1aee655fdbab80bd5295ae6be76b1f3ceb0bd5f74365" + + "ff1ea2") + .withNonce("f0761e8dcd3d000176d457ed") + .withAad( + "e20106d7cd0df0761e8dcd3d88e5400076d457ed08000f101112131415161718191a1b1c1d1e1f2021" + + "22232425262728292a2b2c2d2e2f303132333435363738393a0003") + .withPlaintext("") + .withCiphertext("c2722ff6ca29a257718a529d1f0c6a3b") + .build(), + TestVector.builder() + .withComment("Derived from IEEE 2.4.1 54-byte crypt") + .withKey( + "071b113b0ca743fecccf3d051f737382061a103a0da642ffcdce3c041e727283051913390ea541fcce" + + "cd3f07") + .withNonce("f0761e8dcd3d000176d457ed") + .withAad("e20106d7cd0df0761e8dcd3d88e54c2a76d457ed") + .withPlaintext( + "08000f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333400" + + "04") + .withCiphertext( + "fd96b715b93a13346af51e8acdf792cdc7b2686f8574c70e6b0cbf16291ded427ad73fec48cd298e05" + + "28a1f4c644a949fc31dc9279706ddba33f") + .build(), + TestVector.builder() + .withComment("Derived from IEEE 2.4.2 54-byte crypt") + .withKey( + "691d3ee909d7f54167fd1ca0b5d769081f2bde1aee655fdbab80bd5295ae6be76b1f3ceb0bd5f74365" + + "ff1ea2") + .withNonce("f0761e8dcd3d000176d457ed") + .withAad("e20106d7cd0df0761e8dcd3d88e54c2a76d457ed") + .withPlaintext( + "08000f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333400" + + "04") + .withCiphertext( + "b68f6300c2e9ae833bdc070e24021a3477118e78ccf84e11a485d861476c300f175353d5cdf92008a4" + + "f878e6cc3577768085c50a0e98fda6cbb8") + .build(), + TestVector.builder() + .withComment("Derived from IEEE 2.5.1 65-byte auth") + .withKey( + "013fe00b5f11be7f866d0cbbc55a7a90003ee10a5e10bf7e876c0dbac45b7b91033de2095d13bc7d84" + + "6f0eb9") + .withNonce("7cfde9f9e33724c68932d612") + .withAad( + "84c5d513d2aaf6e5bbd2727788e523008932d6127cfde9f9e33724c608000f10111213141516171819" + + "1a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f" + + "0005") + .withPlaintext("") + .withCiphertext("cca20eecda6283f09bb3543dd99edb9b") + .build(), + TestVector.builder() + .withComment("Derived from IEEE 2.5.2 65-byte auth") + .withKey( + "83c093b58de7ffe1c0da926ac43fb3609ac1c80fee1b624497ef942e2f79a82381c291b78fe5fde3c2" + + "d89068") + .withNonce("7cfde9f9e33724c68932d612") + .withAad( + "84c5d513d2aaf6e5bbd2727788e523008932d6127cfde9f9e33724c608000f10111213141516171819" + + "1a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f" + + "0005") + .withPlaintext("") + .withCiphertext("b232cc1da5117bf15003734fa599d271") + .build(), + TestVector.builder() + .withComment("Derived from IEEE 2.6.1 61-byte crypt") + .withKey( + "013fe00b5f11be7f866d0cbbc55a7a90003ee10a5e10bf7e876c0dbac45b7b91033de2095d13bc7d84" + + "6f0eb9") + .withNonce("7cfde9f9e33724c68932d612") + .withAad("84c5d513d2aaf6e5bbd2727788e52f008932d6127cfde9f9e33724c6") + .withPlaintext( + "08000f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435" + + "363738393a3b0006") + .withCiphertext( + "ff1910d35ad7e5657890c7c560146fd038707f204b66edbc3d161f8ace244b985921023c436e3a1c35" + + "32ecd5d09a056d70be583f0d10829d9387d07d33d872e490") + .build(), + TestVector.builder() + .withComment("Derived from IEEE 2.6.2 61-byte crypt") + .withKey( + "83c093b58de7ffe1c0da926ac43fb3609ac1c80fee1b624497ef942e2f79a82381c291b78fe5fde3c2" + + "d89068") + .withNonce("7cfde9f9e33724c68932d612") + .withAad("84c5d513d2aaf6e5bbd2727788e52f008932d6127cfde9f9e33724c6") + .withPlaintext( + "08000f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435" + + "363738393a3b0006") + .withCiphertext( + "0db4cf956b5f97eca4eab82a6955307f9ae02a32dd7d93f83d66ad04e1cfdc5182ad12abdea5bbb619" + + "a1bd5fb9a573590fba908e9c7a46c1f7ba0905d1b55ffda4") + .build(), + TestVector.builder() + .withComment("Derived from IEEE 2.7.1 79-byte crypt") + .withKey( + "88ee087fd95da9fbf6725aa9d757b0cd89ef097ed85ca8faf7735ba8d656b1cc8aec0a7ddb5fabf9f4" + + "7058ab") + .withNonce("7ae8e2ca4ec500012e58495c") + .withAad( + "68f2e77696ce7ae8e2ca4ec588e541002e58495c08000f101112131415161718191a1b1c1d1e1f2021" + + "22232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f4041424344454647" + + "48494a4b4c4d0007") + .withPlaintext("") + .withCiphertext("813f0e630f96fb2d030f58d83f5cdfd0") + .build(), + TestVector.builder() + .withComment("Derived from IEEE 2.7.2 79-byte crypt") + .withKey( + "4c973dbc7364621674f8b5b89e5c15511fced9216490fb1c1a2caa0ffe0407e54e953fbe7166601476" + + "fab7ba") + .withNonce("7ae8e2ca4ec500012e58495c") + .withAad( + "68f2e77696ce7ae8e2ca4ec588e541002e58495c08000f101112131415161718191a1b1c1d1e1f2021" + + "22232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f4041424344454647" + + "48494a4b4c4d0007") + .withPlaintext("") + .withCiphertext("77e5a44c21eb07188aacbd74d1980e97") + .build(), + TestVector.builder() + .withComment("Derived from IEEE 2.8.1 61-byte crypt") + .withKey( + "88ee087fd95da9fbf6725aa9d757b0cd89ef097ed85ca8faf7735ba8d656b1cc8aec0a7ddb5fabf9f4" + + "7058ab") + .withNonce("7ae8e2ca4ec500012e58495c") + .withAad("68f2e77696ce7ae8e2ca4ec588e54d002e58495c") + .withPlaintext( + "08000f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435" + + "363738393a3b3c3d3e3f404142434445464748490008") + .withCiphertext( + "958ec3f6d60afeda99efd888f175e5fcd4c87b9bcc5c2f5426253a8b506296c8c43309ab2adb593946" + + "2541d95e80811e04e706b1498f2c407c7fb234f8cc01a647550ee6b557b35a7e3945381821" + + "f4") + .build(), + TestVector.builder() + .withComment("Derived from IEEE 2.8.2 61-byte crypt") + .withKey( + "4c973dbc7364621674f8b5b89e5c15511fced9216490fb1c1a2caa0ffe0407e54e953fbe7166601476" + + "fab7ba") + .withNonce("7ae8e2ca4ec500012e58495c") + .withAad("68f2e77696ce7ae8e2ca4ec588e54d002e58495c") + .withPlaintext( + "08000f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435" + + "363738393a3b3c3d3e3f404142434445464748490008") + .withCiphertext( + "b44d072011cd36d272a9b7a98db9aa90cbc5c67b93ddce67c854503214e2e896ec7e9db649ed4bcf6f" + + "850aac0223d0cf92c83db80795c3a17ecc1248bb00591712b1ae71e268164196252162810b" + + "00") + .build() + }; +} diff --git a/alts/src/test/java/io/grpc/alts/internal/AltsAuthContextTest.java b/alts/src/test/java/io/grpc/alts/internal/AltsAuthContextTest.java new file mode 100644 index 0000000000000000000000000000000000000000..eb1fbf9cac280b04fad24344e566100354d9ae03 --- /dev/null +++ b/alts/src/test/java/io/grpc/alts/internal/AltsAuthContextTest.java @@ -0,0 +1,81 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import static org.junit.Assert.assertEquals; + +import io.grpc.alts.internal.Handshaker.HandshakerResult; +import io.grpc.alts.internal.Handshaker.Identity; +import io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions; +import io.grpc.alts.internal.TransportSecurityCommon.SecurityLevel; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Unit tests for {@link AltsAuthContext}. */ +@RunWith(JUnit4.class) +public final class AltsAuthContextTest { + private static final int TEST_MAX_RPC_VERSION_MAJOR = 3; + private static final int TEST_MAX_RPC_VERSION_MINOR = 5; + private static final int TEST_MIN_RPC_VERSION_MAJOR = 2; + private static final int TEST_MIN_RPC_VERSION_MINOR = 1; + private static final SecurityLevel TEST_SECURITY_LEVEL = SecurityLevel.INTEGRITY_AND_PRIVACY; + private static final String TEST_APPLICATION_PROTOCOL = "grpc"; + private static final String TEST_LOCAL_SERVICE_ACCOUNT = "local@gserviceaccount.com"; + private static final String TEST_PEER_SERVICE_ACCOUNT = "peer@gserviceaccount.com"; + private static final String TEST_RECORD_PROTOCOL = "ALTSRP_GCM_AES128"; + + private HandshakerResult handshakerResult; + private RpcProtocolVersions rpcVersions; + + @Before + public void setUp() { + rpcVersions = + RpcProtocolVersions.newBuilder() + .setMaxRpcVersion( + RpcProtocolVersions.Version.newBuilder() + .setMajor(TEST_MAX_RPC_VERSION_MAJOR) + .setMinor(TEST_MAX_RPC_VERSION_MINOR) + .build()) + .setMinRpcVersion( + RpcProtocolVersions.Version.newBuilder() + .setMajor(TEST_MIN_RPC_VERSION_MAJOR) + .setMinor(TEST_MIN_RPC_VERSION_MINOR) + .build()) + .build(); + handshakerResult = + HandshakerResult.newBuilder() + .setApplicationProtocol(TEST_APPLICATION_PROTOCOL) + .setRecordProtocol(TEST_RECORD_PROTOCOL) + .setPeerIdentity(Identity.newBuilder().setServiceAccount(TEST_PEER_SERVICE_ACCOUNT)) + .setLocalIdentity(Identity.newBuilder().setServiceAccount(TEST_LOCAL_SERVICE_ACCOUNT)) + .setPeerRpcVersions(rpcVersions) + .build(); + } + + @Test + public void testAltsAuthContext() { + AltsAuthContext authContext = new AltsAuthContext(handshakerResult); + assertEquals(TEST_APPLICATION_PROTOCOL, authContext.getApplicationProtocol()); + assertEquals(TEST_RECORD_PROTOCOL, authContext.getRecordProtocol()); + assertEquals(TEST_SECURITY_LEVEL, authContext.getSecurityLevel()); + assertEquals(TEST_PEER_SERVICE_ACCOUNT, authContext.getPeerServiceAccount()); + assertEquals(TEST_LOCAL_SERVICE_ACCOUNT, authContext.getLocalServiceAccount()); + assertEquals(rpcVersions, authContext.getPeerRpcVersions()); + } +} diff --git a/alts/src/test/java/io/grpc/alts/internal/AltsChannelCrypterTest.java b/alts/src/test/java/io/grpc/alts/internal/AltsChannelCrypterTest.java new file mode 100644 index 0000000000000000000000000000000000000000..0b40a8b31df197600b971f372062ae58e950296a --- /dev/null +++ b/alts/src/test/java/io/grpc/alts/internal/AltsChannelCrypterTest.java @@ -0,0 +1,150 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import static com.google.common.truth.Truth.assertThat; +import static io.grpc.alts.internal.AltsChannelCrypter.incrementCounter; +import static org.junit.Assert.fail; + +import com.google.common.testing.GcFinalization; +import io.netty.util.ReferenceCounted; +import io.netty.util.ResourceLeakDetector; +import io.netty.util.ResourceLeakDetector.Level; +import java.security.GeneralSecurityException; +import java.util.Arrays; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Unit tests for {@link AltsChannelCrypter}. */ +@RunWith(JUnit4.class) +public final class AltsChannelCrypterTest extends ChannelCrypterNettyTestBase { + + @Before + public void setUp() throws GeneralSecurityException { + ResourceLeakDetector.setLevel(Level.PARANOID); + client = new AltsChannelCrypter(new byte[AltsChannelCrypter.getKeyLength()], true); + server = new AltsChannelCrypter(new byte[AltsChannelCrypter.getKeyLength()], false); + } + + @After + public void tearDown() throws GeneralSecurityException { + for (ReferenceCounted reference : references) { + reference.release(); + } + references.clear(); + client.destroy(); + server.destroy(); + // Increase our chances to detect ByteBuf leaks. + GcFinalization.awaitFullGc(); + } + + @Test + public void encryptDecryptKdfCounterIncr() throws GeneralSecurityException { + AltsChannelCrypter client = + new AltsChannelCrypter(new byte[AltsChannelCrypter.getKeyLength()], true); + AltsChannelCrypter server = + new AltsChannelCrypter(new byte[AltsChannelCrypter.getKeyLength()], false); + + String message = "Hello world"; + FrameEncrypt frameEncrypt1 = createFrameEncrypt(message); + + client.encrypt(frameEncrypt1.out, frameEncrypt1.plain); + FrameDecrypt frameDecrypt1 = frameDecryptOfEncrypt(frameEncrypt1); + + server.decrypt(frameDecrypt1.out, frameDecrypt1.tag, frameDecrypt1.ciphertext); + assertThat(frameEncrypt1.plain.get(0).slice(0, frameDecrypt1.out.readableBytes())) + .isEqualTo(frameDecrypt1.out); + + // Increase counters to get a new KDF counter value (first two bytes are skipped). + client.incrementOutCounterForTesting(1 << 17); + server.incrementInCounterForTesting(1 << 17); + + FrameEncrypt frameEncrypt2 = createFrameEncrypt(message); + + client.encrypt(frameEncrypt2.out, frameEncrypt2.plain); + FrameDecrypt frameDecrypt2 = frameDecryptOfEncrypt(frameEncrypt2); + + server.decrypt(frameDecrypt2.out, frameDecrypt2.tag, frameDecrypt2.ciphertext); + assertThat(frameEncrypt2.plain.get(0).slice(0, frameDecrypt2.out.readableBytes())) + .isEqualTo(frameDecrypt2.out); + } + + @Test + public void overflowsClient() throws GeneralSecurityException { + byte[] maxFirst = + new byte[] { + (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, + (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 + }; + + byte[] maxFirstPred = Arrays.copyOf(maxFirst, maxFirst.length); + maxFirstPred[0]--; + + byte[] oldCounter = new byte[AltsChannelCrypter.getCounterLength()]; + byte[] counter = Arrays.copyOf(maxFirstPred, maxFirstPred.length); + + incrementCounter(counter, oldCounter); + + assertThat(oldCounter).isEqualTo(maxFirstPred); + assertThat(counter).isEqualTo(maxFirst); + + try { + incrementCounter(counter, oldCounter); + fail("Exception expected"); + } catch (GeneralSecurityException ex) { + assertThat(ex).hasMessageThat().contains("Counter has overflowed"); + } + + assertThat(oldCounter).isEqualTo(maxFirst); + assertThat(counter).isEqualTo(maxFirst); + } + + @Test + public void overflowsServer() throws GeneralSecurityException { + byte[] maxSecond = + new byte[] { + (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, + (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, + (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x80 + }; + + byte[] maxSecondPred = Arrays.copyOf(maxSecond, maxSecond.length); + maxSecondPred[0]--; + + byte[] oldCounter = new byte[AltsChannelCrypter.getCounterLength()]; + byte[] counter = Arrays.copyOf(maxSecondPred, maxSecondPred.length); + + incrementCounter(counter, oldCounter); + + assertThat(oldCounter).isEqualTo(maxSecondPred); + assertThat(counter).isEqualTo(maxSecond); + + try { + incrementCounter(counter, oldCounter); + fail("Exception expected"); + } catch (GeneralSecurityException ex) { + assertThat(ex).hasMessageThat().contains("Counter has overflowed"); + } + + assertThat(oldCounter).isEqualTo(maxSecond); + assertThat(counter).isEqualTo(maxSecond); + } +} diff --git a/alts/src/test/java/io/grpc/alts/internal/AltsClientOptionsTest.java b/alts/src/test/java/io/grpc/alts/internal/AltsClientOptionsTest.java new file mode 100644 index 0000000000000000000000000000000000000000..cdb44c9aff57767dedad8b725e8270f626e14ac3 --- /dev/null +++ b/alts/src/test/java/io/grpc/alts/internal/AltsClientOptionsTest.java @@ -0,0 +1,55 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import static com.google.common.truth.Truth.assertThat; + +import io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Unit tests for {@link AltsClientOptions}. */ +@RunWith(JUnit4.class) +public final class AltsClientOptionsTest { + + @Test + public void setAndGet() throws Exception { + String targetName = "foo"; + String serviceAccount1 = "bar1"; + String serviceAccount2 = "bar2"; + RpcProtocolVersions rpcVersions = + RpcProtocolVersions.newBuilder() + .setMaxRpcVersion( + RpcProtocolVersions.Version.newBuilder().setMajor(2).setMinor(1).build()) + .setMinRpcVersion( + RpcProtocolVersions.Version.newBuilder().setMajor(2).setMinor(1).build()) + .build(); + + AltsClientOptions options = + new AltsClientOptions.Builder() + .setTargetName(targetName) + .addTargetServiceAccount(serviceAccount1) + .addTargetServiceAccount(serviceAccount2) + .setRpcProtocolVersions(rpcVersions) + .build(); + + assertThat(options.getTargetName()).isEqualTo(targetName); + assertThat(options.getTargetServiceAccounts()).containsAllOf(serviceAccount1, serviceAccount2); + assertThat(options.getRpcProtocolVersions()).isEqualTo(rpcVersions); + } +} diff --git a/alts/src/test/java/io/grpc/alts/internal/AltsFramingTest.java b/alts/src/test/java/io/grpc/alts/internal/AltsFramingTest.java new file mode 100644 index 0000000000000000000000000000000000000000..5ad250e0621c85afec6e2fbb5a6dd2efe8205c76 --- /dev/null +++ b/alts/src/test/java/io/grpc/alts/internal/AltsFramingTest.java @@ -0,0 +1,126 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.fail; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.security.GeneralSecurityException; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Unit tests for {@link AltsFraming}. */ +@RunWith(JUnit4.class) +public class AltsFramingTest { + + @Test + public void parserFrameLengthNegativeFails() throws GeneralSecurityException { + AltsFraming.Parser parser = new AltsFraming.Parser(); + // frame length + one remaining byte (required) + ByteBuffer buffer = ByteBuffer.allocate(AltsFraming.getFrameLengthHeaderSize() + 1); + buffer.order(ByteOrder.LITTLE_ENDIAN); + buffer.putInt(-1); // write invalid length + buffer.put((byte) 0); // write some byte + buffer.flip(); + + try { + parser.readBytes(buffer); + fail("Exception expected"); + } catch (IllegalArgumentException ex) { + assertThat(ex).hasMessageThat().contains("Invalid frame length"); + } + } + + @Test + public void parserFrameLengthSmallerMessageTypeFails() throws GeneralSecurityException { + AltsFraming.Parser parser = new AltsFraming.Parser(); + // frame length + one remaining byte (required) + ByteBuffer buffer = ByteBuffer.allocate(AltsFraming.getFrameLengthHeaderSize() + 1); + buffer.order(ByteOrder.LITTLE_ENDIAN); + buffer.putInt(AltsFraming.getFrameMessageTypeHeaderSize() - 1); // write invalid length + buffer.put((byte) 0); // write some byte + buffer.flip(); + + try { + parser.readBytes(buffer); + fail("Exception expected"); + } catch (IllegalArgumentException ex) { + assertThat(ex).hasMessageThat().contains("Invalid frame length"); + } + } + + @Test + public void parserFrameLengthTooLargeFails() throws GeneralSecurityException { + AltsFraming.Parser parser = new AltsFraming.Parser(); + // frame length + one remaining byte (required) + ByteBuffer buffer = ByteBuffer.allocate(AltsFraming.getFrameLengthHeaderSize() + 1); + buffer.order(ByteOrder.LITTLE_ENDIAN); + buffer.putInt(AltsFraming.getMaxDataLength() + 1); // write invalid length + buffer.put((byte) 0); // write some byte + buffer.flip(); + + try { + parser.readBytes(buffer); + fail("Exception expected"); + } catch (IllegalArgumentException ex) { + assertThat(ex).hasMessageThat().contains("Invalid frame length"); + } + } + + @Test + public void parserFrameLengthMaxOk() throws GeneralSecurityException { + AltsFraming.Parser parser = new AltsFraming.Parser(); + // length of type header + data + int dataLength = AltsFraming.getMaxDataLength(); + // complete frame + 1 byte + ByteBuffer buffer = + ByteBuffer.allocate(AltsFraming.getFrameLengthHeaderSize() + dataLength + 1); + buffer.order(ByteOrder.LITTLE_ENDIAN); + buffer.putInt(dataLength); // write invalid length + buffer.putInt(6); // default message type + buffer.put(new byte[dataLength - AltsFraming.getFrameMessageTypeHeaderSize()]); // write data + buffer.put((byte) 0); + buffer.flip(); + + parser.readBytes(buffer); + + assertThat(parser.isComplete()).isTrue(); + assertThat(buffer.remaining()).isEqualTo(1); + } + + @Test + public void parserFrameLengthZeroOk() throws GeneralSecurityException { + AltsFraming.Parser parser = new AltsFraming.Parser(); + int dataLength = AltsFraming.getFrameMessageTypeHeaderSize(); + // complete frame + 1 byte + ByteBuffer buffer = + ByteBuffer.allocate(AltsFraming.getFrameLengthHeaderSize() + dataLength + 1); + buffer.order(ByteOrder.LITTLE_ENDIAN); + buffer.putInt(dataLength); // write invalid length + buffer.putInt(6); // default message type + buffer.put((byte) 0); + buffer.flip(); + + parser.readBytes(buffer); + + assertThat(parser.isComplete()).isTrue(); + assertThat(buffer.remaining()).isEqualTo(1); + } +} diff --git a/alts/src/test/java/io/grpc/alts/internal/AltsHandshakerClientTest.java b/alts/src/test/java/io/grpc/alts/internal/AltsHandshakerClientTest.java new file mode 100644 index 0000000000000000000000000000000000000000..d5cbecfca59d5efc9289031270015b8dcc6749ec --- /dev/null +++ b/alts/src/test/java/io/grpc/alts/internal/AltsHandshakerClientTest.java @@ -0,0 +1,263 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import io.grpc.alts.internal.Handshaker.HandshakeProtocol; +import io.grpc.alts.internal.Handshaker.HandshakerReq; +import io.grpc.alts.internal.Handshaker.Identity; +import io.grpc.alts.internal.Handshaker.StartClientHandshakeReq; +import io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions; +import java.nio.ByteBuffer; +import java.security.GeneralSecurityException; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.mockito.ArgumentCaptor; +import org.mockito.Matchers; + +/** Unit tests for {@link AltsHandshakerClient}. */ +@RunWith(JUnit4.class) +public class AltsHandshakerClientTest { + private static final int IN_BYTES_SIZE = 100; + private static final int BYTES_CONSUMED = 30; + private static final int PREFIX_POSITION = 20; + private static final String TEST_TARGET_NAME = "target name"; + private static final String TEST_TARGET_SERVICE_ACCOUNT = "peer service account"; + + private AltsHandshakerStub mockStub; + private AltsHandshakerClient handshaker; + private AltsClientOptions clientOptions; + + @Before + public void setUp() { + mockStub = mock(AltsHandshakerStub.class); + clientOptions = + new AltsClientOptions.Builder() + .setTargetName(TEST_TARGET_NAME) + .addTargetServiceAccount(TEST_TARGET_SERVICE_ACCOUNT) + .build(); + handshaker = new AltsHandshakerClient(mockStub, clientOptions); + } + + @Test + public void startClientHandshakeFailure() throws Exception { + when(mockStub.send(Matchers.any())) + .thenReturn(MockAltsHandshakerResp.getErrorResponse()); + + try { + handshaker.startClientHandshake(); + fail("Exception expected"); + } catch (GeneralSecurityException ex) { + assertThat(ex).hasMessageThat().contains(MockAltsHandshakerResp.getTestErrorDetails()); + } + } + + @Test + public void startClientHandshakeSuccess() throws Exception { + when(mockStub.send(Matchers.any())) + .thenReturn(MockAltsHandshakerResp.getOkResponse(0)); + + ByteBuffer outFrame = handshaker.startClientHandshake(); + + assertEquals(ByteString.copyFrom(outFrame), MockAltsHandshakerResp.getOutFrame()); + assertFalse(handshaker.isFinished()); + assertNull(handshaker.getResult()); + assertNull(handshaker.getKey()); + } + + @Test + public void startClientHandshakeWithOptions() throws Exception { + when(mockStub.send(Matchers.any())) + .thenReturn(MockAltsHandshakerResp.getOkResponse(0)); + + ByteBuffer outFrame = handshaker.startClientHandshake(); + assertEquals(ByteString.copyFrom(outFrame), MockAltsHandshakerResp.getOutFrame()); + + HandshakerReq req = + HandshakerReq.newBuilder() + .setClientStart( + StartClientHandshakeReq.newBuilder() + .setHandshakeSecurityProtocol(HandshakeProtocol.ALTS) + .addApplicationProtocols(AltsHandshakerClient.getApplicationProtocol()) + .addRecordProtocols(AltsHandshakerClient.getRecordProtocol()) + .setTargetName(TEST_TARGET_NAME) + .addTargetIdentities( + Identity.newBuilder().setServiceAccount(TEST_TARGET_SERVICE_ACCOUNT)) + .build()) + .build(); + verify(mockStub).send(req); + } + + @Test + public void startServerHandshakeFailure() throws Exception { + when(mockStub.send(Matchers.any())) + .thenReturn(MockAltsHandshakerResp.getErrorResponse()); + + try { + ByteBuffer inBytes = ByteBuffer.allocate(IN_BYTES_SIZE); + handshaker.startServerHandshake(inBytes); + fail("Exception expected"); + } catch (GeneralSecurityException ex) { + assertThat(ex).hasMessageThat().contains(MockAltsHandshakerResp.getTestErrorDetails()); + } + } + + @Test + public void startServerHandshakeSuccess() throws Exception { + when(mockStub.send(Matchers.any())) + .thenReturn(MockAltsHandshakerResp.getOkResponse(BYTES_CONSUMED)); + + ByteBuffer inBytes = ByteBuffer.allocate(IN_BYTES_SIZE); + ByteBuffer outFrame = handshaker.startServerHandshake(inBytes); + + assertEquals(ByteString.copyFrom(outFrame), MockAltsHandshakerResp.getOutFrame()); + assertFalse(handshaker.isFinished()); + assertNull(handshaker.getResult()); + assertNull(handshaker.getKey()); + assertEquals(IN_BYTES_SIZE - BYTES_CONSUMED, inBytes.remaining()); + } + + @Test + public void startServerHandshakeEmptyOutFrame() throws Exception { + when(mockStub.send(Matchers.any())) + .thenReturn(MockAltsHandshakerResp.getEmptyOutFrameResponse(BYTES_CONSUMED)); + + ByteBuffer inBytes = ByteBuffer.allocate(IN_BYTES_SIZE); + ByteBuffer outFrame = handshaker.startServerHandshake(inBytes); + + assertEquals(0, outFrame.remaining()); + assertFalse(handshaker.isFinished()); + assertNull(handshaker.getResult()); + assertNull(handshaker.getKey()); + assertEquals(IN_BYTES_SIZE - BYTES_CONSUMED, inBytes.remaining()); + } + + @Test + public void startServerHandshakeWithPrefixBuffer() throws Exception { + when(mockStub.send(Matchers.any())) + .thenReturn(MockAltsHandshakerResp.getOkResponse(BYTES_CONSUMED)); + + ByteBuffer inBytes = ByteBuffer.allocate(IN_BYTES_SIZE); + inBytes.position(PREFIX_POSITION); + ByteBuffer outFrame = handshaker.startServerHandshake(inBytes); + + assertEquals(ByteString.copyFrom(outFrame), MockAltsHandshakerResp.getOutFrame()); + assertFalse(handshaker.isFinished()); + assertNull(handshaker.getResult()); + assertNull(handshaker.getKey()); + assertEquals(PREFIX_POSITION + BYTES_CONSUMED, inBytes.position()); + assertEquals(IN_BYTES_SIZE - BYTES_CONSUMED - PREFIX_POSITION, inBytes.remaining()); + } + + @Test + public void nextFailure() throws Exception { + when(mockStub.send(Matchers.any())) + .thenReturn(MockAltsHandshakerResp.getErrorResponse()); + + try { + ByteBuffer inBytes = ByteBuffer.allocate(IN_BYTES_SIZE); + handshaker.next(inBytes); + fail("Exception expected"); + } catch (GeneralSecurityException ex) { + assertThat(ex).hasMessageThat().contains(MockAltsHandshakerResp.getTestErrorDetails()); + } + } + + @Test + public void nextSuccess() throws Exception { + when(mockStub.send(Matchers.any())) + .thenReturn(MockAltsHandshakerResp.getOkResponse(BYTES_CONSUMED)); + + ByteBuffer inBytes = ByteBuffer.allocate(IN_BYTES_SIZE); + ByteBuffer outFrame = handshaker.next(inBytes); + + assertEquals(ByteString.copyFrom(outFrame), MockAltsHandshakerResp.getOutFrame()); + assertFalse(handshaker.isFinished()); + assertNull(handshaker.getResult()); + assertNull(handshaker.getKey()); + assertEquals(IN_BYTES_SIZE - BYTES_CONSUMED, inBytes.remaining()); + } + + @Test + public void nextEmptyOutFrame() throws Exception { + when(mockStub.send(Matchers.any())) + .thenReturn(MockAltsHandshakerResp.getEmptyOutFrameResponse(BYTES_CONSUMED)); + + ByteBuffer inBytes = ByteBuffer.allocate(IN_BYTES_SIZE); + ByteBuffer outFrame = handshaker.next(inBytes); + + assertEquals(0, outFrame.remaining()); + assertFalse(handshaker.isFinished()); + assertNull(handshaker.getResult()); + assertNull(handshaker.getKey()); + assertEquals(IN_BYTES_SIZE - BYTES_CONSUMED, inBytes.remaining()); + } + + @Test + public void nextFinished() throws Exception { + when(mockStub.send(Matchers.any())) + .thenReturn(MockAltsHandshakerResp.getFinishedResponse(BYTES_CONSUMED)); + + ByteBuffer inBytes = ByteBuffer.allocate(IN_BYTES_SIZE); + ByteBuffer outFrame = handshaker.next(inBytes); + + assertEquals(ByteString.copyFrom(outFrame), MockAltsHandshakerResp.getOutFrame()); + assertTrue(handshaker.isFinished()); + assertArrayEquals(handshaker.getKey(), MockAltsHandshakerResp.getTestKeyData()); + assertEquals(IN_BYTES_SIZE - BYTES_CONSUMED, inBytes.remaining()); + } + + @Test + public void setRpcVersions() throws Exception { + when(mockStub.send(Matchers.any())) + .thenReturn(MockAltsHandshakerResp.getOkResponse(0)); + + RpcProtocolVersions rpcVersions = + RpcProtocolVersions.newBuilder() + .setMinRpcVersion( + RpcProtocolVersions.Version.newBuilder().setMajor(3).setMinor(4).build()) + .setMaxRpcVersion( + RpcProtocolVersions.Version.newBuilder().setMajor(5).setMinor(6).build()) + .build(); + clientOptions = + new AltsClientOptions.Builder() + .setTargetName(TEST_TARGET_NAME) + .addTargetServiceAccount(TEST_TARGET_SERVICE_ACCOUNT) + .setRpcProtocolVersions(rpcVersions) + .build(); + handshaker = new AltsHandshakerClient(mockStub, clientOptions); + + handshaker.startClientHandshake(); + + ArgumentCaptor reqCaptor = ArgumentCaptor.forClass(HandshakerReq.class); + verify(mockStub).send(reqCaptor.capture()); + assertEquals(rpcVersions, reqCaptor.getValue().getClientStart().getRpcVersions()); + } +} diff --git a/alts/src/test/java/io/grpc/alts/internal/AltsHandshakerOptionsTest.java b/alts/src/test/java/io/grpc/alts/internal/AltsHandshakerOptionsTest.java new file mode 100644 index 0000000000000000000000000000000000000000..6a7814b3006abb514711482b5bc1941e672c0fbe --- /dev/null +++ b/alts/src/test/java/io/grpc/alts/internal/AltsHandshakerOptionsTest.java @@ -0,0 +1,43 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import static com.google.common.truth.Truth.assertThat; + +import io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Unit tests for {@link AltsHandshakerOptions}. */ +@RunWith(JUnit4.class) +public final class AltsHandshakerOptionsTest { + + @Test + public void setAndGet() throws Exception { + RpcProtocolVersions rpcVersions = + RpcProtocolVersions.newBuilder() + .setMaxRpcVersion( + RpcProtocolVersions.Version.newBuilder().setMajor(2).setMinor(1).build()) + .setMinRpcVersion( + RpcProtocolVersions.Version.newBuilder().setMajor(2).setMinor(1).build()) + .build(); + + AltsHandshakerOptions options = new AltsHandshakerOptions(rpcVersions); + assertThat(options.getRpcProtocolVersions()).isEqualTo(rpcVersions); + } +} diff --git a/alts/src/test/java/io/grpc/alts/internal/AltsHandshakerStubTest.java b/alts/src/test/java/io/grpc/alts/internal/AltsHandshakerStubTest.java new file mode 100644 index 0000000000000000000000000000000000000000..b896b5bf776837a88074f78763696dcbb97f47d4 --- /dev/null +++ b/alts/src/test/java/io/grpc/alts/internal/AltsHandshakerStubTest.java @@ -0,0 +1,177 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import com.google.protobuf.ByteString; +import io.grpc.alts.internal.Handshaker.HandshakerReq; +import io.grpc.alts.internal.Handshaker.HandshakerResp; +import io.grpc.alts.internal.Handshaker.NextHandshakeMessageReq; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Unit tests for {@link AltsHandshakerStub}. */ +@RunWith(JUnit4.class) +public class AltsHandshakerStubTest { + /** Mock status of handshaker service. */ + private static enum Status { + OK, + ERROR, + COMPLETE + } + + private AltsHandshakerStub stub; + private MockWriter writer; + + @Before + public void setUp() { + writer = new MockWriter(); + stub = new AltsHandshakerStub(writer); + writer.setReader(stub.getReaderForTest()); + } + + /** Send a message as in_bytes and expect same message as out_frames echo back. */ + private void sendSuccessfulMessage() throws Exception { + String message = "hello world"; + HandshakerReq.Builder req = + HandshakerReq.newBuilder() + .setNext( + NextHandshakeMessageReq.newBuilder() + .setInBytes(ByteString.copyFromUtf8(message)) + .build()); + HandshakerResp resp = stub.send(req.build()); + assertEquals(resp.getOutFrames().toStringUtf8(), message); + } + + /** Send a message and expect an IOException on error. */ + private void sendAndExpectError() throws InterruptedException { + try { + stub.send(HandshakerReq.newBuilder().build()); + fail("Exception expected"); + } catch (IOException ex) { + assertThat(ex).hasMessageThat().contains("Received a terminating error"); + } + } + + /** Send a message and expect an IOException on closing. */ + private void sendAndExpectComplete() throws InterruptedException { + try { + stub.send(HandshakerReq.newBuilder().build()); + fail("Exception expected"); + } catch (IOException ex) { + assertThat(ex).hasMessageThat().contains("Response stream closed"); + } + } + + /** Send a message and expect an IOException on unexpected message. */ + private void sendAndExpectUnexpectedMessage() throws InterruptedException { + try { + stub.send(HandshakerReq.newBuilder().build()); + fail("Exception expected"); + } catch (IOException ex) { + assertThat(ex).hasMessageThat().contains("Received an unexpected response"); + } + } + + @Test + public void sendSuccessfulMessageTest() throws Exception { + writer.setServiceStatus(Status.OK); + sendSuccessfulMessage(); + stub.close(); + } + + @Test + public void getServiceErrorTest() throws InterruptedException { + writer.setServiceStatus(Status.ERROR); + sendAndExpectError(); + stub.close(); + } + + @Test + public void getServiceCompleteTest() throws Exception { + writer.setServiceStatus(Status.COMPLETE); + sendAndExpectComplete(); + stub.close(); + } + + @Test + public void getUnexpectedMessageTest() throws Exception { + writer.setServiceStatus(Status.OK); + writer.sendUnexpectedResponse(); + sendAndExpectUnexpectedMessage(); + stub.close(); + } + + @Test + public void closeEarlyTest() throws InterruptedException { + stub.close(); + sendAndExpectComplete(); + } + + private static class MockWriter implements StreamObserver { + private StreamObserver reader; + private Status status = Status.OK; + + private void setReader(StreamObserver reader) { + this.reader = reader; + } + + private void setServiceStatus(Status status) { + this.status = status; + } + + /** Send a handshaker response to reader. */ + private void sendUnexpectedResponse() { + reader.onNext(HandshakerResp.newBuilder().build()); + } + + /** Mock writer onNext. Will respond based on the server status. */ + @Override + public void onNext(final HandshakerReq req) { + switch (status) { + case OK: + HandshakerResp.Builder resp = HandshakerResp.newBuilder(); + reader.onNext(resp.setOutFrames(req.getNext().getInBytes()).build()); + break; + case ERROR: + reader.onError(new RuntimeException()); + break; + case COMPLETE: + reader.onCompleted(); + break; + default: + return; + } + } + + @Override + public void onError(Throwable t) {} + + /** Mock writer onComplete. */ + @Override + public void onCompleted() { + reader.onCompleted(); + } + } +} diff --git a/alts/src/test/java/io/grpc/alts/internal/AltsProtocolNegotiatorTest.java b/alts/src/test/java/io/grpc/alts/internal/AltsProtocolNegotiatorTest.java new file mode 100644 index 0000000000000000000000000000000000000000..936c298a395d90d8c9ff4bec86facdbf3a515d37 --- /dev/null +++ b/alts/src/test/java/io/grpc/alts/internal/AltsProtocolNegotiatorTest.java @@ -0,0 +1,506 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import static com.google.common.truth.Truth.assertThat; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import io.grpc.Attributes; +import io.grpc.CallCredentials; +import io.grpc.Grpc; +import io.grpc.InternalChannelz; +import io.grpc.SecurityLevel; +import io.grpc.alts.internal.Handshaker.HandshakerResult; +import io.grpc.alts.internal.TsiFrameProtector.Consumer; +import io.grpc.alts.internal.TsiPeer.Property; +import io.grpc.netty.GrpcHttp2ConnectionHandler; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufAllocator; +import io.netty.buffer.CompositeByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelDuplexHandler; +import io.netty.channel.ChannelFuture; +import io.netty.channel.ChannelFutureListener; +import io.netty.channel.ChannelHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelPromise; +import io.netty.channel.embedded.EmbeddedChannel; +import io.netty.handler.codec.http2.DefaultHttp2Connection; +import io.netty.handler.codec.http2.DefaultHttp2ConnectionDecoder; +import io.netty.handler.codec.http2.DefaultHttp2ConnectionEncoder; +import io.netty.handler.codec.http2.DefaultHttp2FrameReader; +import io.netty.handler.codec.http2.DefaultHttp2FrameWriter; +import io.netty.handler.codec.http2.Http2Connection; +import io.netty.handler.codec.http2.Http2ConnectionDecoder; +import io.netty.handler.codec.http2.Http2ConnectionEncoder; +import io.netty.handler.codec.http2.Http2FrameReader; +import io.netty.handler.codec.http2.Http2FrameWriter; +import io.netty.handler.codec.http2.Http2Settings; +import io.netty.util.ReferenceCountUtil; +import io.netty.util.ReferenceCounted; +import java.nio.ByteBuffer; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.Future; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Tests for {@link AltsProtocolNegotiator}. */ +@RunWith(JUnit4.class) +public class AltsProtocolNegotiatorTest { + private final CapturingGrpcHttp2ConnectionHandler grpcHandler = capturingGrpcHandler(); + + private final List references = new ArrayList<>(); + private final LinkedBlockingQueue protectors = new LinkedBlockingQueue<>(); + + private EmbeddedChannel channel; + private Throwable caughtException; + + private volatile TsiHandshakeHandler.TsiHandshakeCompletionEvent tsiEvent; + private ChannelHandler handler; + + private TsiPeer mockedTsiPeer = new TsiPeer(Collections.>emptyList()); + private AltsAuthContext mockedAltsContext = + new AltsAuthContext( + HandshakerResult.newBuilder() + .setPeerRpcVersions(RpcProtocolVersionsUtil.getRpcProtocolVersions()) + .build()); + private final TsiHandshaker mockHandshaker = + new DelegatingTsiHandshaker(FakeTsiHandshaker.newFakeHandshakerServer()) { + @Override + public TsiPeer extractPeer() throws GeneralSecurityException { + return mockedTsiPeer; + } + + @Override + public Object extractPeerObject() throws GeneralSecurityException { + return mockedAltsContext; + } + }; + private final NettyTsiHandshaker serverHandshaker = new NettyTsiHandshaker(mockHandshaker); + + @Before + public void setup() throws Exception { + ChannelHandler userEventHandler = + new ChannelDuplexHandler() { + @Override + public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { + if (evt instanceof TsiHandshakeHandler.TsiHandshakeCompletionEvent) { + tsiEvent = (TsiHandshakeHandler.TsiHandshakeCompletionEvent) evt; + } else { + super.userEventTriggered(ctx, evt); + } + } + }; + + ChannelHandler uncaughtExceptionHandler = + new ChannelDuplexHandler() { + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + caughtException = cause; + super.exceptionCaught(ctx, cause); + } + }; + + TsiHandshakerFactory handshakerFactory = + new DelegatingTsiHandshakerFactory(FakeTsiHandshaker.clientHandshakerFactory()) { + @Override + public TsiHandshaker newHandshaker() { + return new DelegatingTsiHandshaker(super.newHandshaker()) { + @Override + public TsiPeer extractPeer() throws GeneralSecurityException { + return mockedTsiPeer; + } + + @Override + public Object extractPeerObject() throws GeneralSecurityException { + return mockedAltsContext; + } + }; + } + }; + handler = AltsProtocolNegotiator.create(handshakerFactory).newHandler(grpcHandler); + channel = new EmbeddedChannel(uncaughtExceptionHandler, handler, userEventHandler); + } + + @After + public void teardown() throws Exception { + if (channel != null) { + @SuppressWarnings("unused") // go/futurereturn-lsc + Future possiblyIgnoredError = channel.close(); + } + + for (ReferenceCounted reference : references) { + ReferenceCountUtil.safeRelease(reference); + } + } + + @Test + public void handshakeShouldBeSuccessful() throws Exception { + doHandshake(); + } + + @Test + @SuppressWarnings("unchecked") // List cast + public void protectShouldRoundtrip() throws Exception { + // Write the message 1 character at a time. The message should be buffered + // and not interfere with the handshake. + final AtomicInteger writeCount = new AtomicInteger(); + String message = "hello"; + for (int ix = 0; ix < message.length(); ++ix) { + ByteBuf in = Unpooled.copiedBuffer(message, ix, 1, UTF_8); + @SuppressWarnings("unused") // go/futurereturn-lsc + Future possiblyIgnoredError = + channel + .write(in) + .addListener( + new ChannelFutureListener() { + @Override + public void operationComplete(ChannelFuture future) throws Exception { + if (future.isSuccess()) { + writeCount.incrementAndGet(); + } + } + }); + } + channel.flush(); + + // Now do the handshake. The buffered message will automatically be protected + // and sent. + doHandshake(); + + // Capture the protected data written to the wire. + assertEquals(1, channel.outboundMessages().size()); + ByteBuf protectedData = channel.readOutbound(); + assertEquals(message.length(), writeCount.get()); + + // Read the protected message at the server and verify it matches the original message. + TsiFrameProtector serverProtector = serverHandshaker.createFrameProtector(channel.alloc()); + List unprotected = new ArrayList<>(); + serverProtector.unprotect(protectedData, (List) (List) unprotected, channel.alloc()); + // We try our best to remove the HTTP2 handler as soon as possible, but just by constructing it + // a settings frame is written (and an HTTP2 preface). This is hard coded into Netty, so we + // have to remove it here. See {@code Http2ConnectionHandler.PrefaceDecode.sendPreface}. + int settingsFrameLength = 9; + + CompositeByteBuf unprotectedAll = + new CompositeByteBuf(channel.alloc(), false, unprotected.size() + 1, unprotected); + ByteBuf unprotectedData = unprotectedAll.slice(settingsFrameLength, message.length()); + assertEquals(message, unprotectedData.toString(UTF_8)); + + // Protect the same message at the server. + final AtomicReference newlyProtectedData = new AtomicReference<>(); + serverProtector.protectFlush( + Collections.singletonList(unprotectedData), + new Consumer() { + @Override + public void accept(ByteBuf buf) { + newlyProtectedData.set(buf); + } + }, + channel.alloc()); + + // Read the protected message at the client and verify that it matches the original message. + channel.writeInbound(newlyProtectedData.get()); + assertEquals(1, channel.inboundMessages().size()); + assertEquals(message, channel.readInbound().toString(UTF_8)); + } + + @Test + public void unprotectLargeIncomingFrame() throws Exception { + + // We use a server frameprotector with twice the standard frame size. + int serverFrameSize = 4096 * 2; + // This should fit into one frame. + byte[] unprotectedBytes = new byte[serverFrameSize - 500]; + Arrays.fill(unprotectedBytes, (byte) 7); + ByteBuf unprotectedData = Unpooled.wrappedBuffer(unprotectedBytes); + unprotectedData.writerIndex(unprotectedBytes.length); + + // Perform handshake. + doHandshake(); + + // Protect the message on the server. + TsiFrameProtector serverProtector = + serverHandshaker.createFrameProtector(serverFrameSize, channel.alloc()); + serverProtector.protectFlush( + Collections.singletonList(unprotectedData), + new Consumer() { + @Override + public void accept(ByteBuf buf) { + channel.writeInbound(buf); + } + }, + channel.alloc()); + channel.flushInbound(); + + // Read the protected message at the client and verify that it matches the original message. + assertEquals(1, channel.inboundMessages().size()); + + ByteBuf receivedData1 = channel.readInbound(); + int receivedLen1 = receivedData1.readableBytes(); + byte[] receivedBytes = new byte[receivedLen1]; + receivedData1.readBytes(receivedBytes, 0, receivedLen1); + + assertThat(unprotectedBytes.length).isEqualTo(receivedBytes.length); + assertThat(unprotectedBytes).isEqualTo(receivedBytes); + } + + @Test + public void flushShouldFailAllPromises() throws Exception { + doHandshake(); + + channel + .pipeline() + .addFirst( + new ChannelDuplexHandler() { + @Override + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) + throws Exception { + throw new Exception("Fake exception"); + } + }); + + // Write the message 1 character at a time. + String message = "hello"; + final AtomicInteger failures = new AtomicInteger(); + for (int ix = 0; ix < message.length(); ++ix) { + ByteBuf in = Unpooled.copiedBuffer(message, ix, 1, UTF_8); + @SuppressWarnings("unused") // go/futurereturn-lsc + Future possiblyIgnoredError = + channel + .write(in) + .addListener( + new ChannelFutureListener() { + @Override + public void operationComplete(ChannelFuture future) throws Exception { + if (!future.isSuccess()) { + failures.incrementAndGet(); + } + } + }); + } + channel.flush(); + + // Verify that the promises fail. + assertEquals(message.length(), failures.get()); + } + + @Test + public void doNotFlushEmptyBuffer() throws Exception { + doHandshake(); + assertEquals(1, protectors.size()); + InterceptingProtector protector = protectors.poll(); + + String message = "hello"; + ByteBuf in = Unpooled.copiedBuffer(message, UTF_8); + + assertEquals(0, protector.flushes.get()); + Future done = channel.write(in); + channel.flush(); + done.get(5, TimeUnit.SECONDS); + assertEquals(1, protector.flushes.get()); + + done = channel.write(Unpooled.EMPTY_BUFFER); + channel.flush(); + done.get(5, TimeUnit.SECONDS); + assertEquals(1, protector.flushes.get()); + } + + @Test + public void peerPropagated() throws Exception { + doHandshake(); + + assertThat(grpcHandler.attrs.get(AltsProtocolNegotiator.getTsiPeerAttributeKey())) + .isEqualTo(mockedTsiPeer); + assertThat(grpcHandler.attrs.get(AltsProtocolNegotiator.getAltsAuthContextAttributeKey())) + .isEqualTo(mockedAltsContext); + assertThat(grpcHandler.attrs.get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR).toString()) + .isEqualTo("embedded"); + assertThat(grpcHandler.attrs.get(CallCredentials.ATTR_SECURITY_LEVEL)) + .isEqualTo(SecurityLevel.PRIVACY_AND_INTEGRITY); + } + + private void doHandshake() throws Exception { + // Capture the client frame and add to the server. + assertEquals(1, channel.outboundMessages().size()); + ByteBuf clientFrame = channel.readOutbound(); + assertTrue(serverHandshaker.processBytesFromPeer(clientFrame)); + + // Get the server response handshake frames. + ByteBuf serverFrame = channel.alloc().buffer(); + serverHandshaker.getBytesToSendToPeer(serverFrame); + channel.writeInbound(serverFrame); + + // Capture the next client frame and add to the server. + assertEquals(1, channel.outboundMessages().size()); + clientFrame = channel.readOutbound(); + assertTrue(serverHandshaker.processBytesFromPeer(clientFrame)); + + // Get the server response handshake frames. + serverFrame = channel.alloc().buffer(); + serverHandshaker.getBytesToSendToPeer(serverFrame); + channel.writeInbound(serverFrame); + + // Ensure that both sides have confirmed that the handshake has completed. + assertFalse(serverHandshaker.isInProgress()); + + if (caughtException != null) { + throw new RuntimeException(caughtException); + } + assertNotNull(tsiEvent); + } + + private CapturingGrpcHttp2ConnectionHandler capturingGrpcHandler() { + // Netty Boilerplate. We don't really need any of this, but there is a tight coupling + // between a Http2ConnectionHandler and its dependencies. + Http2Connection connection = new DefaultHttp2Connection(true); + Http2FrameWriter frameWriter = new DefaultHttp2FrameWriter(); + Http2FrameReader frameReader = new DefaultHttp2FrameReader(false); + DefaultHttp2ConnectionEncoder encoder = + new DefaultHttp2ConnectionEncoder(connection, frameWriter); + DefaultHttp2ConnectionDecoder decoder = + new DefaultHttp2ConnectionDecoder(connection, encoder, frameReader); + + return new CapturingGrpcHttp2ConnectionHandler(decoder, encoder, new Http2Settings()); + } + + private final class CapturingGrpcHttp2ConnectionHandler extends GrpcHttp2ConnectionHandler { + private Attributes attrs; + + private CapturingGrpcHttp2ConnectionHandler( + Http2ConnectionDecoder decoder, + Http2ConnectionEncoder encoder, + Http2Settings initialSettings) { + super(null, decoder, encoder, initialSettings); + } + + @Override + public void handleProtocolNegotiationCompleted( + Attributes attrs, InternalChannelz.Security securityInfo) { + // If we are added to the pipeline, we need to remove ourselves. The HTTP2 handler + channel.pipeline().remove(this); + this.attrs = attrs; + } + } + + private static class DelegatingTsiHandshakerFactory implements TsiHandshakerFactory { + + private TsiHandshakerFactory delegate; + + DelegatingTsiHandshakerFactory(TsiHandshakerFactory delegate) { + this.delegate = delegate; + } + + @Override + public TsiHandshaker newHandshaker() { + return delegate.newHandshaker(); + } + } + + private class DelegatingTsiHandshaker implements TsiHandshaker { + + private final TsiHandshaker delegate; + + DelegatingTsiHandshaker(TsiHandshaker delegate) { + this.delegate = delegate; + } + + @Override + public void getBytesToSendToPeer(ByteBuffer bytes) throws GeneralSecurityException { + delegate.getBytesToSendToPeer(bytes); + } + + @Override + public boolean processBytesFromPeer(ByteBuffer bytes) throws GeneralSecurityException { + return delegate.processBytesFromPeer(bytes); + } + + @Override + public boolean isInProgress() { + return delegate.isInProgress(); + } + + @Override + public TsiPeer extractPeer() throws GeneralSecurityException { + return delegate.extractPeer(); + } + + @Override + public Object extractPeerObject() throws GeneralSecurityException { + return delegate.extractPeerObject(); + } + + @Override + public TsiFrameProtector createFrameProtector(ByteBufAllocator alloc) { + InterceptingProtector protector = + new InterceptingProtector(delegate.createFrameProtector(alloc)); + protectors.add(protector); + return protector; + } + + @Override + public TsiFrameProtector createFrameProtector(int maxFrameSize, ByteBufAllocator alloc) { + InterceptingProtector protector = + new InterceptingProtector(delegate.createFrameProtector(maxFrameSize, alloc)); + protectors.add(protector); + return protector; + } + } + + private static class InterceptingProtector implements TsiFrameProtector { + private final TsiFrameProtector delegate; + final AtomicInteger flushes = new AtomicInteger(); + + InterceptingProtector(TsiFrameProtector delegate) { + this.delegate = delegate; + } + + @Override + public void protectFlush( + List unprotectedBufs, Consumer ctxWrite, ByteBufAllocator alloc) + throws GeneralSecurityException { + flushes.incrementAndGet(); + delegate.protectFlush(unprotectedBufs, ctxWrite, alloc); + } + + @Override + public void unprotect(ByteBuf in, List out, ByteBufAllocator alloc) + throws GeneralSecurityException { + delegate.unprotect(in, out, alloc); + } + + @Override + public void destroy() { + delegate.destroy(); + } + } +} diff --git a/alts/src/test/java/io/grpc/alts/internal/AltsTsiFrameProtectorTest.java b/alts/src/test/java/io/grpc/alts/internal/AltsTsiFrameProtectorTest.java new file mode 100644 index 0000000000000000000000000000000000000000..4405a99eff02a7d27c4cf65fc3af825ede8b5456 --- /dev/null +++ b/alts/src/test/java/io/grpc/alts/internal/AltsTsiFrameProtectorTest.java @@ -0,0 +1,491 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import static com.google.common.truth.Truth.assertThat; +import static io.grpc.alts.internal.ByteBufTestUtils.getDirectBuffer; +import static io.grpc.alts.internal.ByteBufTestUtils.getRandom; +import static io.grpc.alts.internal.ByteBufTestUtils.writeSlice; +import static org.junit.Assert.fail; + +import com.google.common.testing.GcFinalization; +import io.grpc.alts.internal.ByteBufTestUtils.RegisterRef; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufAllocator; +import io.netty.util.ReferenceCounted; +import io.netty.util.ResourceLeakDetector; +import io.netty.util.ResourceLeakDetector.Level; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Unit tests for {@link AltsTsiFrameProtector}. */ +@RunWith(JUnit4.class) +public class AltsTsiFrameProtectorTest { + private static final int FRAME_MIN_SIZE = + AltsTsiFrameProtector.getHeaderTypeFieldBytes() + FakeChannelCrypter.getTagBytes(); + + private final List references = new ArrayList<>(); + private final RegisterRef ref = + new RegisterRef() { + @Override + public ByteBuf register(ByteBuf buf) { + if (buf != null) { + references.add(buf); + } + return buf; + } + }; + + @Before + public void setUp() { + ResourceLeakDetector.setLevel(Level.PARANOID); + } + + @After + public void teardown() { + for (ReferenceCounted reference : references) { + reference.release(); + } + references.clear(); + // Increase our chances to detect ByteBuf leaks. + GcFinalization.awaitFullGc(); + } + + @Test + public void parserHeader_frameLengthNegativeFails() throws GeneralSecurityException { + ByteBufAllocator alloc = ByteBufAllocator.DEFAULT; + List out = new ArrayList<>(); + FakeChannelCrypter crypter = new FakeChannelCrypter(); + AltsTsiFrameProtector.Unprotector unprotector = + new AltsTsiFrameProtector.Unprotector(crypter, alloc); + ByteBuf in = getDirectBuffer(AltsTsiFrameProtector.getHeaderBytes(), ref); + in.writeIntLE(-1); + in.writeIntLE(6); + try { + unprotector.unprotect(in, out, alloc); + fail("Exception expected"); + } catch (IllegalArgumentException ex) { + assertThat(ex).hasMessageThat().contains("Invalid header field: frame size too small"); + } + + unprotector.destroy(); + } + + @Test + public void parserHeader_frameTooSmall() throws GeneralSecurityException { + ByteBufAllocator alloc = ByteBufAllocator.DEFAULT; + List out = new ArrayList<>(); + FakeChannelCrypter crypter = new FakeChannelCrypter(); + AltsTsiFrameProtector.Unprotector unprotector = + new AltsTsiFrameProtector.Unprotector(crypter, alloc); + ByteBuf in = + getDirectBuffer( + AltsTsiFrameProtector.getHeaderBytes() + FakeChannelCrypter.getTagBytes(), ref); + in.writeIntLE(FRAME_MIN_SIZE - 1); + in.writeIntLE(6); + try { + unprotector.unprotect(in, out, alloc); + fail("Exception expected"); + } catch (IllegalArgumentException ex) { + assertThat(ex).hasMessageThat().contains("Invalid header field: frame size too small"); + } + + unprotector.destroy(); + } + + @Test + public void parserHeader_frameTooLarge() throws GeneralSecurityException { + ByteBufAllocator alloc = ByteBufAllocator.DEFAULT; + List out = new ArrayList<>(); + FakeChannelCrypter crypter = new FakeChannelCrypter(); + AltsTsiFrameProtector.Unprotector unprotector = + new AltsTsiFrameProtector.Unprotector(crypter, alloc); + ByteBuf in = + getDirectBuffer( + AltsTsiFrameProtector.getHeaderBytes() + FakeChannelCrypter.getTagBytes(), ref); + in.writeIntLE( + AltsTsiFrameProtector.getLimitMaxAllowedFrameBytes() + - AltsTsiFrameProtector.getHeaderLenFieldBytes() + + 1); + in.writeIntLE(6); + try { + unprotector.unprotect(in, out, alloc); + fail("Exception expected"); + } catch (IllegalArgumentException ex) { + assertThat(ex).hasMessageThat().contains("Invalid header field: frame size too large"); + } + + unprotector.destroy(); + } + + @Test + public void parserHeader_frameTypeInvalid() throws GeneralSecurityException { + ByteBufAllocator alloc = ByteBufAllocator.DEFAULT; + List out = new ArrayList<>(); + FakeChannelCrypter crypter = new FakeChannelCrypter(); + AltsTsiFrameProtector.Unprotector unprotector = + new AltsTsiFrameProtector.Unprotector(crypter, alloc); + ByteBuf in = + getDirectBuffer( + AltsTsiFrameProtector.getHeaderBytes() + FakeChannelCrypter.getTagBytes(), ref); + in.writeIntLE(FRAME_MIN_SIZE); + in.writeIntLE(5); + try { + unprotector.unprotect(in, out, alloc); + fail("Exception expected"); + } catch (IllegalArgumentException ex) { + assertThat(ex).hasMessageThat().contains("Invalid header field: frame type"); + } + + unprotector.destroy(); + } + + @Test + public void parserHeader_frameZeroOk() throws GeneralSecurityException { + ByteBufAllocator alloc = ByteBufAllocator.DEFAULT; + List out = new ArrayList<>(); + FakeChannelCrypter crypter = new FakeChannelCrypter(); + AltsTsiFrameProtector.Unprotector unprotector = + new AltsTsiFrameProtector.Unprotector(crypter, alloc); + ByteBuf in = + getDirectBuffer( + AltsTsiFrameProtector.getHeaderBytes() + FakeChannelCrypter.getTagBytes(), ref); + in.writeIntLE(FRAME_MIN_SIZE); + in.writeIntLE(6); + + unprotector.unprotect(in, out, alloc); + assertThat(in.readableBytes()).isEqualTo(0); + + unprotector.destroy(); + } + + @Test + public void parserHeader_EmptyUnprotectNoRetain() throws GeneralSecurityException { + ByteBufAllocator alloc = ByteBufAllocator.DEFAULT; + List out = new ArrayList<>(); + FakeChannelCrypter crypter = new FakeChannelCrypter(); + AltsTsiFrameProtector.Unprotector unprotector = + new AltsTsiFrameProtector.Unprotector(crypter, alloc); + ByteBuf emptyBuf = getDirectBuffer(0, ref); + unprotector.unprotect(emptyBuf, out, alloc); + + assertThat(emptyBuf.refCnt()).isEqualTo(1); + + unprotector.destroy(); + } + + @Test + public void parserHeader_frameMaxOk() throws GeneralSecurityException { + ByteBufAllocator alloc = ByteBufAllocator.DEFAULT; + List out = new ArrayList<>(); + FakeChannelCrypter crypter = new FakeChannelCrypter(); + AltsTsiFrameProtector.Unprotector unprotector = + new AltsTsiFrameProtector.Unprotector(crypter, alloc); + ByteBuf in = + getDirectBuffer( + AltsTsiFrameProtector.getHeaderBytes() + FakeChannelCrypter.getTagBytes(), ref); + in.writeIntLE( + AltsTsiFrameProtector.getLimitMaxAllowedFrameBytes() + - AltsTsiFrameProtector.getHeaderLenFieldBytes()); + in.writeIntLE(6); + + unprotector.unprotect(in, out, alloc); + assertThat(in.readableBytes()).isEqualTo(0); + + unprotector.destroy(); + } + + @Test + public void parserHeader_frameOkFragment() throws GeneralSecurityException { + ByteBufAllocator alloc = ByteBufAllocator.DEFAULT; + List out = new ArrayList<>(); + FakeChannelCrypter crypter = new FakeChannelCrypter(); + AltsTsiFrameProtector.Unprotector unprotector = + new AltsTsiFrameProtector.Unprotector(crypter, alloc); + ByteBuf in = + getDirectBuffer( + AltsTsiFrameProtector.getHeaderBytes() + FakeChannelCrypter.getTagBytes(), ref); + in.writeIntLE(FRAME_MIN_SIZE); + in.writeIntLE(6); + ByteBuf in1 = in.readSlice(AltsTsiFrameProtector.getHeaderBytes() - 1); + ByteBuf in2 = in.readSlice(1); + + unprotector.unprotect(in1, out, alloc); + assertThat(in1.readableBytes()).isEqualTo(0); + + unprotector.unprotect(in2, out, alloc); + assertThat(in2.readableBytes()).isEqualTo(0); + + unprotector.destroy(); + } + + @Test + public void parseHeader_frameFailFragment() throws GeneralSecurityException { + ByteBufAllocator alloc = ByteBufAllocator.DEFAULT; + List out = new ArrayList<>(); + FakeChannelCrypter crypter = new FakeChannelCrypter(); + AltsTsiFrameProtector.Unprotector unprotector = + new AltsTsiFrameProtector.Unprotector(crypter, alloc); + ByteBuf in = + getDirectBuffer( + AltsTsiFrameProtector.getHeaderBytes() + FakeChannelCrypter.getTagBytes(), ref); + in.writeIntLE(FRAME_MIN_SIZE - 1); + in.writeIntLE(6); + ByteBuf in1 = in.readSlice(AltsTsiFrameProtector.getHeaderBytes() - 1); + ByteBuf in2 = in.readSlice(1); + + unprotector.unprotect(in1, out, alloc); + assertThat(in1.readableBytes()).isEqualTo(0); + + try { + unprotector.unprotect(in2, out, alloc); + fail("Exception expected"); + } catch (IllegalArgumentException ex) { + assertThat(ex).hasMessageThat().contains("Invalid header field: frame size too small"); + } + + assertThat(in2.readableBytes()).isEqualTo(0); + + unprotector.destroy(); + } + + @Test + public void parseFrame_oneFrameNoFragment() throws GeneralSecurityException { + int payloadBytes = 1024; + ByteBufAllocator alloc = ByteBufAllocator.DEFAULT; + List out = new ArrayList<>(); + FakeChannelCrypter crypter = new FakeChannelCrypter(); + AltsTsiFrameProtector.Unprotector unprotector = + new AltsTsiFrameProtector.Unprotector(crypter, alloc); + ByteBuf plain = getRandom(payloadBytes, ref); + ByteBuf outFrame = + getDirectBuffer( + AltsTsiFrameProtector.getHeaderBytes() + + payloadBytes + + FakeChannelCrypter.getTagBytes(), + ref); + + outFrame.writeIntLE( + AltsTsiFrameProtector.getHeaderTypeFieldBytes() + + payloadBytes + + FakeChannelCrypter.getTagBytes()); + outFrame.writeIntLE(6); + List framePlain = Collections.singletonList(plain); + ByteBuf frameOut = writeSlice(outFrame, payloadBytes + FakeChannelCrypter.getTagBytes()); + crypter.encrypt(frameOut, framePlain); + plain.readerIndex(0); + + unprotector.unprotect(outFrame, out, alloc); + assertThat(outFrame.readableBytes()).isEqualTo(0); + assertThat(out.size()).isEqualTo(1); + ByteBuf out1 = ref((ByteBuf) out.get(0)); + assertThat(out1).isEqualTo(plain); + + unprotector.destroy(); + } + + @Test + public void parseFrame_twoFramesNoFragment() throws GeneralSecurityException { + int payloadBytes = 1536; + int payloadBytes1 = 1024; + int payloadBytes2 = payloadBytes - payloadBytes1; + ByteBufAllocator alloc = ByteBufAllocator.DEFAULT; + List out = new ArrayList<>(); + FakeChannelCrypter crypter = new FakeChannelCrypter(); + AltsTsiFrameProtector.Unprotector unprotector = + new AltsTsiFrameProtector.Unprotector(crypter, alloc); + + ByteBuf plain = getRandom(payloadBytes, ref); + ByteBuf outFrame = + getDirectBuffer( + 2 * (AltsTsiFrameProtector.getHeaderBytes() + FakeChannelCrypter.getTagBytes()) + + payloadBytes, + ref); + + outFrame.writeIntLE( + AltsTsiFrameProtector.getHeaderTypeFieldBytes() + + payloadBytes1 + + FakeChannelCrypter.getTagBytes()); + outFrame.writeIntLE(6); + List framePlain1 = Collections.singletonList(plain.readSlice(payloadBytes1)); + ByteBuf frameOut1 = writeSlice(outFrame, payloadBytes1 + FakeChannelCrypter.getTagBytes()); + + outFrame.writeIntLE( + AltsTsiFrameProtector.getHeaderTypeFieldBytes() + + payloadBytes2 + + FakeChannelCrypter.getTagBytes()); + outFrame.writeIntLE(6); + List framePlain2 = Collections.singletonList(plain); + ByteBuf frameOut2 = writeSlice(outFrame, payloadBytes2 + FakeChannelCrypter.getTagBytes()); + + crypter.encrypt(frameOut1, framePlain1); + crypter.encrypt(frameOut2, framePlain2); + plain.readerIndex(0); + + unprotector.unprotect(outFrame, out, alloc); + assertThat(out.size()).isEqualTo(1); + ByteBuf out1 = ref((ByteBuf) out.get(0)); + assertThat(out1).isEqualTo(plain); + assertThat(outFrame.refCnt()).isEqualTo(1); + assertThat(outFrame.readableBytes()).isEqualTo(0); + + unprotector.destroy(); + } + + @Test + public void parseFrame_twoFramesNoFragment_Leftover() throws GeneralSecurityException { + int payloadBytes = 1536; + int payloadBytes1 = 1024; + int payloadBytes2 = payloadBytes - payloadBytes1; + ByteBufAllocator alloc = ByteBufAllocator.DEFAULT; + List out = new ArrayList<>(); + FakeChannelCrypter crypter = new FakeChannelCrypter(); + AltsTsiFrameProtector.Unprotector unprotector = + new AltsTsiFrameProtector.Unprotector(crypter, alloc); + + ByteBuf plain = getRandom(payloadBytes, ref); + ByteBuf protectedBuf = + getDirectBuffer( + 2 * (AltsTsiFrameProtector.getHeaderBytes() + FakeChannelCrypter.getTagBytes()) + + payloadBytes + + AltsTsiFrameProtector.getHeaderBytes(), + ref); + + protectedBuf.writeIntLE( + AltsTsiFrameProtector.getHeaderTypeFieldBytes() + + payloadBytes1 + + FakeChannelCrypter.getTagBytes()); + protectedBuf.writeIntLE(6); + List framePlain1 = Collections.singletonList(plain.readSlice(payloadBytes1)); + ByteBuf frameOut1 = writeSlice(protectedBuf, payloadBytes1 + FakeChannelCrypter.getTagBytes()); + + protectedBuf.writeIntLE( + AltsTsiFrameProtector.getHeaderTypeFieldBytes() + + payloadBytes2 + + FakeChannelCrypter.getTagBytes()); + protectedBuf.writeIntLE(6); + List framePlain2 = Collections.singletonList(plain); + ByteBuf frameOut2 = writeSlice(protectedBuf, payloadBytes2 + FakeChannelCrypter.getTagBytes()); + // This is an invalid header length field, make sure it triggers an error + // when the remainder of the header is given. + protectedBuf.writeIntLE((byte) -1); + + crypter.encrypt(frameOut1, framePlain1); + crypter.encrypt(frameOut2, framePlain2); + plain.readerIndex(0); + + unprotector.unprotect(protectedBuf, out, alloc); + assertThat(out.size()).isEqualTo(1); + ByteBuf out1 = ref((ByteBuf) out.get(0)); + assertThat(out1).isEqualTo(plain); + + // The protectedBuf is buffered inside the unprotector. + assertThat(protectedBuf.readableBytes()).isEqualTo(0); + assertThat(protectedBuf.refCnt()).isEqualTo(2); + + protectedBuf.writeIntLE(6); + try { + unprotector.unprotect(protectedBuf, out, alloc); + fail("Exception expected"); + } catch (IllegalArgumentException ex) { + assertThat(ex).hasMessageThat().contains("Invalid header field: frame size too small"); + } + + unprotector.destroy(); + + // Make sure that unprotector does not hold onto buffered ByteBuf instance after destroy. + assertThat(protectedBuf.refCnt()).isEqualTo(1); + + // Make sure that destroying twice does not throw. + unprotector.destroy(); + } + + @Test + public void parseFrame_twoFramesFragmentSecond() throws GeneralSecurityException { + int payloadBytes = 1536; + int payloadBytes1 = 1024; + int payloadBytes2 = payloadBytes - payloadBytes1; + ByteBufAllocator alloc = ByteBufAllocator.DEFAULT; + List out = new ArrayList<>(); + FakeChannelCrypter crypter = new FakeChannelCrypter(); + AltsTsiFrameProtector.Unprotector unprotector = + new AltsTsiFrameProtector.Unprotector(crypter, alloc); + + ByteBuf plain = getRandom(payloadBytes, ref); + ByteBuf protectedBuf = + getDirectBuffer( + 2 * (AltsTsiFrameProtector.getHeaderBytes() + FakeChannelCrypter.getTagBytes()) + + payloadBytes + + AltsTsiFrameProtector.getHeaderBytes(), + ref); + + protectedBuf.writeIntLE( + AltsTsiFrameProtector.getHeaderTypeFieldBytes() + + payloadBytes1 + + FakeChannelCrypter.getTagBytes()); + protectedBuf.writeIntLE(6); + List framePlain1 = Collections.singletonList(plain.readSlice(payloadBytes1)); + ByteBuf frameOut1 = writeSlice(protectedBuf, payloadBytes1 + FakeChannelCrypter.getTagBytes()); + + protectedBuf.writeIntLE( + AltsTsiFrameProtector.getHeaderTypeFieldBytes() + + payloadBytes2 + + FakeChannelCrypter.getTagBytes()); + protectedBuf.writeIntLE(6); + List framePlain2 = Collections.singletonList(plain); + ByteBuf frameOut2 = writeSlice(protectedBuf, payloadBytes2 + FakeChannelCrypter.getTagBytes()); + + crypter.encrypt(frameOut1, framePlain1); + crypter.encrypt(frameOut2, framePlain2); + plain.readerIndex(0); + + unprotector.unprotect( + protectedBuf.readSlice( + payloadBytes + + AltsTsiFrameProtector.getHeaderBytes() + + FakeChannelCrypter.getTagBytes() + + AltsTsiFrameProtector.getHeaderBytes()), + out, + alloc); + assertThat(out.size()).isEqualTo(1); + ByteBuf out1 = ref((ByteBuf) out.get(0)); + assertThat(out1).isEqualTo(plain.readSlice(payloadBytes1)); + assertThat(protectedBuf.refCnt()).isEqualTo(2); + + unprotector.unprotect(protectedBuf, out, alloc); + assertThat(out.size()).isEqualTo(2); + ByteBuf out2 = ref((ByteBuf) out.get(1)); + assertThat(out2).isEqualTo(plain); + assertThat(protectedBuf.refCnt()).isEqualTo(1); + + unprotector.destroy(); + } + + private ByteBuf ref(ByteBuf buf) { + if (buf != null) { + references.add(buf); + } + return buf; + } +} diff --git a/alts/src/test/java/io/grpc/alts/internal/AltsTsiHandshakerTest.java b/alts/src/test/java/io/grpc/alts/internal/AltsTsiHandshakerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..ac3dfb8f2d06fbeba9e197b3ac19d5b766e5bdab --- /dev/null +++ b/alts/src/test/java/io/grpc/alts/internal/AltsTsiHandshakerTest.java @@ -0,0 +1,269 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; +import io.grpc.alts.internal.Handshaker.HandshakerResult; +import io.grpc.alts.internal.Handshaker.Identity; +import io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions; +import java.nio.ByteBuffer; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; +import org.mockito.Matchers; + +/** Unit tests for {@link AltsTsiHandshaker}. */ +@RunWith(JUnit4.class) +public class AltsTsiHandshakerTest { + private static final String TEST_KEY_DATA = "super secret 123"; + private static final String TEST_APPLICATION_PROTOCOL = "grpc"; + private static final String TEST_RECORD_PROTOCOL = "ALTSRP_GCM_AES128"; + private static final String TEST_CLIENT_SERVICE_ACCOUNT = "client@developer.gserviceaccount.com"; + private static final String TEST_SERVER_SERVICE_ACCOUNT = "server@developer.gserviceaccount.com"; + private static final int OUT_FRAME_SIZE = 100; + private static final int TRANSPORT_BUFFER_SIZE = 200; + private static final int TEST_MAX_RPC_VERSION_MAJOR = 3; + private static final int TEST_MAX_RPC_VERSION_MINOR = 2; + private static final int TEST_MIN_RPC_VERSION_MAJOR = 2; + private static final int TEST_MIN_RPC_VERSION_MINOR = 1; + private static final RpcProtocolVersions TEST_RPC_PROTOCOL_VERSIONS = + RpcProtocolVersions.newBuilder() + .setMaxRpcVersion( + RpcProtocolVersions.Version.newBuilder() + .setMajor(TEST_MAX_RPC_VERSION_MAJOR) + .setMinor(TEST_MAX_RPC_VERSION_MINOR) + .build()) + .setMinRpcVersion( + RpcProtocolVersions.Version.newBuilder() + .setMajor(TEST_MIN_RPC_VERSION_MAJOR) + .setMinor(TEST_MIN_RPC_VERSION_MINOR) + .build()) + .build(); + + private AltsHandshakerClient mockClient; + private AltsHandshakerClient mockServer; + private AltsTsiHandshaker handshakerClient; + private AltsTsiHandshaker handshakerServer; + + @Before + public void setUp() throws Exception { + mockClient = mock(AltsHandshakerClient.class); + mockServer = mock(AltsHandshakerClient.class); + handshakerClient = new AltsTsiHandshaker(true, mockClient); + handshakerServer = new AltsTsiHandshaker(false, mockServer); + } + + private HandshakerResult getHandshakerResult(boolean isClient) { + HandshakerResult.Builder builder = + HandshakerResult.newBuilder() + .setApplicationProtocol(TEST_APPLICATION_PROTOCOL) + .setRecordProtocol(TEST_RECORD_PROTOCOL) + .setKeyData(ByteString.copyFromUtf8(TEST_KEY_DATA)) + .setPeerRpcVersions(TEST_RPC_PROTOCOL_VERSIONS); + if (isClient) { + builder.setPeerIdentity( + Identity.newBuilder().setServiceAccount(TEST_SERVER_SERVICE_ACCOUNT).build()); + builder.setLocalIdentity( + Identity.newBuilder().setServiceAccount(TEST_CLIENT_SERVICE_ACCOUNT).build()); + } else { + builder.setPeerIdentity( + Identity.newBuilder().setServiceAccount(TEST_CLIENT_SERVICE_ACCOUNT).build()); + builder.setLocalIdentity( + Identity.newBuilder().setServiceAccount(TEST_SERVER_SERVICE_ACCOUNT).build()); + } + return builder.build(); + } + + @Test + public void processBytesFromPeerFalseStart() throws Exception { + verify(mockClient, never()).startClientHandshake(); + verify(mockClient, never()).startServerHandshake(Matchers.any()); + verify(mockClient, never()).next(Matchers.any()); + + ByteBuffer transportBuffer = ByteBuffer.allocate(TRANSPORT_BUFFER_SIZE); + assertTrue(handshakerClient.processBytesFromPeer(transportBuffer)); + } + + @Test + public void processBytesFromPeerStartServer() throws Exception { + ByteBuffer transportBuffer = ByteBuffer.allocate(TRANSPORT_BUFFER_SIZE); + ByteBuffer outputFrame = ByteBuffer.allocate(OUT_FRAME_SIZE); + verify(mockServer, never()).startClientHandshake(); + verify(mockServer, never()).next(Matchers.any()); + // Mock transport buffer all consumed by processBytesFromPeer and there is an output frame. + transportBuffer.position(transportBuffer.limit()); + when(mockServer.startServerHandshake(transportBuffer)).thenReturn(outputFrame); + when(mockServer.isFinished()).thenReturn(false); + + assertTrue(handshakerServer.processBytesFromPeer(transportBuffer)); + } + + @Test + public void processBytesFromPeerStartServerEmptyOutput() throws Exception { + ByteBuffer transportBuffer = ByteBuffer.allocate(TRANSPORT_BUFFER_SIZE); + ByteBuffer emptyOutputFrame = ByteBuffer.allocate(0); + verify(mockServer, never()).startClientHandshake(); + verify(mockServer, never()).next(Matchers.any()); + // Mock transport buffer all consumed by processBytesFromPeer and output frame is empty. + // Expect processBytesFromPeer return False, because more data are needed from the peer. + transportBuffer.position(transportBuffer.limit()); + when(mockServer.startServerHandshake(transportBuffer)).thenReturn(emptyOutputFrame); + when(mockServer.isFinished()).thenReturn(false); + + assertFalse(handshakerServer.processBytesFromPeer(transportBuffer)); + } + + @Test + public void processBytesFromPeerStartServerFinished() throws Exception { + ByteBuffer transportBuffer = ByteBuffer.allocate(TRANSPORT_BUFFER_SIZE); + ByteBuffer outputFrame = ByteBuffer.allocate(OUT_FRAME_SIZE); + verify(mockServer, never()).startClientHandshake(); + verify(mockServer, never()).next(Matchers.any()); + // Mock handshake complete after processBytesFromPeer. + when(mockServer.startServerHandshake(transportBuffer)).thenReturn(outputFrame); + when(mockServer.isFinished()).thenReturn(true); + + assertTrue(handshakerServer.processBytesFromPeer(transportBuffer)); + } + + @Test + public void processBytesFromPeerNoBytesConsumed() throws Exception { + ByteBuffer transportBuffer = ByteBuffer.allocate(TRANSPORT_BUFFER_SIZE); + ByteBuffer emptyOutputFrame = ByteBuffer.allocate(0); + verify(mockServer, never()).startClientHandshake(); + verify(mockServer, never()).next(Matchers.any()); + when(mockServer.startServerHandshake(transportBuffer)).thenReturn(emptyOutputFrame); + when(mockServer.isFinished()).thenReturn(false); + + try { + assertTrue(handshakerServer.processBytesFromPeer(transportBuffer)); + fail("Expected IllegalStateException"); + } catch (IllegalStateException expected) { + assertEquals("Handshaker did not consume any bytes.", expected.getMessage()); + } + } + + @Test + public void processBytesFromPeerClientNext() throws Exception { + ByteBuffer transportBuffer = ByteBuffer.allocate(TRANSPORT_BUFFER_SIZE); + ByteBuffer outputFrame = ByteBuffer.allocate(OUT_FRAME_SIZE); + verify(mockClient, never()).startServerHandshake(Matchers.any()); + when(mockClient.startClientHandshake()).thenReturn(outputFrame); + when(mockClient.next(transportBuffer)).thenReturn(outputFrame); + when(mockClient.isFinished()).thenReturn(false); + + handshakerClient.getBytesToSendToPeer(transportBuffer); + transportBuffer.position(transportBuffer.limit()); + assertFalse(handshakerClient.processBytesFromPeer(transportBuffer)); + } + + @Test + public void processBytesFromPeerClientNextFinished() throws Exception { + ByteBuffer transportBuffer = ByteBuffer.allocate(TRANSPORT_BUFFER_SIZE); + ByteBuffer outputFrame = ByteBuffer.allocate(OUT_FRAME_SIZE); + verify(mockClient, never()).startServerHandshake(Matchers.any()); + when(mockClient.startClientHandshake()).thenReturn(outputFrame); + when(mockClient.next(transportBuffer)).thenReturn(outputFrame); + when(mockClient.isFinished()).thenReturn(true); + + handshakerClient.getBytesToSendToPeer(transportBuffer); + assertTrue(handshakerClient.processBytesFromPeer(transportBuffer)); + } + + @Test + public void extractPeerFailure() throws Exception { + when(mockClient.isFinished()).thenReturn(false); + + try { + handshakerClient.extractPeer(); + fail("Expected IllegalStateException"); + } catch (IllegalStateException expected) { + assertEquals("Handshake is not complete.", expected.getMessage()); + } + } + + @Test + public void extractPeerObjectFailure() throws Exception { + when(mockClient.isFinished()).thenReturn(false); + + try { + handshakerClient.extractPeerObject(); + fail("Expected IllegalStateException"); + } catch (IllegalStateException expected) { + assertEquals("Handshake is not complete.", expected.getMessage()); + } + } + + @Test + public void extractClientPeerSuccess() throws Exception { + ByteBuffer outputFrame = ByteBuffer.allocate(OUT_FRAME_SIZE); + ByteBuffer transportBuffer = ByteBuffer.allocate(TRANSPORT_BUFFER_SIZE); + when(mockClient.startClientHandshake()).thenReturn(outputFrame); + when(mockClient.isFinished()).thenReturn(true); + when(mockClient.getResult()).thenReturn(getHandshakerResult(/* isClient = */ true)); + + handshakerClient.getBytesToSendToPeer(transportBuffer); + TsiPeer clientPeer = handshakerClient.extractPeer(); + + assertEquals(1, clientPeer.getProperties().size()); + assertEquals( + TEST_SERVER_SERVICE_ACCOUNT, + clientPeer.getProperty(AltsTsiHandshaker.TSI_SERVICE_ACCOUNT_PEER_PROPERTY).getValue()); + + AltsAuthContext clientContext = (AltsAuthContext) handshakerClient.extractPeerObject(); + assertEquals(TEST_APPLICATION_PROTOCOL, clientContext.getApplicationProtocol()); + assertEquals(TEST_RECORD_PROTOCOL, clientContext.getRecordProtocol()); + assertEquals(TEST_SERVER_SERVICE_ACCOUNT, clientContext.getPeerServiceAccount()); + assertEquals(TEST_CLIENT_SERVICE_ACCOUNT, clientContext.getLocalServiceAccount()); + assertEquals(TEST_RPC_PROTOCOL_VERSIONS, clientContext.getPeerRpcVersions()); + } + + @Test + public void extractServerPeerSuccess() throws Exception { + ByteBuffer outputFrame = ByteBuffer.allocate(OUT_FRAME_SIZE); + ByteBuffer transportBuffer = ByteBuffer.allocate(TRANSPORT_BUFFER_SIZE); + when(mockServer.startServerHandshake(Matchers.any())).thenReturn(outputFrame); + when(mockServer.isFinished()).thenReturn(true); + when(mockServer.getResult()).thenReturn(getHandshakerResult(/* isClient = */ false)); + + handshakerServer.processBytesFromPeer(transportBuffer); + handshakerServer.getBytesToSendToPeer(transportBuffer); + TsiPeer serverPeer = handshakerServer.extractPeer(); + + assertEquals(1, serverPeer.getProperties().size()); + assertEquals( + TEST_CLIENT_SERVICE_ACCOUNT, + serverPeer.getProperty(AltsTsiHandshaker.TSI_SERVICE_ACCOUNT_PEER_PROPERTY).getValue()); + + AltsAuthContext serverContext = (AltsAuthContext) handshakerServer.extractPeerObject(); + assertEquals(TEST_APPLICATION_PROTOCOL, serverContext.getApplicationProtocol()); + assertEquals(TEST_RECORD_PROTOCOL, serverContext.getRecordProtocol()); + assertEquals(TEST_CLIENT_SERVICE_ACCOUNT, serverContext.getPeerServiceAccount()); + assertEquals(TEST_SERVER_SERVICE_ACCOUNT, serverContext.getLocalServiceAccount()); + assertEquals(TEST_RPC_PROTOCOL_VERSIONS, serverContext.getPeerRpcVersions()); + } +} diff --git a/alts/src/test/java/io/grpc/alts/internal/AltsTsiTest.java b/alts/src/test/java/io/grpc/alts/internal/AltsTsiTest.java new file mode 100644 index 0000000000000000000000000000000000000000..8d990bda8800ffaa95f4f2879946c985a6f59fe6 --- /dev/null +++ b/alts/src/test/java/io/grpc/alts/internal/AltsTsiTest.java @@ -0,0 +1,198 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import static org.junit.Assert.assertEquals; + +import com.google.common.testing.GcFinalization; +import io.grpc.alts.internal.ByteBufTestUtils.RegisterRef; +import io.grpc.alts.internal.Handshaker.HandshakeProtocol; +import io.grpc.alts.internal.Handshaker.HandshakerReq; +import io.grpc.alts.internal.Handshaker.HandshakerResp; +import io.grpc.alts.internal.TsiTest.Handshakers; +import io.netty.buffer.ByteBuf; +import io.netty.util.ReferenceCounted; +import io.netty.util.ResourceLeakDetector; +import io.netty.util.ResourceLeakDetector.Level; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.List; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Unit tests for {@link AltsTsiHandshaker}. */ +@RunWith(JUnit4.class) +public class AltsTsiTest { + private static final int OVERHEAD = + FakeChannelCrypter.getTagBytes() + AltsTsiFrameProtector.getHeaderBytes(); + + private final List references = new ArrayList<>(); + private AltsHandshakerClient client; + private AltsHandshakerClient server; + private final RegisterRef ref = + new RegisterRef() { + @Override + public ByteBuf register(ByteBuf buf) { + if (buf != null) { + references.add(buf); + } + return buf; + } + }; + + @Before + public void setUp() throws Exception { + ResourceLeakDetector.setLevel(Level.PARANOID); + // Use MockAltsHandshakerStub for all the tests. + AltsHandshakerOptions handshakerOptions = new AltsHandshakerOptions(null); + MockAltsHandshakerStub clientStub = new MockAltsHandshakerStub(); + MockAltsHandshakerStub serverStub = new MockAltsHandshakerStub(); + client = new AltsHandshakerClient(clientStub, handshakerOptions); + server = new AltsHandshakerClient(serverStub, handshakerOptions); + } + + @After + public void tearDown() { + for (ReferenceCounted reference : references) { + reference.release(); + } + references.clear(); + // Increase our chances to detect ByteBuf leaks. + GcFinalization.awaitFullGc(); + } + + private Handshakers newHandshakers() { + TsiHandshaker clientHandshaker = new AltsTsiHandshaker(true, client); + TsiHandshaker serverHandshaker = new AltsTsiHandshaker(false, server); + return new Handshakers(clientHandshaker, serverHandshaker); + } + + @Test + public void verifyHandshakePeer() throws Exception { + Handshakers handshakers = newHandshakers(); + TsiTest.performHandshake(TsiTest.getDefaultTransportBufferSize(), handshakers); + TsiPeer clientPeer = handshakers.getClient().extractPeer(); + assertEquals(1, clientPeer.getProperties().size()); + assertEquals( + MockAltsHandshakerResp.getTestPeerAccount(), + clientPeer.getProperty("service_account").getValue()); + TsiPeer serverPeer = handshakers.getServer().extractPeer(); + assertEquals(1, serverPeer.getProperties().size()); + assertEquals( + MockAltsHandshakerResp.getTestPeerAccount(), + serverPeer.getProperty("service_account").getValue()); + } + + @Test + public void handshake() throws GeneralSecurityException { + TsiTest.handshakeTest(newHandshakers()); + } + + @Test + public void handshakeSmallBuffer() throws GeneralSecurityException { + TsiTest.handshakeSmallBufferTest(newHandshakers()); + } + + @Test + public void pingPong() throws GeneralSecurityException { + TsiTest.pingPongTest(newHandshakers(), ref); + } + + @Test + public void pingPongExactFrameSize() throws GeneralSecurityException { + TsiTest.pingPongExactFrameSizeTest(newHandshakers(), ref); + } + + @Test + public void pingPongSmallBuffer() throws GeneralSecurityException { + TsiTest.pingPongSmallBufferTest(newHandshakers(), ref); + } + + @Test + public void pingPongSmallFrame() throws GeneralSecurityException { + TsiTest.pingPongSmallFrameTest(OVERHEAD, newHandshakers(), ref); + } + + @Test + public void pingPongSmallFrameSmallBuffer() throws GeneralSecurityException { + TsiTest.pingPongSmallFrameSmallBufferTest(OVERHEAD, newHandshakers(), ref); + } + + @Test + public void corruptedCounter() throws GeneralSecurityException { + TsiTest.corruptedCounterTest(newHandshakers(), ref); + } + + @Test + public void corruptedCiphertext() throws GeneralSecurityException { + TsiTest.corruptedCiphertextTest(newHandshakers(), ref); + } + + @Test + public void corruptedTag() throws GeneralSecurityException { + TsiTest.corruptedTagTest(newHandshakers(), ref); + } + + @Test + public void reflectedCiphertext() throws GeneralSecurityException { + TsiTest.reflectedCiphertextTest(newHandshakers(), ref); + } + + private static class MockAltsHandshakerStub extends AltsHandshakerStub { + private boolean started = false; + + @Override + public HandshakerResp send(HandshakerReq req) { + if (started) { + // Expect handshake next message. + if (req.getReqOneofCase().getNumber() != 3) { + return MockAltsHandshakerResp.getErrorResponse(); + } + return MockAltsHandshakerResp.getFinishedResponse(req.getNext().getInBytes().size()); + } else { + List recordProtocols; + int bytesConsumed = 0; + switch (req.getReqOneofCase().getNumber()) { + case 1: + recordProtocols = req.getClientStart().getRecordProtocolsList(); + break; + case 2: + recordProtocols = + req.getServerStart() + .getHandshakeParametersMap() + .get(HandshakeProtocol.ALTS.getNumber()) + .getRecordProtocolsList(); + bytesConsumed = req.getServerStart().getInBytes().size(); + break; + default: + return MockAltsHandshakerResp.getErrorResponse(); + } + if (recordProtocols.isEmpty()) { + return MockAltsHandshakerResp.getErrorResponse(); + } + started = true; + return MockAltsHandshakerResp.getOkResponse(bytesConsumed); + } + } + + @Override + public void close() {} + } +} diff --git a/alts/src/test/java/io/grpc/alts/internal/BufUnwrapperTest.java b/alts/src/test/java/io/grpc/alts/internal/BufUnwrapperTest.java new file mode 100644 index 0000000000000000000000000000000000000000..67f318e86113d4a5b23fce6336555d9a73e5df01 --- /dev/null +++ b/alts/src/test/java/io/grpc/alts/internal/BufUnwrapperTest.java @@ -0,0 +1,137 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import static org.junit.Assert.assertEquals; + +import com.google.common.truth.Truth; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufAllocator; +import io.netty.buffer.CompositeByteBuf; +import io.netty.buffer.UnpooledByteBufAllocator; +import java.nio.ByteBuffer; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class BufUnwrapperTest { + + private final ByteBufAllocator alloc = UnpooledByteBufAllocator.DEFAULT; + + @Test + public void closeEmptiesBuffers() { + BufUnwrapper unwrapper = new BufUnwrapper(); + ByteBuf buf = alloc.buffer(); + try { + ByteBuffer[] readableBufs = unwrapper.readableNioBuffers(buf); + ByteBuffer[] writableBufs = unwrapper.writableNioBuffers(buf); + Truth.assertThat(readableBufs).hasLength(1); + Truth.assertThat(readableBufs[0]).isNotNull(); + Truth.assertThat(writableBufs).hasLength(1); + Truth.assertThat(writableBufs[0]).isNotNull(); + + unwrapper.close(); + + Truth.assertThat(readableBufs[0]).isNull(); + Truth.assertThat(writableBufs[0]).isNull(); + } finally { + buf.release(); + } + } + + @Test + public void readableNioBuffers_worksWithNormal() { + ByteBuf buf = alloc.buffer(1).writeByte('a'); + try (BufUnwrapper unwrapper = new BufUnwrapper()) { + ByteBuffer[] internalBufs = unwrapper.readableNioBuffers(buf); + Truth.assertThat(internalBufs).hasLength(1); + + assertEquals('a', internalBufs[0].get(0)); + } finally { + buf.release(); + } + } + + @Test + public void readableNioBuffers_worksWithComposite() { + CompositeByteBuf buf = alloc.compositeBuffer(); + buf.addComponent(true, alloc.buffer(1).writeByte('a')); + try (BufUnwrapper unwrapper = new BufUnwrapper()) { + ByteBuffer[] internalBufs = unwrapper.readableNioBuffers(buf); + Truth.assertThat(internalBufs).hasLength(1); + + assertEquals('a', internalBufs[0].get(0)); + } finally { + buf.release(); + } + } + + @Test + public void writableNioBuffers_indexesPreserved() { + ByteBuf buf = alloc.buffer(1); + int ridx = buf.readerIndex(); + int widx = buf.writerIndex(); + int cap = buf.capacity(); + try (BufUnwrapper unwrapper = new BufUnwrapper()) { + ByteBuffer[] internalBufs = unwrapper.writableNioBuffers(buf); + Truth.assertThat(internalBufs).hasLength(1); + + internalBufs[0].put((byte) 'a'); + + assertEquals(ridx, buf.readerIndex()); + assertEquals(widx, buf.writerIndex()); + assertEquals(cap, buf.capacity()); + } finally { + buf.release(); + } + } + + @Test + public void writableNioBuffers_worksWithNormal() { + ByteBuf buf = alloc.buffer(1); + try (BufUnwrapper unwrapper = new BufUnwrapper()) { + ByteBuffer[] internalBufs = unwrapper.writableNioBuffers(buf); + Truth.assertThat(internalBufs).hasLength(1); + + internalBufs[0].put((byte) 'a'); + + buf.writerIndex(1); + assertEquals('a', buf.readByte()); + } finally { + buf.release(); + } + } + + @Test + public void writableNioBuffers_worksWithComposite() { + CompositeByteBuf buf = alloc.compositeBuffer(); + buf.addComponent(alloc.buffer(1)); + buf.capacity(1); + try (BufUnwrapper unwrapper = new BufUnwrapper()) { + ByteBuffer[] internalBufs = unwrapper.writableNioBuffers(buf); + Truth.assertThat(internalBufs).hasLength(1); + + internalBufs[0].put((byte) 'a'); + + buf.writerIndex(1); + assertEquals('a', buf.readByte()); + } finally { + buf.release(); + } + } +} diff --git a/alts/src/test/java/io/grpc/alts/internal/ByteBufTestUtils.java b/alts/src/test/java/io/grpc/alts/internal/ByteBufTestUtils.java new file mode 100644 index 0000000000000000000000000000000000000000..0d0f13c9cc4ab6b45a697fda1a1b4aa87b5fa966 --- /dev/null +++ b/alts/src/test/java/io/grpc/alts/internal/ByteBufTestUtils.java @@ -0,0 +1,71 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import com.google.common.base.Preconditions; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +public final class ByteBufTestUtils { + public interface RegisterRef { + ByteBuf register(ByteBuf buf); + } + + private static final Random random = new SecureRandom(); + + // The {@code ref} argument can be used to register the buffer for {@code release}. + // TODO: allow the allocator to be passed in. + public static ByteBuf getDirectBuffer(int len, RegisterRef ref) { + return ref.register(Unpooled.directBuffer(len)); + } + + /** Get random bytes. */ + public static ByteBuf getRandom(int len, RegisterRef ref) { + ByteBuf buf = getDirectBuffer(len, ref); + byte[] bytes = new byte[len]; + random.nextBytes(bytes); + buf.writeBytes(bytes); + return buf; + } + + /** Fragment byte buffer into multiple pieces. */ + public static List fragmentByteBuf(ByteBuf in, int num, RegisterRef ref) { + ByteBuf buf = in.slice(); + Preconditions.checkArgument(num > 0); + List fragmentedBufs = new ArrayList<>(num); + int fragmentSize = buf.readableBytes() / num; + while (buf.isReadable()) { + int readBytes = num == 0 ? buf.readableBytes() : fragmentSize; + ByteBuf tmpBuf = getDirectBuffer(readBytes, ref); + tmpBuf.writeBytes(buf, readBytes); + fragmentedBufs.add(tmpBuf); + num--; + } + return fragmentedBufs; + } + + static ByteBuf writeSlice(ByteBuf in, int len) { + Preconditions.checkArgument(len <= in.writableBytes()); + ByteBuf out = in.slice(in.writerIndex(), len); + in.writerIndex(in.writerIndex() + len); + return out.writerIndex(0); + } +} diff --git a/alts/src/test/java/io/grpc/alts/internal/ChannelCrypterNettyTestBase.java b/alts/src/test/java/io/grpc/alts/internal/ChannelCrypterNettyTestBase.java new file mode 100644 index 0000000000000000000000000000000000000000..6de3c59671c6463c1f3caa3118b45419062d835b --- /dev/null +++ b/alts/src/test/java/io/grpc/alts/internal/ChannelCrypterNettyTestBase.java @@ -0,0 +1,226 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import static com.google.common.truth.Truth.assertThat; +import static io.grpc.alts.internal.ByteBufTestUtils.getDirectBuffer; +import static io.grpc.alts.internal.ByteBufTestUtils.getRandom; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.Assert.fail; + +import io.grpc.alts.internal.ByteBufTestUtils.RegisterRef; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.util.ReferenceCounted; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import javax.crypto.AEADBadTagException; +import org.junit.Test; + +/** Abstract class for unit tests of {@link ChannelCrypterNetty}. */ +public abstract class ChannelCrypterNettyTestBase { + private static final String DECRYPTION_FAILURE_MESSAGE = "Tag mismatch"; + + protected final List references = new ArrayList<>(); + public ChannelCrypterNetty client; + public ChannelCrypterNetty server; + private final RegisterRef ref = + new RegisterRef() { + @Override + public ByteBuf register(ByteBuf buf) { + if (buf != null) { + references.add(buf); + } + return buf; + } + }; + + static final class FrameEncrypt { + List plain; + ByteBuf out; + } + + static final class FrameDecrypt { + List ciphertext; + ByteBuf out; + ByteBuf tag; + } + + FrameEncrypt createFrameEncrypt(String message) { + byte[] messageBytes = message.getBytes(UTF_8); + FrameEncrypt frame = new FrameEncrypt(); + ByteBuf plain = getDirectBuffer(messageBytes.length, ref); + plain.writeBytes(messageBytes); + frame.plain = Collections.singletonList(plain); + frame.out = getDirectBuffer(messageBytes.length + client.getSuffixLength(), ref); + return frame; + } + + FrameDecrypt frameDecryptOfEncrypt(FrameEncrypt frameEncrypt) { + int tagLen = client.getSuffixLength(); + FrameDecrypt frameDecrypt = new FrameDecrypt(); + ByteBuf out = frameEncrypt.out; + frameDecrypt.ciphertext = + Collections.singletonList(out.slice(out.readerIndex(), out.readableBytes() - tagLen)); + frameDecrypt.tag = out.slice(out.readerIndex() + out.readableBytes() - tagLen, tagLen); + frameDecrypt.out = getDirectBuffer(out.readableBytes(), ref); + return frameDecrypt; + } + + @Test + public void encryptDecrypt() throws GeneralSecurityException { + String message = "Hello world"; + FrameEncrypt frameEncrypt = createFrameEncrypt(message); + client.encrypt(frameEncrypt.out, frameEncrypt.plain); + FrameDecrypt frameDecrypt = frameDecryptOfEncrypt(frameEncrypt); + + server.decrypt(frameDecrypt.out, frameDecrypt.tag, frameDecrypt.ciphertext); + assertThat(frameEncrypt.plain.get(0).slice(0, frameDecrypt.out.readableBytes())) + .isEqualTo(frameDecrypt.out); + } + + @Test + public void encryptDecryptLarge() throws GeneralSecurityException { + FrameEncrypt frameEncrypt = new FrameEncrypt(); + ByteBuf plain = getRandom(17 * 1024, ref); + frameEncrypt.plain = Collections.singletonList(plain); + frameEncrypt.out = getDirectBuffer(plain.readableBytes() + client.getSuffixLength(), ref); + + client.encrypt(frameEncrypt.out, frameEncrypt.plain); + FrameDecrypt frameDecrypt = frameDecryptOfEncrypt(frameEncrypt); + + // Call decrypt overload that takes ciphertext and tag. + server.decrypt(frameDecrypt.out, frameEncrypt.out); + assertThat(frameEncrypt.plain.get(0).slice(0, frameDecrypt.out.readableBytes())) + .isEqualTo(frameDecrypt.out); + } + + @Test + public void encryptDecryptMultiple() throws GeneralSecurityException { + String message = "Hello world"; + for (int i = 0; i < 512; ++i) { + FrameEncrypt frameEncrypt = createFrameEncrypt(message); + client.encrypt(frameEncrypt.out, frameEncrypt.plain); + FrameDecrypt frameDecrypt = frameDecryptOfEncrypt(frameEncrypt); + + server.decrypt(frameDecrypt.out, frameDecrypt.tag, frameDecrypt.ciphertext); + assertThat(frameEncrypt.plain.get(0).slice(0, frameDecrypt.out.readableBytes())) + .isEqualTo(frameDecrypt.out); + } + } + + @Test + public void encryptDecryptComposite() throws GeneralSecurityException { + String message = "Hello world"; + int lastLen = 2; + byte[] messageBytes = message.getBytes(UTF_8); + FrameEncrypt frameEncrypt = new FrameEncrypt(); + ByteBuf plain1 = getDirectBuffer(messageBytes.length - lastLen, ref); + ByteBuf plain2 = getDirectBuffer(lastLen, ref); + plain1.writeBytes(messageBytes, 0, messageBytes.length - lastLen); + plain2.writeBytes(messageBytes, messageBytes.length - lastLen, lastLen); + ByteBuf plain = Unpooled.wrappedBuffer(plain1, plain2); + frameEncrypt.plain = Collections.singletonList(plain); + frameEncrypt.out = getDirectBuffer(messageBytes.length + client.getSuffixLength(), ref); + + client.encrypt(frameEncrypt.out, frameEncrypt.plain); + + int tagLen = client.getSuffixLength(); + FrameDecrypt frameDecrypt = new FrameDecrypt(); + ByteBuf out = frameEncrypt.out; + int outLen = out.readableBytes(); + ByteBuf cipher1 = getDirectBuffer(outLen - lastLen - tagLen, ref); + ByteBuf cipher2 = getDirectBuffer(lastLen, ref); + cipher1.writeBytes(out, 0, outLen - lastLen - tagLen); + cipher2.writeBytes(out, outLen - tagLen - lastLen, lastLen); + ByteBuf cipher = Unpooled.wrappedBuffer(cipher1, cipher2); + frameDecrypt.ciphertext = Collections.singletonList(cipher); + frameDecrypt.tag = out.slice(out.readerIndex() + out.readableBytes() - tagLen, tagLen); + frameDecrypt.out = getDirectBuffer(out.readableBytes(), ref); + + server.decrypt(frameDecrypt.out, frameDecrypt.tag, frameDecrypt.ciphertext); + assertThat(frameEncrypt.plain.get(0).slice(0, frameDecrypt.out.readableBytes())) + .isEqualTo(frameDecrypt.out); + } + + @Test + public void reflection() throws GeneralSecurityException { + String message = "Hello world"; + FrameEncrypt frameEncrypt = createFrameEncrypt(message); + client.encrypt(frameEncrypt.out, frameEncrypt.plain); + FrameDecrypt frameDecrypt = frameDecryptOfEncrypt(frameEncrypt); + try { + client.decrypt(frameDecrypt.out, frameDecrypt.tag, frameDecrypt.ciphertext); + fail("Exception expected"); + } catch (AEADBadTagException ex) { + assertThat(ex).hasMessageThat().contains(DECRYPTION_FAILURE_MESSAGE); + } + } + + @Test + public void skipMessage() throws GeneralSecurityException { + String message = "Hello world"; + FrameEncrypt frameEncrypt1 = createFrameEncrypt(message); + client.encrypt(frameEncrypt1.out, frameEncrypt1.plain); + FrameEncrypt frameEncrypt2 = createFrameEncrypt(message); + client.encrypt(frameEncrypt2.out, frameEncrypt2.plain); + FrameDecrypt frameDecrypt = frameDecryptOfEncrypt(frameEncrypt2); + + try { + client.decrypt(frameDecrypt.out, frameDecrypt.tag, frameDecrypt.ciphertext); + fail("Exception expected"); + } catch (AEADBadTagException ex) { + assertThat(ex).hasMessageThat().contains(DECRYPTION_FAILURE_MESSAGE); + } + } + + @Test + public void corruptMessage() throws GeneralSecurityException { + String message = "Hello world"; + FrameEncrypt frameEncrypt = createFrameEncrypt(message); + client.encrypt(frameEncrypt.out, frameEncrypt.plain); + FrameDecrypt frameDecrypt = frameDecryptOfEncrypt(frameEncrypt); + frameEncrypt.out.setByte(3, frameEncrypt.out.getByte(3) + 1); + + try { + client.decrypt(frameDecrypt.out, frameDecrypt.tag, frameDecrypt.ciphertext); + fail("Exception expected"); + } catch (AEADBadTagException ex) { + assertThat(ex).hasMessageThat().contains(DECRYPTION_FAILURE_MESSAGE); + } + } + + @Test + public void replayMessage() throws GeneralSecurityException { + String message = "Hello world"; + FrameEncrypt frameEncrypt = createFrameEncrypt(message); + client.encrypt(frameEncrypt.out, frameEncrypt.plain); + FrameDecrypt frameDecrypt1 = frameDecryptOfEncrypt(frameEncrypt); + FrameDecrypt frameDecrypt2 = frameDecryptOfEncrypt(frameEncrypt); + + server.decrypt(frameDecrypt1.out, frameDecrypt1.tag, frameDecrypt1.ciphertext); + + try { + server.decrypt(frameDecrypt2.out, frameDecrypt2.tag, frameDecrypt2.ciphertext); + fail("Exception expected"); + } catch (AEADBadTagException ex) { + assertThat(ex).hasMessageThat().contains(DECRYPTION_FAILURE_MESSAGE); + } + } +} diff --git a/alts/src/test/java/io/grpc/alts/internal/FakeChannelCrypter.java b/alts/src/test/java/io/grpc/alts/internal/FakeChannelCrypter.java new file mode 100644 index 0000000000000000000000000000000000000000..037af017ae908ab3df4dabee1ca7996d0e01fdce --- /dev/null +++ b/alts/src/test/java/io/grpc/alts/internal/FakeChannelCrypter.java @@ -0,0 +1,78 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import static com.google.common.base.Preconditions.checkState; + +import io.netty.buffer.ByteBuf; +import java.security.GeneralSecurityException; +import java.util.Collections; +import java.util.List; +import javax.crypto.AEADBadTagException; + +public final class FakeChannelCrypter implements ChannelCrypterNetty { + private static final int TAG_BYTES = 16; + private static final byte TAG_BYTE = (byte) 0xa1; + + private boolean destroyCalled = false; + + public static int getTagBytes() { + return TAG_BYTES; + } + + @Override + public void encrypt(ByteBuf out, List plain) throws GeneralSecurityException { + checkState(!destroyCalled); + for (ByteBuf buf : plain) { + out.writeBytes(buf); + for (int i = 0; i < TAG_BYTES; ++i) { + out.writeByte(TAG_BYTE); + } + } + } + + @Override + public void decrypt(ByteBuf out, ByteBuf tag, List ciphertext) + throws GeneralSecurityException { + checkState(!destroyCalled); + for (ByteBuf buf : ciphertext) { + out.writeBytes(buf); + } + while (tag.isReadable()) { + if (tag.readByte() != TAG_BYTE) { + throw new AEADBadTagException("Tag mismatch!"); + } + } + } + + @Override + public void decrypt(ByteBuf out, ByteBuf ciphertextAndTag) throws GeneralSecurityException { + checkState(!destroyCalled); + ByteBuf ciphertext = ciphertextAndTag.readSlice(ciphertextAndTag.readableBytes() - TAG_BYTES); + decrypt(out, /*tag=*/ ciphertextAndTag, Collections.singletonList(ciphertext)); + } + + @Override + public int getSuffixLength() { + return TAG_BYTES; + } + + @Override + public void destroy() { + destroyCalled = true; + } +} diff --git a/alts/src/test/java/io/grpc/alts/internal/FakeTsiHandshaker.java b/alts/src/test/java/io/grpc/alts/internal/FakeTsiHandshaker.java new file mode 100644 index 0000000000000000000000000000000000000000..ea728e3bb19669276f708df8a4f93df6879a3f3b --- /dev/null +++ b/alts/src/test/java/io/grpc/alts/internal/FakeTsiHandshaker.java @@ -0,0 +1,228 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import static java.nio.charset.StandardCharsets.UTF_8; + +import com.google.common.base.Preconditions; +import io.grpc.alts.internal.TsiPeer.Property; +import io.netty.buffer.ByteBufAllocator; +import java.nio.ByteBuffer; +import java.security.GeneralSecurityException; +import java.util.Collections; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * A fake handshaker compatible with security/transport_security/fake_transport_security.h See + * {@link TsiHandshaker} for documentation. + */ +public class FakeTsiHandshaker implements TsiHandshaker { + private static final Logger logger = Logger.getLogger(FakeTsiHandshaker.class.getName()); + + private static final TsiHandshakerFactory clientHandshakerFactory = + new TsiHandshakerFactory() { + @Override + public TsiHandshaker newHandshaker() { + return new FakeTsiHandshaker(true); + } + }; + + private static final TsiHandshakerFactory serverHandshakerFactory = + new TsiHandshakerFactory() { + @Override + public TsiHandshaker newHandshaker() { + return new FakeTsiHandshaker(false); + } + }; + + private boolean isClient; + private ByteBuffer sendBuffer = null; + private AltsFraming.Parser frameParser = new AltsFraming.Parser(); + + private State sendState; + private State receiveState; + + enum State { + CLIENT_NONE, + SERVER_NONE, + CLIENT_INIT, + SERVER_INIT, + CLIENT_FINISHED, + SERVER_FINISHED; + + // Returns the next State. In order to advance to sendState=N, receiveState must be N-1. + public State next() { + if (ordinal() + 1 < values().length) { + return values()[ordinal() + 1]; + } + throw new UnsupportedOperationException("Can't call next() on last element: " + this); + } + } + + public static TsiHandshakerFactory clientHandshakerFactory() { + return clientHandshakerFactory; + } + + public static TsiHandshakerFactory serverHandshakerFactory() { + return serverHandshakerFactory; + } + + public static TsiHandshaker newFakeHandshakerClient() { + return clientHandshakerFactory.newHandshaker(); + } + + public static TsiHandshaker newFakeHandshakerServer() { + return serverHandshakerFactory.newHandshaker(); + } + + protected FakeTsiHandshaker(boolean isClient) { + this.isClient = isClient; + if (isClient) { + sendState = State.CLIENT_NONE; + receiveState = State.SERVER_NONE; + } else { + sendState = State.SERVER_NONE; + receiveState = State.CLIENT_NONE; + } + } + + private State getNextState(State state) { + switch (state) { + case CLIENT_NONE: + return State.CLIENT_INIT; + case SERVER_NONE: + return State.SERVER_INIT; + case CLIENT_INIT: + return State.CLIENT_FINISHED; + case SERVER_INIT: + return State.SERVER_FINISHED; + default: + return null; + } + } + + private String getNextMessage() { + State result = getNextState(sendState); + return result == null ? "BAD STATE" : result.toString(); + } + + private String getExpectedMessage() { + State result = getNextState(receiveState); + return result == null ? "BAD STATE" : result.toString(); + } + + private void incrementSendState() { + sendState = getNextState(sendState); + } + + private void incrementReceiveState() { + receiveState = getNextState(receiveState); + } + + @Override + public void getBytesToSendToPeer(ByteBuffer bytes) throws GeneralSecurityException { + Preconditions.checkNotNull(bytes); + + // If we're done, return nothing. + if (sendState == State.CLIENT_FINISHED || sendState == State.SERVER_FINISHED) { + return; + } + + // Prepare the next message, if neeeded. + if (sendBuffer == null) { + if (sendState.next() != receiveState) { + // We're still waiting for bytes from the peer, so bail. + return; + } + ByteBuffer payload = ByteBuffer.wrap(getNextMessage().getBytes(UTF_8)); + sendBuffer = AltsFraming.toFrame(payload, payload.remaining()); + logger.log(Level.FINE, "Buffered message: {0}", getNextMessage()); + } + while (bytes.hasRemaining() && sendBuffer.hasRemaining()) { + bytes.put(sendBuffer.get()); + } + if (!sendBuffer.hasRemaining()) { + // Get ready to send the next message. + sendBuffer = null; + incrementSendState(); + } + } + + @Override + public boolean processBytesFromPeer(ByteBuffer bytes) throws GeneralSecurityException { + Preconditions.checkNotNull(bytes); + + frameParser.readBytes(bytes); + if (frameParser.isComplete()) { + ByteBuffer messageBytes = frameParser.getRawFrame(); + int offset = AltsFraming.getFramingOverhead(); + int length = messageBytes.limit() - offset; + String message = new String(messageBytes.array(), offset, length, UTF_8); + logger.log(Level.FINE, "Read message: {0}", message); + + if (!message.equals(getExpectedMessage())) { + throw new IllegalArgumentException( + "Bad handshake message. Got " + + message + + " (length = " + + message.length() + + ") expected " + + getExpectedMessage() + + " (length = " + + getExpectedMessage().length() + + ")"); + } + incrementReceiveState(); + return true; + } + return false; + } + + @Override + public boolean isInProgress() { + boolean finishedReceiving = + receiveState == State.CLIENT_FINISHED || receiveState == State.SERVER_FINISHED; + boolean finishedSending = + sendState == State.CLIENT_FINISHED || sendState == State.SERVER_FINISHED; + return !finishedSending || !finishedReceiving; + } + + @Override + public TsiPeer extractPeer() { + return new TsiPeer(Collections.>emptyList()); + } + + @Override + public Object extractPeerObject() { + return AltsAuthContext.getDefaultInstance(); + } + + @Override + public TsiFrameProtector createFrameProtector(int maxFrameSize, ByteBufAllocator alloc) { + Preconditions.checkState(!isInProgress(), "Handshake is not complete."); + + // We use an all-zero key, since this is the fake handshaker. + byte[] key = new byte[AltsChannelCrypter.getKeyLength()]; + return new AltsTsiFrameProtector(maxFrameSize, new AltsChannelCrypter(key, isClient), alloc); + } + + @Override + public TsiFrameProtector createFrameProtector(ByteBufAllocator alloc) { + return createFrameProtector(AltsTsiFrameProtector.getMaxAllowedFrameBytes(), alloc); + } +} diff --git a/alts/src/test/java/io/grpc/alts/internal/FakeTsiTest.java b/alts/src/test/java/io/grpc/alts/internal/FakeTsiTest.java new file mode 100644 index 0000000000000000000000000000000000000000..cf7c3133e7bff15c70c45f3641a4cc7459837b92 --- /dev/null +++ b/alts/src/test/java/io/grpc/alts/internal/FakeTsiTest.java @@ -0,0 +1,213 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +import com.google.common.testing.GcFinalization; +import io.grpc.alts.internal.ByteBufTestUtils.RegisterRef; +import io.grpc.alts.internal.TsiTest.Handshakers; +import io.netty.buffer.ByteBuf; +import io.netty.util.ReferenceCounted; +import io.netty.util.ResourceLeakDetector; +import io.netty.util.ResourceLeakDetector.Level; +import java.nio.ByteBuffer; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.List; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Unit tests for {@link TsiHandshaker}. */ +@RunWith(JUnit4.class) +public class FakeTsiTest { + + private static final int OVERHEAD = + FakeChannelCrypter.getTagBytes() + AltsTsiFrameProtector.getHeaderBytes(); + + private final List references = new ArrayList<>(); + private final RegisterRef ref = + new RegisterRef() { + @Override + public ByteBuf register(ByteBuf buf) { + if (buf != null) { + references.add(buf); + } + return buf; + } + }; + + private static Handshakers newHandshakers() { + TsiHandshaker clientHandshaker = FakeTsiHandshaker.newFakeHandshakerClient(); + TsiHandshaker serverHandshaker = FakeTsiHandshaker.newFakeHandshakerServer(); + return new Handshakers(clientHandshaker, serverHandshaker); + } + + @Before + public void setUp() { + ResourceLeakDetector.setLevel(Level.PARANOID); + } + + @After + public void tearDown() { + for (ReferenceCounted reference : references) { + reference.release(); + } + references.clear(); + // Increase our chances to detect ByteBuf leaks. + GcFinalization.awaitFullGc(); + } + + @Test + public void handshakeStateOrderTest() { + try { + Handshakers handshakers = newHandshakers(); + TsiHandshaker clientHandshaker = handshakers.getClient(); + TsiHandshaker serverHandshaker = handshakers.getServer(); + + byte[] transportBufferBytes = new byte[TsiTest.getDefaultTransportBufferSize()]; + ByteBuffer transportBuffer = ByteBuffer.wrap(transportBufferBytes); + transportBuffer.limit(0); // Start off with an empty buffer + + transportBuffer.clear(); + clientHandshaker.getBytesToSendToPeer(transportBuffer); + transportBuffer.flip(); + assertEquals( + FakeTsiHandshaker.State.CLIENT_INIT.toString().trim(), + new String(transportBufferBytes, 4, transportBuffer.remaining(), UTF_8).trim()); + + serverHandshaker.processBytesFromPeer(transportBuffer); + assertFalse(transportBuffer.hasRemaining()); + + // client shouldn't offer any more bytes + transportBuffer.clear(); + clientHandshaker.getBytesToSendToPeer(transportBuffer); + transportBuffer.flip(); + assertFalse(transportBuffer.hasRemaining()); + + transportBuffer.clear(); + serverHandshaker.getBytesToSendToPeer(transportBuffer); + transportBuffer.flip(); + assertEquals( + FakeTsiHandshaker.State.SERVER_INIT.toString().trim(), + new String(transportBufferBytes, 4, transportBuffer.remaining(), UTF_8).trim()); + + clientHandshaker.processBytesFromPeer(transportBuffer); + assertFalse(transportBuffer.hasRemaining()); + + // server shouldn't offer any more bytes + transportBuffer.clear(); + serverHandshaker.getBytesToSendToPeer(transportBuffer); + transportBuffer.flip(); + assertFalse(transportBuffer.hasRemaining()); + + transportBuffer.clear(); + clientHandshaker.getBytesToSendToPeer(transportBuffer); + transportBuffer.flip(); + assertEquals( + FakeTsiHandshaker.State.CLIENT_FINISHED.toString().trim(), + new String(transportBufferBytes, 4, transportBuffer.remaining(), UTF_8).trim()); + + serverHandshaker.processBytesFromPeer(transportBuffer); + assertFalse(transportBuffer.hasRemaining()); + + // client shouldn't offer any more bytes + transportBuffer.clear(); + clientHandshaker.getBytesToSendToPeer(transportBuffer); + transportBuffer.flip(); + assertFalse(transportBuffer.hasRemaining()); + + transportBuffer.clear(); + serverHandshaker.getBytesToSendToPeer(transportBuffer); + transportBuffer.flip(); + assertEquals( + FakeTsiHandshaker.State.SERVER_FINISHED.toString().trim(), + new String(transportBufferBytes, 4, transportBuffer.remaining(), UTF_8).trim()); + + clientHandshaker.processBytesFromPeer(transportBuffer); + assertFalse(transportBuffer.hasRemaining()); + + // server shouldn't offer any more bytes + transportBuffer.clear(); + serverHandshaker.getBytesToSendToPeer(transportBuffer); + transportBuffer.flip(); + assertFalse(transportBuffer.hasRemaining()); + } catch (GeneralSecurityException e) { + throw new AssertionError(e); + } + } + + @Test + public void handshake() throws GeneralSecurityException { + TsiTest.handshakeTest(newHandshakers()); + } + + @Test + public void handshakeSmallBuffer() throws GeneralSecurityException { + TsiTest.handshakeSmallBufferTest(newHandshakers()); + } + + @Test + public void pingPong() throws GeneralSecurityException { + TsiTest.pingPongTest(newHandshakers(), ref); + } + + @Test + public void pingPongExactFrameSize() throws GeneralSecurityException { + TsiTest.pingPongExactFrameSizeTest(newHandshakers(), ref); + } + + @Test + public void pingPongSmallBuffer() throws GeneralSecurityException { + TsiTest.pingPongSmallBufferTest(newHandshakers(), ref); + } + + @Test + public void pingPongSmallFrame() throws GeneralSecurityException { + TsiTest.pingPongSmallFrameTest(OVERHEAD, newHandshakers(), ref); + } + + @Test + public void pingPongSmallFrameSmallBuffer() throws GeneralSecurityException { + TsiTest.pingPongSmallFrameSmallBufferTest(OVERHEAD, newHandshakers(), ref); + } + + @Test + public void corruptedCounter() throws GeneralSecurityException { + TsiTest.corruptedCounterTest(newHandshakers(), ref); + } + + @Test + public void corruptedCiphertext() throws GeneralSecurityException { + TsiTest.corruptedCiphertextTest(newHandshakers(), ref); + } + + @Test + public void corruptedTag() throws GeneralSecurityException { + TsiTest.corruptedTagTest(newHandshakers(), ref); + } + + @Test + public void reflectedCiphertext() throws GeneralSecurityException { + TsiTest.reflectedCiphertextTest(newHandshakers(), ref); + } +} diff --git a/alts/src/test/java/io/grpc/alts/internal/GoogleDefaultProtocolNegotiatorTest.java b/alts/src/test/java/io/grpc/alts/internal/GoogleDefaultProtocolNegotiatorTest.java new file mode 100644 index 0000000000000000000000000000000000000000..74e342ece47214aae253be42a69ffd362f7798e7 --- /dev/null +++ b/alts/src/test/java/io/grpc/alts/internal/GoogleDefaultProtocolNegotiatorTest.java @@ -0,0 +1,69 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.Attributes; +import io.grpc.internal.GrpcAttributes; +import io.grpc.netty.GrpcHttp2ConnectionHandler; +import io.grpc.netty.ProtocolNegotiator; +import io.grpc.netty.ProtocolNegotiator.Handler; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public final class GoogleDefaultProtocolNegotiatorTest { + private ProtocolNegotiator altsProtocolNegotiator; + private ProtocolNegotiator tlsProtocolNegotiator; + private GoogleDefaultProtocolNegotiator googleProtocolNegotiator; + + @Before + public void setUp() { + altsProtocolNegotiator = mock(ProtocolNegotiator.class); + tlsProtocolNegotiator = mock(ProtocolNegotiator.class); + googleProtocolNegotiator = + new GoogleDefaultProtocolNegotiator(altsProtocolNegotiator, tlsProtocolNegotiator); + } + + @Test + public void altsHandler() { + Attributes eagAttributes = + Attributes.newBuilder().set(GrpcAttributes.ATTR_LB_PROVIDED_BACKEND, true).build(); + GrpcHttp2ConnectionHandler mockHandler = mock(GrpcHttp2ConnectionHandler.class); + when(mockHandler.getEagAttributes()).thenReturn(eagAttributes); + Handler handler = googleProtocolNegotiator.newHandler(mockHandler); + verify(altsProtocolNegotiator, times(1)).newHandler(mockHandler); + verify(tlsProtocolNegotiator, never()).newHandler(mockHandler); + } + + @Test + public void tlsHandler() { + Attributes eagAttributes = Attributes.EMPTY; + GrpcHttp2ConnectionHandler mockHandler = mock(GrpcHttp2ConnectionHandler.class); + when(mockHandler.getEagAttributes()).thenReturn(eagAttributes); + Handler handler = googleProtocolNegotiator.newHandler(mockHandler); + verify(altsProtocolNegotiator, never()).newHandler(mockHandler); + verify(tlsProtocolNegotiator, times(1)).newHandler(mockHandler); + } +} diff --git a/alts/src/test/java/io/grpc/alts/internal/MockAltsHandshakerResp.java b/alts/src/test/java/io/grpc/alts/internal/MockAltsHandshakerResp.java new file mode 100644 index 0000000000000000000000000000000000000000..205746690dcdc6766eaf6362d7396c0be8e20e12 --- /dev/null +++ b/alts/src/test/java/io/grpc/alts/internal/MockAltsHandshakerResp.java @@ -0,0 +1,117 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import static java.nio.charset.StandardCharsets.UTF_8; + +import com.google.protobuf.ByteString; +import io.grpc.Status; +import io.grpc.alts.internal.Handshaker.HandshakerResp; +import io.grpc.alts.internal.Handshaker.HandshakerResult; +import io.grpc.alts.internal.Handshaker.HandshakerStatus; +import io.grpc.alts.internal.Handshaker.Identity; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.security.SecureRandom; +import java.util.Random; + +/** A class for mocking ALTS Handshaker Responses. */ +class MockAltsHandshakerResp { + private static final String TEST_ERROR_DETAILS = "handshake error"; + private static final String TEST_APPLICATION_PROTOCOL = "grpc"; + private static final String TEST_RECORD_PROTOCOL = "ALTSRP_GCM_AES128"; + private static final String TEST_OUT_FRAME = "output frame"; + private static final String TEST_LOCAL_ACCOUNT = "local@developer.gserviceaccount.com"; + private static final String TEST_PEER_ACCOUNT = "peer@developer.gserviceaccount.com"; + private static final byte[] TEST_KEY_DATA = initializeTestKeyData(); + private static final int FRAME_HEADER_SIZE = 4; + + static String getTestErrorDetails() { + return TEST_ERROR_DETAILS; + } + + static String getTestPeerAccount() { + return TEST_PEER_ACCOUNT; + } + + private static byte[] initializeTestKeyData() { + Random random = new SecureRandom(); + byte[] randombytes = new byte[AltsChannelCrypter.getKeyLength()]; + random.nextBytes(randombytes); + return randombytes; + } + + static byte[] getTestKeyData() { + return TEST_KEY_DATA; + } + + /** Returns a mock output frame. */ + static ByteString getOutFrame() { + int frameSize = TEST_OUT_FRAME.length(); + ByteBuffer buffer = ByteBuffer.allocate(FRAME_HEADER_SIZE + frameSize); + buffer.order(ByteOrder.LITTLE_ENDIAN); + buffer.putInt(frameSize); + buffer.put(TEST_OUT_FRAME.getBytes(UTF_8)); + buffer.flip(); + return ByteString.copyFrom(buffer); + } + + /** Returns a mock error handshaker response. */ + static HandshakerResp getErrorResponse() { + HandshakerResp.Builder resp = HandshakerResp.newBuilder(); + resp.setStatus( + HandshakerStatus.newBuilder() + .setCode(Status.Code.UNKNOWN.value()) + .setDetails(TEST_ERROR_DETAILS) + .build()); + return resp.build(); + } + + /** Returns a mock normal handshaker response. */ + static HandshakerResp getOkResponse(int bytesConsumed) { + HandshakerResp.Builder resp = HandshakerResp.newBuilder(); + resp.setOutFrames(getOutFrame()); + resp.setBytesConsumed(bytesConsumed); + resp.setStatus(HandshakerStatus.newBuilder().setCode(Status.Code.OK.value()).build()); + return resp.build(); + } + + /** Returns a mock normal handshaker response. */ + static HandshakerResp getEmptyOutFrameResponse(int bytesConsumed) { + HandshakerResp.Builder resp = HandshakerResp.newBuilder(); + resp.setBytesConsumed(bytesConsumed); + resp.setStatus(HandshakerStatus.newBuilder().setCode(Status.Code.OK.value()).build()); + return resp.build(); + } + + /** Returns a mock final handshaker response with handshake result. */ + static HandshakerResp getFinishedResponse(int bytesConsumed) { + HandshakerResp.Builder resp = HandshakerResp.newBuilder(); + HandshakerResult.Builder result = + HandshakerResult.newBuilder() + .setApplicationProtocol(TEST_APPLICATION_PROTOCOL) + .setRecordProtocol(TEST_RECORD_PROTOCOL) + .setPeerIdentity(Identity.newBuilder().setServiceAccount(TEST_PEER_ACCOUNT).build()) + .setLocalIdentity(Identity.newBuilder().setServiceAccount(TEST_LOCAL_ACCOUNT).build()) + .setKeyData(ByteString.copyFrom(TEST_KEY_DATA)); + resp.setOutFrames(getOutFrame()); + resp.setBytesConsumed(bytesConsumed); + resp.setStatus(HandshakerStatus.newBuilder().setCode(Status.Code.OK.value()).build()); + resp.setResult(result.build()); + return resp.build(); + } +} diff --git a/alts/src/test/java/io/grpc/alts/internal/NettyTsiHandshakerTest.java b/alts/src/test/java/io/grpc/alts/internal/NettyTsiHandshakerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..2ef0ad20dd68128044df15525e57e597553e7133 --- /dev/null +++ b/alts/src/test/java/io/grpc/alts/internal/NettyTsiHandshakerTest.java @@ -0,0 +1,204 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import static com.google.common.truth.Truth.assertThat; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufAllocator; +import io.netty.buffer.UnpooledByteBufAllocator; +import io.netty.util.ReferenceCounted; +import java.lang.reflect.Method; +import java.nio.ByteBuffer; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.List; +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +@RunWith(JUnit4.class) +public class NettyTsiHandshakerTest { + private final UnpooledByteBufAllocator alloc = UnpooledByteBufAllocator.DEFAULT; + private final List references = new ArrayList<>(); + + private final NettyTsiHandshaker clientHandshaker = + new NettyTsiHandshaker(FakeTsiHandshaker.newFakeHandshakerClient()); + private final NettyTsiHandshaker serverHandshaker = + new NettyTsiHandshaker(FakeTsiHandshaker.newFakeHandshakerServer()); + + @After + public void teardown() { + for (ReferenceCounted reference : references) { + reference.release(reference.refCnt()); + } + } + + @Test + public void failsOnNullHandshaker() { + try { + new NettyTsiHandshaker(null); + fail("Exception expected"); + } catch (NullPointerException ex) { + // Do nothing. + } + } + + @Test + public void processPeerHandshakeShouldAcceptPartialFrames() throws GeneralSecurityException { + for (int i = 0; i < 1024; i++) { + ByteBuf clientData = ref(alloc.buffer(1)); + clientHandshaker.getBytesToSendToPeer(clientData); + if (clientData.isReadable()) { + if (serverHandshaker.processBytesFromPeer(clientData)) { + // Done. + return; + } + } + } + fail("Failed to process the handshake frame."); + } + + @Test + public void handshakeShouldSucceed() throws GeneralSecurityException { + doHandshake(); + } + + @Test + public void isInProgress() throws GeneralSecurityException { + assertTrue(clientHandshaker.isInProgress()); + assertTrue(serverHandshaker.isInProgress()); + + doHandshake(); + + assertFalse(clientHandshaker.isInProgress()); + assertFalse(serverHandshaker.isInProgress()); + } + + @Test + public void extractPeer_notNull() throws GeneralSecurityException { + doHandshake(); + + assertNotNull(serverHandshaker.extractPeer()); + assertNotNull(clientHandshaker.extractPeer()); + } + + @Test + public void extractPeer_failsBeforeHandshake() throws GeneralSecurityException { + try { + clientHandshaker.extractPeer(); + fail("Exception expected"); + } catch (IllegalStateException ex) { + // Do nothing. + } + } + + @Test + public void extractPeerObject_notNull() throws GeneralSecurityException { + doHandshake(); + + assertNotNull(serverHandshaker.extractPeerObject()); + assertNotNull(clientHandshaker.extractPeerObject()); + } + + @Test + public void extractPeerObject_failsBeforeHandshake() throws GeneralSecurityException { + try { + clientHandshaker.extractPeerObject(); + fail("Exception expected"); + } catch (IllegalStateException ex) { + // Do nothing. + } + } + + /** + * NettyTsiHandshaker just converts {@link ByteBuffer} to {@link ByteBuf}, so check that the other + * methods are otherwise the same. + */ + @Test + public void handshakerMethodsMatch() { + List expectedMethods = new ArrayList<>(); + for (Method m : TsiHandshaker.class.getDeclaredMethods()) { + expectedMethods.add(m.getName()); + } + + List actualMethods = new ArrayList<>(); + for (Method m : NettyTsiHandshaker.class.getDeclaredMethods()) { + actualMethods.add(m.getName()); + } + + assertThat(actualMethods).containsAllIn(expectedMethods); + } + + static void doHandshake( + NettyTsiHandshaker clientHandshaker, + NettyTsiHandshaker serverHandshaker, + ByteBufAllocator alloc, + Function ref) + throws GeneralSecurityException { + // Get the server response handshake frames. + for (int i = 0; i < 10; i++) { + if (!(clientHandshaker.isInProgress() || serverHandshaker.isInProgress())) { + return; + } + + ByteBuf clientData = ref.apply(alloc.buffer()); + clientHandshaker.getBytesToSendToPeer(clientData); + if (clientData.isReadable()) { + serverHandshaker.processBytesFromPeer(clientData); + } + + ByteBuf serverData = ref.apply(alloc.buffer()); + serverHandshaker.getBytesToSendToPeer(serverData); + if (serverData.isReadable()) { + clientHandshaker.processBytesFromPeer(serverData); + } + } + + throw new AssertionError("Failed to complete the handshake."); + } + + private void doHandshake() throws GeneralSecurityException { + doHandshake( + clientHandshaker, + serverHandshaker, + alloc, + new Function() { + @Override + public ByteBuf apply(ByteBuf buf) { + return ref(buf); + } + }); + } + + private ByteBuf ref(ByteBuf buf) { + if (buf != null) { + references.add(buf); + } + return buf; + } + + /** A mirror of java.util.function.Function without the Java 8 dependency. */ + private interface Function { + R apply(T t); + } +} diff --git a/alts/src/test/java/io/grpc/alts/internal/RpcProtocolVersionsUtilTest.java b/alts/src/test/java/io/grpc/alts/internal/RpcProtocolVersionsUtilTest.java new file mode 100644 index 0000000000000000000000000000000000000000..dc3c7eb5d837faf90bde268d71bd3ad9a1fe78dc --- /dev/null +++ b/alts/src/test/java/io/grpc/alts/internal/RpcProtocolVersionsUtilTest.java @@ -0,0 +1,248 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import io.grpc.alts.internal.RpcProtocolVersionsUtil.RpcVersionsCheckResult; +import io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions; +import io.grpc.alts.internal.TransportSecurityCommon.RpcProtocolVersions.Version; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + +/** Unit tests for {@link RpcProtocolVersionsUtil}. */ +@RunWith(JUnit4.class) +public final class RpcProtocolVersionsUtilTest { + + @Test + public void compareVersions() throws Exception { + assertTrue( + RpcProtocolVersionsUtil.isGreaterThanOrEqualTo( + Version.newBuilder().setMajor(3).setMinor(2).build(), + Version.newBuilder().setMajor(2).setMinor(1).build())); + assertTrue( + RpcProtocolVersionsUtil.isGreaterThanOrEqualTo( + Version.newBuilder().setMajor(3).setMinor(2).build(), + Version.newBuilder().setMajor(2).setMinor(1).build())); + assertTrue( + RpcProtocolVersionsUtil.isGreaterThanOrEqualTo( + Version.newBuilder().setMajor(3).setMinor(2).build(), + Version.newBuilder().setMajor(3).setMinor(2).build())); + assertFalse( + RpcProtocolVersionsUtil.isGreaterThanOrEqualTo( + Version.newBuilder().setMajor(2).setMinor(3).build(), + Version.newBuilder().setMajor(3).setMinor(2).build())); + assertFalse( + RpcProtocolVersionsUtil.isGreaterThanOrEqualTo( + Version.newBuilder().setMajor(3).setMinor(1).build(), + Version.newBuilder().setMajor(3).setMinor(2).build())); + } + + @Test + public void checkRpcVersions() throws Exception { + // local.max > peer.max and local.min > peer.min + RpcVersionsCheckResult checkResult = + RpcProtocolVersionsUtil.checkRpcProtocolVersions( + RpcProtocolVersions.newBuilder() + .setMaxRpcVersion(Version.newBuilder().setMajor(3).setMinor(2).build()) + .setMinRpcVersion(Version.newBuilder().setMajor(2).setMinor(1).build()) + .build(), + RpcProtocolVersions.newBuilder() + .setMaxRpcVersion(Version.newBuilder().setMajor(2).setMinor(1).build()) + .setMinRpcVersion(Version.newBuilder().setMajor(1).setMinor(2).build()) + .build()); + assertTrue(checkResult.getResult()); + assertEquals( + Version.newBuilder().setMajor(2).setMinor(1).build(), + checkResult.getHighestCommonVersion()); + // local.max > peer.max and local.min < peer.min + checkResult = + RpcProtocolVersionsUtil.checkRpcProtocolVersions( + RpcProtocolVersions.newBuilder() + .setMaxRpcVersion(Version.newBuilder().setMajor(3).setMinor(2).build()) + .setMinRpcVersion(Version.newBuilder().setMajor(1).setMinor(2).build()) + .build(), + RpcProtocolVersions.newBuilder() + .setMaxRpcVersion(Version.newBuilder().setMajor(2).setMinor(1).build()) + .setMinRpcVersion(Version.newBuilder().setMajor(2).setMinor(1).build()) + .build()); + assertTrue(checkResult.getResult()); + assertEquals( + Version.newBuilder().setMajor(2).setMinor(1).build(), + checkResult.getHighestCommonVersion()); + // local.max > peer.max and local.min = peer.min + checkResult = + RpcProtocolVersionsUtil.checkRpcProtocolVersions( + RpcProtocolVersions.newBuilder() + .setMaxRpcVersion(Version.newBuilder().setMajor(3).setMinor(2).build()) + .setMinRpcVersion(Version.newBuilder().setMajor(2).setMinor(1).build()) + .build(), + RpcProtocolVersions.newBuilder() + .setMaxRpcVersion(Version.newBuilder().setMajor(2).setMinor(1).build()) + .setMinRpcVersion(Version.newBuilder().setMajor(2).setMinor(1).build()) + .build()); + assertTrue(checkResult.getResult()); + assertEquals( + Version.newBuilder().setMajor(2).setMinor(1).build(), + checkResult.getHighestCommonVersion()); + // local.max < peer.max and local.min > peer.min + checkResult = + RpcProtocolVersionsUtil.checkRpcProtocolVersions( + RpcProtocolVersions.newBuilder() + .setMaxRpcVersion(Version.newBuilder().setMajor(2).setMinor(1).build()) + .setMinRpcVersion(Version.newBuilder().setMajor(2).setMinor(1).build()) + .build(), + RpcProtocolVersions.newBuilder() + .setMaxRpcVersion(Version.newBuilder().setMajor(3).setMinor(2).build()) + .setMinRpcVersion(Version.newBuilder().setMajor(1).setMinor(2).build()) + .build()); + assertTrue(checkResult.getResult()); + assertEquals( + Version.newBuilder().setMajor(2).setMinor(1).build(), + checkResult.getHighestCommonVersion()); + // local.max = peer.max and local.min > peer.min + checkResult = + RpcProtocolVersionsUtil.checkRpcProtocolVersions( + RpcProtocolVersions.newBuilder() + .setMaxRpcVersion(Version.newBuilder().setMajor(2).setMinor(1).build()) + .setMinRpcVersion(Version.newBuilder().setMajor(2).setMinor(1).build()) + .build(), + RpcProtocolVersions.newBuilder() + .setMaxRpcVersion(Version.newBuilder().setMajor(2).setMinor(1).build()) + .setMinRpcVersion(Version.newBuilder().setMajor(1).setMinor(2).build()) + .build()); + assertTrue(checkResult.getResult()); + assertEquals( + Version.newBuilder().setMajor(2).setMinor(1).build(), + checkResult.getHighestCommonVersion()); + // local.max < peer.max and local.min < peer.min + checkResult = + RpcProtocolVersionsUtil.checkRpcProtocolVersions( + RpcProtocolVersions.newBuilder() + .setMaxRpcVersion(Version.newBuilder().setMajor(2).setMinor(1).build()) + .setMinRpcVersion(Version.newBuilder().setMajor(1).setMinor(2).build()) + .build(), + RpcProtocolVersions.newBuilder() + .setMaxRpcVersion(Version.newBuilder().setMajor(3).setMinor(2).build()) + .setMinRpcVersion(Version.newBuilder().setMajor(2).setMinor(1).build()) + .build()); + assertTrue(checkResult.getResult()); + assertEquals( + Version.newBuilder().setMajor(2).setMinor(1).build(), + checkResult.getHighestCommonVersion()); + // local.max < peer.max and local.min = peer.min + checkResult = + RpcProtocolVersionsUtil.checkRpcProtocolVersions( + RpcProtocolVersions.newBuilder() + .setMaxRpcVersion(Version.newBuilder().setMajor(2).setMinor(1).build()) + .setMinRpcVersion(Version.newBuilder().setMajor(1).setMinor(2).build()) + .build(), + RpcProtocolVersions.newBuilder() + .setMaxRpcVersion(Version.newBuilder().setMajor(3).setMinor(2).build()) + .setMinRpcVersion(Version.newBuilder().setMajor(1).setMinor(2).build()) + .build()); + assertTrue(checkResult.getResult()); + assertEquals( + Version.newBuilder().setMajor(2).setMinor(1).build(), + checkResult.getHighestCommonVersion()); + // local.max = peer.max and local.min < peer.min + checkResult = + RpcProtocolVersionsUtil.checkRpcProtocolVersions( + RpcProtocolVersions.newBuilder() + .setMaxRpcVersion(Version.newBuilder().setMajor(2).setMinor(1).build()) + .setMinRpcVersion(Version.newBuilder().setMajor(1).setMinor(2).build()) + .build(), + RpcProtocolVersions.newBuilder() + .setMaxRpcVersion(Version.newBuilder().setMajor(2).setMinor(1).build()) + .setMinRpcVersion(Version.newBuilder().setMajor(1).setMinor(2).build()) + .build()); + assertTrue(checkResult.getResult()); + assertEquals( + Version.newBuilder().setMajor(2).setMinor(1).build(), + checkResult.getHighestCommonVersion()); + // all equal + checkResult = + RpcProtocolVersionsUtil.checkRpcProtocolVersions( + RpcProtocolVersions.newBuilder() + .setMaxRpcVersion(Version.newBuilder().setMajor(2).setMinor(1).build()) + .setMinRpcVersion(Version.newBuilder().setMajor(2).setMinor(1).build()) + .build(), + RpcProtocolVersions.newBuilder() + .setMaxRpcVersion(Version.newBuilder().setMajor(2).setMinor(1).build()) + .setMinRpcVersion(Version.newBuilder().setMajor(2).setMinor(1).build()) + .build()); + assertTrue(checkResult.getResult()); + assertEquals( + Version.newBuilder().setMajor(2).setMinor(1).build(), + checkResult.getHighestCommonVersion()); + // max is smaller than min + checkResult = + RpcProtocolVersionsUtil.checkRpcProtocolVersions( + RpcProtocolVersions.newBuilder() + .setMaxRpcVersion(Version.newBuilder().setMajor(1).setMinor(2).build()) + .setMinRpcVersion(Version.newBuilder().setMajor(2).setMinor(1).build()) + .build(), + RpcProtocolVersions.newBuilder() + .setMaxRpcVersion(Version.newBuilder().setMajor(1).setMinor(2).build()) + .setMinRpcVersion(Version.newBuilder().setMajor(2).setMinor(1).build()) + .build()); + assertFalse(checkResult.getResult()); + assertEquals(null, checkResult.getHighestCommonVersion()); + // no overlap, local > peer + checkResult = + RpcProtocolVersionsUtil.checkRpcProtocolVersions( + RpcProtocolVersions.newBuilder() + .setMaxRpcVersion(Version.newBuilder().setMajor(6).setMinor(5).build()) + .setMinRpcVersion(Version.newBuilder().setMajor(4).setMinor(3).build()) + .build(), + RpcProtocolVersions.newBuilder() + .setMaxRpcVersion(Version.newBuilder().setMajor(2).setMinor(1).build()) + .setMinRpcVersion(Version.newBuilder().setMajor(0).setMinor(0).build()) + .build()); + assertFalse(checkResult.getResult()); + assertEquals(null, checkResult.getHighestCommonVersion()); + // no overlap, local < peer + checkResult = + RpcProtocolVersionsUtil.checkRpcProtocolVersions( + RpcProtocolVersions.newBuilder() + .setMaxRpcVersion(Version.newBuilder().setMajor(2).setMinor(1).build()) + .setMinRpcVersion(Version.newBuilder().setMajor(1).setMinor(0).build()) + .build(), + RpcProtocolVersions.newBuilder() + .setMaxRpcVersion(Version.newBuilder().setMajor(6).setMinor(5).build()) + .setMinRpcVersion(Version.newBuilder().setMajor(4).setMinor(3).build()) + .build()); + assertFalse(checkResult.getResult()); + assertEquals(null, checkResult.getHighestCommonVersion()); + // no overlap, max < min + checkResult = + RpcProtocolVersionsUtil.checkRpcProtocolVersions( + RpcProtocolVersions.newBuilder() + .setMaxRpcVersion(Version.newBuilder().setMajor(4).setMinor(3).build()) + .setMinRpcVersion(Version.newBuilder().setMajor(6).setMinor(5).build()) + .build(), + RpcProtocolVersions.newBuilder() + .setMaxRpcVersion(Version.newBuilder().setMajor(1).setMinor(0).build()) + .setMinRpcVersion(Version.newBuilder().setMajor(2).setMinor(1).build()) + .build()); + assertFalse(checkResult.getResult()); + assertEquals(null, checkResult.getHighestCommonVersion()); + } +} diff --git a/alts/src/test/java/io/grpc/alts/internal/TsiTest.java b/alts/src/test/java/io/grpc/alts/internal/TsiTest.java new file mode 100644 index 0000000000000000000000000000000000000000..5c9cf265e250a5e23f1bb3f84d3d0d3d1dd0f929 --- /dev/null +++ b/alts/src/test/java/io/grpc/alts/internal/TsiTest.java @@ -0,0 +1,405 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.alts.internal; + +import static com.google.common.truth.Truth.assertThat; +import static io.grpc.alts.internal.ByteBufTestUtils.getDirectBuffer; +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.Assert.fail; + +import io.grpc.alts.internal.ByteBufTestUtils.RegisterRef; +import io.grpc.alts.internal.TsiFrameProtector.Consumer; +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.buffer.UnpooledByteBufAllocator; +import java.nio.ByteBuffer; +import java.security.GeneralSecurityException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import javax.crypto.AEADBadTagException; + +/** Utility class that provides tests for implementations of @{link TsiHandshaker}. */ +public final class TsiTest { + private static final String DECRYPTION_FAILURE_RE = "Tag mismatch!"; + + private TsiTest() {} + + /** A @{code TsiHandshaker} pair for running tests. */ + public static class Handshakers { + private final TsiHandshaker client; + private final TsiHandshaker server; + + public Handshakers(TsiHandshaker client, TsiHandshaker server) { + this.client = client; + this.server = server; + } + + public TsiHandshaker getClient() { + return client; + } + + public TsiHandshaker getServer() { + return server; + } + } + + private static final int DEFAULT_TRANSPORT_BUFFER_SIZE = 2048; + + private static final UnpooledByteBufAllocator alloc = UnpooledByteBufAllocator.DEFAULT; + + private static final String EXAMPLE_MESSAGE1 = "hello world"; + private static final String EXAMPLE_MESSAGE2 = "oysteroystersoysterseateateat"; + + private static final int EXAMPLE_MESSAGE1_LEN = EXAMPLE_MESSAGE1.getBytes(UTF_8).length; + private static final int EXAMPLE_MESSAGE2_LEN = EXAMPLE_MESSAGE2.getBytes(UTF_8).length; + + static int getDefaultTransportBufferSize() { + return DEFAULT_TRANSPORT_BUFFER_SIZE; + } + + /** + * Performs a handshake between the client handshaker and server handshaker using a transport of + * length transportBufferSize. + */ + static void performHandshake(int transportBufferSize, Handshakers handshakers) + throws GeneralSecurityException { + TsiHandshaker clientHandshaker = handshakers.getClient(); + TsiHandshaker serverHandshaker = handshakers.getServer(); + + byte[] transportBufferBytes = new byte[transportBufferSize]; + ByteBuffer transportBuffer = ByteBuffer.wrap(transportBufferBytes); + transportBuffer.limit(0); // Start off with an empty buffer + + while (clientHandshaker.isInProgress() || serverHandshaker.isInProgress()) { + for (TsiHandshaker handshaker : new TsiHandshaker[] {clientHandshaker, serverHandshaker}) { + if (handshaker.isInProgress()) { + // Process any bytes on the wire. + if (transportBuffer.hasRemaining()) { + handshaker.processBytesFromPeer(transportBuffer); + } + // Put new bytes on the wire, if needed. + if (handshaker.isInProgress()) { + transportBuffer.clear(); + handshaker.getBytesToSendToPeer(transportBuffer); + transportBuffer.flip(); + } + } + } + } + clientHandshaker.extractPeer(); + serverHandshaker.extractPeer(); + } + + public static void handshakeTest(Handshakers handshakers) throws GeneralSecurityException { + performHandshake(DEFAULT_TRANSPORT_BUFFER_SIZE, handshakers); + } + + public static void handshakeSmallBufferTest(Handshakers handshakers) + throws GeneralSecurityException { + performHandshake(9, handshakers); + } + + /** Sends a message between the sender and receiver. */ + private static void sendMessage( + TsiFrameProtector sender, + TsiFrameProtector receiver, + int recvFragmentSize, + String message, + RegisterRef ref) + throws GeneralSecurityException { + + ByteBuf plaintextBuffer = Unpooled.wrappedBuffer(message.getBytes(UTF_8)); + final List protectOut = new ArrayList<>(); + List unprotectOut = new ArrayList<>(); + + sender.protectFlush( + Collections.singletonList(plaintextBuffer), + new Consumer() { + @Override + public void accept(ByteBuf buf) { + protectOut.add(buf); + } + }, + alloc); + assertThat(protectOut.size()).isEqualTo(1); + + ByteBuf protect = ref.register(protectOut.get(0)); + while (protect.isReadable()) { + ByteBuf buf = protect; + if (recvFragmentSize > 0) { + int size = Math.min(protect.readableBytes(), recvFragmentSize); + buf = protect.readSlice(size); + } + receiver.unprotect(buf, unprotectOut, alloc); + } + ByteBuf plaintextRecvd = getDirectBuffer(message.getBytes(UTF_8).length, ref); + for (Object unprotect : unprotectOut) { + ByteBuf unprotectBuf = ref.register((ByteBuf) unprotect); + plaintextRecvd.writeBytes(unprotectBuf); + } + assertThat(plaintextRecvd).isEqualTo(Unpooled.wrappedBuffer(message.getBytes(UTF_8))); + } + + /** Ping pong test. */ + public static void pingPongTest(Handshakers handshakers, RegisterRef ref) + throws GeneralSecurityException { + performHandshake(DEFAULT_TRANSPORT_BUFFER_SIZE, handshakers); + + TsiFrameProtector clientProtector = handshakers.getClient().createFrameProtector(alloc); + TsiFrameProtector serverProtector = handshakers.getServer().createFrameProtector(alloc); + + sendMessage(clientProtector, serverProtector, -1, EXAMPLE_MESSAGE1, ref); + sendMessage(serverProtector, clientProtector, -1, EXAMPLE_MESSAGE2, ref); + + clientProtector.destroy(); + serverProtector.destroy(); + } + + /** Ping pong test with exact frame size. */ + public static void pingPongExactFrameSizeTest(Handshakers handshakers, RegisterRef ref) + throws GeneralSecurityException { + performHandshake(DEFAULT_TRANSPORT_BUFFER_SIZE, handshakers); + + int frameSize = + EXAMPLE_MESSAGE1.getBytes(UTF_8).length + + AltsTsiFrameProtector.getHeaderBytes() + + FakeChannelCrypter.getTagBytes(); + + TsiFrameProtector clientProtector = + handshakers.getClient().createFrameProtector(frameSize, alloc); + TsiFrameProtector serverProtector = + handshakers.getServer().createFrameProtector(frameSize, alloc); + + sendMessage(clientProtector, serverProtector, -1, EXAMPLE_MESSAGE1, ref); + sendMessage(serverProtector, clientProtector, -1, EXAMPLE_MESSAGE1, ref); + + clientProtector.destroy(); + serverProtector.destroy(); + } + + /** Ping pong test with small buffer size. */ + public static void pingPongSmallBufferTest(Handshakers handshakers, RegisterRef ref) + throws GeneralSecurityException { + performHandshake(DEFAULT_TRANSPORT_BUFFER_SIZE, handshakers); + + TsiFrameProtector clientProtector = handshakers.getClient().createFrameProtector(alloc); + TsiFrameProtector serverProtector = handshakers.getServer().createFrameProtector(alloc); + + sendMessage(clientProtector, serverProtector, 1, EXAMPLE_MESSAGE1, ref); + sendMessage(serverProtector, clientProtector, 1, EXAMPLE_MESSAGE2, ref); + + clientProtector.destroy(); + serverProtector.destroy(); + } + + /** Ping pong test with small frame size. */ + public static void pingPongSmallFrameTest( + int frameProtectorOverhead, Handshakers handshakers, RegisterRef ref) + throws GeneralSecurityException { + performHandshake(DEFAULT_TRANSPORT_BUFFER_SIZE, handshakers); + + // We send messages using small non-aligned buffers. We use 3 and 5, small primes. + TsiFrameProtector clientProtector = + handshakers.getClient().createFrameProtector(frameProtectorOverhead + 3, alloc); + TsiFrameProtector serverProtector = + handshakers.getServer().createFrameProtector(frameProtectorOverhead + 5, alloc); + + sendMessage(clientProtector, serverProtector, EXAMPLE_MESSAGE1_LEN, EXAMPLE_MESSAGE1, ref); + sendMessage(serverProtector, clientProtector, EXAMPLE_MESSAGE2_LEN, EXAMPLE_MESSAGE2, ref); + + clientProtector.destroy(); + serverProtector.destroy(); + } + + /** Ping pong test with small frame and small buffer. */ + public static void pingPongSmallFrameSmallBufferTest( + int frameProtectorOverhead, Handshakers handshakers, RegisterRef ref) + throws GeneralSecurityException { + performHandshake(DEFAULT_TRANSPORT_BUFFER_SIZE, handshakers); + + // We send messages using small non-aligned buffers. We use 3 and 5, small primes. + TsiFrameProtector clientProtector = + handshakers.getClient().createFrameProtector(frameProtectorOverhead + 3, alloc); + TsiFrameProtector serverProtector = + handshakers.getServer().createFrameProtector(frameProtectorOverhead + 5, alloc); + + sendMessage(clientProtector, serverProtector, EXAMPLE_MESSAGE1_LEN, EXAMPLE_MESSAGE1, ref); + sendMessage(serverProtector, clientProtector, EXAMPLE_MESSAGE2_LEN, EXAMPLE_MESSAGE2, ref); + + sendMessage(clientProtector, serverProtector, EXAMPLE_MESSAGE1_LEN, EXAMPLE_MESSAGE1, ref); + sendMessage(serverProtector, clientProtector, EXAMPLE_MESSAGE2_LEN, EXAMPLE_MESSAGE2, ref); + + clientProtector.destroy(); + serverProtector.destroy(); + } + + /** Test corrupted counter. */ + public static void corruptedCounterTest(Handshakers handshakers, RegisterRef ref) + throws GeneralSecurityException { + performHandshake(DEFAULT_TRANSPORT_BUFFER_SIZE, handshakers); + + TsiFrameProtector sender = handshakers.getClient().createFrameProtector(alloc); + TsiFrameProtector receiver = handshakers.getServer().createFrameProtector(alloc); + + String message = "hello world"; + ByteBuf plaintextBuffer = Unpooled.wrappedBuffer(message.getBytes(UTF_8)); + final List protectOut = new ArrayList<>(); + List unprotectOut = new ArrayList<>(); + + sender.protectFlush( + Collections.singletonList(plaintextBuffer), + new Consumer() { + @Override + public void accept(ByteBuf buf) { + protectOut.add(buf); + } + }, + alloc); + assertThat(protectOut.size()).isEqualTo(1); + + ByteBuf protect = ref.register(protectOut.get(0)); + // Unprotect once to increase receiver counter. + receiver.unprotect(protect.slice(), unprotectOut, alloc); + assertThat(unprotectOut.size()).isEqualTo(1); + ref.register((ByteBuf) unprotectOut.get(0)); + + try { + receiver.unprotect(protect, unprotectOut, alloc); + fail("Exception expected"); + } catch (AEADBadTagException ex) { + assertThat(ex).hasMessageThat().contains(DECRYPTION_FAILURE_RE); + } + + sender.destroy(); + receiver.destroy(); + } + + /** Test corrupted ciphertext. */ + public static void corruptedCiphertextTest(Handshakers handshakers, RegisterRef ref) + throws GeneralSecurityException { + performHandshake(DEFAULT_TRANSPORT_BUFFER_SIZE, handshakers); + + TsiFrameProtector sender = handshakers.getClient().createFrameProtector(alloc); + TsiFrameProtector receiver = handshakers.getServer().createFrameProtector(alloc); + + String message = "hello world"; + ByteBuf plaintextBuffer = Unpooled.wrappedBuffer(message.getBytes(UTF_8)); + final List protectOut = new ArrayList<>(); + List unprotectOut = new ArrayList<>(); + + sender.protectFlush( + Collections.singletonList(plaintextBuffer), + new Consumer() { + @Override + public void accept(ByteBuf buf) { + protectOut.add(buf); + } + }, + alloc); + assertThat(protectOut.size()).isEqualTo(1); + + ByteBuf protect = ref.register(protectOut.get(0)); + int ciphertextIdx = protect.writerIndex() - FakeChannelCrypter.getTagBytes() - 2; + protect.setByte(ciphertextIdx, protect.getByte(ciphertextIdx) + 1); + + try { + receiver.unprotect(protect, unprotectOut, alloc); + fail("Exception expected"); + } catch (AEADBadTagException ex) { + assertThat(ex).hasMessageThat().contains(DECRYPTION_FAILURE_RE); + } + + sender.destroy(); + receiver.destroy(); + } + + /** Test corrupted tag. */ + public static void corruptedTagTest(Handshakers handshakers, RegisterRef ref) + throws GeneralSecurityException { + performHandshake(DEFAULT_TRANSPORT_BUFFER_SIZE, handshakers); + + TsiFrameProtector sender = handshakers.getClient().createFrameProtector(alloc); + TsiFrameProtector receiver = handshakers.getServer().createFrameProtector(alloc); + + String message = "hello world"; + ByteBuf plaintextBuffer = Unpooled.wrappedBuffer(message.getBytes(UTF_8)); + final List protectOut = new ArrayList<>(); + List unprotectOut = new ArrayList<>(); + + sender.protectFlush( + Collections.singletonList(plaintextBuffer), + new Consumer() { + @Override + public void accept(ByteBuf buf) { + protectOut.add(buf); + } + }, + alloc); + assertThat(protectOut.size()).isEqualTo(1); + + ByteBuf protect = ref.register(protectOut.get(0)); + int tagIdx = protect.writerIndex() - 1; + protect.setByte(tagIdx, protect.getByte(tagIdx) + 1); + + try { + receiver.unprotect(protect, unprotectOut, alloc); + fail("Exception expected"); + } catch (AEADBadTagException ex) { + assertThat(ex).hasMessageThat().contains(DECRYPTION_FAILURE_RE); + } + + sender.destroy(); + receiver.destroy(); + } + + /** Test reflected ciphertext. */ + public static void reflectedCiphertextTest(Handshakers handshakers, RegisterRef ref) + throws GeneralSecurityException { + performHandshake(DEFAULT_TRANSPORT_BUFFER_SIZE, handshakers); + + TsiFrameProtector sender = handshakers.getClient().createFrameProtector(alloc); + TsiFrameProtector receiver = handshakers.getServer().createFrameProtector(alloc); + + String message = "hello world"; + ByteBuf plaintextBuffer = Unpooled.wrappedBuffer(message.getBytes(UTF_8)); + final List protectOut = new ArrayList<>(); + List unprotectOut = new ArrayList<>(); + + sender.protectFlush( + Collections.singletonList(plaintextBuffer), + new Consumer() { + @Override + public void accept(ByteBuf buf) { + protectOut.add(buf); + } + }, + alloc); + assertThat(protectOut.size()).isEqualTo(1); + + ByteBuf protect = ref.register(protectOut.get(0)); + try { + sender.unprotect(protect.slice(), unprotectOut, alloc); + fail("Exception expected"); + } catch (AEADBadTagException ex) { + assertThat(ex).hasMessageThat().contains(DECRYPTION_FAILURE_RE); + } + + sender.destroy(); + receiver.destroy(); + } +} diff --git a/android-interop-testing/README.md b/android-interop-testing/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c1abcee4d7fe483b6e869cde9bcc854713387083 --- /dev/null +++ b/android-interop-testing/README.md @@ -0,0 +1,53 @@ +gRPC Android test App +======================= + +Implements gRPC integration tests in an Android App. + +TODO(madongfly) integrate this App into the gRPC-Java build system. + +In order to build this app, you need a local.properties file under this directory which specifies +the location of your android sdk: +``` +sdk.dir=/somepath/somepath/sdk +``` + +Connect your Android device or start the emulator: +``` +$ ./start-emulator.sh & ./wait-for-emulator.sh +``` + +Start test server +----------------- + +Start the test server by: +``` +$ ../run-test-server.sh +``` + + +Manually test +------------- + +Install the App by: +``` +$ ../gradlew installDebug +``` +Then manually test it with the UI. + + +Instrumentation tests +---------------- + +Instrumentation tests must be run on a connected device or emulator. Run with the +following gradle command: + +``` +$ ../gradlew connectedAndroidTest \ + -Pandroid.testInstrumentationRunnerArguments.server_host=10.0.2.2 \ + -Pandroid.testInstrumentationRunnerArguments.server_port=8080 \ + -Pandroid.testInstrumentationRunnerArguments.use_tls=true \ + -Pandroid.testInstrumentationRunnerArguments.server_host_override=foo.test.google.fr \ + -Pandroid.testInstrumentationRunnerArguments.use_test_ca=true \ + -Pandroid.testInstrumentationRunnerArguments.test_case=all +``` + diff --git a/android-interop-testing/app/build.gradle b/android-interop-testing/app/build.gradle new file mode 100644 index 0000000000000000000000000000000000000000..37238baede67ee5f3a3c0a612ce021cc7727ef83 --- /dev/null +++ b/android-interop-testing/app/build.gradle @@ -0,0 +1,89 @@ +apply plugin: 'com.android.application' +apply plugin: 'com.google.protobuf' + +android { + sourceSets { + main { + java { + srcDirs += "${projectDir}/../../interop-testing/src/main/java/" + setIncludes(["io/grpc/android/integrationtest/**", + "io/grpc/testing/integration/AbstractInteropTest.java", + "io/grpc/testing/integration/TestServiceImpl.java", + "io/grpc/testing/integration/Util.java"]) + } + proto { + srcDirs += "${projectDir}/../../interop-testing/src/main/proto/" + } + } + } + compileSdkVersion 26 + + defaultConfig { + applicationId "io.grpc.android.integrationtest" + // API level 14+ is required for TLS since Google Play Services v10.2 + minSdkVersion 14 + targetSdkVersion 26 + versionCode 1 + versionName "1.0" + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + multiDexEnabled true + } + buildTypes { + debug { minifyEnabled false } + release { + minifyEnabled true + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } + lintOptions { disable 'InvalidPackage', 'HardcodedText' } +} + +protobuf { + protoc { artifact = 'com.google.protobuf:protoc:3.5.1-1' } + plugins { + javalite { artifact = "com.google.protobuf:protoc-gen-javalite:3.0.0" } + grpc { artifact = 'io.grpc:protoc-gen-grpc-java:1.16.0-SNAPSHOT' // CURRENT_GRPC_VERSION + } + } + generateProtoTasks { + all().each { task -> + task.plugins { + javalite {} + grpc { + // Options added to --grpc_out + option 'lite' + } + } + } + } +} + +dependencies { + implementation 'com.android.support:appcompat-v7:26.1.0' + implementation 'com.android.support:multidex:1.0.3' + implementation 'com.android.support:support-annotations:27.1.1' + implementation 'com.google.android.gms:play-services-base:15.0.1' + implementation ('com.google.auth:google-auth-library-oauth2-http:0.9.0') { + exclude group: 'org.apache.httpcomponents', module: 'httpclient' + } + implementation 'com.google.truth:truth:0.36' + implementation 'javax.annotation:javax.annotation-api:1.2' + implementation 'junit:junit:4.12' + + // You need to build grpc-java to obtain the grpc libraries below. + implementation 'io.grpc:grpc-auth:1.16.0-SNAPSHOT' // CURRENT_GRPC_VERSION + implementation 'io.grpc:grpc-okhttp:1.16.0-SNAPSHOT' // CURRENT_GRPC_VERSION + implementation 'io.grpc:grpc-protobuf-lite:1.16.0-SNAPSHOT' // CURRENT_GRPC_VERSION + implementation 'io.grpc:grpc-stub:1.16.0-SNAPSHOT' // CURRENT_GRPC_VERSION + implementation 'io.grpc:grpc-testing:1.16.0-SNAPSHOT' // CURRENT_GRPC_VERSION + + // workaround for https://github.com/google/protobuf/issues/1889 + protobuf 'com.google.protobuf:protobuf-java:3.0.2' + + androidTestImplementation 'androidx.test:rules:1.1.0-alpha1' + androidTestImplementation 'androidx.test:runner:1.1.0-alpha1' +} + +gradle.projectsEvaluated { + tasks.withType(JavaCompile) { options.compilerArgs << "-Xlint:deprecation" } +} diff --git a/android-interop-testing/app/proguard-rules.pro b/android-interop-testing/app/proguard-rules.pro new file mode 100644 index 0000000000000000000000000000000000000000..8af8035207681c881645fab98229e622146f79aa --- /dev/null +++ b/android-interop-testing/app/proguard-rules.pro @@ -0,0 +1,23 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in $ANDROID_HOME/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +-dontwarn android.test.** +-dontwarn com.google.common.** +-dontwarn javax.naming.** +-dontwarn okio.** +-dontwarn org.junit.** +-dontwarn org.mockito.** +-dontwarn sun.reflect.** +# Ignores: can't find referenced class javax.lang.model.element.Modifier +-dontwarn com.google.errorprone.annotations.** + +# Ignores: can't find referenced method from grpc-testing's compileOnly dependency on Truth +-dontwarn io.grpc.testing.DeadlineSubject diff --git a/android-interop-testing/app/src/androidTest/AndroidManifest.xml b/android-interop-testing/app/src/androidTest/AndroidManifest.xml new file mode 100644 index 0000000000000000000000000000000000000000..340300c4c599b030196328255fb20b90f3085096 --- /dev/null +++ b/android-interop-testing/app/src/androidTest/AndroidManifest.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + diff --git a/android-interop-testing/app/src/androidTest/java/io/grpc/android/integrationtest/InteropInstrumentationTest.java b/android-interop-testing/app/src/androidTest/java/io/grpc/android/integrationtest/InteropInstrumentationTest.java new file mode 100644 index 0000000000000000000000000000000000000000..0d88341b2b13a8fa9ffb96f1eaf3ff4952d45105 --- /dev/null +++ b/android-interop-testing/app/src/androidTest/java/io/grpc/android/integrationtest/InteropInstrumentationTest.java @@ -0,0 +1,136 @@ +/* + * Copyright 2017 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.android.integrationtest; + +import static junit.framework.Assert.assertEquals; + +import android.util.Log; +import androidx.test.InstrumentationRegistry; +import androidx.test.rule.ActivityTestRule; +import androidx.test.runner.AndroidJUnit4; +import com.google.android.gms.common.GooglePlayServicesNotAvailableException; +import com.google.android.gms.common.GooglePlayServicesRepairableException; +import com.google.android.gms.security.ProviderInstaller; +import com.google.common.util.concurrent.SettableFuture; +import io.grpc.ClientInterceptor; +import io.grpc.android.integrationtest.InteropTask.Listener; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.concurrent.TimeUnit; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; + +@RunWith(AndroidJUnit4.class) +public class InteropInstrumentationTest { + private static final int TIMEOUT_SECONDS = 60; + private static final String LOG_TAG = "GrpcInteropInstrumentationTest"; + + private String host; + private int port; + private boolean useTls; + private String serverHostOverride; + private boolean useTestCa; + private String testCase; + + // Ensures Looper is initialized for tests running on API level 15. Otherwise instantiating an + // AsyncTask throws an exception. + @Rule + public ActivityTestRule activityRule = + new ActivityTestRule(TesterActivity.class); + + @Before + public void setUp() throws Exception { + host = InstrumentationRegistry.getArguments().getString("server_host", "10.0.2.2"); + port = + Integer.parseInt(InstrumentationRegistry.getArguments().getString("server_port", "8080")); + useTls = + Boolean.parseBoolean(InstrumentationRegistry.getArguments().getString("use_tls", "true")); + serverHostOverride = InstrumentationRegistry.getArguments().getString("server_host_override"); + useTestCa = + Boolean.parseBoolean( + InstrumentationRegistry.getArguments().getString("use_test_ca", "false")); + testCase = InstrumentationRegistry.getArguments().getString("test_case", "all"); + + if (useTls) { + try { + ProviderInstaller.installIfNeeded(InstrumentationRegistry.getTargetContext()); + } catch (GooglePlayServicesRepairableException e) { + // The provider is helpful, but it is possible to succeed without it. + // Hope that the system-provided libraries are new enough. + Log.i(LOG_TAG, "Failed installing security provider", e); + } catch (GooglePlayServicesNotAvailableException e) { + // The provider is helpful, but it is possible to succeed without it. + // Hope that the system-provided libraries are new enough. + Log.i(LOG_TAG, "Failed installing security provider", e); + } + } + } + + @Test + public void interopTests() throws Exception { + if (testCase.equals("all")) { + runTest("empty_unary"); + runTest("large_unary"); + runTest("client_streaming"); + runTest("server_streaming"); + runTest("ping_pong"); + runTest("empty_stream"); + runTest("cancel_after_begin"); + runTest("cancel_after_first_response"); + runTest("full_duplex_call_should_succeed"); + runTest("half_duplex_call_should_succeed"); + runTest("server_streaming_should_be_flow_controlled"); + runTest("very_large_request"); + runTest("very_large_response"); + runTest("deadline_not_exceeded"); + runTest("deadline_exceeded"); + runTest("deadline_exceeded_server_streaming"); + runTest("unimplemented_method"); + runTest("timeout_on_sleeping_server"); + runTest("graceful_shutdown"); + } else { + runTest(testCase); + } + } + + private void runTest(String testCase) throws Exception { + final SettableFuture resultFuture = SettableFuture.create(); + InteropTask.Listener listener = + new Listener() { + @Override + public void onComplete(String result) { + resultFuture.set(result); + } + }; + InputStream testCa; + if (useTestCa) { + testCa = InstrumentationRegistry.getTargetContext().getResources().openRawResource(R.raw.ca); + } else { + testCa = null; + } + new InteropTask( + listener, + TesterOkHttpChannelBuilder.build(host, port, serverHostOverride, useTls, testCa), + new ArrayList<>(), + testCase) + .execute(); + String result = resultFuture.get(TIMEOUT_SECONDS, TimeUnit.SECONDS); + assertEquals(testCase + " failed", InteropTask.SUCCESS_MESSAGE, result); + } +} diff --git a/android-interop-testing/app/src/main/AndroidManifest.xml b/android-interop-testing/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000000000000000000000000000000000000..cb9f81e24264c9f25872074ee7a7ca760b86f4d9 --- /dev/null +++ b/android-interop-testing/app/src/main/AndroidManifest.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + diff --git a/android-interop-testing/app/src/main/java/io/grpc/android/integrationtest/InteropTask.java b/android-interop-testing/app/src/main/java/io/grpc/android/integrationtest/InteropTask.java new file mode 100644 index 0000000000000000000000000000000000000000..d1d181df28c0d53b55a5db674465db77c6155b82 --- /dev/null +++ b/android-interop-testing/app/src/main/java/io/grpc/android/integrationtest/InteropTask.java @@ -0,0 +1,174 @@ +/* + * Copyright 2018 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.android.integrationtest; + +import android.os.AsyncTask; +import android.util.Log; +import io.grpc.ClientInterceptor; +import io.grpc.ManagedChannel; +import io.grpc.testing.integration.AbstractInteropTest; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.ref.WeakReference; +import java.util.List; +import org.junit.AssumptionViolatedException; + +/** AsyncTask for interop test cases. */ +final class InteropTask extends AsyncTask { + private static final String LOG_TAG = "GrpcInteropTask"; + + interface Listener { + void onComplete(String result); + } + + static final String SUCCESS_MESSAGE = "Success!"; + + private final WeakReference listenerReference; + private final String testCase; + private final Tester tester; + + InteropTask( + Listener listener, + ManagedChannel channel, + List interceptors, + String testCase) { + this.listenerReference = new WeakReference(listener); + this.testCase = testCase; + this.tester = new Tester(channel, interceptors); + } + + @Override + protected void onPreExecute() { + tester.setUp(); + } + + @Override + protected String doInBackground(Void... ignored) { + try { + runTest(testCase); + return SUCCESS_MESSAGE; + } catch (Throwable t) { + // Print the stack trace to logcat. + t.printStackTrace(); + // Then print to the error message. + StringWriter sw = new StringWriter(); + t.printStackTrace(new PrintWriter(sw)); + return "Failed... : " + t.getMessage() + "\n" + sw; + } finally { + try { + tester.tearDown(); + } catch (RuntimeException ex) { + throw ex; + } catch (Exception ex) { + throw new RuntimeException(ex); + } + } + } + + private void runTest(String testCase) throws Exception { + Log.i(LOG_TAG, "Running test case: " + testCase); + if ("empty_unary".equals(testCase)) { + tester.emptyUnary(); + } else if ("large_unary".equals(testCase)) { + try { + tester.largeUnary(); + } catch (AssumptionViolatedException e) { + // This test case requires more memory than most Android devices have available + Log.w(LOG_TAG, "Skipping " + testCase + " due to assumption violation", e); + } + } else if ("client_streaming".equals(testCase)) { + tester.clientStreaming(); + } else if ("server_streaming".equals(testCase)) { + tester.serverStreaming(); + } else if ("ping_pong".equals(testCase)) { + tester.pingPong(); + } else if ("empty_stream".equals(testCase)) { + tester.emptyStream(); + } else if ("cancel_after_begin".equals(testCase)) { + tester.cancelAfterBegin(); + } else if ("cancel_after_first_response".equals(testCase)) { + tester.cancelAfterFirstResponse(); + } else if ("full_duplex_call_should_succeed".equals(testCase)) { + tester.fullDuplexCallShouldSucceed(); + } else if ("half_duplex_call_should_succeed".equals(testCase)) { + tester.halfDuplexCallShouldSucceed(); + } else if ("server_streaming_should_be_flow_controlled".equals(testCase)) { + tester.serverStreamingShouldBeFlowControlled(); + } else if ("very_large_request".equals(testCase)) { + try { + tester.veryLargeRequest(); + } catch (AssumptionViolatedException e) { + // This test case requires more memory than most Android devices have available + Log.w(LOG_TAG, "Skipping " + testCase + " due to assumption violation", e); + } + } else if ("very_large_response".equals(testCase)) { + try { + tester.veryLargeResponse(); + } catch (AssumptionViolatedException e) { + // This test case requires more memory than most Android devices have available + Log.w(LOG_TAG, "Skipping " + testCase + " due to assumption violation", e); + } + } else if ("deadline_not_exceeded".equals(testCase)) { + tester.deadlineNotExceeded(); + } else if ("deadline_exceeded".equals(testCase)) { + tester.deadlineExceeded(); + } else if ("deadline_exceeded_server_streaming".equals(testCase)) { + tester.deadlineExceededServerStreaming(); + } else if ("unimplemented_method".equals(testCase)) { + tester.unimplementedMethod(); + } else if ("timeout_on_sleeping_server".equals(testCase)) { + tester.timeoutOnSleepingServer(); + } else if ("graceful_shutdown".equals(testCase)) { + tester.gracefulShutdown(); + } else { + throw new IllegalArgumentException("Unimplemented/Unknown test case: " + testCase); + } + } + + @Override + protected void onPostExecute(String result) { + Listener listener = listenerReference.get(); + if (listener != null) { + listener.onComplete(result); + } + } + + private static class Tester extends AbstractInteropTest { + private final ManagedChannel channel; + private final List interceptors; + + private Tester(ManagedChannel channel, List interceptors) { + this.channel = channel; + this.interceptors = interceptors; + } + + @Override + protected ManagedChannel createChannel() { + return channel; + } + + @Override + protected ClientInterceptor[] getAdditionalInterceptors() { + return interceptors.toArray(new ClientInterceptor[0]); + } + + @Override + protected boolean metricsExpected() { + return false; + } + } +} diff --git a/android-interop-testing/app/src/main/java/io/grpc/android/integrationtest/TesterActivity.java b/android-interop-testing/app/src/main/java/io/grpc/android/integrationtest/TesterActivity.java new file mode 100644 index 0000000000000000000000000000000000000000..e365f048e51166fe6df5e0c26bcff0406b48c4e5 --- /dev/null +++ b/android-interop-testing/app/src/main/java/io/grpc/android/integrationtest/TesterActivity.java @@ -0,0 +1,166 @@ +/* + * Copyright 2015 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.grpc.android.integrationtest; + +import android.content.Context; +import android.content.Intent; +import android.os.Bundle; +import android.support.v7.app.AppCompatActivity; +import android.text.TextUtils; +import android.util.Log; +import android.view.View; +import android.view.inputmethod.InputMethodManager; +import android.widget.Button; +import android.widget.CheckBox; +import android.widget.EditText; +import android.widget.TextView; +import com.google.android.gms.security.ProviderInstaller; +import io.grpc.CallOptions; +import io.grpc.Channel; +import io.grpc.ClientCall; +import io.grpc.ClientInterceptor; +import io.grpc.ClientInterceptors.CheckedForwardingClientCall; +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +public class TesterActivity extends AppCompatActivity + implements ProviderInstaller.ProviderInstallListener, InteropTask.Listener { + private static final String LOG_TAG = "GrpcTesterActivity"; + + private List