├── .builder └── actions │ ├── aws_crt_java_build.py │ ├── aws_crt_java_test.py │ └── localhost_test.py ├── .clang-format ├── .clang-tidy ├── .github ├── ISSUE_TEMPLATE │ ├── bug-report.yml │ ├── config.yml │ ├── documentation.yml │ └── feature-request.yml ├── PULL_REQUEST_TEMPLATE.md └── workflows │ ├── ci.yml │ ├── clang-format.yml │ ├── closed-issue-message.yml │ ├── docs.yml │ ├── handle-stale-discussions.yml │ ├── issue-regression-labeler.yml │ ├── run_android_ci.py │ └── stale_issue.yml ├── .gitignore ├── .gitmodules ├── .lgtm.yml ├── CMakeLists.txt ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── NOTICE ├── README.md ├── android ├── .gitignore ├── ANDROID.md ├── build.gradle ├── crt │ ├── .gitignore │ ├── build.gradle │ ├── consumer-rules.pro │ ├── proguard-rules.pro │ └── src │ │ ├── androidTest │ │ ├── assets │ │ │ ├── .gitignore │ │ │ └── README.md │ │ └── java │ │ │ └── software │ │ │ └── amazon │ │ │ └── awssdk │ │ │ └── crt │ │ │ └── test │ │ │ ├── AndroidPermissionsTest.java │ │ │ └── android │ │ │ └── CrtPlatformImpl.java │ │ └── main │ │ ├── AndroidManifest.xml │ │ └── java │ │ └── software │ │ └── amazon │ │ └── awssdk │ │ └── crt │ │ ├── android │ │ └── CrtPlatformImpl.java │ │ └── io │ │ └── TlsAndroidPrivateKeyOperationHandler.java ├── gradle.properties └── settings.gradle ├── build.gradle.kts ├── builder.json ├── cmake ├── AwsPlatformDetect.cmake ├── archdetect.c └── osdetect.c ├── codebuild ├── CanaryWrapper.py ├── CanaryWrapper_24_7.py ├── CanaryWrapper_Classes.py ├── CanaryWrapper_MetricFunctions.py ├── cd │ ├── deploy-platform-specific-jars.sh │ ├── deploy-snapshot-android.sh │ ├── deploy-snapshot.yml │ ├── fips-where-available-jar-build.yml │ ├── generic-unix-build.sh │ ├── linux-aarch64-fips-build.sh │ ├── manylinux-x64-build.yml │ ├── manylinux-x64-fips-build.yml │ ├── manylinux-x86-build.yml │ ├── musl-arm64-build.yml │ ├── musl-armv7-build.yml │ ├── musl-linux-build.sh │ ├── musl-x64-build.yml │ ├── osx-arm64-build.sh │ ├── osx-x64-build.sh │ ├── promote-release.yml │ ├── test-fips-branch.sh │ ├── test-platform-specific-jar-snapshot.sh │ ├── test-snapshot.yml │ ├── test-version-exists.sh │ ├── test-version-exists.yml │ ├── windows-vs2015-x64-build.bat │ └── windows-vs2015-x86-build.bat ├── linux-integration-tests.yml ├── macos_compatibility_check.py ├── mqtt5-java-canary-test.yml └── test-aws-java-sdk-v2.yml ├── dockcross-build.sh ├── format-check.py ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── integration-testing └── java_elasticurl_runner.py ├── make-docs.sh ├── pom.xml ├── samples ├── CustomKeyOps │ ├── pom.xml │ └── src │ │ └── main │ │ └── java │ │ └── com │ │ └── example │ │ └── customkeyops │ │ └── CustomKeyOps.java ├── mqtt5 │ ├── pom.xml │ └── src │ │ └── main │ │ └── java │ │ └── com │ │ └── example │ │ └── mqtt5 │ │ └── Mqtt5Sample.java └── s3 │ ├── pom.xml │ └── src │ └── main │ └── java │ └── com │ └── example │ └── s3 │ └── PutGet.java ├── settings.gradle.kts ├── src ├── main │ ├── java │ │ └── software │ │ │ └── amazon │ │ │ └── awssdk │ │ │ └── crt │ │ │ ├── AsyncCallback.java │ │ │ ├── CRT.java │ │ │ ├── CrtPlatform.java │ │ │ ├── CrtResource.java │ │ │ ├── CrtRuntimeException.java │ │ │ ├── Log.java │ │ │ ├── Process.java │ │ │ ├── SystemInfo.java │ │ │ ├── auth │ │ │ ├── credentials │ │ │ │ ├── CachedCredentialsProvider.java │ │ │ │ ├── CognitoCredentialsProvider.java │ │ │ │ ├── CognitoLoginTokenSource.java │ │ │ │ ├── Credentials.java │ │ │ │ ├── CredentialsProvider.java │ │ │ │ ├── DefaultChainCredentialsProvider.java │ │ │ │ ├── DelegateCredentialsHandler.java │ │ │ │ ├── DelegateCredentialsProvider.java │ │ │ │ ├── EcsCredentialsProvider.java │ │ │ │ ├── ProfileCredentialsProvider.java │ │ │ │ ├── StaticCredentialsProvider.java │ │ │ │ ├── StsCredentialsProvider.java │ │ │ │ ├── StsWebIdentityCredentialsProvider.java │ │ │ │ └── X509CredentialsProvider.java │ │ │ └── signing │ │ │ │ ├── AwsSigner.java │ │ │ │ ├── AwsSigningConfig.java │ │ │ │ ├── AwsSigningResult.java │ │ │ │ └── AwsSigningUtils.java │ │ │ ├── cal │ │ │ └── EccKeyPair.java │ │ │ ├── checksums │ │ │ ├── CRC32.java │ │ │ ├── CRC32C.java │ │ │ └── CRC64NVME.java │ │ │ ├── eventstream │ │ │ ├── ClientConnection.java │ │ │ ├── ClientConnectionContinuation.java │ │ │ ├── ClientConnectionContinuationHandler.java │ │ │ ├── ClientConnectionHandler.java │ │ │ ├── Header.java │ │ │ ├── HeaderType.java │ │ │ ├── Message.java │ │ │ ├── MessageFlags.java │ │ │ ├── MessageFlushCallback.java │ │ │ ├── MessageType.java │ │ │ ├── OperationRoutingServerConnectionHandler.java │ │ │ ├── ServerConnection.java │ │ │ ├── ServerConnectionContinuation.java │ │ │ ├── ServerConnectionContinuationHandler.java │ │ │ ├── ServerConnectionHandler.java │ │ │ ├── ServerListener.java │ │ │ └── ServerListenerHandler.java │ │ │ ├── http │ │ │ ├── Http2ClientConnection.java │ │ │ ├── Http2ConnectionSetting.java │ │ │ ├── Http2ConnectionSettingListBuilder.java │ │ │ ├── Http2Request.java │ │ │ ├── Http2Stream.java │ │ │ ├── Http2StreamManager.java │ │ │ ├── Http2StreamManagerOptions.java │ │ │ ├── HttpClientConnection.java │ │ │ ├── HttpClientConnectionManager.java │ │ │ ├── HttpClientConnectionManagerOptions.java │ │ │ ├── HttpException.java │ │ │ ├── HttpHeader.java │ │ │ ├── HttpHeaderBlock.java │ │ │ ├── HttpManagerMetrics.java │ │ │ ├── HttpMonitoringOptions.java │ │ │ ├── HttpProxyEnvironmentVariableSetting.java │ │ │ ├── HttpProxyOptions.java │ │ │ ├── HttpRequest.java │ │ │ ├── HttpRequestBase.java │ │ │ ├── HttpRequestBodyStream.java │ │ │ ├── HttpStream.java │ │ │ ├── HttpStreamBase.java │ │ │ ├── HttpStreamBaseResponseHandler.java │ │ │ ├── HttpStreamMetrics.java │ │ │ ├── HttpStreamResponseHandler.java │ │ │ ├── HttpStreamResponseHandlerNativeAdapter.java │ │ │ └── HttpVersion.java │ │ │ ├── internal │ │ │ ├── ExtractLib.java │ │ │ └── GraalVMNativeFeature.java │ │ │ ├── io │ │ │ ├── ClientBootstrap.java │ │ │ ├── ClientTlsContext.java │ │ │ ├── DirectoryEntry.java │ │ │ ├── DirectoryTraversal.java │ │ │ ├── DirectoryTraversalHandler.java │ │ │ ├── EventLoopGroup.java │ │ │ ├── ExponentialBackoffRetryOptions.java │ │ │ ├── HostResolver.java │ │ │ ├── Pkcs11Lib.java │ │ │ ├── ServerBootstrap.java │ │ │ ├── ServerTlsContext.java │ │ │ ├── SocketOptions.java │ │ │ ├── StandardRetryOptions.java │ │ │ ├── TlsCipherPreference.java │ │ │ ├── TlsConnectionOptions.java │ │ │ ├── TlsContext.java │ │ │ ├── TlsContextCustomKeyOperationOptions.java │ │ │ ├── TlsContextOptions.java │ │ │ ├── TlsContextPkcs11Options.java │ │ │ ├── TlsHashAlgorithm.java │ │ │ ├── TlsKeyOperation.java │ │ │ ├── TlsKeyOperationHandler.java │ │ │ ├── TlsSignatureAlgorithm.java │ │ │ └── Uri.java │ │ │ ├── iot │ │ │ ├── IncomingPublishEvent.java │ │ │ ├── MqttRequestResponse.java │ │ │ ├── MqttRequestResponseClient.java │ │ │ ├── MqttRequestResponseClientOptions.java │ │ │ ├── RequestResponseOperation.java │ │ │ ├── ResponsePath.java │ │ │ ├── StreamingOperation.java │ │ │ ├── StreamingOperationOptions.java │ │ │ ├── SubscriptionStatusEvent.java │ │ │ └── SubscriptionStatusEventType.java │ │ │ ├── mqtt │ │ │ ├── MqttClient.java │ │ │ ├── MqttClientConnection.java │ │ │ ├── MqttClientConnectionEvents.java │ │ │ ├── MqttClientConnectionOperationStatistics.java │ │ │ ├── MqttConnectionConfig.java │ │ │ ├── MqttException.java │ │ │ ├── MqttMessage.java │ │ │ ├── OnConnectionClosedReturn.java │ │ │ ├── OnConnectionFailureReturn.java │ │ │ ├── OnConnectionSuccessReturn.java │ │ │ ├── QualityOfService.java │ │ │ └── WebsocketHandshakeTransformArgs.java │ │ │ ├── mqtt5 │ │ │ ├── Mqtt5Client.java │ │ │ ├── Mqtt5ClientOperationStatistics.java │ │ │ ├── Mqtt5ClientOptions.java │ │ │ ├── Mqtt5WebsocketHandshakeTransformArgs.java │ │ │ ├── NegotiatedSettings.java │ │ │ ├── OnAttemptingConnectReturn.java │ │ │ ├── OnConnectionFailureReturn.java │ │ │ ├── OnConnectionSuccessReturn.java │ │ │ ├── OnDisconnectionReturn.java │ │ │ ├── OnStoppedReturn.java │ │ │ ├── PublishResult.java │ │ │ ├── PublishReturn.java │ │ │ ├── QOS.java │ │ │ ├── TopicAliasingOptions.java │ │ │ └── packets │ │ │ │ ├── ConnAckPacket.java │ │ │ │ ├── ConnectPacket.java │ │ │ │ ├── DisconnectPacket.java │ │ │ │ ├── PubAckPacket.java │ │ │ │ ├── PublishPacket.java │ │ │ │ ├── SubAckPacket.java │ │ │ │ ├── SubscribePacket.java │ │ │ │ ├── UnsubAckPacket.java │ │ │ │ ├── UnsubscribePacket.java │ │ │ │ └── UserProperty.java │ │ │ ├── s3 │ │ │ ├── ChecksumAlgorithm.java │ │ │ ├── ChecksumConfig.java │ │ │ ├── ResumeToken.java │ │ │ ├── S3Client.java │ │ │ ├── S3ClientOptions.java │ │ │ ├── S3ExpressCredentialsProperties.java │ │ │ ├── S3ExpressCredentialsProvider.java │ │ │ ├── S3ExpressCredentialsProviderFactory.java │ │ │ ├── S3ExpressCredentialsProviderHandler.java │ │ │ ├── S3FinishedResponseContext.java │ │ │ ├── S3MetaRequest.java │ │ │ ├── S3MetaRequestOptions.java │ │ │ ├── S3MetaRequestProgress.java │ │ │ ├── S3MetaRequestResponseHandler.java │ │ │ ├── S3MetaRequestResponseHandlerNativeAdapter.java │ │ │ └── S3TcpKeepAliveOptions.java │ │ │ └── utils │ │ │ ├── ByteBufferUtils.java │ │ │ ├── PackageInfo.java │ │ │ ├── PemUtils.java │ │ │ └── StringUtils.java │ └── resources │ │ └── META-INF │ │ └── native-image │ │ └── software.amazon.awssdk │ │ └── crt │ │ └── aws-crt │ │ ├── jni-config.json │ │ ├── native-image.properties │ │ └── reflect-config.json ├── native │ ├── aws_signing.c │ ├── aws_signing.h │ ├── build.gradle.kts │ ├── checksums.c │ ├── client_bootstrap.c │ ├── credentials.c │ ├── credentials.h │ ├── credentials_provider.c │ ├── crt.c │ ├── crt.h │ ├── custom_key_op_handler.c │ ├── custom_key_op_handler.h │ ├── directory_traversal.c │ ├── ecc_key_pair.c │ ├── event_loop_group.c │ ├── event_stream_message.c │ ├── event_stream_message.h │ ├── event_stream_rpc_client.c │ ├── event_stream_rpc_server.c │ ├── host_resolver.c │ ├── http2_stream_manager.c │ ├── http_connection_manager.c │ ├── http_connection_manager.h │ ├── http_proxy_options.c │ ├── http_proxy_options.h │ ├── http_proxy_options_environment_variable.c │ ├── http_proxy_options_environment_variable.h │ ├── http_request_response.c │ ├── http_request_response.h │ ├── http_request_utils.c │ ├── http_request_utils.h │ ├── java_class_ids.c │ ├── java_class_ids.h │ ├── jni.c │ ├── logging.c │ ├── logging.h │ ├── mqtt5_client.c │ ├── mqtt5_client_jni.h │ ├── mqtt5_packets.c │ ├── mqtt5_packets.h │ ├── mqtt5_utils.c │ ├── mqtt5_utils.h │ ├── mqtt_client.c │ ├── mqtt_connection.c │ ├── mqtt_connection.h │ ├── mqtt_request_response.c │ ├── pkcs11_lib.c │ ├── process.c │ ├── retry_utils.c │ ├── retry_utils.h │ ├── s3_client.c │ ├── server_bootstrap.c │ ├── socket_options.c │ ├── string_utils.c │ ├── system_info.c │ ├── tls_connection_options.c │ ├── tls_context_options.c │ ├── tls_context_pkcs11_options.c │ ├── tls_context_pkcs11_options.h │ ├── tls_ctx.c │ ├── tls_key_operation.c │ └── uri.c └── test │ ├── android │ └── testapp │ │ ├── .gitignore │ │ ├── build.gradle │ │ ├── gradle.properties │ │ ├── gradlew │ │ ├── gradlew.bat │ │ ├── instrumentedTestSpec.yml │ │ ├── settings.gradle │ │ └── src │ │ ├── androidTest │ │ ├── assets │ │ │ └── .gitignore │ │ └── java │ │ │ └── software │ │ │ └── amazon │ │ │ └── awssdk │ │ │ └── crt │ │ │ └── test │ │ │ └── android │ │ │ └── CrtPlatformImpl.java │ │ └── main │ │ ├── AndroidManifest.xml │ │ ├── assets │ │ ├── .gitignore │ │ └── android_file_creation.py │ │ ├── java │ │ └── software │ │ │ └── amazon │ │ │ └── awssdk │ │ │ └── crttest │ │ │ └── MainActivity.kt │ │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ └── ic_launcher_background.xml │ │ ├── layout │ │ └── activity_main.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── java │ └── software │ └── amazon │ └── awssdk │ └── crt │ └── test │ ├── ClientBootstrapTest.java │ ├── CrcTest.java │ ├── CredentialsProviderTest.java │ ├── CrtMemoryLeakDetector.java │ ├── CrtTestContext.java │ ├── CrtTestFixture.java │ ├── CustomKeyOpsTest.java │ ├── DirectoryTraversalTest.java │ ├── EccKeyPairTest.java │ ├── Elasticurl.java │ ├── EventLoopGroupTest.java │ ├── EventStreamClientConnectionTest.java │ ├── EventStreamHeaderTest.java │ ├── FailFastListener.java │ ├── Http2ClientConnectionTest.java │ ├── Http2ClientLocalHostTest.java │ ├── Http2RequestResponseTest.java │ ├── Http2StreamManagerTest.java │ ├── HttpClientConnectionManagerTest.java │ ├── HttpClientConnectionTest.java │ ├── HttpClientTestFixture.java │ ├── HttpRequestResponseFixture.java │ ├── HttpRequestResponseTest.java │ ├── InitTest.java │ ├── IotServiceTest.java │ ├── JniExceptionTest.java │ ├── Mqtt5ClientTest.java │ ├── Mqtt5ClientTestFixture.java │ ├── Mqtt5ClientTestSigv4HandshakeTransformer.java │ ├── Mqtt5to3AdapterConnectionTest.java │ ├── MqttClientConnectionFixture.java │ ├── MqttClientConnectionMethodTest.java │ ├── MqttClientConnectionSigv4HandshakeTransformer.java │ ├── MqttClientConnectionTest.java │ ├── MqttRequestResponseClientTests.java │ ├── PackageInfoTest.java │ ├── Pkcs11LibTest.java │ ├── ProcessTest.java │ ├── ProxyTest.java │ ├── PublishTest.java │ ├── S3ClientTest.java │ ├── S3ExpressCredentialsProviderHandlerSample.java │ ├── SelfPubSubTest.java │ ├── ServerBootstrapTest.java │ ├── ServerListenerTest.java │ ├── ShutdownTest.java │ ├── SigningTest.java │ ├── StringUtilsTest.java │ ├── SubscribeTest.java │ ├── SystemInfoTest.java │ ├── TlsContextOptionsTest.java │ ├── UriTest.java │ └── WillTest.java └── utils ├── Canary ├── pom.xml └── src │ └── main │ └── java │ └── canary │ └── mqtt5 │ └── Mqtt5Canary.java └── mqtt5_test_setup.sh /.builder/actions/aws_crt_java_build.py: -------------------------------------------------------------------------------- 1 | 2 | import Builder 3 | import os 4 | import argparse 5 | 6 | 7 | class AWSCrtJavaBuild(Builder.Action): 8 | 9 | def run(self, env): 10 | if os.getenv("CRT_FIPS") is not None: 11 | env.shell.exec("mvn", "-P", "continuous-integration", "-B", "compile", 12 | "-Dcmake.crt_fips=ON", check=True) 13 | else: 14 | env.shell.exec("mvn", "-P", "continuous-integration", 15 | "-B", "compile", check=True) 16 | 17 | parser = argparse.ArgumentParser() 18 | parser.add_argument('--classifier') 19 | args = parser.parse_known_args(env.args.args)[0] 20 | if args.classifier: 21 | env.shell.exec("mvn", "-B", "install", "-DskipTests", "-Dshared-lib.skip=true", 22 | f"-Dcrt.classifier={args.classifier}", check=True) 23 | -------------------------------------------------------------------------------- /.builder/actions/localhost_test.py: -------------------------------------------------------------------------------- 1 | import Builder 2 | import sys 3 | import os 4 | 5 | 6 | class LocalhostTest(Builder.Action): 7 | 8 | def run(self, env): 9 | env.shell.setenv('AWS_CRT_MEMORY_TRACING', '2') 10 | actions = [] 11 | if os.system("mvn -Dtest=Http2ClientLocalHostTest test -DredirectTestOutputToFile=true -DforkCount=0 \ 12 | -Daws.crt.memory.tracing=2 \ 13 | -Daws.crt.debugnative=true \ 14 | -Daws.crt.log.level=Debug \ 15 | -Daws.crt.localhost=true"): 16 | # Failed 17 | actions.append("exit 1") 18 | 19 | return Builder.Script(actions, name='aws-crt-java-test') 20 | -------------------------------------------------------------------------------- /.clang-format: -------------------------------------------------------------------------------- 1 | --- 2 | Language: Cpp 3 | # BasedOnStyle: Mozilla 4 | AlignAfterOpenBracket: AlwaysBreak 5 | AlignConsecutiveAssignments: false 6 | AlignConsecutiveDeclarations: false 7 | AlignEscapedNewlines: Right 8 | AlignOperands: true 9 | AlignTrailingComments: true 10 | AllowAllParametersOfDeclarationOnNextLine: false 11 | AllowShortBlocksOnASingleLine: false 12 | AllowShortCaseLabelsOnASingleLine: false 13 | AllowShortFunctionsOnASingleLine: Inline 14 | AllowShortIfStatementsOnASingleLine: false 15 | AllowShortLoopsOnASingleLine: false 16 | AlwaysBreakAfterReturnType: None 17 | AlwaysBreakBeforeMultilineStrings: false 18 | BinPackArguments: false 19 | BinPackParameters: false 20 | BreakBeforeBinaryOperators: None 21 | BreakBeforeBraces: Attach 22 | BreakBeforeTernaryOperators: true 23 | BreakStringLiterals: true 24 | ColumnLimit: 120 25 | ContinuationIndentWidth: 4 26 | DerivePointerAlignment: false 27 | IncludeBlocks: Preserve 28 | IndentCaseLabels: true 29 | IndentPPDirectives: AfterHash 30 | IndentWidth: 4 31 | IndentWrappedFunctionNames: true 32 | KeepEmptyLinesAtTheStartOfBlocks: true 33 | MacroBlockBegin: '' 34 | MacroBlockEnd: '' 35 | MaxEmptyLinesToKeep: 1 36 | PenaltyBreakAssignment: 2 37 | PenaltyBreakBeforeFirstCallParameter: 19 38 | PenaltyBreakComment: 300 39 | PenaltyBreakFirstLessLess: 120 40 | PenaltyBreakString: 1000 41 | PenaltyExcessCharacter: 1000000 42 | PenaltyReturnTypeOnItsOwnLine: 100000 43 | PointerAlignment: Right 44 | ReflowComments: true 45 | SortIncludes: true 46 | SpaceAfterCStyleCast: false 47 | SpaceBeforeAssignmentOperators: true 48 | SpaceBeforeParens: ControlStatements 49 | SpaceInEmptyParentheses: false 50 | SpacesInContainerLiterals: true 51 | SpacesInCStyleCastParentheses: false 52 | SpacesInParentheses: false 53 | SpacesInSquareBrackets: false 54 | Standard: Cpp11 55 | TabWidth: 4 56 | UseTab: Never 57 | ... 58 | 59 | -------------------------------------------------------------------------------- /.clang-tidy: -------------------------------------------------------------------------------- 1 | --- 2 | Checks: 'clang-diagnostic-*,clang-analyzer-*,readability-*,modernize-*,bugprone-*,misc-*,google-runtime-int,llvm-header-guard,fuchsia-restrict-system-includes,-clang-analyzer-valist.Uninitialized,-clang-analyzer-security.insecureAPI.rand,-clang-analyzer-alpha.*,-readability-magic-numbers' 3 | WarningsAsErrors: '*' 4 | HeaderFilterRegex: '.*(? 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /android/crt/src/main/java/software/amazon/awssdk/crt/android/CrtPlatformImpl.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * SPDX-License-Identifier: Apache-2.0. 5 | */ 6 | 7 | package software.amazon.awssdk.crt.android; 8 | 9 | import software.amazon.awssdk.crt.BuildConfig; 10 | import software.amazon.awssdk.crt.CrtPlatform; 11 | import software.amazon.awssdk.crt.utils.PackageInfo; 12 | import java.util.Locale; 13 | import android.os.Build; 14 | 15 | public class CrtPlatformImpl extends CrtPlatform { 16 | public String getOSIdentifier() { 17 | return "android"; 18 | } 19 | 20 | public String getArchIdentifier() { 21 | return System.getProperty("os.arch"); 22 | } 23 | 24 | private String normalize(String value) { 25 | if (value == null) { 26 | return ""; 27 | } 28 | return value.toLowerCase(Locale.US).replaceAll("[^a-z0-9]+", ""); 29 | } 30 | 31 | public String getResourcePath(String cRuntime, String libraryName) { 32 | // Internal folder structure of Android aar libraries are different from jar libraries and arch must 33 | // be retrieved using Build class instead of a system property. 34 | String arch = Build.CPU_ABI; 35 | 36 | if (arch.matches("^(x8664|amd64|ia32e|em64t|x64|x86_64)$")) { 37 | arch = "x86_64"; 38 | } else if (arch.matches("^(x8632|x86|i[3-6]86|ia32|x32)$")) { 39 | arch = "x86"; 40 | } else if (arch.startsWith("armeabi")) { 41 | if (arch.contains("v7")) { 42 | arch = "armeabi-v7a"; 43 | } else { 44 | throw new RuntimeException("AWS CRT: architecture not supported on Android: " + arch); 45 | } 46 | } else if (arch.startsWith("arm64") || arch.startsWith("aarch64") || arch.equals("armv8a")) { 47 | arch = "arm64-v8a"; 48 | } else if (arch.equals("armv7l")) { 49 | arch = "armeabi-v7a"; 50 | } else { 51 | throw new RuntimeException("AWS CRT: architecture not supported on Android: " + arch); 52 | } 53 | 54 | return "/lib/" + arch + "/" + libraryName; 55 | } 56 | 57 | public PackageInfo.Version getVersion() { 58 | return new PackageInfo.Version(BuildConfig.VERSION_NAME); 59 | } 60 | } -------------------------------------------------------------------------------- /android/gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | # org.gradle.jvmargs=-Xmx2G 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | # AndroidX package structure to make it clearer which packages are bundled with the 15 | # Android operating system, and which are packaged with your app's APK 16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 17 | android.useAndroidX=true 18 | # Automatically convert third-party libraries to use AndroidX 19 | android.enableJetifier=true 20 | # Kotlin code style for this project: "official" or "obsolete": 21 | kotlin.code.style=official 22 | -------------------------------------------------------------------------------- /android/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name='aws-crt-android' 2 | include ':crt' 3 | -------------------------------------------------------------------------------- /cmake/AwsPlatformDetect.cmake: -------------------------------------------------------------------------------- 1 | 2 | # save the folder when this file is included, for use later 3 | set(THIS_FILE_DIR ${CMAKE_CURRENT_LIST_DIR}) 4 | 5 | function(aws_detect_target_platform out_os out_arch) 6 | if (CMAKE_CROSSCOMPILING AND CMAKE_SYSTEM_NAME STREQUAL "Android") 7 | set(${out_os} "android" PARENT_SCOPE) 8 | set(${out_arch} "${ANDROID_ABI}" PARENT_SCOPE) 9 | return() 10 | endif() 11 | try_compile( 12 | RESULT_UNUSED 13 | ${CMAKE_CURRENT_BINARY_DIR} 14 | SOURCES "${THIS_FILE_DIR}/osdetect.c" 15 | OUTPUT_VARIABLE OS_OUTPUT 16 | ) 17 | # Find the error in the output, then strip the identifier off 18 | string(REGEX MATCH "OS ([a-zA-Z]+)" OS "${OS_OUTPUT}") 19 | string(REPLACE "OS " "" OS "${OS}") 20 | 21 | try_compile( 22 | RESULT_UNUSED 23 | ${CMAKE_CURRENT_BINARY_DIR} 24 | SOURCES "${THIS_FILE_DIR}/archdetect.c" 25 | OUTPUT_VARIABLE ARCH_OUTPUT 26 | ) 27 | 28 | # Find the error in the output, then strip the identifier off 29 | string(REGEX MATCH "ARCH ([a-zA-Z0-9_]+)" ARCH "${ARCH_OUTPUT}") 30 | string(REPLACE "ARCH " "" ARCH "${ARCH}") 31 | 32 | set(${out_os} "${OS}" PARENT_SCOPE) 33 | set(${out_arch} "${ARCH}" PARENT_SCOPE) 34 | endfunction() 35 | -------------------------------------------------------------------------------- /cmake/archdetect.c: -------------------------------------------------------------------------------- 1 | /* Use # error to output the arch, and then parse from cmake */ 2 | /* See https://sourceforge.net/p/predef/wiki/Architectures/ for reference */ 3 | #if defined(__i386) || defined(__i386__) || defined(_M_IX86) 4 | # error ARCH x86_32 5 | #elif defined(__x86_64) || defined(__x86_64__) || defined(__amd64) || defined(_M_X64) 6 | # error ARCH x86_64 7 | #elif defined(__aarch64__) 8 | # error ARCH armv8 9 | #elif defined(__arm__) 10 | # if defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7S__) 11 | # error ARCH armv7 12 | # elif defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) 13 | # error ARCH armv6 14 | # endif 15 | #else 16 | # error ARCH unknown 17 | #endif 18 | 19 | -------------------------------------------------------------------------------- /cmake/osdetect.c: -------------------------------------------------------------------------------- 1 | /* Use #error to emit os, parse from cmake */ 2 | #if defined(_WIN32) 3 | # error OS windows 4 | #elif defined(__APPLE__) 5 | # include 6 | # if TARGET_OS_MAC == 1 7 | # error OS osx 8 | # endif 9 | #elif defined(__linux__) 10 | # error OS linux 11 | #elif defined(__FreeBSD__) 12 | # error OS freebsd 13 | #elif defined(__ANDROID__) 14 | # error OS android 15 | #elif defined(__sun) 16 | # error OS solaris 17 | #endif 18 | #error OS unknown 19 | -------------------------------------------------------------------------------- /codebuild/CanaryWrapper_MetricFunctions.py: -------------------------------------------------------------------------------- 1 | # Contains all of the metric reporting functions for the Canary Wrappers 2 | 3 | # Needs to be installed prior to running 4 | import psutil 5 | 6 | 7 | cache_cpu_psutil_process = None 8 | def get_metric_total_cpu_usage(psutil_process : psutil.Process): 9 | global cache_cpu_psutil_process 10 | 11 | try: 12 | if (psutil_process == None): 13 | print ("ERROR - No psutil.process passed! Cannot gather metric!", flush=True) 14 | return None 15 | # We always need to skip the first CPU poll 16 | if (cache_cpu_psutil_process != psutil_process): 17 | psutil.cpu_percent(interval=None) 18 | cache_cpu_psutil_process = psutil_process 19 | return None 20 | return psutil.cpu_percent(interval=None) 21 | except Exception as e: 22 | print ("ERROR - exception occurred gathering metrics!") 23 | print ("Exception: " + str(e), flush=True) 24 | return None 25 | 26 | # Note: This value is in BYTES. 27 | def get_metric_total_memory_usage_value(psutil_process : psutil.Process): 28 | try: 29 | if (psutil_process == None): 30 | print ("ERROR - No psutil.process passed! Cannot gather metric!", flush=True) 31 | return None 32 | return psutil.virtual_memory()[3] 33 | except Exception as e: 34 | print ("ERROR - exception occurred gathering metrics!") 35 | print ("Exception: " + str(e), flush=True) 36 | return None 37 | 38 | 39 | def get_metric_total_memory_usage_percent(psutil_process : psutil.Process): 40 | try: 41 | if (psutil_process == None): 42 | print ("ERROR - No psutil.process passed! Cannot gather metric!", flush=True) 43 | return None 44 | return psutil.virtual_memory()[2] 45 | except Exception as e: 46 | print ("ERROR - exception occurred gathering metrics!") 47 | print ("Exception: " + str(e), flush=True) 48 | return None 49 | -------------------------------------------------------------------------------- /codebuild/cd/deploy-platform-specific-jars.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | set -ex 4 | 5 | if [[ $DEPLOY_VERSION = *-SNAPSHOT ]]; then 6 | # snapshot doesn't need to gpg sign the file to deploy 7 | DEPLOY_FILE_GOAL=deploy:deploy-file 8 | DEPLOY_REPOSITORY_URL=https://aws.oss.sonatype.org/content/repositories/snapshots 9 | else 10 | # Need to sign the file to deploy to staging repo 11 | # pin to 3.1.0, somehow the latest 3.2.0 breaks the file deploy with 401. 12 | DEPLOY_FILE_GOAL=org.apache.maven.plugins:maven-gpg-plugin:3.1.0:sign-and-deploy-file 13 | DEPLOY_REPOSITORY_URL=https://aws.oss.sonatype.org:443/service/local/staging/deployByRepositoryId/${STAGING_REPO_ID} 14 | fi 15 | 16 | CLASSIFIERS_ARRAY=("linux-armv6" "linux-armv7" "linux-aarch_64" "linux-x86_32" "linux-x86_64" "osx-aarch_64" "osx-x86_64" "windows-x86_32" "windows-x86_64" "linux-x86_64-musl" "linux-armv7-musl" "linux-aarch_64-musl" "fips-where-available") 17 | 18 | for str in ${CLASSIFIERS_ARRAY[@]}; do 19 | FILES="${FILES}target/aws-crt-1.0.0-SNAPSHOT-$str.jar," 20 | CLASSIFIERS="${CLASSIFIERS}${str}," 21 | TYPES="${TYPES}jar," 22 | done 23 | 24 | # remove the last "," 25 | FILES=${FILES::-1} 26 | CLASSIFIERS=${CLASSIFIERS::-1} 27 | TYPES=${TYPES::-1} 28 | 29 | 30 | mvn -B -X $DEPLOY_FILE_GOAL \ 31 | -Dgpg.passphrase=$GPG_PASSPHRASE \ 32 | -DgroupId=software.amazon.awssdk.crt -DartifactId=aws-crt -Dpackaging=jar \ 33 | -Dversion=$DEPLOY_VERSION \ 34 | -Dfile=./target/aws-crt-$DEPLOY_VERSION.jar \ 35 | -Dfiles=$FILES \ 36 | -Dclassifiers=$CLASSIFIERS \ 37 | -Dtypes=$TYPES \ 38 | -DpomFile=pom.xml \ 39 | -DrepositoryId=ossrh -Durl=$DEPLOY_REPOSITORY_URL 40 | -------------------------------------------------------------------------------- /codebuild/cd/deploy-snapshot-android.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -ex 4 | set -o pipefail # Make sure one process in pipe fail gets bubble up 5 | 6 | git submodule update --init 7 | cd ./android 8 | 9 | GPG_KEY=$(cat /tmp/aws-sdk-common-runtime.key.asc) 10 | # Publish to nexus 11 | ../gradlew -PsigningKey=$"$GPG_KEY" -PsigningPassword=$GPG_PASSPHRASE -PsonatypeUsername=$ST_USERNAME -PsonatypePassword=$ST_PASSWORD publishToAwsNexus closeAwsNexusStagingRepository | tee /tmp/android_deploy.log 12 | # Get the staging repository id and save it 13 | cat /tmp/android_deploy.log | grep "Created staging repository" | cut -d\' -f2 | tee /tmp/android_repositoryId.txt 14 | -------------------------------------------------------------------------------- /codebuild/cd/fips-where-available-jar-build.yml: -------------------------------------------------------------------------------- 1 | version: 0.2 2 | #this buildspec assumes the aws-common-runtime/ubuntu-16.04 image 3 | # This job is responsible for artifacting the JAR which will have all of the other shared libs stuffed 4 | # into it once all platforms are built and artifacted 5 | phases: 6 | install: 7 | commands: 8 | - sudo add-apt-repository ppa:openjdk-r/ppa 9 | - sudo apt-get update -y 10 | - sudo apt-get install openjdk-11-jdk-headless maven wget unzip -y -f 11 | build: 12 | commands: 13 | - cd $CODEBUILD_SRC_DIR/aws-crt-java 14 | # upload artifacts to S3 15 | - export GIT_TAG=$(git describe --tags) 16 | - mkdir -p target/cmake-build/lib 17 | # prepare fips-where-available uber jar, download the regular libs 18 | - aws s3 cp --recursive s3://aws-crt-java-pipeline/${GIT_TAG}/lib $CODEBUILD_SRC_DIR/aws-crt-java/target/cmake-build/lib 19 | # Override with the FIPS libs 20 | - aws s3 cp --recursive s3://aws-crt-java-pipeline/${GIT_TAG}/fips_lib $CODEBUILD_SRC_DIR/aws-crt-java/target/cmake-build/lib 21 | # Run a test to make sure we get the FIPS libs 22 | - CRT_FIPS=ON mvn test -Dtest=software.amazon.awssdk.crt.test.SystemInfoTest#testIsFIPS -Dshared-lib.skip=true 23 | - mvn -B package -DskipTests -Dshared-lib.skip=true -Dcrt.classifier=fips-where-available 24 | 25 | post_build: 26 | commands: 27 | # upload artifacts to S3 28 | - export GIT_TAG=$(git describe --tags) 29 | - aws s3 cp --recursive --exclude "*" --include "aws-crt*.jar" ./target s3://aws-crt-java-pipeline/${GIT_TAG}/jar 30 | 31 | cache: 32 | paths: 33 | - "/root/.m2/**/*" 34 | -------------------------------------------------------------------------------- /codebuild/cd/generic-unix-build.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -ex 4 | 5 | cd $(dirname $0)/../.. 6 | 7 | git submodule update --init 8 | 9 | AWS_CRT_HOST=$(uname | tr '[:upper:]' '[:lower:]')-$(uname -m) 10 | 11 | if [ -z "$AWS_CRT_TARGET" ]; then 12 | AWS_CRT_TARGET=$AWS_CRT_HOST 13 | fi 14 | 15 | if [[ $AWS_CRT_TARGET == linux-armv8 ]]; then 16 | CLASSIFIER=linux-aarch_64 17 | else 18 | CLASSIFIER=$AWS_CRT_TARGET 19 | fi 20 | 21 | # Pry the builder version this CRT is using out of ci.yml 22 | BUILDER_VERSION=$(cat .github/workflows/ci.yml | grep 'BUILDER_VERSION:' | sed 's/\s*BUILDER_VERSION:\s*\(.*\)/\1/') 23 | echo "Using builder version ${BUILDER_VERSION}" 24 | 25 | aws s3 cp s3://aws-crt-builder/releases/${BUILDER_VERSION}/builder.pyz ./builder 26 | chmod a+x builder 27 | 28 | # Upload the lib to S3 29 | GIT_TAG=$(git describe --tags) 30 | 31 | ./builder build -p aws-crt-java --target=$AWS_CRT_TARGET run_tests=false 32 | 33 | # When cross-compiling with builder, the shared lib gets an extra "/aws-crt-java/" in its path. 34 | # Move it to expected location. 35 | if [ -d target/cmake-build/aws-crt-java/lib ]; then 36 | mv target/cmake-build/aws-crt-java/lib target/cmake-build/lib 37 | fi 38 | 39 | # Double check that shared lib is where we expect 40 | if ! find target/cmake-build/lib -type f -name "*.so" | grep -q .; then 41 | echo "No .so files found" 42 | exit 1 43 | fi 44 | 45 | JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64 mvn -B package -DskipTests -Dshared-lib.skip=true -Dcrt.classifier=$CLASSIFIER 46 | 47 | aws s3 cp --recursive --exclude "*" --include "*.so" target/cmake-build/lib s3://aws-crt-java-pipeline/${GIT_TAG}/lib 48 | aws s3 cp target/ s3://aws-crt-java-pipeline/${GIT_TAG}/jar/ --recursive --exclude "*" --include "aws-crt*.jar" 49 | -------------------------------------------------------------------------------- /codebuild/cd/linux-aarch64-fips-build.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -ex 4 | 5 | cd $(dirname $0)/../.. 6 | 7 | git submodule update --init 8 | # double check aws-lc is the FIPS approved branch. 9 | bash ./codebuild/cd/test-fips-branch.sh 10 | 11 | # Pry the builder version this CRT is using out of ci.yml 12 | BUILDER_VERSION=$(cat .github/workflows/ci.yml | grep 'BUILDER_VERSION:' | sed 's/\s*BUILDER_VERSION:\s*\(.*\)/\1/') 13 | echo "Using builder version ${BUILDER_VERSION}" 14 | 15 | aws s3 cp s3://aws-crt-builder/releases/${BUILDER_VERSION}/builder.pyz ./builder 16 | chmod a+x builder 17 | 18 | GIT_TAG=$(git describe --tags) 19 | 20 | ./builder build -p aws-crt-java run_tests=false --target=linux-arm64 --cmake-extra=-DCRT_FIPS=ON 21 | 22 | # When cross-compiling with builder, the shared lib gets an extra "/aws-crt-java/" in its path. 23 | # Move it to expected location. 24 | if [ -d target/cmake-build/aws-crt-java/lib ]; then 25 | mv target/cmake-build/aws-crt-java/lib target/cmake-build/lib 26 | fi 27 | 28 | # Double check that shared lib is where we expect 29 | if ! find target/cmake-build/lib -type f -name "*.so" | grep -q .; then 30 | echo "No .so files found" 31 | exit 1 32 | fi 33 | 34 | JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64 mvn -B package -DskipTests -Dshared-lib.skip=true -Dcrt.classifier=linux-aarch_64-fips 35 | 36 | aws s3 cp --recursive --exclude "*" --include "*.so" target/cmake-build/lib s3://aws-crt-java-pipeline/${GIT_TAG}/fips_lib 37 | -------------------------------------------------------------------------------- /codebuild/cd/manylinux-x64-build.yml: -------------------------------------------------------------------------------- 1 | version: 0.2 2 | phases: 3 | install: 4 | commands: 5 | pre_build: 6 | commands: 7 | - export CC=gcc 8 | build: 9 | commands: 10 | - cd aws-crt-java 11 | - git submodule update --init 12 | - mvn -B package -DskipTests -Dcrt.classifier=linux-x86_64 13 | 14 | post_build: 15 | commands: 16 | # upload artifacts to S3 17 | - export GIT_TAG=$(git describe --tags) 18 | - aws s3 cp --recursive --exclude "*" --include "*.so" ./target/cmake-build/lib s3://aws-crt-java-pipeline/${GIT_TAG}/lib 19 | - aws s3 cp --recursive --exclude "*" --include "aws-crt*.jar" ./target s3://aws-crt-java-pipeline/${GIT_TAG}/jar 20 | cache: 21 | paths: 22 | - '/root/.m2/**/*' 23 | -------------------------------------------------------------------------------- /codebuild/cd/manylinux-x64-fips-build.yml: -------------------------------------------------------------------------------- 1 | version: 0.2 2 | phases: 3 | install: 4 | commands: 5 | pre_build: 6 | commands: 7 | - export CC=gcc 8 | build: 9 | commands: 10 | - cd aws-crt-java 11 | - git submodule update --init 12 | # double check aws-lc is the FIPS approved branch. 13 | - bash ./codebuild/cd/test-fips-branch.sh 14 | # aws-lc FIPS build requires golang for codegen 15 | - yum install -y golang 16 | - mvn -B package -DskipTests -Dcrt.classifier=linux-x86_64-fips -Dcmake.crt_fips=ON 17 | 18 | post_build: 19 | commands: 20 | # upload artifacts to S3 21 | - export GIT_TAG=$(git describe --tags) 22 | - aws s3 cp --recursive --exclude "*" --include "*.so" target/cmake-build/lib s3://aws-crt-java-pipeline/${GIT_TAG}/fips_lib 23 | 24 | cache: 25 | paths: 26 | - '/root/.m2/**/*' 27 | -------------------------------------------------------------------------------- /codebuild/cd/manylinux-x86-build.yml: -------------------------------------------------------------------------------- 1 | version: 0.2 2 | phases: 3 | install: 4 | commands: 5 | pre_build: 6 | commands: 7 | - export CC=gcc 8 | build: 9 | commands: 10 | - cd aws-crt-java 11 | - git submodule update --init 12 | - setarch i386 mvn -B package -DskipTests -Punix-x86 -Dcrt.classifier=linux-x86_32 13 | post_build: 14 | commands: 15 | # upload artifacts to S3 16 | - export GIT_TAG=$(git describe --tags) 17 | - aws s3 cp --recursive --exclude "*" --include "*.so" ./target/cmake-build/lib s3://aws-crt-java-pipeline/${GIT_TAG}/lib 18 | - aws s3 cp --recursive --exclude "*" --include "aws-crt*.jar" ./target s3://aws-crt-java-pipeline/${GIT_TAG}/jar 19 | 20 | cache: 21 | paths: 22 | - '/root/.m2/**/*' 23 | -------------------------------------------------------------------------------- /codebuild/cd/musl-arm64-build.yml: -------------------------------------------------------------------------------- 1 | version: 0.2 2 | phases: 3 | install: 4 | commands: 5 | pre_build: 6 | commands: 7 | - export CC=gcc 8 | build: 9 | commands: 10 | - cd aws-crt-java 11 | - ./codebuild/cd/musl-linux-build.sh aws-crt-alpine-3.16-arm64 linux-aarch_64-musl linux/aarch64 12 | 13 | post_build: 14 | commands: 15 | 16 | artifacts: 17 | files: 18 | - 'dist/**/*' 19 | 20 | cache: 21 | paths: 22 | - '/root/.m2/**/*' 23 | -------------------------------------------------------------------------------- /codebuild/cd/musl-armv7-build.yml: -------------------------------------------------------------------------------- 1 | version: 0.2 2 | phases: 3 | install: 4 | commands: 5 | pre_build: 6 | commands: 7 | - export CC=gcc 8 | build: 9 | commands: 10 | - cd aws-crt-java 11 | - export AWS_CRT_ARCH=armv7 12 | - ./codebuild/cd/musl-linux-build.sh aws-crt-alpine-3.16-armv7 linux-armv7-musl linux/arm/v7 13 | 14 | post_build: 15 | commands: 16 | 17 | artifacts: 18 | files: 19 | - 'dist/**/*' 20 | 21 | cache: 22 | paths: 23 | - '/root/.m2/**/*' 24 | -------------------------------------------------------------------------------- /codebuild/cd/musl-linux-build.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -ex 4 | 5 | IMAGE_NAME=$1 6 | shift 7 | CLASSIFIER=$1 8 | shift 9 | ARCH=$1 10 | shift 11 | 12 | # Pry the builder version this CRT is using out of ci.yml 13 | BUILDER_VERSION=$(cat .github/workflows/ci.yml | grep 'BUILDER_VERSION:' | sed 's/\s*BUILDER_VERSION:\s*\(.*\)/\1/') 14 | echo "Using builder version ${BUILDER_VERSION}" 15 | 16 | aws ecr get-login-password | docker login 123124136734.dkr.ecr.us-east-1.amazonaws.com -u AWS --password-stdin 17 | export DOCKER_IMAGE=123124136734.dkr.ecr.us-east-1.amazonaws.com/${IMAGE_NAME}:${BUILDER_VERSION} 18 | 19 | # on x86-64 and aarch64 we run on native images in codebuild 20 | # on other platforms we require emulation which is done through binfmt 21 | if [ "$ARCH" != "linux/aarch64" ]; then 22 | export QEMU_IMAGE=123124136734.dkr.ecr.us-east-1.amazonaws.com/multiarch-qemu-user-static:latest 23 | docker run --rm --privileged ${QEMU_IMAGE} --reset -p yes 24 | fi 25 | 26 | export BRANCH_TAG=$(git describe --tags) 27 | docker run --mount type=bind,src=$(pwd),dst=/root/aws-crt-java --env CXXFLAGS --env AWS_CRT_ARCH --platform ${ARCH} $DOCKER_IMAGE --version=${BUILDER_VERSION} build -p aws-crt-java --classifier ${CLASSIFIER} --branch ${BRANCH_TAG} run_tests=false 28 | docker container prune -f 29 | 30 | # Upload the artifacts to S3 31 | export GIT_TAG=$(git describe --tags) 32 | 33 | # Double check that shared lib is where we expect 34 | if ! find target/cmake-build/lib -type f -name "*.so" | grep -q .; then 35 | echo "No .so files found" 36 | exit 1 37 | fi 38 | 39 | aws s3 cp --recursive --exclude "*" --include "*.so" target/cmake-build/lib s3://aws-crt-java-pipeline/${GIT_TAG}/lib 40 | aws s3 cp target/ s3://aws-crt-java-pipeline/${GIT_TAG}/jar/ --recursive --exclude "*" --include "aws-crt*.jar" 41 | -------------------------------------------------------------------------------- /codebuild/cd/musl-x64-build.yml: -------------------------------------------------------------------------------- 1 | version: 0.2 2 | phases: 3 | install: 4 | commands: 5 | pre_build: 6 | commands: 7 | - export CC=gcc 8 | build: 9 | commands: 10 | - cd aws-crt-java 11 | - ./codebuild/cd/musl-linux-build.sh aws-crt-alpine-3.16-x64 linux-x86_64-musl linux/amd64 12 | 13 | post_build: 14 | commands: 15 | 16 | artifacts: 17 | files: 18 | - 'dist/**/*' 19 | 20 | cache: 21 | paths: 22 | - '/root/.m2/**/*' 23 | -------------------------------------------------------------------------------- /codebuild/cd/osx-arm64-build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | set -ex 4 | 5 | cd $(dirname $0)/../.. 6 | 7 | git submodule update --init 8 | export GIT_TAG=$(git describe --tags) 9 | 10 | mvn -B package -DskipTests -P mac-arm64 -Dcrt.classifier=osx-aarch_64 11 | 12 | # Copy artifacts to dist 13 | mkdir -p ../dist 14 | # Note: as we ran mvn install, the dist has unexpected files, using S3 bucket to transfer artifact instead 15 | cp -rv target/cmake-build/lib ../dist/ 16 | 17 | aws s3 cp --recursive --exclude "*" --include "*.dylib" ./target/cmake-build/lib s3://aws-crt-java-pipeline/${GIT_TAG}/lib 18 | 19 | aws s3 cp --recursive --exclude "*" --include "aws-crt*.jar" ./target s3://aws-crt-java-pipeline/${GIT_TAG}/jar 20 | -------------------------------------------------------------------------------- /codebuild/cd/osx-x64-build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | set -ex 4 | 5 | cd $(dirname $0)/../.. 6 | 7 | git submodule update --init 8 | 9 | export GIT_TAG=$(git describe --tags) 10 | 11 | mvn -B package -DskipTests -P mac-x64 -Dcrt.classifier=osx-x86_64 12 | 13 | # Copy artifacts to dist 14 | mkdir -p ../dist 15 | cp -rv target/cmake-build/lib ../dist/ 16 | 17 | aws s3 cp --recursive --exclude "*" --include "*.dylib" ./target/cmake-build/lib s3://aws-crt-java-pipeline/${GIT_TAG}/lib 18 | aws s3 cp --recursive --exclude "*" --include "aws-crt*.jar" ./target s3://aws-crt-java-pipeline/${GIT_TAG}/jar 19 | -------------------------------------------------------------------------------- /codebuild/cd/promote-release.yml: -------------------------------------------------------------------------------- 1 | version: 0.2 2 | #this buildspec assumes the aws-common-runtime/ubuntu-16.04 image 3 | # This job is responsible for artifacting the JAR which will have all of the other shared libs stuffed 4 | # into it once all platforms are built and artifacted 5 | phases: 6 | install: 7 | commands: 8 | - sudo add-apt-repository ppa:openjdk-r/ppa 9 | - sudo apt-get update -y 10 | - sudo apt-get install openjdk-8-jdk-headless maven -y -f 11 | 12 | pre_build: 13 | commands: 14 | - cd $CODEBUILD_SRC_DIR/aws-crt-java 15 | - export PKG_VERSION=$(git describe --tags | cut -f2 -dv) 16 | - echo PKG_VERSION=$PKG_VERSION 17 | # install settings.xml to ~/.m2/settings.xml 18 | - mkdir -p $HOME/.m2 19 | - aws s3 cp s3://code-sharing-aws-crt/aws-crt-java.settings.token.xml $HOME/.m2/settings.xml 20 | # import gpg key 21 | - aws s3 cp s3://code-sharing-aws-crt/aws-sdk-common-runtime.key.asc /tmp/aws-sdk-common-runtime.key.asc 22 | - gpg --import /tmp/aws-sdk-common-runtime.key.asc 23 | - export GPG_PASSPHRASE=$(aws --query "SecretString" secretsmanager get-secret-value --secret-id aws-sdk-common-runtime.key.asc/password | cut -f2 -d":" | sed -e 's/[\\\"\}]//g') 24 | - export REPOSITORY_ID=$(cat $CODEBUILD_SRC_DIR_aws_crt/repositoryId.txt) 25 | - export ANDROID_REPOSITORY_ID=$(cat $CODEBUILD_SRC_DIR_aws_crt/android_repositoryId.txt) 26 | - export ST_USERNAME=$(aws --query "SecretString" secretsmanager get-secret-value --secret-id Sonatype/JIRA/token | cut -f2 -d":" | cut -f1 -d"," | sed -e 's/[\\\"\}]//g') 27 | - export ST_PASSWORD=$(aws --query "SecretString" secretsmanager get-secret-value --secret-id Sonatype/JIRA/token | cut -f3 -d":" | sed -e 's/[\\\"\}]//g') 28 | # Use the username and password from secret manager to update the settings 29 | - sed -i 's|token-username|'"$ST_USERNAME"'|g' $HOME/.m2/settings.xml 30 | - sed -i 's|token-password|'"$ST_PASSWORD"'|g' $HOME/.m2/settings.xml 31 | build: 32 | commands: 33 | - cd $CODEBUILD_SRC_DIR/aws-crt-java 34 | # Trigger the release of the last staged package in the staging repository 35 | - mvn -B nexus-staging:release -Prelease -DstagingRepositoryId=$REPOSITORY_ID 36 | - mvn -B nexus-staging:release -Prelease -DstagingRepositoryId=$ANDROID_REPOSITORY_ID 37 | post_build: 38 | commands: 39 | 40 | cache: 41 | paths: 42 | - "/root/.m2/**/*" 43 | -------------------------------------------------------------------------------- /codebuild/cd/test-fips-branch.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -e 3 | set -x 4 | 5 | # Store the current working directory 6 | original_dir=$(pwd) 7 | cd ./crt/aws-lc || exit 1 8 | 9 | # Get the current commit hash 10 | current_commit=$(git rev-parse HEAD) 11 | 12 | # Check if the current commit is from the FIPS branch 13 | fips_branch="fips-2024-09-27" 14 | if git merge-base --is-ancestor "$current_commit" "origin/$fips_branch"; then 15 | echo "Current aws-lc commit is from the '$fips_branch' branch" 16 | status=0 17 | else 18 | echo "Error: Current aws-lc commit is not from the '$fips_branch' branch" 19 | status=1 20 | fi 21 | 22 | # Change back to the original working directory 23 | cd "$original_dir" || exit 1 24 | 25 | exit $status 26 | -------------------------------------------------------------------------------- /codebuild/cd/test-platform-specific-jar-snapshot.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | set -ex 4 | 5 | PLATFORM_ARRAY=("linux-armv6" "linux-armv7" "linux-aarch_64" "linux-x86_32" "linux-x86_64" "osx-aarch_64" "osx-x86_64" "windows-x86_32" "windows-x86_64" "linux-x86_64-musl" "linux-armv7-musl" "linux-aarch_64-musl" "fips-where-available") 6 | 7 | # test uber jar 8 | mvn -B dependency:get -DrepoUrl=https://aws.oss.sonatype.org/content/repositories/snapshots -Dartifact=software.amazon.awssdk.crt:aws-crt:${CRT_VERSION}-SNAPSHOT -Dtransitive=false 9 | 10 | for str in ${PLATFORM_ARRAY[@]}; do 11 | # Test platform specific jar 12 | mvn -B dependency:get -DrepoUrl=https://aws.oss.sonatype.org/content/repositories/snapshots -Dartifact=software.amazon.awssdk.crt:aws-crt:${CRT_VERSION}-SNAPSHOT:jar:${str} -Dtransitive=false 13 | done 14 | -------------------------------------------------------------------------------- /codebuild/cd/test-snapshot.yml: -------------------------------------------------------------------------------- 1 | version: 0.2 2 | #this buildspec assumes the aws-common-runtime/ubuntu-16.04 image 3 | # This job is responsible for artifacting the JAR which will have all of the other shared libs stuffed 4 | # into it once all platforms are built and artifacted 5 | phases: 6 | install: 7 | commands: 8 | - sudo add-apt-repository ppa:openjdk-r/ppa 9 | - sudo apt-get update -y 10 | - sudo apt-get install openjdk-8-jdk-headless maven -y -f 11 | 12 | pre_build: 13 | commands: 14 | - cd aws-crt-java 15 | - export CRT_VERSION=$(git describe --tags | sed -e s/^v//) 16 | 17 | build: 18 | commands: 19 | # Verify that the package can be found in the snapshot repo 20 | # note that this uses an ancient version of maven and the maven dependency plugin because we're on trusty 21 | # http://maven.apache.org/plugins-archives/maven-dependency-plugin-2.1/get-mojo.html 22 | - bash ./codebuild/cd/test-platform-specific-jar-snapshot.sh 23 | 24 | post_build: 25 | commands: 26 | - echo Build completed on `date` 27 | 28 | cache: 29 | paths: 30 | - '/root/.m2/**/*' 31 | -------------------------------------------------------------------------------- /codebuild/cd/test-version-exists.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -e 3 | set -x 4 | # force a failure if there's no tag 5 | git describe --tags 6 | # now get the tag 7 | CURRENT_TAG=$(git describe --tags | cut -f2 -dv) 8 | # convert v0.2.12-2-g50254a9 to 0.2.12 9 | CURRENT_TAG_VERSION=$(git describe --tags | cut -f1 -d'-' | cut -f2 -dv) 10 | # if there's a hash on the tag, then this is not a release tagged commit 11 | if [ "$CURRENT_TAG" != "$CURRENT_TAG_VERSION" ]; then 12 | echo "Current tag version is not a release tag, cut a new release if you want to publish." 13 | exit 1 14 | fi 15 | 16 | PUBLISHED_TAG_VERSION=$(curl -s "https://repo.maven.apache.org/maven2/software/amazon/awssdk/crt/aws-crt/maven-metadata.xml" | grep "" | cut -f2 -d ">" | cut -f1 -d "<") 17 | if [ "$PUBLISHED_TAG_VERSION" == "$CURRENT_TAG_VERSION" ]; then 18 | echo "$CURRENT_TAG_VERSION is already in Sonatype, cut a new tag if you want to upload another version." 19 | exit 1 20 | fi 21 | 22 | echo "$CURRENT_TAG_VERSION currently does not exist in Sonatype, allowing pipeline to continue." 23 | exit 0 24 | -------------------------------------------------------------------------------- /codebuild/cd/test-version-exists.yml: -------------------------------------------------------------------------------- 1 | version: 0.2 2 | #this build spec assumes the aws-common-runtime/ubuntu-16.04 image 3 | #this build run simply verifies we haven't published something at this tag yet. 4 | #if we have we fail the build and stop the pipeline, if we haven't we allow the pipeline to run. 5 | phases: 6 | install: 7 | commands: 8 | pre_build: 9 | commands: 10 | build: 11 | commands: 12 | - echo Build started on `date` 13 | - cd aws-crt-java 14 | - bash ./codebuild/cd/test-version-exists.sh 15 | post_build: 16 | commands: 17 | - echo Build completed on `date` 18 | 19 | -------------------------------------------------------------------------------- /codebuild/cd/windows-vs2015-x64-build.bat: -------------------------------------------------------------------------------- 1 | 2 | @setlocal enableextensions enabledelayedexpansion 3 | 4 | echo PATH=%PATH% 5 | echo JAVA_HOME=%JAVA_HOME% 6 | 7 | set AWS_CMAKE_GENERATOR=Visual Studio 14 2015 Win64 8 | 9 | git submodule update --init 10 | 11 | for /f %%A in ('git describe --tags') do ( 12 | set GIT_TAG=%%A 13 | ) 14 | 15 | mvn -X install -DskipTests -Dcrt.classifier=windows-x86_64 || goto error 16 | 17 | aws s3 cp --recursive --exclude "*" --include "*.dll" .\target\cmake-build\lib s3://aws-crt-java-pipeline/%GIT_TAG%/lib 18 | aws s3 cp --recursive --exclude "*" --include "*.jar" .\target s3://aws-crt-java-pipeline/%GIT_TAG%/jar 19 | 20 | 21 | @endlocal 22 | goto :EOF 23 | 24 | :error 25 | @endlocal 26 | echo Failed with error #%errorlevel%. 27 | exit /b %errorlevel% 28 | -------------------------------------------------------------------------------- /codebuild/cd/windows-vs2015-x86-build.bat: -------------------------------------------------------------------------------- 1 | 2 | @setlocal enableextensions enabledelayedexpansion 3 | 4 | echo PATH=%PATH% 5 | echo JAVA_HOME=%JAVA_HOME% 6 | 7 | set AWS_CMAKE_GENERATOR=Visual Studio 14 2015 8 | 9 | git submodule update --init 10 | 11 | for /f %%A in ('git describe --tags') do ( 12 | set GIT_TAG=%%A 13 | ) 14 | 15 | mvn -X install -DskipTests -Dcrt.classifier=windows-x86_32 || goto error 16 | 17 | aws s3 cp --recursive --exclude "*" --include "*.dll" .\target\cmake-build\lib s3://aws-crt-java-pipeline/%GIT_TAG%/lib 18 | aws s3 cp --recursive --exclude "*" --include "*.jar" .\target s3://aws-crt-java-pipeline/%GIT_TAG%/jar 19 | 20 | 21 | @endlocal 22 | goto :EOF 23 | 24 | :error 25 | @endlocal 26 | echo Failed with error #%errorlevel%. 27 | exit /b %errorlevel% 28 | -------------------------------------------------------------------------------- /codebuild/linux-integration-tests.yml: -------------------------------------------------------------------------------- 1 | version: 0.2 2 | 3 | env: 4 | shell: bash 5 | variables: 6 | BUILDER_HOST: https://d19elf31gohf1l.cloudfront.net 7 | PACKAGE_NAME: aws-crt-java 8 | 9 | phases: 10 | install: 11 | commands: 12 | - sudo add-apt-repository ppa:openjdk-r/ppa 13 | - sudo add-apt-repository ppa:ubuntu-toolchain-r/test 14 | - sudo apt-get update -y 15 | - sudo apt-get install cmake -y 16 | build: 17 | commands: 18 | - echo Build started on `date` 19 | # Update the submodules 20 | - git submodule update --init 21 | - export BUILDER_VERSION=$(cat .github/workflows/ci.yml | grep 'BUILDER_VERSION:' | sed 's/\s*BUILDER_VERSION:\s*\(.*\)/\1/') 22 | - export BUILDER_SOURCE=$(cat .github/workflows/ci.yml | grep 'BUILDER_SOURCE:' | sed 's/\s*BUILDER_SOURCE:\s*\(.*\)/\1/') 23 | - echo "Using builder version='${BUILDER_VERSION}' source='${BUILDER_SOURCE}'" 24 | # Build library and test 25 | - python3 -c "from urllib.request import urlretrieve; urlretrieve('$BUILDER_HOST/$BUILDER_SOURCE/$BUILDER_VERSION/builder.pyz?run=$CODEBUILD_BUILD_ID', 'builder.pyz')" 26 | - python3 builder.pyz build --project aws-crt-java downstream 27 | post_build: 28 | commands: 29 | - echo Build completed on `date` 30 | -------------------------------------------------------------------------------- /codebuild/macos_compatibility_check.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import subprocess 3 | import os 4 | import re 5 | 6 | 7 | def main(): 8 | if sys.platform != 'darwin': 9 | print("WARNING: Not running on macos. Skip the compatibility validation.") 10 | # Exit quietly if run on a non-darwin machine. 11 | sys.exit(0) 12 | 13 | # Default target macos version setup in pom.xml > ${cmake.min_osx_version} 14 | supported_version = "10.15" 15 | arch = "x86_64" 16 | 17 | if len(sys.argv) > 1: 18 | # Parsing the macos archtecture 19 | arch = sys.argv[1] 20 | else: 21 | # If the archtecture is not set, set from system call 22 | arch = os.uname().machine 23 | print("uname result {}".format(arch)) 24 | 25 | if re.match(r'^(aarch64|armv[6-8]|arm64)', arch): 26 | arch = "armv8" 27 | # The oldest version we can target on arm64 is 11.0 28 | supported_version = "11.0" 29 | 30 | # otool result has a different format between arm and x64 31 | # for arm: we check for "minos" 32 | # for x64: The format will be: 33 | # 34 | # Load command 8 35 | # cmd LC_VERSION_MIN_MACOSX 36 | # cmdsize 16 37 | # version 10.15 38 | # sdk 12.1 39 | # Load command 9 40 | otool_cmd = """ 41 | otool -l target/cmake-build/lib/osx/{}/cruntime/libaws-crt-jni.dylib | 42 | grep -A5 -E 'LC_VERSION_MIN_MACOSX|LC_BUILD_VERSION' | 43 | grep -E '(version|minos)' | 44 | head -1 | 45 | tr -s ' ' | 46 | cut -f3 -d' ' | 47 | tr -d '[:space:]' 48 | """.format(arch) 49 | 50 | print("Start to validate the build binary for MacOS with architecture {}, expected min os version: {}".format(arch,supported_version)) 51 | result = subprocess.check_output(otool_cmd, shell=True).decode("utf-8") 52 | 53 | if result != supported_version: 54 | # Failed 55 | print("Failed the compatibility validation on MacOS architecture {}, expected '{}' and built '{}'".format(arch, supported_version, result)) 56 | sys.exit(1) 57 | 58 | print("Pass the compatibility validation on MacOS architecture {} with min supported os version '{}'".format(arch,result)) 59 | sys.exit(0) 60 | 61 | if __name__ == "__main__": 62 | main() 63 | 64 | -------------------------------------------------------------------------------- /codebuild/mqtt5-java-canary-test.yml: -------------------------------------------------------------------------------- 1 | version: 0.2 2 | env: 3 | shell: bash 4 | variables: 5 | CANARY_DURATION: 25200 6 | CANARY_THREADS: 3 7 | CANARY_TPS: 50 8 | CANARY_CLIENT_COUNT: 10 9 | CANARY_LOG_FILE: 'canary_log.txt' 10 | CANARY_LOG_LEVEL: 'Error' 11 | PACKAGE_NAME: 'aws-crt-java' 12 | CANARY_SERVER_ARN: Mqtt5MosquittoSever 13 | CANARY_BUILD_S3_DST: mqtt5-canary/s3 14 | CODEBUILD_TICKET_ITEM: "IoT SDK for Java" 15 | phases: 16 | install: 17 | commands: 18 | - add-apt-repository ppa:openjdk-r/ppa 19 | - add-apt-repository ppa:ubuntu-toolchain-r/test 20 | - apt-get update -y 21 | - sudo apt-get install cmake -y 22 | - git submodule update --init --recursive 23 | # Install necessary lib for canary wrapper 24 | - sudo apt-get install gcc python3-dev -y -f 25 | - sudo apt-get install pip -y -f 26 | - python3 -m pip install psutil 27 | - python3 -m pip install boto3 28 | build: 29 | commands: 30 | - echo Build started on `date` 31 | - mvn install -DskipTests 32 | # Get secrets needed 33 | - export S3_DST=$(aws secretsmanager get-secret-value --secret-id "$CANARY_BUILD_S3_DST" --query "SecretString" | cut -f2,3 -d":" | sed -e 's/[\\\"\}]//g') 34 | - export GIT_HASH=$(git rev-parse HEAD) 35 | # Get the endpoint, certificate, and key for connecting to IoT Core 36 | - export ENDPOINT=$(aws secretsmanager get-secret-value --secret-id ${CANARY_SERVER_ARN} --query "SecretString" | cut -f2 -d":" | sed -e 's/[\\\"\}]//g') 37 | # Run the Canary 38 | - cd ./utils/Canary 39 | - python3 ../../codebuild/CanaryWrapper.py --canary_executable mvn --canary_arguments "compile exec:java -Dexec.mainClass=canary.mqtt5.Mqtt5Canary -Dexec.args=\"--endpoint \"${ENDPOINT}\" --port 1883 --seconds ${CANARY_DURATION} --threads ${CANARY_THREADS} --tps ${CANARY_TPS} --clients ${CANARY_CLIENT_COUNT}\" -Daws.crt.debugnative=true -Daws.crt.log.destination=Stdout -Daws.crt.log.level=${CANARY_LOG_LEVEL}" --git_hash ${GIT_HASH} --git_repo_name $PACKAGE_NAME --codebuild_log_path $CODEBUILD_LOG_PATH --ticket_item "${CODEBUILD_TICKET_ITEM}" 40 | post_build: 41 | commands: 42 | - echo Build completed on `date` 43 | -------------------------------------------------------------------------------- /codebuild/test-aws-java-sdk-v2.yml: -------------------------------------------------------------------------------- 1 | version: 0.2 2 | #this build spec assumes the ubuntu aws/codebuild/java:openjdk-8 image 3 | phases: 4 | install: 5 | runtime-versions: 6 | java: "corretto8" 7 | commands: 8 | - add-apt-repository ppa:openjdk-r/ppa 9 | - add-apt-repository ppa:ubuntu-toolchain-r/test 10 | - apt-get update -y 11 | - apt-get install gcc-7 cmake ninja-build -y 12 | - git submodule update --init --recursive 13 | - git clone https://github.com/aws/aws-sdk-java-v2.git 14 | # change the version from SDK to local SNAPSHOT version 15 | - sed -i 's/.*<\/awscrt.version>/1.0.0-SNAPSHOT<\/awscrt.version>/g' aws-sdk-java-v2/pom.xml 16 | # check if it works 17 | - cat aws-sdk-java-v2/pom.xml | grep -E '.*' 18 | pre_build: 19 | commands: 20 | - export CC=gcc-7 21 | build: 22 | commands: 23 | - echo Build started on `date` 24 | - mvn install -DskipTests 25 | - cd aws-sdk-java-v2/ 26 | - mvn clean install -P crt-tests 27 | post_build: 28 | commands: 29 | - echo Build completed on `date` 30 | 31 | artifacts: 32 | discard-paths: yes 33 | files: 34 | - "target/surefire-reports/**" 35 | - "hs_err_pid*" 36 | - "core*" 37 | -------------------------------------------------------------------------------- /dockcross-build.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Examples: 4 | # ./dockcross-build.sh build -p aws-crt-java --target=linux-armv6 5 | # ./dockcross-build.sh build -p aws-crt-java --target=linux-armv7 6 | # ./dockcross-build.sh build -p aws-crt-java --target=linux-aarch64 7 | 8 | set -ex 9 | 10 | args=("$@") 11 | 12 | version=LATEST 13 | if [[ "${args[0]}" == "--version="* ]]; then 14 | version=${args[0]} 15 | version=$(echo $version | cut -f2 -d=) 16 | args=${args[@]:1} 17 | fi 18 | 19 | if [ $(echo $version | grep -E '^v[0-9\.]+$') ]; then 20 | version=releases/$version 21 | elif [[ $version != 'channels/'* ]] && [[ $version != 'LATEST' ]]; then 22 | version=channels/$version 23 | fi 24 | 25 | # download the version of builder requested 26 | builder=/tmp/builder.pyz 27 | curl -sSL -o $builder --retry 3 https://d19elf31gohf1l.cloudfront.net/${version}/builder.pyz?date=`date +%s` 28 | chmod a+x $builder 29 | 30 | # on manylinux, use the latest python3 via symlink 31 | if [ -x /opt/python/cp39-cp39/bin/python ] && [ ! -e /usr/local/bin/python3 ]; then 32 | ln -s /opt/python/cp39-cp39/bin/python /usr/local/bin/python3 33 | fi 34 | 35 | # Launch the builder with whatever args were passed to this script 36 | $builder ${args[@]} 37 | -------------------------------------------------------------------------------- /format-check.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | import argparse 3 | import os 4 | from pathlib import Path 5 | import re 6 | from subprocess import list2cmdline, run 7 | from tempfile import NamedTemporaryFile 8 | 9 | CLANG_FORMAT_VERSION = '18.1.6' 10 | 11 | INCLUDE_REGEX = re.compile(r'^src/native/.*\.(c|h|inl)$') 12 | EXCLUDE_REGEX = re.compile(r'^$') 13 | 14 | arg_parser = argparse.ArgumentParser(description="Check with clang-format") 15 | arg_parser.add_argument('-i', '--inplace-edit', action='store_true', 16 | help="Edit files inplace") 17 | args = arg_parser.parse_args() 18 | 19 | os.chdir(Path(__file__).parent) 20 | 21 | # create file containing list of all files to format 22 | filepaths_file = NamedTemporaryFile(delete=False) 23 | for dirpath, dirnames, filenames in os.walk('.'): 24 | for filename in filenames: 25 | # our regexes expect filepath to use forward slash 26 | filepath = Path(dirpath, filename).as_posix() 27 | if not INCLUDE_REGEX.match(filepath): 28 | continue 29 | if EXCLUDE_REGEX.match(filepath): 30 | continue 31 | 32 | filepaths_file.write(f"{filepath}\n".encode()) 33 | filepaths_file.close() 34 | 35 | # use pipx to run clang-format from PyPI 36 | # this is a simple way to run the same clang-format version regardless of OS 37 | cmd = ['pipx', 'run', f'clang-format=={CLANG_FORMAT_VERSION}', 38 | f'--files={filepaths_file.name}'] 39 | if args.inplace_edit: 40 | cmd += ['-i'] 41 | else: 42 | cmd += ['--Werror', '--dry-run'] 43 | 44 | print(f"{Path.cwd()}$ {list2cmdline(cmd)}") 45 | if run(cmd).returncode: 46 | exit(1) 47 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awslabs/aws-crt-java/479239ddb6bae42530f929e9da6fe566a28e7964/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Wed Oct 16 16:47:56 PDT 2024 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-bin.zip 5 | zipStoreBase=GRADLE_USER_HOME 6 | zipStorePath=wrapper/dists 7 | -------------------------------------------------------------------------------- /integration-testing/java_elasticurl_runner.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | import subprocess 4 | import shlex 5 | 6 | TIMEOUT = 300 7 | # Runner for elasticurl integration tests 8 | 9 | mvn_args = " ".join(map(shlex.quote, sys.argv[1:])) 10 | 11 | java_command = ['mvn', '-e', 'exec:java', '-Dexec.classpathScope=\"test\"', 12 | '-Dexec.mainClass=\"software.amazon.awssdk.crt.test.Elasticurl\"', '-Dexec.args=\"{}\"'.format(mvn_args), 13 | '-Daws.crt.log.level=Trace'] 14 | 15 | if os.name == 'nt': 16 | # Windows uses mvn.cmd instead 17 | java_command[0] = 'mvn.cmd' 18 | command_string = " ".join(java_command) 19 | 20 | 21 | def run_command(args_str): 22 | print(args_str) 23 | # gather all stderr and stdout to a single string that we print only if things go wrong 24 | process = subprocess.Popen( 25 | args_str, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) 26 | timedout = False 27 | try: 28 | output = process.communicate(timeout=TIMEOUT)[0] 29 | except subprocess.TimeoutExpired: 30 | timedout = True 31 | process.kill() 32 | output = process.communicate()[0] 33 | finally: 34 | if process.returncode != 0 or timedout: 35 | for line in output.splitlines(): 36 | print(line.decode()) 37 | if timedout: 38 | raise RuntimeError("Timeout happened after {secs} secs from: {cmd}".format( 39 | secs=TIMEOUT, cmd=args_str)) 40 | else: 41 | raise RuntimeError("Return code {code} from: {cmd}".format( 42 | code=process.returncode, cmd=args_str)) 43 | 44 | 45 | run_command(command_string) 46 | -------------------------------------------------------------------------------- /make-docs.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e 4 | 5 | pushd $(dirname $0) > /dev/null 6 | 7 | # clean 8 | rm -rf docs/ 9 | 10 | # build 11 | mvn javadoc:javadoc -Dmaven.javadoc.failOnWarnings=true 12 | 13 | # copy to docs/ 14 | cp -r target/site/apidocs/ docs/ 15 | 16 | popd > /dev/null 17 | -------------------------------------------------------------------------------- /samples/CustomKeyOps/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 4.0.0 6 | 7 | com.example.customkeyops 8 | customkeyops 9 | 1.0-SNAPSHOT 10 | 11 | 12 | UTF-8 13 | 1.8 14 | 1.8 15 | 16 | 17 | 18 | 19 | software.amazon.awssdk.crt 20 | aws-crt 21 | 1.0.0-SNAPSHOT 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /samples/mqtt5/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 4.0.0 6 | 7 | com.example.mqtt5 8 | mqtt5 9 | 1.0.0-SNAPSHOT 10 | 11 | 12 | UTF-8 13 | 1.8 14 | 1.8 15 | 16 | 17 | 18 | 19 | software.amazon.awssdk.crt 20 | aws-crt 21 | 1.0.0-SNAPSHOT 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /samples/s3/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 4.0.0 6 | 7 | com.example.s3 8 | s3 9 | 1.0-SNAPSHOT 10 | 11 | 12 | UTF-8 13 | 1.8 14 | 1.8 15 | 16 | 17 | 18 | 19 | software.amazon.awssdk.crt 20 | aws-crt 21 | 0.10.2 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | /* 2 | * This file was generated by the Gradle 'init' task. 3 | */ 4 | 5 | rootProject.name = "aws-crt" 6 | 7 | include(":native") 8 | project(":native").projectDir = File("${settingsDir}/src/native") 9 | 10 | 11 | val localPropertiesFile = File(rootProject.projectDir, "local.properties") 12 | val localProperties = java.util.Properties() 13 | if (localPropertiesFile.exists()) { 14 | localProperties.load(localPropertiesFile.inputStream()) 15 | } 16 | 17 | val androidHomeSet = System.getenv().containsKey("ANDROID_HOME") || localProperties.containsKey("sdk.dir") 18 | if (androidHomeSet) { 19 | val androidHome = System.getenv()["ANDROID_HOME"] ?: localProperties.getProperty("sdk.dir") 20 | println("Android home: $androidHome") 21 | includeBuild("./android") 22 | }else { 23 | logger.warn("Android SDK dir not set, android build disabled. Define location with `sdk.dir` in local.properties file or with `ANDROID_HOME` environment variable ") 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/AsyncCallback.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | package software.amazon.awssdk.crt; 7 | 8 | import java.util.concurrent.CompletableFuture; 9 | 10 | /** 11 | * Async io completion abstraction used by the native mqtt layer. We moved to using futures directly but 12 | * that might have been a mistake and we should consider moving back to this for our other async 13 | * operations that cross the managed/native boundary 14 | */ 15 | public interface AsyncCallback { 16 | 17 | static AsyncCallback wrapFuture(CompletableFuture future, T value) { 18 | return new AsyncCallback() { 19 | @Override 20 | public void onSuccess() { 21 | future.complete(value); 22 | } 23 | 24 | @Override 25 | @SuppressWarnings("unchecked") 26 | public void onSuccess(Object val) { 27 | future.complete((T)(val)); 28 | } 29 | 30 | @Override 31 | public void onFailure(Throwable reason) { 32 | future.completeExceptionally(reason); 33 | } 34 | }; 35 | } 36 | 37 | void onSuccess(); 38 | void onSuccess(Object value); 39 | void onFailure(Throwable reason); 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/CrtPlatform.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | package software.amazon.awssdk.crt; 7 | 8 | import software.amazon.awssdk.crt.utils.PackageInfo; 9 | 10 | public abstract class CrtPlatform { 11 | // Called before any native code is loaded, just to configure the JVM 12 | public void jvmInit() {} 13 | 14 | // Gets the package version. If not overridden, the Java Package that the 15 | // CRT class is in will be read for version info. 16 | public PackageInfo.Version getVersion() { 17 | return null; 18 | } 19 | 20 | // Get the OS identifier, used to determine platform and to load the 21 | // JNI library 22 | public String getOSIdentifier() { 23 | return System.getProperty("os.name"); 24 | } 25 | 26 | // Get the architecture, used to determine platform and to load the 27 | // JNI library 28 | public String getArchIdentifier() { 29 | return System.getProperty("os.arch"); 30 | } 31 | 32 | // Get the library resource path to load the JNI library 33 | public String getResourcePath(String cRuntime, String libraryName) throws RuntimeException { 34 | return null; 35 | } 36 | 37 | // Called one and only one time during setup for testing 38 | public void setupOnce() {} 39 | 40 | // Called before every JUnit test 41 | public void testSetup(Object context) {} 42 | 43 | // Called after every JUnit test 44 | public void testTearDown(Object context) {} 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/SystemInfo.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | package software.amazon.awssdk.crt; 7 | 8 | /** 9 | * Utility class for querying system hardware properties 10 | */ 11 | public class SystemInfo { 12 | 13 | /** 14 | * @return active count of processors configured on this system. 15 | */ 16 | public static int getProcessorCount() { 17 | return processorCount(); 18 | } 19 | 20 | /** 21 | * @return number of active Cpu groupings on this system. This currently refers to NUMA nodes. 22 | */ 23 | public static short getCpuGroupCount() { 24 | return cpuGroupCount(); 25 | } 26 | 27 | /** 28 | * Get info on all active Cpus in a Cpu group. 29 | * @param groupIdx group index to query. 30 | * @return Array of CpuInfo objects configured for this group. This value is never null even if groupIdx was invalid. 31 | */ 32 | public static CpuInfo[] getCpuInfoForGroup(short groupIdx) { 33 | return cpuInfoForGroup(groupIdx); 34 | } 35 | 36 | public static class CpuInfo { 37 | /** 38 | * OS CpuId that can be used for pinning a thread to a specific Cpu 39 | */ 40 | public final int cpuId; 41 | /** 42 | * If true, the Cpu is suspected of being virtual. If false, it's likely a hw core. 43 | */ 44 | public final boolean isSuspectedHyperThread; 45 | 46 | private CpuInfo(int cpuId, boolean isSuspectedHyperThread) { 47 | this.cpuId = cpuId; 48 | this.isSuspectedHyperThread = isSuspectedHyperThread; 49 | } 50 | } 51 | 52 | /* native functions */ 53 | private static native int processorCount(); 54 | private static native short cpuGroupCount(); 55 | private static native CpuInfo[] cpuInfoForGroup(short groupIdx); 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/auth/credentials/DelegateCredentialsHandler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | package software.amazon.awssdk.crt.auth.credentials; 7 | 8 | /** 9 | * Interface that synchronously provides custom credentials. 10 | */ 11 | public interface DelegateCredentialsHandler { 12 | 13 | /** 14 | * Called from Native when delegate credential provider needs to fetch a 15 | * credential. 16 | * @return Credentials 17 | */ 18 | Credentials getCredentials(); 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/auth/credentials/DelegateCredentialsProvider.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | package software.amazon.awssdk.crt.auth.credentials; 7 | 8 | /** 9 | * A credentials provider that sources credentials from a custom synchronous 10 | * callback 11 | */ 12 | public class DelegateCredentialsProvider extends CredentialsProvider { 13 | 14 | /** 15 | * A simple builder class for a delegate credentials provider and its options 16 | */ 17 | static public class DelegateCredentialsProviderBuilder { 18 | 19 | private DelegateCredentialsHandler handler; 20 | 21 | /** 22 | * Default constructor 23 | */ 24 | public DelegateCredentialsProviderBuilder() { 25 | } 26 | 27 | /** 28 | * Sets the delegate this provider should use for sourcing credentials 29 | * @param handler credentials-sourcing delegate 30 | * @return this builder object 31 | */ 32 | public DelegateCredentialsProviderBuilder withHandler(DelegateCredentialsHandler handler) { 33 | this.handler = handler; 34 | 35 | return this; 36 | } 37 | 38 | DelegateCredentialsHandler getHandler() { 39 | return handler; 40 | } 41 | 42 | /** 43 | * Builds a new delegate credentials provider using the builder's configuration 44 | * @return a new delegate credentials provider 45 | */ 46 | public DelegateCredentialsProvider build() { 47 | return new DelegateCredentialsProvider(this); 48 | } 49 | } 50 | 51 | private DelegateCredentialsProvider(DelegateCredentialsProviderBuilder builder) { 52 | super(); 53 | DelegateCredentialsHandler handler = builder.getHandler(); 54 | 55 | long nativeHandle = delegateCredentialsProviderNew(this, handler); 56 | acquireNativeHandle(nativeHandle); 57 | } 58 | 59 | /******************************************************************************* 60 | * Native methods 61 | ******************************************************************************/ 62 | 63 | private static native long delegateCredentialsProviderNew(DelegateCredentialsProvider thisObj, 64 | DelegateCredentialsHandler handler); 65 | 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/auth/signing/AwsSigningResult.java: -------------------------------------------------------------------------------- 1 | package software.amazon.awssdk.crt.auth.signing; 2 | 3 | import software.amazon.awssdk.crt.http.HttpRequest; 4 | 5 | /** 6 | * Wrapper that holds signing-related output. Depending on the signing configuration, not all members may be 7 | * assigned and some members, like signature, may have a variable format. 8 | */ 9 | public class AwsSigningResult { 10 | private HttpRequest signedRequest; 11 | private byte[] signature; 12 | 13 | /** 14 | * Default constructor 15 | */ 16 | public AwsSigningResult() {} 17 | 18 | /** 19 | * Gets the signed http request from the result 20 | * @return the signed http request, or NULL if an http request was not signed 21 | */ 22 | public HttpRequest getSignedRequest() { return signedRequest; } 23 | 24 | /** 25 | * Gets the signature value from the result. Depending on the requested signature type and algorithm, this value 26 | * will be in one of the following formats: 27 | * 28 | * (1) HTTP_REQUEST_VIA_HEADERS - hex encoding of the binary signature value 29 | * (2) HTTP_REQUEST_VIA_QUERY_PARAMS - hex encoding of the binary signature value 30 | * (3) HTTP_REQUEST_CHUNK/SIGV4 - hex encoding of the binary signature value 31 | * (4) HTTP_REQUEST_CHUNK/SIGV4_ASYMMETRIC - '*'-padded hex encoding of the binary signature value 32 | * (5) HTTP_REQUEST_EVENT - binary signature value (NYI) 33 | * 34 | * @return the signature value from the signing process 35 | */ 36 | public byte[] getSignature() { return signature; } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/auth/signing/AwsSigningUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2010-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"). 5 | * You may not use this file except in compliance with the License. 6 | * A copy of the License is located at 7 | * 8 | * http://aws.amazon.com/apache2.0 9 | * 10 | * or in the "license" file accompanying this file. This file is distributed 11 | * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either 12 | * express or implied. See the License for the specific language governing 13 | * permissions and limitations under the License. 14 | */ 15 | package software.amazon.awssdk.crt.auth.signing; 16 | 17 | import software.amazon.awssdk.crt.http.HttpRequest; 18 | 19 | /** 20 | * Internal utility/testing functions for verifying sigv4a signatures. 21 | */ 22 | public class AwsSigningUtils { 23 | 24 | public static boolean verifySigv4aEcdsaSignature(HttpRequest request, String expectedCanonicalRequest, AwsSigningConfig config, byte[] hexEncodedSignature, String verifierPubX, String verifierPubY) { 25 | return awsSigningUtilsVerifyEcdsaSignature(request, request.marshalForJni(), expectedCanonicalRequest, config, hexEncodedSignature, verifierPubX, verifierPubY); 26 | } 27 | 28 | public static boolean verifyRawSha256EcdsaSignature(byte[] stringToSign, byte[] hexEncodedSignature, String verifierPubX, String verifierPubY) { 29 | return awsSigningUtilsVerifyRawSha256EcdsaSignature(stringToSign, hexEncodedSignature, verifierPubX, verifierPubY); 30 | } 31 | 32 | /******************************************************************************* 33 | * native methods 34 | ******************************************************************************/ 35 | private static native boolean awsSigningUtilsVerifyEcdsaSignature( 36 | HttpRequest request, 37 | byte[] marshalledRequest, 38 | String expectedCanonicalRequest, 39 | AwsSigningConfig config, 40 | byte[] hexEncodedSignature, 41 | String verifierPubX, 42 | String verifiedPubY); 43 | 44 | private static native boolean awsSigningUtilsVerifyRawSha256EcdsaSignature( 45 | byte[] stringToSign, 46 | byte[] hexEncodedSignature, 47 | String verifierPubX, 48 | String verifiedPubY); 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/eventstream/HeaderType.java: -------------------------------------------------------------------------------- 1 | package software.amazon.awssdk.crt.eventstream; 2 | 3 | import software.amazon.awssdk.crt.CrtRuntimeException; 4 | 5 | /** 6 | * Java mirror of the native aws_event_stream_header_value_type enum, specifying properties of 7 | * the type of a header's value 8 | */ 9 | public enum HeaderType { 10 | BooleanTrue(0, 0,false), 11 | BooleanFalse(1, 0,false), 12 | Byte(2, 0,false), 13 | Int16(3, 0,false), 14 | Int32(4, 0,false), 15 | Int64(5, 0,false), 16 | ByteBuf(6, 2,true), 17 | String(7, 2,true), 18 | TimeStamp(8, 0,false), 19 | UUID(9, 0,false); 20 | 21 | private int intValue; 22 | private boolean isVariableLength; 23 | private int overhead; 24 | 25 | HeaderType(int intValue, int overhead, boolean isVariableLength) { 26 | this.intValue = intValue; 27 | this.overhead = overhead; 28 | this.isVariableLength = isVariableLength; 29 | } 30 | 31 | /** 32 | * 33 | * @return additional bytes needed to serialize the header's value, beyond the value's data itself 34 | */ 35 | public int getWireBytesOverhead() { 36 | return overhead; 37 | } 38 | 39 | /** 40 | * 41 | * @return the native integer value associated with this Java enum value 42 | */ 43 | public int getEnumIntValue() { 44 | return intValue; 45 | } 46 | 47 | /** 48 | * 49 | * @return true if encoding this type requires a variable number of bytes, false if a fixed number of bytes 50 | */ 51 | public boolean isVariableLength() { 52 | return isVariableLength; 53 | } 54 | 55 | /** 56 | * Creates a Java header type enum from an associated native integer value 57 | * @param intValue native integer value 58 | * @return a new Java header type value 59 | */ 60 | public static HeaderType getValueFromInt(int intValue) { 61 | for (HeaderType type : HeaderType.values()) { 62 | if (type.intValue == intValue) { 63 | return type; 64 | } 65 | } 66 | 67 | throw new CrtRuntimeException("Invalid event-stream header int value."); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/eventstream/Message.java: -------------------------------------------------------------------------------- 1 | package software.amazon.awssdk.crt.eventstream; 2 | 3 | import software.amazon.awssdk.crt.CrtResource; 4 | 5 | import java.nio.ByteBuffer; 6 | import java.util.List; 7 | 8 | /** 9 | * Wrapper around an instance of aws-event-stream-message. It's auto closable, so be sure 10 | * to call close when finished with the object. 11 | */ 12 | public class Message extends CrtResource { 13 | /** 14 | * Creates a message using headers and payload. 15 | * @param headers list of headers to include in the message's header block. Can be null. 16 | * @param payload payload body to include in the message's payload block. Can be null. 17 | */ 18 | public Message(List
headers, byte[] payload) { 19 | acquireNativeHandle(messageNew(Header.marshallHeadersForJNI(headers), payload)); 20 | } 21 | 22 | /** 23 | * Get the binary format of this message (i.e. for sending across the wire manually) 24 | * @return ByteBuffer wrapping the underlying message data. This buffer is only valid 25 | * as long as the message itself is valid. 26 | */ 27 | public ByteBuffer getMessageBuffer() { 28 | return messageBuffer(getNativeHandle()); 29 | } 30 | 31 | @Override 32 | protected void releaseNativeHandle() { 33 | if (!isNull()) { 34 | messageDelete(getNativeHandle()); 35 | } 36 | } 37 | 38 | @Override 39 | protected boolean canReleaseReferencesImmediately() { 40 | return true; 41 | } 42 | 43 | private static native long messageNew(byte[] serializedHeaders, byte[] payload); 44 | private static native void messageDelete(long messageHandle); 45 | private static native ByteBuffer messageBuffer(long messageHandle); 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/eventstream/MessageFlags.java: -------------------------------------------------------------------------------- 1 | package software.amazon.awssdk.crt.eventstream; 2 | 3 | /** 4 | * Java mirror of the native aws_event_stream_rpc_message_flag enum, specifying rpc message-related flags 5 | */ 6 | public enum MessageFlags { 7 | ConnectionAccepted(1), 8 | TerminateStream(2); 9 | 10 | private int byteValue; 11 | 12 | MessageFlags(int byteValue) { 13 | this.byteValue = byteValue; 14 | } 15 | 16 | /** 17 | * @return the native enum value associated with this Java enum value 18 | */ 19 | public int getByteValue() { 20 | return this.byteValue; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/eventstream/MessageFlushCallback.java: -------------------------------------------------------------------------------- 1 | package software.amazon.awssdk.crt.eventstream; 2 | 3 | /** 4 | * Functor interface for receiving message flush events. 5 | */ 6 | public interface MessageFlushCallback { 7 | /** 8 | * Invoked when a message has been flushed to the underlying transport mechanism. 9 | * @param errorCode If this is 0, the message was successfully written. Otherwise, 10 | * errorCode represents the reason the message flush failed. 11 | */ 12 | void onCallbackInvoked(int errorCode); 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/eventstream/MessageType.java: -------------------------------------------------------------------------------- 1 | package software.amazon.awssdk.crt.eventstream; 2 | 3 | /** 4 | * Java mirror of the native aws_event_stream_rpc_message_type enum, specifying the type of rpc message 5 | */ 6 | public enum MessageType { 7 | ApplicationMessage((byte)0), 8 | ApplicationError((byte)1), 9 | Ping((byte)2), 10 | PingResponse((byte)3), 11 | Connect((byte)4), 12 | ConnectAck((byte)5), 13 | ProtocolError((byte)6), 14 | ServerError((byte)7); 15 | 16 | private byte enumValue; 17 | 18 | MessageType(byte enumValue) { 19 | this.enumValue = enumValue; 20 | } 21 | 22 | /** 23 | * @return the native enum value associated with this Java enum value 24 | */ 25 | public byte getEnumValue() { 26 | return this.enumValue; 27 | } 28 | 29 | /** 30 | * Create a MessageType enum value from a native enum value 31 | * @param enumValue native enum value 32 | * @return a new MessageType enum value 33 | */ 34 | public static MessageType fromEnumValue(int enumValue) { 35 | for (MessageType type : MessageType.values()) { 36 | if (type.enumValue == enumValue) { 37 | return type; 38 | } 39 | } 40 | 41 | throw new IllegalArgumentException("Unknown MessageType enum value: " + enumValue); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/eventstream/ServerListenerHandler.java: -------------------------------------------------------------------------------- 1 | package software.amazon.awssdk.crt.eventstream; 2 | 3 | /** 4 | * Handler interface for processing incoming event-stream-rpc connections and their lifetimes. 5 | */ 6 | public abstract class ServerListenerHandler { 7 | /** 8 | * Invoked upon receiving a new connection, or if an error happened upon connection 9 | * creation. If errorCode is non-zero, onConnectionShutdown() will never be invoked. 10 | * 11 | * @param serverConnection The new server connection to use for communications. Is non-null 12 | * when errorCode is 0. 13 | * @param errorCode represents any error that occurred during connection establishment 14 | * @return Return an instance of ServerConnectionHandler, for processing connection specific events. 15 | */ 16 | protected abstract ServerConnectionHandler onNewConnection(final ServerConnection serverConnection, int errorCode); 17 | 18 | /** 19 | * Invoked upon connection shutdown. serverConnection will never be null. This function is 20 | * only invoked if onNewConnection() was invoked with a zero errorCode. 21 | * @param serverConnection connection the shutdown occurred on. 22 | * @param errorCode shutdown reason. 0 means clean shutdown. 23 | */ 24 | protected abstract void onConnectionShutdown(final ServerConnection serverConnection, int errorCode); 25 | 26 | /** 27 | * Invoked from JNI. Completes the closure future and invokes onConnectionShutdown() 28 | */ 29 | void onConnectionShutdownShim(final ServerConnection serverConnection, int errorCode) { 30 | onConnectionShutdown(serverConnection, errorCode); 31 | serverConnection.closedFuture.complete(errorCode); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/http/Http2Request.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | package software.amazon.awssdk.crt.http; 7 | 8 | import software.amazon.awssdk.crt.http.HttpVersion; 9 | 10 | /** 11 | * Represents a single Client Request to be sent on a HTTP connection 12 | */ 13 | public class Http2Request extends HttpRequestBase { 14 | /** 15 | * An empty HTTP/2 Request. 16 | */ 17 | public Http2Request() { 18 | this(new HttpHeader[] {}, null); 19 | } 20 | 21 | /** 22 | * An empty HTTP/2 Request with headers and body stream. 23 | * 24 | * @param headers set of http request headers to include, note: pseudo 25 | * headers should be set to make a good HTTP/2 request. 26 | * @param bodyStream (optional) interface to an object that will stream out the 27 | * request body 28 | */ 29 | public Http2Request(HttpHeader[] headers, HttpRequestBodyStream bodyStream) { 30 | super(headers, bodyStream); 31 | this.version = HttpVersion.HTTP_2; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/http/Http2Stream.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | package software.amazon.awssdk.crt.http; 7 | 8 | import software.amazon.awssdk.crt.CrtRuntimeException; 9 | 10 | import java.util.concurrent.CompletableFuture; 11 | 12 | /** 13 | * An HttpStream represents a single HTTP/2 specific Http Request/Response. 14 | */ 15 | public class Http2Stream extends HttpStreamBase { 16 | 17 | protected Http2Stream(long ptr) { 18 | super(ptr); 19 | } 20 | 21 | /** 22 | * Reset the HTTP/2 stream. Note that if the stream closes before this async 23 | * call is fully processed, the RST_STREAM frame will not be sent. 24 | * 25 | * @param errorCode aws_http2_error_code. Reason to reset the stream. 26 | */ 27 | public void resetStream(final Http2ClientConnection.Http2ErrorCode errorCode) { 28 | if (isNull()) { 29 | throw new IllegalStateException("Http2Stream has been closed."); 30 | } 31 | http2StreamResetStream(getNativeHandle(), errorCode.getValue()); 32 | } 33 | 34 | /** 35 | * TODO: getters for reset stream. Not sure anyone needs it though. 36 | */ 37 | private static native void http2StreamResetStream(long http_stream, int errorCode); 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/http/HttpException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | package software.amazon.awssdk.crt.http; 7 | 8 | import software.amazon.awssdk.crt.CRT; 9 | 10 | /** 11 | * This exception will be thrown by any exceptional cases encountered within the 12 | * JNI bindings to the AWS Common Runtime 13 | */ 14 | public class HttpException extends RuntimeException { 15 | private final int errorCode; 16 | 17 | /** 18 | * Constructs a new HttpException 19 | * @param errorCode native error code representing the error source/reason 20 | */ 21 | public HttpException(int errorCode) { 22 | super(CRT.awsErrorString(errorCode)); 23 | this.errorCode = errorCode; 24 | } 25 | 26 | /** 27 | * Returns the error code captured when the exception occurred. This can be fed to CRT.awsErrorString() to 28 | * get a user-friendly error string 29 | * @return The error code associated with this exception 30 | */ 31 | public int getErrorCode() { 32 | return errorCode; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/http/HttpHeaderBlock.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | package software.amazon.awssdk.crt.http; 7 | 8 | /** 9 | * Type of header block. Syncs with the native enum aws_http_header_block 10 | */ 11 | public enum HttpHeaderBlock { 12 | 13 | MAIN(0), 14 | 15 | INFORMATIONAL(1), 16 | 17 | TRAILING(2); 18 | 19 | private int blockType; 20 | 21 | HttpHeaderBlock(int value) { 22 | blockType = value; 23 | } 24 | 25 | /** 26 | * @return the native enum value associated with this Java enum value 27 | */ 28 | public int getValue() { 29 | return blockType; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/http/HttpManagerMetrics.java: -------------------------------------------------------------------------------- 1 | package software.amazon.awssdk.crt.http; 2 | 3 | public class HttpManagerMetrics { 4 | private final long availableConcurrency; 5 | private final long pendingConcurrencyAcquires; 6 | private final long leasedConcurrency; 7 | 8 | HttpManagerMetrics(long availableConcurrency, long pendingConcurrencyAcquires, long leasedConcurrency) { 9 | this.availableConcurrency = availableConcurrency; 10 | this.pendingConcurrencyAcquires = pendingConcurrencyAcquires; 11 | this.leasedConcurrency = leasedConcurrency; 12 | } 13 | 14 | /** 15 | * @return The number of additional concurrent requests that can be supported by the HTTP manager without needing to 16 | * establish additional connections to the target server. 17 | *

18 | * For connection manager, this value represents idle connections. 19 | * For stream manager, this value represents the number of streams that are possible to be made without creating new 20 | * connections, although the implementation can create new connection without fully filling it. 21 | */ 22 | public long getAvailableConcurrency() { 23 | return availableConcurrency; 24 | } 25 | 26 | /** 27 | * @return The number of requests that are awaiting concurrency to be made available from the HTTP manager. 28 | */ 29 | public long getPendingConcurrencyAcquires() { 30 | return pendingConcurrencyAcquires; 31 | } 32 | 33 | /** 34 | * @return the amount of concurrency units currently out for lease. For http 1.1 this will be connections while 35 | * for http2 this will be number of streams leased out. 36 | */ 37 | public long getLeasedConcurrency() { 38 | return this.leasedConcurrency; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/http/HttpRequestBodyStream.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | package software.amazon.awssdk.crt.http; 7 | 8 | import java.nio.ByteBuffer; 9 | 10 | /** 11 | * Interface that Native code knows how to call when handling Http Request bodies 12 | * 13 | */ 14 | public interface HttpRequestBodyStream { 15 | 16 | 17 | /** 18 | * Called from Native when the Http Request has a Body (Eg PUT/POST requests). 19 | * Note that this function may be called many times as Native sends the Request Body. 20 | * 21 | * Do NOT keep a reference to this ByteBuffer past the lifetime of this function call. The CommonRuntime reserves 22 | * the right to use DirectByteBuffers pointing to memory that only lives as long as the function call. 23 | * 24 | * @param bodyBytesOut The Buffer to write the Request Body Bytes to. 25 | * @return True if Request body is complete, false otherwise. 26 | */ 27 | default boolean sendRequestBody(ByteBuffer bodyBytesOut) { 28 | /* Optional Callback, return empty request body by default unless user wants to return one. */ 29 | return true; 30 | } 31 | 32 | /** 33 | * Called from native when the processing needs the stream to rewind itself back to its beginning. 34 | * If the stream does not support rewinding or the rewind fails, false should be returned 35 | * 36 | * Signing requires a rewindable stream, but basic http does not. 37 | * 38 | * @return True if the stream was successfully rewound, false otherwise. 39 | */ 40 | default boolean resetPosition() { return false; } 41 | 42 | /** 43 | * Called from native when the processing needs to know the length of the stream. 44 | * If the stream does not know/support length, 0 should be returned. 45 | * 46 | * Signing requires a rewindable stream, but basic http does not. 47 | * 48 | * @return Stream length, or 0 if unknown stream or length is unsupported 49 | */ 50 | default long getLength() { return 0; } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/http/HttpVersion.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | package software.amazon.awssdk.crt.http; 7 | 8 | import java.util.Map; 9 | import java.util.HashMap; 10 | 11 | public enum HttpVersion { 12 | 13 | UNKNOWN(0), 14 | HTTP_1_0(1), 15 | HTTP_1_1(2), 16 | HTTP_2(3); 17 | 18 | private int value; 19 | private static Map enumMapping = buildEnumMapping(); 20 | 21 | HttpVersion(int value) { 22 | this.value = value; 23 | } 24 | 25 | public static HttpVersion getEnumValueFromInteger(int value) { 26 | HttpVersion enumValue = enumMapping.get(value); 27 | if (enumValue != null) { 28 | return enumValue; 29 | } 30 | 31 | throw new RuntimeException("Illegal signature type value in signing configuration"); 32 | } 33 | 34 | private static Map buildEnumMapping() { 35 | Map enumMapping = new HashMap(); 36 | enumMapping.put(UNKNOWN.getValue(), UNKNOWN); 37 | enumMapping.put(HTTP_1_0.getValue(), HTTP_1_0); 38 | enumMapping.put(HTTP_1_1.getValue(), HTTP_1_1); 39 | enumMapping.put(HTTP_2.getValue(), HTTP_2); 40 | 41 | return enumMapping; 42 | } 43 | 44 | public int getValue() { 45 | return value; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/internal/GraalVMNativeFeature.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | package software.amazon.awssdk.crt.internal; 6 | 7 | import org.graalvm.nativeimage.hosted.Feature; 8 | 9 | import software.amazon.awssdk.crt.CRT; 10 | 11 | /** 12 | * Implementation of GraalVM feature to extract the share lib to the image path. 13 | * From GraalVM docs: 14 | * > When loading native libraries using System.loadLibrary() (and related APIs), 15 | * > the native image will search the directory containing the native image before searching the Java library path 16 | * https://www.graalvm.org/latest/reference-manual/native-image/dynamic-features/JNI/#loading-native-libraries 17 | * Internal API, not for external usage. 18 | */ 19 | public class GraalVMNativeFeature implements Feature { 20 | 21 | @Override 22 | public void afterImageWrite(AfterImageWriteAccess access) { 23 | new CRT(); 24 | ExtractLib.extractLibrary(access.getImagePath().getParent().toString()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/io/ClientTlsContext.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | package software.amazon.awssdk.crt.io; 6 | 7 | import software.amazon.awssdk.crt.CrtRuntimeException; 8 | 9 | /** 10 | * This class wraps the aws_tls_context from aws-c-io to provide access to TLS 11 | * configuration contexts in the AWS Common Runtime. 12 | */ 13 | public final class ClientTlsContext extends TlsContext { 14 | 15 | /** 16 | * Creates a new Client TlsContext. There are significant native resources 17 | * consumed to create a TlsContext, so most applications will only need to 18 | * create one and re-use it for all connections. 19 | * 20 | * @param options A set of options for this context 21 | * @throws CrtRuntimeException If the provided options are malformed or the 22 | * system is unable to allocate space for a native 23 | * tls context 24 | */ 25 | public ClientTlsContext(TlsContextOptions options) throws CrtRuntimeException { 26 | super(options); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/io/DirectoryTraversal.java: -------------------------------------------------------------------------------- 1 | package software.amazon.awssdk.crt.io; 2 | 3 | /** 4 | * This class wraps the directory traversal implementation provided by the CRT. 5 | * 6 | * @deprecated It is currently an EXPERIMENTAL feature meant for internal use only. It may be changed incompatibly 7 | * or removed in a future version. 8 | */ 9 | @Deprecated() 10 | public final class DirectoryTraversal { 11 | 12 | /** 13 | * Traverse a directory starting at the path provided. 14 | * If you want the traversal to recurse the entire directory, pass recursive as true. Passing false for this parameter 15 | * will only iterate the contents of the directory, but will not descend into any directories it encounters. 16 | * 17 | * If recursive is set to true, the traversal is performed post-order, depth-first 18 | * (for practical reasons such as deleting a directory that contains subdirectories or files). 19 | * 20 | * The traversal iteration can be cancelled by the user by returning false from the callback. If the 21 | * traversal is cancelled either returning false from the callback or an unhandled exception is thrown 22 | * from the callback, the traverse method will throw a RuntimeException to notify user about incomplete 23 | * results. 24 | * 25 | * @param path directory to traverse. 26 | * @param recursive true to recurse the entire directory, false will only iterate the path specified 27 | * @param handler callback to invoke for each file or directory found during the traversal. 28 | */ 29 | public static void traverse(final String path, boolean recursive, final DirectoryTraversalHandler handler) { 30 | if (path == null) { 31 | throw new IllegalArgumentException("path must not be null"); 32 | } 33 | if (handler == null) { 34 | throw new IllegalArgumentException("handler must not be null"); 35 | } 36 | 37 | crtTraverse(path, recursive, handler); 38 | } 39 | 40 | private static native void crtTraverse(final String path, boolean recursive, final DirectoryTraversalHandler handler); 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/io/DirectoryTraversalHandler.java: -------------------------------------------------------------------------------- 1 | package software.amazon.awssdk.crt.io; 2 | 3 | /** 4 | * Handler invoked during calls to DirectoryTraversal.traverse() as each entry is encountered. 5 | */ 6 | public interface DirectoryTraversalHandler { 7 | 8 | /** 9 | * Invoked during calls to DirectoryTraversal.traverse() as each entry is encountered. 10 | * 11 | * @param directoryEntry Information about the directory entry encountered 12 | * @return true to continue the traversal, or false to abort it 13 | */ 14 | boolean onDirectoryEntry(final DirectoryEntry directoryEntry); 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/io/ServerBootstrap.java: -------------------------------------------------------------------------------- 1 | package software.amazon.awssdk.crt.io; 2 | 3 | import software.amazon.awssdk.crt.CrtResource; 4 | import software.amazon.awssdk.crt.CrtRuntimeException; 5 | 6 | /** 7 | * This class wraps the aws_server_bootstrap from aws-c-io to provide 8 | * a server context for all protocol stacks in the AWS Common Runtime. 9 | */ 10 | public class ServerBootstrap extends CrtResource { 11 | private EventLoopGroup eventLoopGroup = null; 12 | 13 | /** 14 | * @param elg event loop group to map server connections into 15 | */ 16 | public ServerBootstrap(final EventLoopGroup elg) { 17 | eventLoopGroup = elg; 18 | acquireNativeHandle(serverBootstrapNew(this, eventLoopGroup.getNativeHandle())); 19 | addReferenceTo(eventLoopGroup); 20 | } 21 | 22 | @Override 23 | protected void releaseNativeHandle() { 24 | if (!isNull()) { 25 | serverBootstrapDestroy(getNativeHandle()); 26 | removeReferenceTo(eventLoopGroup); 27 | } 28 | } 29 | 30 | @Override 31 | protected boolean canReleaseReferencesImmediately() { 32 | return false; 33 | } 34 | 35 | private static native long serverBootstrapNew(ServerBootstrap bootstrap, long elg) throws CrtRuntimeException; 36 | private static native void serverBootstrapDestroy(long bootstrap); 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/io/ServerTlsContext.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | package software.amazon.awssdk.crt.io; 6 | 7 | import software.amazon.awssdk.crt.CrtRuntimeException; 8 | 9 | /** 10 | * This class wraps the aws_tls_context from aws-c-io to provide access to TLS 11 | * configuration contexts in the AWS Common Runtime. 12 | */ 13 | public final class ServerTlsContext extends TlsContext { 14 | 15 | /** 16 | * Creates a new Server TlsContext. There are significant native resources 17 | * consumed to create a TlsContext, so most applications will only need to 18 | * create one and re-use it for all connections. 19 | * 20 | * @param options A set of options for this context 21 | * @throws CrtRuntimeException If the provided options are malformed or the 22 | * system is unable to allocate space for a native 23 | * tls context 24 | */ 25 | public ServerTlsContext(TlsContextOptions options) throws CrtRuntimeException { 26 | super(options); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/io/StandardRetryOptions.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | package software.amazon.awssdk.crt.io; 7 | 8 | /** 9 | * Top-level configuration for http retries. 10 | */ 11 | public class StandardRetryOptions { 12 | 13 | private ExponentialBackoffRetryOptions backoffRetryOptions; 14 | private long initialBucketCapacity; 15 | 16 | /** 17 | * Sets the exponential backoff configuration 18 | * @param backoffRetryOptions exponential backoff configuration 19 | * @return this options object 20 | */ 21 | public StandardRetryOptions withBackoffRetryOptions(ExponentialBackoffRetryOptions backoffRetryOptions) { 22 | this.backoffRetryOptions = backoffRetryOptions; 23 | return this; 24 | } 25 | 26 | /** 27 | * @return current exponential backoff retry options 28 | */ 29 | public ExponentialBackoffRetryOptions getBackoffRetryOptions() { 30 | return this.backoffRetryOptions; 31 | } 32 | 33 | /** 34 | * Sets the initial capacity of the token bucket in the standard retry strategy 35 | * @param initialBucketCapacity initial token bucket capacity 36 | * @return this options object 37 | */ 38 | public StandardRetryOptions withInitialBucketCapacity(long initialBucketCapacity) { 39 | this.initialBucketCapacity = initialBucketCapacity; 40 | return this; 41 | } 42 | 43 | /** 44 | * @return current initial bucket capacity 45 | */ 46 | public long getInitialBucketCapacity() { 47 | return this.initialBucketCapacity; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/io/TlsContext.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | package software.amazon.awssdk.crt.io; 6 | 7 | import software.amazon.awssdk.crt.CrtResource; 8 | import software.amazon.awssdk.crt.CrtRuntimeException; 9 | 10 | /** 11 | * This class wraps the aws_tls_context from aws-c-io to provide 12 | * access to TLS configuration contexts in the AWS Common Runtime. 13 | */ 14 | public class TlsContext extends CrtResource { 15 | 16 | /** 17 | * Creates a new Client TlsContext. There are significant native resources consumed to create a TlsContext, so most 18 | * applications will only need to create one and re-use it for all connections. 19 | * @param options A set of options for this context 20 | * @throws CrtRuntimeException If the provided options are malformed or the system is unable 21 | * to allocate space for a native tls context 22 | */ 23 | public TlsContext(TlsContextOptions options) throws CrtRuntimeException { 24 | acquireNativeHandle(tlsContextNew(options.getNativeHandle())); 25 | } 26 | 27 | /** 28 | * Creates a new Client TlsContext. There are significant native resources consumed to create a TlsContext, so most 29 | * applications will only need to create one and re-use it for all connections. 30 | */ 31 | public TlsContext() throws CrtRuntimeException { 32 | try (TlsContextOptions options = TlsContextOptions.createDefaultClient()) { 33 | acquireNativeHandle(tlsContextNew(options.getNativeHandle())); 34 | } 35 | } 36 | 37 | /** 38 | * Determines whether a resource releases its dependencies at the same time the native handle is released or if it waits. 39 | * Resources that wait are responsible for calling releaseReferences() manually. 40 | */ 41 | @Override 42 | protected boolean canReleaseReferencesImmediately() { return true; } 43 | 44 | /** 45 | * Frees all native resources associated with the context. This object is unusable after close is called. 46 | */ 47 | @Override 48 | protected void releaseNativeHandle() { 49 | if (!isNull()) { 50 | tlsContextDestroy(getNativeHandle()); 51 | } 52 | } 53 | 54 | protected static native long tlsContextNew(long options) throws CrtRuntimeException; 55 | 56 | private static native void tlsContextDestroy(long elg); 57 | }; 58 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/io/TlsHashAlgorithm.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | package software.amazon.awssdk.crt.io; 6 | 7 | import java.util.HashMap; 8 | import java.util.Map; 9 | 10 | /** 11 | * The hash algorithm of a TLS private key operation. Any custom private key operation handlers are expected to perform 12 | * operations on the input TLS data using the correct hash algorithm or fail the operation. 13 | */ 14 | public enum TlsHashAlgorithm { 15 | UNKNOWN(0), SHA1(1), SHA224(2), SHA256(3), SHA384(4), SHA512(5); 16 | 17 | static Map buildEnumMapping() { 18 | Map enumMapping = new HashMap(); 19 | for (TlsHashAlgorithm i : TlsHashAlgorithm.values()) { 20 | enumMapping.put(i.nativeValue, i); 21 | } 22 | return enumMapping; 23 | } 24 | 25 | public static TlsHashAlgorithm getEnumValueFromInteger(int value) { 26 | TlsHashAlgorithm enumValue = enumMapping.get(value); 27 | if (enumValue != null) { 28 | return enumValue; 29 | } 30 | throw new RuntimeException("Illegal TlsKeyOperation.TlsHashAlgorithm"); 31 | } 32 | 33 | TlsHashAlgorithm(int nativeValue) { 34 | this.nativeValue = nativeValue; 35 | } 36 | 37 | public int getNativeValue() { 38 | return nativeValue; 39 | } 40 | 41 | int nativeValue; 42 | static Map enumMapping = buildEnumMapping(); 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/io/TlsKeyOperationHandler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | package software.amazon.awssdk.crt.io; 6 | 7 | import software.amazon.awssdk.crt.Log; 8 | import software.amazon.awssdk.crt.Log.LogLevel; 9 | import software.amazon.awssdk.crt.Log.LogSubject; 10 | 11 | /** 12 | * Interface for handling private key operations during the TLS handshake. 13 | */ 14 | public interface TlsKeyOperationHandler { 15 | 16 | /** 17 | * Invoked each time a private key operation needs to be performed. 18 | * 19 | * You MUST call either operation.complete(output) or 20 | * operation.completeExceptionally(exception) or the TLS connection will hang 21 | * forever. 22 | * 23 | * You may complete the operation synchronously, or async. You may complete the 24 | * operation on any thread. 25 | * 26 | * The function is always invoked from an IO event-loop thread. Therefore you 27 | * MUST NOT perform an async call and wait for it in a blocking way from within 28 | * this function. Such behavior is likely to deadlock your program. 29 | * 30 | * Additionally, this may be called from multiple times from multiple threads 31 | * at once, so keep this in mind if using a private key operation that has to 32 | * be single-threaded and synchronously called. 33 | * 34 | * @param operation The operation to be acted on 35 | */ 36 | void performOperation(TlsKeyOperation operation); 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/io/TlsSignatureAlgorithm.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | package software.amazon.awssdk.crt.io; 6 | 7 | import java.util.HashMap; 8 | import java.util.Map; 9 | 10 | /** 11 | * The signature of a TLS private key operation. Any custom private key operation handlers are expected to perform 12 | * operations on the input TLS data using the correct signature algorithm or fail the operation. 13 | */ 14 | public enum TlsSignatureAlgorithm { 15 | UNKNOWN(0), RSA(1), ECDSA(2); 16 | 17 | static Map buildEnumMapping() { 18 | Map enumMapping = new HashMap(); 19 | for (TlsSignatureAlgorithm i : TlsSignatureAlgorithm.values()) { 20 | enumMapping.put(i.nativeValue, i); 21 | } 22 | return enumMapping; 23 | } 24 | 25 | public static TlsSignatureAlgorithm getEnumValueFromInteger(int value) { 26 | TlsSignatureAlgorithm enumValue = enumMapping.get(value); 27 | if (enumValue != null) { 28 | return enumValue; 29 | } 30 | throw new RuntimeException("Illegal TlsKeyOperation.TlsSignatureAlgorithm"); 31 | } 32 | 33 | TlsSignatureAlgorithm(int nativeValue) { 34 | this.nativeValue = nativeValue; 35 | } 36 | 37 | public int getNativeValue() { 38 | return nativeValue; 39 | } 40 | 41 | int nativeValue; 42 | static Map enumMapping = buildEnumMapping(); 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/iot/IncomingPublishEvent.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | package software.amazon.awssdk.crt.iot; 7 | 8 | import software.amazon.awssdk.crt.mqtt5.packets.UserProperty; 9 | 10 | import java.util.List; 11 | 12 | /** 13 | * An event that describes an incoming publish message received on a streaming operation. 14 | */ 15 | public class IncomingPublishEvent { 16 | 17 | private final byte[] payload; 18 | 19 | private final String topic; 20 | 21 | private String contentType; 22 | 23 | private List userProperties; 24 | 25 | private Long messageExpiryIntervalSeconds; 26 | 27 | private IncomingPublishEvent(byte[] payload, String topic) { 28 | this.payload = payload; 29 | this.topic = topic; 30 | } 31 | 32 | /** 33 | * Gets the payload of the IncomingPublishEvent. 34 | * 35 | * @return Payload of the IncomingPublishEvent. 36 | */ 37 | public byte[] getPayload() { 38 | return payload; 39 | } 40 | 41 | /** 42 | * Gets the topic of the IncomingPublishEvent. 43 | * 44 | * @return Topic of the IncomingPublishEvent. 45 | */ 46 | public String getTopic() { 47 | return topic; 48 | } 49 | 50 | /** 51 | * Gets the content type of the IncomingPublishEvent. 52 | * 53 | * @return Content type of the IncomingPublishEvent. 54 | */ 55 | public String getContentType() { 56 | return contentType; 57 | } 58 | 59 | /** 60 | * Gets the user properties of the IncomingPublishEvent. 61 | * 62 | * @return User properties of the IncomingPublishEvent. 63 | */ 64 | public List getUserProperties() { 65 | return userProperties; 66 | } 67 | 68 | /** 69 | * Gets the message expiry interval seconds of the IncomingPublishEvent. 70 | * 71 | * @return Message expiry interval seconds of the IncomingPublishEvent. 72 | */ 73 | public Long getMessageExpiryIntervalSeconds() { 74 | return messageExpiryIntervalSeconds; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/iot/MqttRequestResponse.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | package software.amazon.awssdk.crt.iot; 7 | 8 | /** 9 | * Encapsulates a response to an AWS IoT Core MQTT-based service request 10 | */ 11 | public class MqttRequestResponse { 12 | 13 | private String topic; 14 | private byte[] payload; 15 | 16 | private MqttRequestResponse() { 17 | } 18 | 19 | /** 20 | * Gets the MQTT topic that the response was received on. 21 | * 22 | * Different topics map to different types within the 23 | * service model, so we need this value in order to know what to deserialize the payload into. 24 | * 25 | * @return the MQTT topic that the response was received on 26 | */ 27 | public String getTopic() { 28 | return topic; 29 | } 30 | 31 | /** 32 | * Gets the payload of the response that correlates to a submitted request. 33 | * 34 | * @return Payload of the response that correlates to a submitted request. 35 | */ 36 | public byte[] getPayload() { 37 | return payload; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/iot/SubscriptionStatusEvent.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | package software.amazon.awssdk.crt.iot; 7 | 8 | import java.util.Optional; 9 | 10 | /** 11 | * An event that describes a change in subscription status for a streaming operation. 12 | */ 13 | public class SubscriptionStatusEvent { 14 | private final SubscriptionStatusEventType type; 15 | private final Optional error; 16 | 17 | private SubscriptionStatusEvent(SubscriptionStatusEventType type, int errorCode) { 18 | this.type = type; 19 | if (errorCode != 0) { 20 | this.error = Optional.of(errorCode); 21 | } else { 22 | this.error = Optional.empty(); 23 | } 24 | } 25 | 26 | /** 27 | * Gets the type of status change represented by the event. 28 | * 29 | * @return The type of status change represented by the event 30 | */ 31 | public SubscriptionStatusEventType getType() { 32 | return this.type; 33 | } 34 | 35 | /** 36 | * Gets the underlying reason for the event. Only set for SubscriptionLost and SubscriptionHalted. Use 37 | * CRT.awsErrorString() to convert the integer error code into an error description. 38 | * 39 | * @return underlying reason for the event 40 | */ 41 | public Optional getError() { 42 | return this.error; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/iot/SubscriptionStatusEventType.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | package software.amazon.awssdk.crt.iot; 7 | 8 | import java.util.Map; 9 | import java.util.function.Function; 10 | import java.util.stream.Collectors; 11 | import java.util.stream.Stream; 12 | 13 | /** 14 | * The type of change to the state of a streaming operation subscription 15 | */ 16 | public enum SubscriptionStatusEventType { 17 | 18 | /** 19 | * The streaming operation is successfully subscribed to its topic (filter) 20 | */ 21 | SUBSCRIPTION_ESTABLISHED(0), 22 | 23 | /** 24 | * The streaming operation has temporarily lost its subscription to its topic (filter) 25 | */ 26 | SUBSCRIPTION_LOST(1), 27 | 28 | /** 29 | * The streaming operation has entered a terminal state where it has given up trying to subscribe 30 | * to its topic (filter). This is always due to user error (bad topic filter or IoT Core permission policy). 31 | */ 32 | SUBSCRIPTION_HALTED(2); 33 | 34 | private final int type; 35 | 36 | SubscriptionStatusEventType(int value) { 37 | type = value; 38 | } 39 | 40 | 41 | /** 42 | * @return the native enum integer value associated with this Java enum value 43 | */ 44 | public int getValue() { 45 | return type; 46 | } 47 | 48 | /** 49 | * Creates a Java SubscriptionStatusEventType enum value from a native integer value 50 | * @param value native integer value to convert to a SubscriptionStatusEventType instance 51 | * @return a SubscriptionStatusEventType value 52 | */ 53 | public static SubscriptionStatusEventType getEnumValueFromInteger(int value) { 54 | SubscriptionStatusEventType enumValue = enumMapping.get(value); 55 | if (enumValue != null) { 56 | return enumValue; 57 | } 58 | throw new RuntimeException("Illegal SubscriptionStatusEventType"); 59 | } 60 | 61 | private static Map buildEnumMapping() { 62 | return Stream.of(SubscriptionStatusEventType.values()) 63 | .collect(Collectors.toMap(SubscriptionStatusEventType::getValue, Function.identity())); 64 | } 65 | 66 | private final static Map enumMapping = buildEnumMapping(); 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/mqtt/MqttClientConnectionEvents.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * SPDX-License-Identifier: Apache-2.0. 5 | */ 6 | package software.amazon.awssdk.crt.mqtt; 7 | 8 | /** 9 | * Interface used to receive connection events from the CRT 10 | */ 11 | public interface MqttClientConnectionEvents { 12 | /** 13 | * Called when the connection was lost (or disconnected), reconnect will be attempted automatically until 14 | * disconnect() is called 15 | * @param errorCode AWS CRT error code, pass to {@link software.amazon.awssdk.crt.CRT#awsErrorString(int)} for a human readable error 16 | */ 17 | void onConnectionInterrupted(int errorCode); 18 | 19 | /** 20 | * Called whenever a reconnect succeeds; not called on an initial connect success 21 | * @param sessionPresent true if the session has been resumed, false if the session is clean 22 | */ 23 | void onConnectionResumed(boolean sessionPresent); 24 | 25 | /** 26 | * Called on every successful connect and every successful reconnect. 27 | * Optional and is not required to be defined. 28 | * @param data The data sent from the client alongside the successful connection callback. 29 | */ 30 | default void onConnectionSuccess(OnConnectionSuccessReturn data) {}; 31 | 32 | /** 33 | * Called on every unsuccessful connect and every unsuccessful disconnect. 34 | * Optional and is not required to be defined. 35 | * @param data The data sent from the client alongside the failed connection callback. 36 | */ 37 | default void onConnectionFailure(OnConnectionFailureReturn data) {}; 38 | 39 | /** 40 | * Called when the connection was disconnected and shutdown successfully. 41 | * Optional and is not required to be defined. 42 | * @param data The data sent from the client alongside the successful disconnect. 43 | */ 44 | default void onConnectionClosed(OnConnectionClosedReturn data) {}; 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/mqtt/MqttClientConnectionOperationStatistics.java: -------------------------------------------------------------------------------- 1 | package software.amazon.awssdk.crt.mqtt; 2 | 3 | /** 4 | * Simple statistics about the current state of the connection's queue of operations 5 | */ 6 | public class MqttClientConnectionOperationStatistics { 7 | 8 | private long incompleteOperationCount; 9 | private long incompleteOperationSize; 10 | private long unackedOperationCount; 11 | private long unackedOperationSize; 12 | 13 | public MqttClientConnectionOperationStatistics() {} 14 | 15 | /** 16 | * Returns the total number of operations submitted to the connection that have not yet been completed. 17 | * Note: Unacked operations are a subset of this. 18 | * @return Total number of operations submitted to the connection that have not yet been completed 19 | */ 20 | public long getIncompleteOperationCount() { 21 | return incompleteOperationCount; 22 | } 23 | 24 | /** 25 | * Returns the total packet size of operations submitted to the connection that have not yet been completed. 26 | * Note: Unacked operations are a subset of this. 27 | * @return Total packet size of operations submitted to the connection that have not yet been completed 28 | */ 29 | public long getIncompleteOperationSize() { 30 | return incompleteOperationSize; 31 | } 32 | 33 | /** 34 | * Returns the total number of operations that have been sent and are waiting for a corresponding ACK before 35 | * they can be completed. 36 | * @return Total number of operations that have been sent and are waiting for a corresponding ACK 37 | */ 38 | public long getUnackedOperationCount() { 39 | return unackedOperationCount; 40 | } 41 | 42 | /** 43 | * Returns the total packet size of operations that have been sent and are waiting for a corresponding ACK before 44 | * they can be completed. 45 | * @return Total packet size of operations that have been sent and are waiting for a corresponding ACK 46 | */ 47 | public long getUnackedOperationSize() { 48 | return unackedOperationSize; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/mqtt/MqttException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | package software.amazon.awssdk.crt.mqtt; 6 | 7 | import software.amazon.awssdk.crt.CRT; 8 | 9 | /** 10 | * This exception will be thrown by any exceptional cases encountered within the 11 | * JNI bindings to the AWS Common Runtime 12 | */ 13 | public class MqttException extends RuntimeException { 14 | private int errorCode; 15 | 16 | /** 17 | * @param msg mqtt exception message 18 | */ 19 | public MqttException(String msg) { 20 | super(msg); 21 | this.errorCode = -1; 22 | } 23 | 24 | /** 25 | * @param errorCode native CRT error code indicating the reason for the exception 26 | */ 27 | public MqttException(int errorCode) { 28 | super(CRT.awsErrorString(errorCode)); 29 | this.errorCode = errorCode; 30 | } 31 | 32 | /** 33 | * Returns the error code captured when the exception occurred. This can be fed to {@link CRT.awsErrorString} to 34 | * get a user-friendly error string 35 | * @return The error code associated with this exception 36 | */ 37 | int getErrorCode() { 38 | return errorCode; 39 | } 40 | }; 41 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/mqtt/OnConnectionClosedReturn.java: -------------------------------------------------------------------------------- 1 | package software.amazon.awssdk.crt.mqtt; 2 | 3 | /** 4 | * The data returned when the connection closed callback is invoked in a connection. 5 | *

6 | * Note: This class is currently empty, but this may contain additional data in the future. 7 | * @see software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents 8 | */ 9 | public class OnConnectionClosedReturn { 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/mqtt/OnConnectionFailureReturn.java: -------------------------------------------------------------------------------- 1 | package software.amazon.awssdk.crt.mqtt; 2 | 3 | /** 4 | * The data returned when the connection failure callback is invoked in a connection. 5 | * @see software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents 6 | */ 7 | public class OnConnectionFailureReturn { 8 | 9 | private int errorCode; 10 | 11 | /** 12 | * Gets the AWS CRT error code for the connection failure. 13 | * Pass to {@link software.amazon.awssdk.crt.CRT#awsErrorString(int)} for a human readable error 14 | * @return The AWS CRT error code for the connection failure. 15 | */ 16 | public int getErrorCode() { 17 | return errorCode; 18 | } 19 | 20 | /** 21 | * Constructs a new OnConnectionFailureReturn with an error code 22 | * @param errorCode The AWS CRT error code 23 | */ 24 | protected OnConnectionFailureReturn(int errorCode) { 25 | this.errorCode = errorCode; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/mqtt/OnConnectionSuccessReturn.java: -------------------------------------------------------------------------------- 1 | package software.amazon.awssdk.crt.mqtt; 2 | 3 | /** 4 | * The data returned when the connection success callback is invoked in a connection. 5 | * @see software.amazon.awssdk.crt.mqtt.MqttClientConnectionEvents 6 | */ 7 | public class OnConnectionSuccessReturn { 8 | 9 | private boolean sessionPresent; 10 | 11 | /** 12 | * Returns whether a session was present and resumed for this successful connection. 13 | * Will be set to true if the connection resumed an already present MQTT connection session. 14 | * @return whether a session was present and resumed 15 | */ 16 | public boolean getSessionPresent() { 17 | return sessionPresent; 18 | } 19 | 20 | /** 21 | * Constructs a new OnConnectionSuccessReturn with a session present. 22 | * @param sessionPresent whether a session was present and resumed 23 | */ 24 | protected OnConnectionSuccessReturn(boolean sessionPresent) { 25 | this.sessionPresent = sessionPresent; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/mqtt5/Mqtt5ClientOperationStatistics.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | package software.amazon.awssdk.crt.mqtt5; 6 | 7 | /** 8 | * Simple statistics about the current state of the client's queue of operations 9 | */ 10 | public class Mqtt5ClientOperationStatistics { 11 | 12 | private long incompleteOperationCount; 13 | private long incompleteOperationSize; 14 | private long unackedOperationCount; 15 | private long unackedOperationSize; 16 | 17 | public Mqtt5ClientOperationStatistics() {} 18 | 19 | /** 20 | * Returns the total number of operations submitted to the client that have not yet been completed. 21 | * Note: Unacked operations are a subset of this. 22 | * @return Total number of operations submitted to the client that have not yet been completed 23 | */ 24 | public long getIncompleteOperationCount() { 25 | return incompleteOperationCount; 26 | } 27 | 28 | /** 29 | * Returns the total packet size of operations submitted to the client that have not yet been completed. 30 | * Note: Unacked operations are a subset of this. 31 | * @return Total packet size of operations submitted to the client that have not yet been completed 32 | */ 33 | public long getIncompleteOperationSize() { 34 | return incompleteOperationSize; 35 | } 36 | 37 | /** 38 | * Returns the total number of operations that have been sent and are waiting for a corresponding ACK before 39 | * they can be completed. 40 | * @return Total number of operations that have been sent and are waiting for a corresponding ACK 41 | */ 42 | public long getUnackedOperationCount() { 43 | return unackedOperationCount; 44 | } 45 | 46 | /** 47 | * Returns the total packet size of operations that have been sent and are waiting for a corresponding ACK before 48 | * they can be completed. 49 | * @return Total packet size of operations that have been sent and are waiting for a corresponding ACK 50 | */ 51 | public long getUnackedOperationSize() { 52 | return unackedOperationSize; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/mqtt5/OnAttemptingConnectReturn.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | package software.amazon.awssdk.crt.mqtt5; 6 | 7 | /** 8 | * The data returned when AttemptingConnect is invoked in the LifecycleEvents callback. 9 | * Currently empty, but may be used in the future for passing additional data. 10 | */ 11 | public class OnAttemptingConnectReturn { 12 | /** 13 | * This is only called in JNI to make a new OnAttemptingConnectReturn. 14 | */ 15 | private OnAttemptingConnectReturn() {} 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/mqtt5/OnConnectionFailureReturn.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | package software.amazon.awssdk.crt.mqtt5; 6 | 7 | import software.amazon.awssdk.crt.mqtt5.packets.ConnAckPacket; 8 | 9 | /** 10 | * The data returned when OnConnectionFailure is invoked in the LifecycleEvents callback. 11 | * The data contained within can be gotten using the get functions. 12 | * For example, getConnAckPacket will return the ConnAckPacket from the server. 13 | */ 14 | public class OnConnectionFailureReturn { 15 | private int errorCode; 16 | private ConnAckPacket connAckPacket; 17 | 18 | /** 19 | * Returns the error code returned from the server on the connection failure. 20 | * Pass to {@link software.amazon.awssdk.crt.CRT#awsErrorString(int)} for a human readable error. 21 | * @return The error code returned from the server. 22 | */ 23 | public int getErrorCode() { 24 | return errorCode; 25 | } 26 | 27 | /** 28 | * Returns the ConnAckPacket returned from the server on the connection failure, or Null if none was returned. 29 | * @return The ConnAckPacket returned from the server. 30 | */ 31 | public ConnAckPacket getConnAckPacket() { 32 | return connAckPacket; 33 | } 34 | 35 | /** 36 | * This is only called in JNI to make a new OnConnectionFailureReturn. 37 | */ 38 | private OnConnectionFailureReturn(int newErrorCode, ConnAckPacket newConnAckPacket) 39 | { 40 | this.errorCode = newErrorCode; 41 | this.connAckPacket = newConnAckPacket; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/mqtt5/OnConnectionSuccessReturn.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | package software.amazon.awssdk.crt.mqtt5; 6 | 7 | import software.amazon.awssdk.crt.mqtt5.packets.ConnAckPacket; 8 | 9 | /** 10 | * The data returned when OnConnectionSuccess is invoked in the LifecycleEvents callback. 11 | * The data contained within can be gotten using the get functions. 12 | * For example, getResultPublishPacket will return the PublishPacket from the server. 13 | */ 14 | public class OnConnectionSuccessReturn { 15 | private ConnAckPacket connAckPacket; 16 | private NegotiatedSettings negotiatedSettings; 17 | 18 | /** 19 | * Returns the ConnAckPacket returned from the server on the connection success or Null if none was returned. 20 | * @return The ConnAckPacket returned from the server. 21 | */ 22 | public ConnAckPacket getConnAckPacket() { 23 | return connAckPacket; 24 | } 25 | 26 | /** 27 | * Returns the NegotiatedSettings returned from the server on the connection success or Null if none was returned. 28 | * @return The NegotiatedSettings returned from the server. 29 | */ 30 | public NegotiatedSettings getNegotiatedSettings() { 31 | return negotiatedSettings; 32 | } 33 | 34 | /** 35 | * This is only called in JNI to make a new OnConnectionSuccessReturn. 36 | */ 37 | private OnConnectionSuccessReturn(ConnAckPacket newConnAckPacket, NegotiatedSettings newNegotiatedSettings) 38 | { 39 | this.connAckPacket = newConnAckPacket; 40 | this.negotiatedSettings = newNegotiatedSettings; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/mqtt5/OnDisconnectionReturn.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | package software.amazon.awssdk.crt.mqtt5; 6 | 7 | import software.amazon.awssdk.crt.mqtt5.packets.DisconnectPacket; 8 | 9 | /** 10 | * The data returned when OnDisconnect is invoked in the LifecycleEvents callback. 11 | * The data contained within can be gotten using the get functions. 12 | * For example, getDisconnectPacket will return the DisconnectPacket from the server. 13 | */ 14 | public class OnDisconnectionReturn { 15 | private int errorCode; 16 | private DisconnectPacket disconnectPacket; 17 | 18 | /** 19 | * Returns the error code returned from the server on the disconnection. 20 | * Pass to {@link software.amazon.awssdk.crt.CRT#awsErrorString(int)} for a human readable error. 21 | * @return The error code returned from the server. 22 | */ 23 | public int getErrorCode() { 24 | return errorCode; 25 | } 26 | 27 | /** 28 | * Returns the ConnAckPacket returned from the server on the disconnection, or Null if none was returned. 29 | * @return The ConnAckPacket returned from the server. 30 | */ 31 | public DisconnectPacket getDisconnectPacket() { 32 | return disconnectPacket; 33 | } 34 | 35 | /** 36 | * This is only called in JNI to make a new OnDisconnectionReturn. 37 | */ 38 | private OnDisconnectionReturn(int newErrorCode, DisconnectPacket newDisconnectPacket) 39 | { 40 | this.errorCode = newErrorCode; 41 | this.disconnectPacket = newDisconnectPacket; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/mqtt5/OnStoppedReturn.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | package software.amazon.awssdk.crt.mqtt5; 6 | 7 | /** 8 | * The data returned when OnStopped is invoked in the LifecycleEvents callback. 9 | * Currently empty, but may be used in the future for passing additional data. 10 | */ 11 | public class OnStoppedReturn { 12 | /** 13 | * This is only called in JNI to make a new OnStoppedReturn. 14 | */ 15 | private OnStoppedReturn() {} 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/mqtt5/PublishReturn.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | package software.amazon.awssdk.crt.mqtt5; 6 | 7 | import software.amazon.awssdk.crt.mqtt5.packets.PublishPacket; 8 | 9 | /** 10 | * The data returned when a publish is made to a topic the MQTT5 client is subscribed to. 11 | * The data contained within can be gotten using the get functions. 12 | * For example, getPublishPacket will return the PublishPacket received from the server. 13 | */ 14 | public class PublishReturn { 15 | private PublishPacket publishPacket; 16 | 17 | /** 18 | * Returns the PublishPacket returned from the server or Null if none was returned. 19 | * @return The PublishPacket returned from the server. 20 | */ 21 | public PublishPacket getPublishPacket() { 22 | return publishPacket; 23 | } 24 | 25 | /** 26 | * This is only called in JNI to make a new PublishReturn with a PUBLISH packet. 27 | * @param newPublishPacket The PubAckPacket data for QoS 1 packets. Can be null if result is non QoS 1. 28 | * @return A newly created PublishResult 29 | */ 30 | private PublishReturn(PublishPacket newPublishPacket) { 31 | this.publishPacket = newPublishPacket; 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/mqtt5/QOS.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | package software.amazon.awssdk.crt.mqtt5; 7 | 8 | import java.util.Map; 9 | import java.util.function.Function; 10 | import java.util.stream.Collectors; 11 | import java.util.stream.Stream; 12 | 13 | /** 14 | * MQTT message delivery quality of service. 15 | * 16 | * Enum values match MQTT5 spec encoding values. 17 | */ 18 | public enum QOS { 19 | /** 20 | * The message is delivered according to the capabilities of the underlying network. No response is sent by the 21 | * receiver and no retry is performed by the sender. The message arrives at the receiver either once or not at all. 22 | */ 23 | AT_MOST_ONCE(0), 24 | 25 | /** 26 | * A level of service that ensures that the message arrives at the receiver at least once. 27 | */ 28 | AT_LEAST_ONCE(1), 29 | 30 | /** 31 | * A level of service that ensures that the message arrives at the receiver exactly once. 32 | */ 33 | EXACTLY_ONCE(2); 34 | 35 | private int qos; 36 | 37 | private QOS(int value) { 38 | qos = value; 39 | } 40 | 41 | /** 42 | * @return The native enum integer value associated with this Java enum value 43 | */ 44 | public int getValue() { 45 | return qos; 46 | } 47 | 48 | /** 49 | * Creates a Java QualityOfService enum value from a native integer value. 50 | * 51 | * @param value native integer value for quality of service 52 | * @return a new QualityOfService value 53 | */ 54 | public static QOS getEnumValueFromInteger(int value) { 55 | QOS enumValue = enumMapping.get(value); 56 | if (enumValue != null) { 57 | return enumValue; 58 | } 59 | throw new RuntimeException("Illegal QOS"); 60 | } 61 | 62 | private static Map buildEnumMapping() { 63 | return Stream.of(QOS.values()) 64 | .collect(Collectors.toMap(QOS::getValue, Function.identity())); 65 | } 66 | 67 | private static Map enumMapping = buildEnumMapping(); 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/mqtt5/packets/UserProperty.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | package software.amazon.awssdk.crt.mqtt5.packets; 6 | 7 | /** 8 | * A simple key-value pair struct to define a user property. 9 | * A user property is a name-value pair of utf-8 strings that can be added to MQTT5 packets. 10 | */ 11 | public class UserProperty { 12 | 13 | public final String key; 14 | public final String value; 15 | 16 | public UserProperty(String key, String value) { 17 | this.key = key; 18 | this.value = value; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/s3/S3ExpressCredentialsProperties.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | package software.amazon.awssdk.crt.s3; 6 | 7 | public class S3ExpressCredentialsProperties { 8 | private String hostValue; 9 | private String region; 10 | 11 | public S3ExpressCredentialsProperties withHostValue (String hostValue) { 12 | this.hostValue = hostValue; 13 | return this; 14 | } 15 | 16 | public String getHostValue () { 17 | return this.hostValue; 18 | } 19 | 20 | public S3ExpressCredentialsProperties withRegion (String region) { 21 | this.region = region; 22 | return this; 23 | } 24 | 25 | public String getRegion () { 26 | return this.region; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/s3/S3ExpressCredentialsProvider.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | package software.amazon.awssdk.crt.s3; 6 | 7 | import software.amazon.awssdk.crt.auth.credentials.Credentials; 8 | 9 | /** 10 | * The Java object for Native code to invoke. 11 | */ 12 | public class S3ExpressCredentialsProvider { 13 | 14 | private S3ExpressCredentialsProviderHandler handler; 15 | 16 | public S3ExpressCredentialsProvider(S3ExpressCredentialsProviderHandler handler) { 17 | this.handler = handler; 18 | } 19 | 20 | public void getS3ExpressCredentials(S3ExpressCredentialsProperties properties, Credentials origCredentials, long nativeHandler) { 21 | handler.getS3ExpressCredentials(properties, origCredentials).whenComplete((result, ex) -> { 22 | if(ex != null) { 23 | s3expressCredentialsProviderGetCredentialsCompleted(nativeHandler, null); 24 | } else { 25 | s3expressCredentialsProviderGetCredentialsCompleted(nativeHandler, result); 26 | } 27 | }); 28 | } 29 | 30 | public void destroyProvider() throws Exception { 31 | /* Block until handler finishes shutdown. It doesn't matter to wait for shutdown */ 32 | this.handler.destroyProvider().get(); 33 | } 34 | 35 | /******************************************************************************* 36 | * native methods 37 | ******************************************************************************/ 38 | private static native void s3expressCredentialsProviderGetCredentialsCompleted(long nativeHandler, Credentials credentials); 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/s3/S3ExpressCredentialsProviderFactory.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | package software.amazon.awssdk.crt.s3; 6 | 7 | 8 | public interface S3ExpressCredentialsProviderFactory { 9 | /** 10 | * A handler to create a S3ExpressCredentialsProvider for the client to use. 11 | * 12 | * Warning: 13 | * You cannot use the client while creating the provider 14 | * (You can use the client for fetching credentials) 15 | * @param client The S3Client creates and owns the provider. 16 | * @return S3ExpressCredentialsProvider created. 17 | */ 18 | public S3ExpressCredentialsProvider createS3ExpressCredentialsProvider(S3Client client); 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/s3/S3ExpressCredentialsProviderHandler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | package software.amazon.awssdk.crt.s3; 6 | 7 | import java.util.concurrent.CompletableFuture; 8 | 9 | import software.amazon.awssdk.crt.auth.credentials.Credentials; 10 | 11 | /** 12 | * Interface to override the S3Express Credentials provider. 13 | */ 14 | public interface S3ExpressCredentialsProviderHandler { 15 | /** 16 | * To resolve the S3Express Credentials. Invoked when a single request needs to be signed. 17 | * 18 | * @param properties The properties needed to derive the S3Express credentials from. 19 | * @param origCredentials The original Credentials for fetching S3Express credentials. 20 | * @return The future to be resolved when the S3 Express credentials are resolved. 21 | */ 22 | public CompletableFuture getS3ExpressCredentials(S3ExpressCredentialsProperties properties, Credentials origCredentials); 23 | 24 | /** 25 | * Invoked when the S3 client starts to destroy to clean up related resource. 26 | * 27 | * @return The future to be resolved when the resource finishes cleaning up. 28 | */ 29 | public CompletableFuture destroyProvider(); 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/s3/S3MetaRequestProgress.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | package software.amazon.awssdk.crt.s3; 6 | 7 | /** 8 | * Information about the meta request progress. 9 | */ 10 | public class S3MetaRequestProgress { 11 | 12 | private long bytesTransferred; 13 | private long contentLength; 14 | 15 | /** 16 | * @param bytesTransferred bytes transferred since the previous progress update 17 | * @return this progress object 18 | */ 19 | public S3MetaRequestProgress withBytesTransferred(long bytesTransferred) { 20 | this.bytesTransferred = bytesTransferred; 21 | return this; 22 | } 23 | 24 | /** 25 | * @return bytes transferred since the previous progress update 26 | */ 27 | public long getBytesTransferred() { 28 | return bytesTransferred; 29 | } 30 | 31 | /** 32 | * @param contentLength length of the entire meta request operation 33 | * @return this progress object 34 | */ 35 | public S3MetaRequestProgress withContentLength(long contentLength) { 36 | this.contentLength = contentLength; 37 | return this; 38 | } 39 | 40 | /** 41 | * 42 | * @return length of the entire meta request operation 43 | */ 44 | public long getContentLength() { 45 | return contentLength; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/s3/S3MetaRequestResponseHandlerNativeAdapter.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | package software.amazon.awssdk.crt.s3; 6 | 7 | import software.amazon.awssdk.crt.http.HttpHeader; 8 | 9 | import java.nio.ByteBuffer; 10 | 11 | class S3MetaRequestResponseHandlerNativeAdapter { 12 | private S3MetaRequestResponseHandler responseHandler; 13 | 14 | S3MetaRequestResponseHandlerNativeAdapter(S3MetaRequestResponseHandler responseHandler) { 15 | this.responseHandler = responseHandler; 16 | } 17 | 18 | int onResponseBody(byte[] bodyBytesIn, long objectRangeStart, long objectRangeEnd) { 19 | return this.responseHandler.onResponseBody(ByteBuffer.wrap(bodyBytesIn), objectRangeStart, objectRangeEnd); 20 | } 21 | 22 | void onFinished(int errorCode, int responseStatus, byte[] errorPayload, String errorOperationName, int checksumAlgorithm, boolean didValidateChecksum, Throwable cause, final ByteBuffer headersBlob) { 23 | HttpHeader[] errorHeaders = headersBlob == null ? null : HttpHeader.loadHeadersFromMarshalledHeadersBlob(headersBlob); 24 | S3FinishedResponseContext context = new S3FinishedResponseContext(errorCode, responseStatus, errorPayload, errorOperationName, ChecksumAlgorithm.getEnumValueFromInteger(checksumAlgorithm), didValidateChecksum, cause, errorHeaders); 25 | this.responseHandler.onFinished(context); 26 | } 27 | 28 | void onResponseHeaders(final int statusCode, final ByteBuffer headersBlob) { 29 | responseHandler.onResponseHeaders(statusCode, HttpHeader.loadHeadersFromMarshalledHeadersBlob(headersBlob)); 30 | } 31 | 32 | void onProgress(final S3MetaRequestProgress progress) { 33 | responseHandler.onProgress(progress); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/s3/S3TcpKeepAliveOptions.java: -------------------------------------------------------------------------------- 1 | package software.amazon.awssdk.crt.s3; 2 | 3 | /** 4 | * This class provides access to setting Tcp Keep Alive Options. 5 | * If interval or timeout are zero, then default values are used. 6 | */ 7 | public class S3TcpKeepAliveOptions { 8 | 9 | private short keepAliveIntervalSec; 10 | 11 | private short keepAliveTimeoutSec; 12 | 13 | /* If set, sets the number of keep alive probes allowed to fail before the connection is considered 14 | * lost. If zero OS defaults are used. On Windows, this option is meaningless until Windows 10 1703.*/ 15 | private short keepAliveMaxFailedProbes; 16 | 17 | public short getKeepAliveIntervalSec() { 18 | return keepAliveIntervalSec; 19 | } 20 | 21 | public void setKeepAliveIntervalSec(short keepAliveIntervalSec) { 22 | this.keepAliveIntervalSec = keepAliveIntervalSec; 23 | } 24 | 25 | public short getKeepAliveTimeoutSec() { 26 | return keepAliveTimeoutSec; 27 | } 28 | 29 | public void setKeepAliveTimeoutSec(short keepAliveTimeoutSec) { 30 | this.keepAliveTimeoutSec = keepAliveTimeoutSec; 31 | } 32 | 33 | public short getKeepAliveMaxFailedProbes() { 34 | return keepAliveMaxFailedProbes; 35 | } 36 | 37 | public void setKeepAliveMaxFailedProbes(short keepAliveMaxFailedProbes) { 38 | this.keepAliveMaxFailedProbes = keepAliveMaxFailedProbes; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/utils/ByteBufferUtils.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | package software.amazon.awssdk.crt.utils; 7 | 8 | import java.nio.ByteBuffer; 9 | import java.nio.Buffer; 10 | 11 | /** 12 | * Utility Class with Helper functions for working with ByteBuffers 13 | */ 14 | public class ByteBufferUtils { 15 | private ByteBufferUtils() {} 16 | 17 | /** 18 | * Transfers as much data as possible from an input ByteBuffer to an output ByteBuffer 19 | * @param in The input ByteBuffer 20 | * @param out The output ByteBuffer 21 | * @return The number of bytes transferred 22 | */ 23 | public static int transferData(ByteBuffer in, ByteBuffer out) { 24 | int amtToTransfer = Math.min(in.remaining(), out.remaining()); 25 | 26 | // Make a new ByteBuffer that shares the same underlying buffer as the input ByteBuffer 27 | ByteBuffer shallowCopy = in.duplicate(); 28 | 29 | // Modify the shallow copy's read limit so that it matches the write space remaining in the output Buffer so 30 | // we don't throw an OutOfBounds exception 31 | // The weird cast is to avoid certain JDK8 JREs that don't think ByteBuffer 32 | // inherits from Buffer 33 | ((Buffer) shallowCopy).limit(shallowCopy.position() + amtToTransfer); 34 | 35 | // Transfer the data 36 | out.put(shallowCopy); 37 | 38 | // Increment the read position of the original input buffer by the number of bytes transferred 39 | in.position(in.position() + amtToTransfer); 40 | return amtToTransfer; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/software/amazon/awssdk/crt/utils/StringUtils.java: -------------------------------------------------------------------------------- 1 | package software.amazon.awssdk.crt.utils; 2 | 3 | import software.amazon.awssdk.crt.CRT; 4 | 5 | public class StringUtils { 6 | static { 7 | new CRT(); 8 | }; 9 | 10 | /** 11 | * Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter. 12 | * Like `Strings.join()` but works on Android before API 26. 13 | * 14 | * @param delimiter a sequence of characters that is used to separate each of the elements in the resulting String 15 | * @param elements an Iterable that will have its elements joined together 16 | * @return a new String that is composed from the elements argument 17 | */ 18 | public static String join(CharSequence delimiter, Iterable elements) { 19 | if (delimiter == null || elements == null) throw new NullPointerException("delimiter and elements must not be null"); 20 | StringBuilder sb = new StringBuilder(); 21 | 22 | boolean first = true; 23 | for(CharSequence cs : elements) { 24 | if (!first) { 25 | sb.append(delimiter); 26 | } 27 | sb.append(cs); 28 | first = false; 29 | } 30 | return sb.toString(); 31 | } 32 | 33 | /** 34 | * Encode a byte array into a Base64 byte array. 35 | * @param data The byte array to encode 36 | * @return The byte array encoded as Byte64 37 | */ 38 | public static byte[] base64Encode(byte[] data) { 39 | return stringUtilsBase64Encode(data); 40 | } 41 | 42 | /** 43 | * Decode a Base64 byte array into a non-Base64 byte array. 44 | * @param data The byte array to decode. 45 | * @return Byte array decoded from Base64. 46 | */ 47 | public static byte[] base64Decode(byte[] data) { 48 | return stringUtilsBase64Decode(data); 49 | } 50 | 51 | private static native byte[] stringUtilsBase64Encode(byte[] data_to_encode); 52 | private static native byte[] stringUtilsBase64Decode(byte[] data_to_decode); 53 | } 54 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/native-image/software.amazon.awssdk/crt/aws-crt/native-image.properties: -------------------------------------------------------------------------------- 1 | Args=--enable-url-protocols=jar --features=software.amazon.awssdk.crt.internal.GraalVMNativeFeature 2 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/native-image/software.amazon.awssdk/crt/aws-crt/reflect-config.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "condition": { 4 | "typeReachable": "org.junit.Assume" 5 | }, 6 | "name": "org.hamcrest.core.Every", 7 | "queryAllDeclaredMethods": true 8 | } 9 | ] -------------------------------------------------------------------------------- /src/native/aws_signing.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | #ifndef AWS_JNI_CRT_AWS_SIGNING_H 7 | #define AWS_JNI_CRT_AWS_SIGNING_H 8 | 9 | #include 10 | #include 11 | 12 | struct aws_signing_config_aws; 13 | 14 | struct aws_signing_config_data { 15 | JavaVM *jvm; 16 | struct aws_string *region; 17 | struct aws_string *service; 18 | struct aws_string *signed_body_value; 19 | 20 | jobject java_sign_header_predicate; 21 | struct aws_credentials *credentials; 22 | jobject java_credentials_provider; 23 | }; 24 | 25 | /* Initialize the native `config` from Java Object and Keep the required data around with `config_data`. You need to 26 | * clean up the `config_data` after the signing config is not used anymore */ 27 | int aws_build_signing_config( 28 | JNIEnv *env, 29 | jobject java_config, 30 | struct aws_signing_config_data *config_data, 31 | struct aws_signing_config_aws *config); 32 | 33 | void aws_signing_config_data_clean_up(struct aws_signing_config_data *data, JNIEnv *env); 34 | 35 | #endif /* AWS_JNI_CRT_AWS_SIGNING_H */ 36 | -------------------------------------------------------------------------------- /src/native/build.gradle.kts: -------------------------------------------------------------------------------- 1 | 2 | plugins { 3 | `c` 4 | } 5 | 6 | description = "JNI bindings for the AWS Common Runtime" 7 | 8 | buildDir = File("../../build") 9 | 10 | var buildType = "RelWithDebInfo" 11 | if (project.hasProperty("buildType")) { 12 | buildType = project.property("buildType").toString() 13 | logger.info("Using custom build type: ${buildType}") 14 | } 15 | 16 | val cmakeConfigure = tasks.register("cmakeConfigure") { 17 | var cmakeArgs = listOf( 18 | "-B${buildDir}/cmake-build", 19 | "-H${projectDir}/../../", 20 | "-DCMAKE_BUILD_TYPE=${buildType}", 21 | "-DCMAKE_INSTALL_PREFIX=${buildDir}/cmake-build", 22 | "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON", 23 | "-DBUILD_DEPS=ON", 24 | "-DBUILD_TESTING=OFF" 25 | ) 26 | 27 | inputs.file("../../CMakeLists.txt") 28 | outputs.file("${buildDir}/cmake-build/CMakeCache.txt") 29 | 30 | doLast { 31 | val argsStr = cmakeArgs.joinToString(separator=" ") 32 | logger.info("cmake ${argsStr}") 33 | exec { 34 | executable("cmake") 35 | args(cmakeArgs) 36 | environment(mapOf("JAVA_HOME" to System.getProperty("java.home"))) 37 | } 38 | } 39 | } 40 | 41 | val cmakeBuild = tasks.register("cmakeBuild") { 42 | dependsOn(cmakeConfigure) 43 | inputs.file("../../CMakeLists.txt") 44 | inputs.file("${buildDir}/cmake-build/CMakeCache.txt") 45 | inputs.files(fileTree(".").matching { 46 | include(listOf("**/*.c", "**/*.h")) 47 | }) 48 | inputs.files(fileTree("../../crt").matching { 49 | include(listOf("**/CMakeLists.txt", "**/*.c", "**/*.h")) 50 | }) 51 | outputs.file("${buildDir}/cmake-build/lib/libaws-crt-jni.so") 52 | outputs.upToDateWhen { false } //shared lib doesn't seem to get placed in jar without this 53 | 54 | var cmakeArgs = listOf( 55 | "--build", "${buildDir}/cmake-build", 56 | "--target", "all" 57 | ) 58 | 59 | doLast { 60 | val argsStr = cmakeArgs.joinToString(separator=" ") 61 | logger.info("cmake ${argsStr}") 62 | exec { 63 | executable("cmake") 64 | args(cmakeArgs) 65 | } 66 | } 67 | } 68 | 69 | tasks.assemble { 70 | dependsOn(cmakeBuild) 71 | } 72 | -------------------------------------------------------------------------------- /src/native/credentials.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | #ifndef AWS_JNI_CRT_CREDENTIALS_H 7 | #define AWS_JNI_CRT_CREDENTIALS_H 8 | 9 | #include 10 | 11 | struct aws_credentials; 12 | 13 | struct aws_credentials *aws_credentials_new_from_java_credentials(JNIEnv *env, jobject java_credentials); 14 | jobject aws_java_credentials_from_native_new(JNIEnv *env, const struct aws_credentials *credentials); 15 | 16 | #endif /* AWS_JNI_CRT_CREDENTIALS_H */ 17 | -------------------------------------------------------------------------------- /src/native/custom_key_op_handler.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | #ifndef AWS_JNI_CRT_CUSTOM_KEY_OP_HANDLER_H 6 | #define AWS_JNI_CRT_CUSTOM_KEY_OP_HANDLER_H 7 | 8 | #include "crt.h" 9 | #include 10 | 11 | struct aws_custom_key_op_handler *aws_custom_key_op_handler_java_new(JNIEnv *env, jobject jni_custom_key_op); 12 | 13 | void aws_custom_key_op_handler_java_release(struct aws_custom_key_op_handler *java_custom_key_op_handler); 14 | 15 | #endif /* AWS_JNI_CRT_CUSTOM_KEY_OP_HANDLER_H */ 16 | -------------------------------------------------------------------------------- /src/native/event_stream_message.h: -------------------------------------------------------------------------------- 1 | #ifndef CRT_EVENT_STREAM_MESSAGE_H 2 | #define CRT_EVENT_STREAM_MESSAGE_H 3 | /** 4 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 5 | * SPDX-License-Identifier: Apache-2.0. 6 | */ 7 | #include 8 | 9 | #include 10 | #include 11 | 12 | struct aws_event_stream_rpc_marshalled_message { 13 | struct aws_allocator *allocator; 14 | bool headers_init; 15 | struct aws_array_list headers_list; 16 | struct aws_byte_buf headers_buf; 17 | struct aws_byte_buf payload_buf; 18 | struct aws_byte_buf operation_buf; 19 | struct aws_event_stream_rpc_message_args message_args; 20 | }; 21 | 22 | int aws_event_stream_rpc_marshall_message_args_init( 23 | struct aws_event_stream_rpc_marshalled_message *message_args, 24 | struct aws_allocator *allocator, 25 | JNIEnv *env, 26 | jbyteArray headers, 27 | jbyteArray payload, 28 | jbyteArray operation, 29 | jint message_flags, 30 | jint message_type); 31 | 32 | void aws_event_stream_rpc_marshall_message_args_clean_up(struct aws_event_stream_rpc_marshalled_message *message_args); 33 | 34 | jbyteArray aws_event_stream_rpc_marshall_headers_to_byteArray( 35 | struct aws_allocator *allocator, 36 | JNIEnv *env, 37 | struct aws_event_stream_header_value_pair *pair, 38 | size_t length); 39 | 40 | #endif /* CRT_EVENT_STREAM_MESSAGE_H */ 41 | -------------------------------------------------------------------------------- /src/native/http_connection_manager.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | #ifndef AWS_JNI_CRT_HTTP_CONNECTION_MANAGER_H 7 | #define AWS_JNI_CRT_HTTP_CONNECTION_MANAGER_H 8 | 9 | #include 10 | 11 | struct aws_http_connection; 12 | struct aws_http_connection_manager; 13 | struct aws_http_proxy_options; 14 | struct aws_tls_connection_options; 15 | struct aws_tls_ctx; 16 | 17 | struct aws_http_connection_binding { 18 | JavaVM *jvm; 19 | jobject java_acquire_connection_future; 20 | struct aws_http_connection_manager *manager; 21 | struct aws_http_connection *connection; 22 | }; 23 | 24 | #endif /* AWS_JNI_CRT_HTTP_CONNECTION_MANAGER_H */ 25 | -------------------------------------------------------------------------------- /src/native/http_proxy_options.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | #ifndef AWS_JNI_CRT_HTTP_PROXY_OPTIONS_H 7 | #define AWS_JNI_CRT_HTTP_PROXY_OPTIONS_H 8 | 9 | #include 10 | 11 | struct aws_http_proxy_options; 12 | struct aws_tls_connection_options; 13 | struct aws_tls_ctx; 14 | 15 | void aws_http_proxy_options_jni_init( 16 | JNIEnv *env, 17 | struct aws_http_proxy_options *options, 18 | jint proxy_connection_type, 19 | struct aws_tls_connection_options *tls_options, 20 | jbyteArray proxy_host, 21 | jint proxy_port, 22 | jbyteArray proxy_authorization_username, 23 | jbyteArray proxy_authorization_password, 24 | int proxy_authorization_type, 25 | struct aws_tls_ctx *proxy_tls_ctx); 26 | 27 | void aws_http_proxy_options_jni_clean_up( 28 | JNIEnv *env, 29 | struct aws_http_proxy_options *options, 30 | jbyteArray proxy_host, 31 | jbyteArray proxy_authorization_username, 32 | jbyteArray proxy_authorization_password); 33 | 34 | #endif /* AWS_JNI_CRT_HTTP_PROXY_OPTIONS_H */ 35 | -------------------------------------------------------------------------------- /src/native/http_proxy_options_environment_variable.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | #include "crt.h" 7 | #include "java_class_ids.h" 8 | 9 | #include 10 | #include 11 | 12 | #include 13 | #include 14 | 15 | /* on 32-bit platforms, casting pointers to longs throws a warning we don't need */ 16 | #if UINTPTR_MAX == 0xffffffff 17 | # if defined(_MSC_VER) 18 | # pragma warning(push) 19 | # pragma warning(disable : 4305) /* 'type cast': truncation from 'jlong' to 'jni_tls_ctx_options *' */ 20 | # else 21 | # pragma GCC diagnostic push 22 | # pragma GCC diagnostic ignored "-Wpointer-to-int-cast" 23 | # pragma GCC diagnostic ignored "-Wint-to-pointer-cast" 24 | # endif 25 | #endif 26 | 27 | void aws_http_proxy_environment_variable_setting_jni_init( 28 | struct proxy_env_var_settings *options, 29 | jint environment_variable_proxy_connection_type, 30 | jint environment_variable_type, 31 | struct aws_tls_connection_options *proxy_tls_connection_options) { 32 | options->connection_type = environment_variable_proxy_connection_type; 33 | options->env_var_type = environment_variable_type; 34 | options->tls_options = proxy_tls_connection_options; 35 | } 36 | 37 | #if UINTPTR_MAX == 0xffffffff 38 | # if defined(_MSC_VER) 39 | # pragma warning(pop) 40 | # else 41 | # pragma GCC diagnostic pop 42 | # endif 43 | #endif 44 | -------------------------------------------------------------------------------- /src/native/http_proxy_options_environment_variable.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | #ifndef AWS_JNI_CRT_HTTP_PROXY_ENVIRONMENT_VARIABLE_SETTING_H 7 | #define AWS_JNI_CRT_HTTP_PROXY_ENVIRONMENT_VARIABLE_SETTING_H 8 | 9 | #include 10 | 11 | struct proxy_env_var_settings; 12 | struct aws_tls_connection_options; 13 | struct aws_tls_ctx; 14 | 15 | void aws_http_proxy_environment_variable_setting_jni_init( 16 | struct proxy_env_var_settings *options, 17 | jint environment_variable_proxy_connection_type, 18 | jint environment_variable_type, 19 | struct aws_tls_connection_options *proxy_tls_connection_options); 20 | 21 | #endif /* AWS_JNI_CRT_HTTP_PROXY_ENVIRONMENT_VARIABLE_SETTING_H */ 22 | -------------------------------------------------------------------------------- /src/native/http_request_response.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | #ifndef AWS_JNI_CRT_HTTP_REQUEST_RESPONSE_H 7 | #define AWS_JNI_CRT_HTTP_REQUEST_RESPONSE_H 8 | 9 | #include 10 | #include 11 | 12 | struct aws_http_message; 13 | struct aws_http_stream; 14 | struct aws_byte_buf; 15 | struct aws_atomic_var; 16 | 17 | struct http_stream_binding { 18 | JavaVM *jvm; 19 | 20 | // TEMP: Until Java API changes to match "H1B" native HTTP API, 21 | // create aws_http_message and aws_input_stream under the hood. 22 | struct aws_http_message *native_request; 23 | 24 | jobject java_http_response_stream_handler; 25 | jobject java_http_stream_base; 26 | struct aws_http_stream *native_stream; 27 | struct aws_byte_buf headers_buf; 28 | int response_status; 29 | /* For the native http stream and the Java stream object */ 30 | struct aws_atomic_var ref; 31 | }; 32 | 33 | jobject aws_java_http_stream_from_native_new(JNIEnv *env, void *opaque, int version); 34 | void aws_java_http_stream_from_native_delete(JNIEnv *env, jobject jHttpStream); 35 | 36 | void *aws_http_stream_binding_release(JNIEnv *env, struct http_stream_binding *binding); 37 | void *aws_http_stream_binding_acquire(struct http_stream_binding *binding); 38 | 39 | // If error occurs, A Java exception is thrown and NULL is returned. 40 | struct http_stream_binding *aws_http_stream_binding_new(JNIEnv *env, jobject java_callback_handler); 41 | 42 | /* Default callbacks using binding */ 43 | int aws_java_http_stream_on_incoming_headers_fn( 44 | struct aws_http_stream *stream, 45 | enum aws_http_header_block block_type, 46 | const struct aws_http_header *header_array, 47 | size_t num_headers, 48 | void *user_data); 49 | int aws_java_http_stream_on_incoming_header_block_done_fn( 50 | struct aws_http_stream *stream, 51 | enum aws_http_header_block block_type, 52 | void *user_data); 53 | int aws_java_http_stream_on_incoming_body_fn( 54 | struct aws_http_stream *stream, 55 | const struct aws_byte_cursor *data, 56 | void *user_data); 57 | void aws_java_http_stream_on_stream_complete_fn(struct aws_http_stream *stream, int error_code, void *user_data); 58 | void aws_java_http_stream_on_stream_destroy_fn(void *user_data); 59 | 60 | #endif /* AWS_JNI_CRT_HTTP_REQUEST_RESPONSE_H */ 61 | -------------------------------------------------------------------------------- /src/native/http_request_utils.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | #ifndef AWS_JNI_CRT_HTTP_REQUEST_UTILS_H 7 | #define AWS_JNI_CRT_HTTP_REQUEST_UTILS_H 8 | 9 | #include 10 | 11 | #include 12 | 13 | struct aws_allocator; 14 | struct aws_http_header; 15 | struct aws_http_headers; 16 | struct aws_http_message; 17 | struct aws_input_stream; 18 | 19 | struct aws_input_stream *aws_input_stream_new_from_java_http_request_body_stream( 20 | struct aws_allocator *allocator, 21 | JNIEnv *env, 22 | jobject http_request_body_stream); 23 | 24 | struct aws_http_message *aws_http_request_new_from_java_http_request( 25 | JNIEnv *env, 26 | jbyteArray marshalled_request, 27 | jobject jni_body_stream); 28 | 29 | struct aws_http_headers *aws_http_headers_new_from_java_http_headers(JNIEnv *env, jbyteArray marshalled_headers); 30 | 31 | int aws_marshal_http_headers_array_to_dynamic_buffer( 32 | struct aws_byte_buf *buf, 33 | const struct aws_http_header *header_array, 34 | size_t num_headers); 35 | 36 | int aws_marshal_http_headers_to_dynamic_buffer(struct aws_byte_buf *buf, const struct aws_http_headers *headers); 37 | 38 | /* if this fails a java exception has been set. */ 39 | int aws_apply_java_http_request_changes_to_native_request( 40 | JNIEnv *env, 41 | jbyteArray marshalled_request, 42 | jobject jni_body_stream, 43 | struct aws_http_message *message); 44 | 45 | /* if this fails a java exception has been set. */ 46 | jobject aws_java_http_request_from_native(JNIEnv *env, struct aws_http_message *message, jobject request_body_stream); 47 | 48 | #endif /* AWS_JNI_CRT_HTTP_REQUEST_UTILS_H */ 49 | -------------------------------------------------------------------------------- /src/native/jni.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | #include 6 | 7 | /* Tell the JNI loader that JNI 1.6 (JDK7) is required */ 8 | JNIEXPORT 9 | jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) { 10 | (void)vm; 11 | (void)reserved; 12 | return JNI_VERSION_1_6; 13 | } 14 | -------------------------------------------------------------------------------- /src/native/logging.h: -------------------------------------------------------------------------------- 1 | #ifndef AWS_JNI_LOGGING_H 2 | #define AWS_JNI_LOGGING_H 3 | 4 | /** 5 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 6 | * SPDX-License-Identifier: Apache-2.0. 7 | */ 8 | 9 | #include 10 | 11 | /******************************************************************************* 12 | * aws_jni_cleanup_logging - cleans up the native logger; invoked on atexit 13 | ******************************************************************************/ 14 | void aws_jni_cleanup_logging(void); 15 | 16 | #endif /* AWS_JNI_LOGGING_H */ 17 | -------------------------------------------------------------------------------- /src/native/mqtt5_client_jni.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | #ifndef AWS_JNI_CLIENT_H 6 | #define AWS_JNI_CLIENT_H 7 | 8 | #include 9 | 10 | #include 11 | 12 | struct aws_mqtt5_client; 13 | 14 | struct aws_mqtt5_client_java_jni { 15 | struct aws_mqtt5_client *client; 16 | jobject jni_client; 17 | JavaVM *jvm; 18 | 19 | struct aws_tls_connection_options tls_options; 20 | struct aws_tls_connection_options http_proxy_tls_options; 21 | 22 | jobject jni_publish_events; 23 | jobject jni_lifecycle_events; 24 | }; 25 | 26 | #endif /* AWS_JNI_CLIENT_H */ 27 | -------------------------------------------------------------------------------- /src/native/mqtt_client.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | #include 6 | 7 | #include 8 | 9 | #include "crt.h" 10 | #include "java_class_ids.h" 11 | 12 | /* on 32-bit platforms, casting pointers to longs throws a warning we don't need */ 13 | #if UINTPTR_MAX == 0xffffffff 14 | # if defined(_MSC_VER) 15 | # pragma warning(push) 16 | # pragma warning(disable : 4305) /* 'type cast': truncation from 'jlong' to 'jni_tls_ctx_options *' */ 17 | # else 18 | # pragma GCC diagnostic push 19 | # pragma GCC diagnostic ignored "-Wpointer-to-int-cast" 20 | # pragma GCC diagnostic ignored "-Wint-to-pointer-cast" 21 | # endif 22 | #endif 23 | 24 | JNIEXPORT jlong JNICALL 25 | Java_software_amazon_awssdk_crt_mqtt_MqttClient_mqttClientNew(JNIEnv *env, jclass jni_class, jlong jni_bootstrap) { 26 | (void)jni_class; 27 | aws_cache_jni_ids(env); 28 | 29 | struct aws_client_bootstrap *bootstrap = (struct aws_client_bootstrap *)jni_bootstrap; 30 | if (!bootstrap) { 31 | aws_jni_throw_runtime_exception(env, "Invalid ClientBootstrap"); 32 | return (jlong)NULL; 33 | } 34 | 35 | struct aws_allocator *allocator = aws_jni_get_allocator(); 36 | struct aws_mqtt_client *client = aws_mqtt_client_new(allocator, bootstrap); 37 | if (client == NULL) { 38 | aws_jni_throw_runtime_exception(env, "MqttClient.mqtt_client_init: aws_mqtt_client_new failed"); 39 | return (jlong)NULL; 40 | } 41 | 42 | return (jlong)client; 43 | } 44 | 45 | JNIEXPORT void JNICALL Java_software_amazon_awssdk_crt_mqtt_MqttClient_mqttClientDestroy( 46 | JNIEnv *env, 47 | jclass jni_class, 48 | jlong jni_mqtt_client) { 49 | (void)jni_class; 50 | aws_cache_jni_ids(env); 51 | 52 | struct aws_mqtt_client *client = (struct aws_mqtt_client *)jni_mqtt_client; 53 | if (!client) { 54 | aws_jni_throw_runtime_exception(env, "MqttClient.mqtt_client_destroy: Invalid/null client"); 55 | return; 56 | } 57 | 58 | aws_mqtt_client_release(client); 59 | } 60 | 61 | #if UINTPTR_MAX == 0xffffffff 62 | # if defined(_MSC_VER) 63 | # pragma warning(pop) 64 | # else 65 | # pragma GCC diagnostic pop 66 | # endif 67 | #endif 68 | -------------------------------------------------------------------------------- /src/native/mqtt_connection.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | #ifndef AWS_JAVA_CRT_MQTT_CONNECTION_H 6 | #define AWS_JAVA_CRT_MQTT_CONNECTION_H 7 | 8 | #include 9 | 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | struct aws_mqtt_client; 16 | struct aws_mqtt_client_connection; 17 | struct mqtt_jni_connection; 18 | 19 | /******************************************************************************* 20 | * mqtt_jni_async_callback - carries an AsyncCallback around as user data to mqtt 21 | * async ops, and is used to deliver callbacks. Also hangs on to JNI references 22 | * to buffers and strings that need to outlive the request 23 | ******************************************************************************/ 24 | struct mqtt_jni_async_callback { 25 | struct mqtt_jni_connection *connection; 26 | jobject async_callback; 27 | struct aws_byte_buf buffer; /* payloads or other pinned resources go in here, freed when callback is delivered */ 28 | }; 29 | 30 | /******************************************************************************* 31 | * mqtt_jni_connection - represents an aws_mqtt_client_connection to Java 32 | ******************************************************************************/ 33 | struct mqtt_jni_connection { 34 | struct aws_mqtt_client *client; /* Provided to mqtt_connect */ 35 | struct aws_mqtt_client_connection *client_connection; 36 | struct aws_socket_options socket_options; 37 | struct aws_tls_connection_options tls_options; 38 | 39 | JavaVM *jvm; 40 | jweak java_mqtt_connection; /* MqttClientConnection instance */ 41 | struct mqtt_jni_async_callback *on_message; 42 | 43 | struct aws_atomic_var ref_count; 44 | }; 45 | 46 | #endif /* AWS_JAVA_CRT_MQTT_CONNECTION_H */ 47 | -------------------------------------------------------------------------------- /src/native/process.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | #include 7 | #include 8 | 9 | #include "java_class_ids.h" 10 | 11 | JNIEXPORT 12 | jint JNICALL Java_software_amazon_awssdk_crt_Process_processGetPid(JNIEnv *env, jclass jni_crt_class) { 13 | (void)jni_crt_class; 14 | aws_cache_jni_ids(env); 15 | 16 | return (jint)aws_get_pid(); 17 | } 18 | 19 | JNIEXPORT 20 | jlong JNICALL 21 | Java_software_amazon_awssdk_crt_Process_processGetMaxIOHandlesSoftLimit(JNIEnv *env, jclass jni_crt_class) { 22 | (void)jni_crt_class; 23 | aws_cache_jni_ids(env); 24 | 25 | return (jlong)aws_get_soft_limit_io_handles(); 26 | } 27 | 28 | JNIEXPORT 29 | jlong JNICALL 30 | Java_software_amazon_awssdk_crt_Process_processGetMaxIOHandlesHardLimit(JNIEnv *env, jclass jni_crt_class) { 31 | (void)jni_crt_class; 32 | aws_cache_jni_ids(env); 33 | 34 | return (jlong)aws_get_hard_limit_io_handles(); 35 | } 36 | 37 | JNIEXPORT 38 | jboolean JNICALL Java_software_amazon_awssdk_crt_Process_processSetMaxIOHandlesSoftLimit( 39 | JNIEnv *env, 40 | jclass jni_crt_class, 41 | jlong max_handles) { 42 | (void)jni_crt_class; 43 | (void)max_handles; 44 | aws_cache_jni_ids(env); 45 | 46 | return aws_set_soft_limit_io_handles((size_t)max_handles) == AWS_OP_SUCCESS; 47 | } 48 | -------------------------------------------------------------------------------- /src/native/retry_utils.h: -------------------------------------------------------------------------------- 1 | #ifndef AWS_JNI_RETRY_UTILS_H 2 | #define AWS_JNI_RETRY_UTILS_H 3 | 4 | /** 5 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 6 | * SPDX-License-Identifier: Apache-2.0. 7 | */ 8 | 9 | #include 10 | 11 | struct aws_exponential_backoff_retry_options; 12 | struct aws_standard_retry_options; 13 | 14 | int aws_exponential_backoff_retry_options_from_java( 15 | JNIEnv *env, 16 | jobject jni_backoff_retry_options, 17 | struct aws_exponential_backoff_retry_options *backoff_retry_options); 18 | 19 | int aws_standard_retry_options_from_java( 20 | JNIEnv *env, 21 | jobject jni_standard_retry_options, 22 | struct aws_standard_retry_options *standard_retry_options); 23 | 24 | bool aws_exponential_backoff_retry_options_equals( 25 | const struct aws_exponential_backoff_retry_options *options, 26 | const struct aws_exponential_backoff_retry_options *expected_options); 27 | 28 | bool aws_standard_retry_options_equals( 29 | const struct aws_standard_retry_options *options, 30 | const struct aws_standard_retry_options *expected_options); 31 | 32 | #endif /* AWS_JNI_RETRY_STRATEGY_H */ 33 | -------------------------------------------------------------------------------- /src/native/system_info.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | #include 7 | 8 | #include 9 | 10 | #include "crt.h" 11 | #include "java_class_ids.h" 12 | 13 | JNIEXPORT 14 | jint JNICALL Java_software_amazon_awssdk_crt_SystemInfo_processorCount(JNIEnv *env, jclass cls) { 15 | (void)cls; 16 | aws_cache_jni_ids(env); 17 | 18 | return (jint)aws_system_info_processor_count(); 19 | } 20 | 21 | JNIEXPORT 22 | jshort JNICALL Java_software_amazon_awssdk_crt_SystemInfo_cpuGroupCount(JNIEnv *env, jclass cls) { 23 | (void)cls; 24 | aws_cache_jni_ids(env); 25 | 26 | return aws_get_cpu_group_count(); 27 | } 28 | 29 | JNIEXPORT 30 | jobjectArray JNICALL 31 | Java_software_amazon_awssdk_crt_SystemInfo_cpuInfoForGroup(JNIEnv *env, jclass cls, jshort groupIdx) { 32 | (void)cls; 33 | aws_cache_jni_ids(env); 34 | 35 | size_t cpu_count = aws_get_cpu_count_for_group(groupIdx); 36 | 37 | struct aws_cpu_info *cpu_info = aws_mem_calloc(aws_default_allocator(), cpu_count, sizeof(struct aws_cpu_info)); 38 | AWS_FATAL_ASSERT(cpu_info && "allocation failed in Java_software_amazon_awssdk_crt_SystemInfo_getCpuIdsForGroup"); 39 | 40 | aws_get_cpu_ids_for_group(groupIdx, cpu_info, cpu_count); 41 | 42 | jobjectArray cpu_info_array = 43 | (*env)->NewObjectArray(env, (jsize)cpu_count, cpu_info_properties.cpu_info_class, NULL); 44 | 45 | for (size_t i = 0; i < cpu_count; ++i) { 46 | jobject cpu_info_obj = (*env)->NewObject( 47 | env, 48 | cpu_info_properties.cpu_info_class, 49 | cpu_info_properties.cpu_info_constructor, 50 | cpu_info[i].cpu_id, 51 | cpu_info[i].suspected_hyper_thread); 52 | (*env)->SetObjectArrayElement(env, cpu_info_array, (jsize)i, cpu_info_obj); 53 | (*env)->DeleteLocalRef(env, cpu_info_obj); 54 | } 55 | 56 | aws_mem_release(aws_default_allocator(), cpu_info); 57 | 58 | return cpu_info_array; 59 | } 60 | -------------------------------------------------------------------------------- /src/native/tls_context_pkcs11_options.h: -------------------------------------------------------------------------------- 1 | #ifndef AWS_JNI_CRT_TLS_CONTEXT_PKCS11_OPTIONS_H 2 | #define AWS_JNI_CRT_TLS_CONTEXT_PKCS11_OPTIONS_H 3 | /** 4 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 5 | * SPDX-License-Identifier: Apache-2.0. 6 | */ 7 | 8 | #include 9 | 10 | struct aws_tls_ctx_pkcs11_options; 11 | 12 | /* Create a aws_tls_ctx_pkcs11_options from a TlsContextPkcs11Options java object. 13 | * All values are copied out of the Java object and stored in this allocation, 14 | * there's no need to keep the java object around. 15 | * This MUST be destroyed via aws_pkcs11_tls_options_from_java_destroy(). 16 | * Returns NULL and throws a java exception if something goes wrong. */ 17 | struct aws_tls_ctx_pkcs11_options *aws_tls_ctx_pkcs11_options_from_java_new(JNIEnv *env, jobject options_jni); 18 | 19 | void aws_tls_ctx_pkcs11_options_from_java_destroy(struct aws_tls_ctx_pkcs11_options *options); 20 | 21 | #endif /* AWS_JNI_CRT_TLS_CONTEXT_PKCS11_OPTIONS_H */ 22 | -------------------------------------------------------------------------------- /src/native/tls_ctx.c: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | #include 7 | 8 | #include 9 | #include 10 | 11 | #include "crt.h" 12 | #include "java_class_ids.h" 13 | 14 | /* on 32-bit platforms, casting pointers to longs throws a warning we don't need */ 15 | #if UINTPTR_MAX == 0xffffffff 16 | # if defined(_MSC_VER) 17 | # pragma warning(push) 18 | # pragma warning(disable : 4305) /* 'type cast': truncation from 'jlong' to 'jni_tls_ctx_options *' */ 19 | # else 20 | # pragma GCC diagnostic push 21 | # pragma GCC diagnostic ignored "-Wpointer-to-int-cast" 22 | # pragma GCC diagnostic ignored "-Wint-to-pointer-cast" 23 | # endif 24 | #endif 25 | 26 | JNIEXPORT 27 | jlong JNICALL 28 | Java_software_amazon_awssdk_crt_io_TlsContext_tlsContextNew(JNIEnv *env, jclass jni_class, jlong jni_options) { 29 | (void)jni_class; 30 | aws_cache_jni_ids(env); 31 | 32 | struct aws_tls_ctx_options *options = (struct aws_tls_ctx_options *)jni_options; 33 | if (!options) { 34 | aws_jni_throw_runtime_exception(env, "TlsContext.tls_ctx_new: Invalid TlsOptions"); 35 | return (jlong)NULL; 36 | } 37 | 38 | struct aws_allocator *allocator = aws_jni_get_allocator(); 39 | struct aws_tls_ctx *tls_ctx = aws_tls_client_ctx_new(allocator, options); 40 | if (!tls_ctx) { 41 | aws_jni_throw_runtime_exception(env, "TlsContext.tls_ctx_new: Failed to create new aws_tls_ctx"); 42 | return (jlong)NULL; 43 | } 44 | return (jlong)tls_ctx; 45 | } 46 | 47 | JNIEXPORT 48 | void JNICALL 49 | Java_software_amazon_awssdk_crt_io_TlsContext_tlsContextDestroy(JNIEnv *env, jclass jni_class, jlong jni_ctx) { 50 | (void)jni_class; 51 | aws_cache_jni_ids(env); 52 | 53 | struct aws_tls_ctx *tls_ctx = (struct aws_tls_ctx *)jni_ctx; 54 | if (!tls_ctx) { 55 | return; 56 | } 57 | 58 | aws_tls_ctx_release(tls_ctx); 59 | } 60 | 61 | #if UINTPTR_MAX == 0xffffffff 62 | # if defined(_MSC_VER) 63 | # pragma warning(pop) 64 | # else 65 | # pragma GCC diagnostic pop 66 | # endif 67 | #endif 68 | -------------------------------------------------------------------------------- /src/test/android/testapp/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | .gradle 3 | /local.properties -------------------------------------------------------------------------------- /src/test/android/testapp/gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx1536m 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | # AndroidX package structure to make it clearer which packages are bundled with the 15 | # Android operating system, and which are packaged with your app's APK 16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 17 | android.useAndroidX=true 18 | # Automatically convert third-party libraries to use AndroidX 19 | android.enableJetifier=true 20 | # Kotlin code style for this project: "official" or "obsolete": 21 | kotlin.code.style=official -------------------------------------------------------------------------------- /src/test/android/testapp/settings.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Necessary file for the testapp gradle project 3 | */ -------------------------------------------------------------------------------- /src/test/android/testapp/src/androidTest/assets/.gitignore: -------------------------------------------------------------------------------- 1 | *.txt 2 | *.pem -------------------------------------------------------------------------------- /src/test/android/testapp/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /src/test/android/testapp/src/main/assets/.gitignore: -------------------------------------------------------------------------------- 1 | *.txt 2 | *.pem -------------------------------------------------------------------------------- /src/test/android/testapp/src/main/java/software/amazon/awssdk/crttest/MainActivity.kt: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | package software.amazon.awssdk.crttest 7 | 8 | import androidx.appcompat.app.AppCompatActivity 9 | 10 | /* 11 | * The "TEST APP" is merely a shell that contains the aws-crt-java android library and is used by the 12 | * instrumentation test package to test against. There is nothing here. The assets folder will contain the 13 | * files generated in GitHub CI for testing and the res folder contains the bare essentials for an android app. 14 | */ 15 | 16 | class MainActivity : AppCompatActivity() { 17 | } 18 | -------------------------------------------------------------------------------- /src/test/android/testapp/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | 15 | 18 | 21 | 22 | 23 | 24 | 30 | -------------------------------------------------------------------------------- /src/test/android/testapp/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 21 | 22 | 40 | 41 | -------------------------------------------------------------------------------- /src/test/android/testapp/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /src/test/android/testapp/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /src/test/android/testapp/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awslabs/aws-crt-java/479239ddb6bae42530f929e9da6fe566a28e7964/src/test/android/testapp/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /src/test/android/testapp/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awslabs/aws-crt-java/479239ddb6bae42530f929e9da6fe566a28e7964/src/test/android/testapp/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /src/test/android/testapp/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awslabs/aws-crt-java/479239ddb6bae42530f929e9da6fe566a28e7964/src/test/android/testapp/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /src/test/android/testapp/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awslabs/aws-crt-java/479239ddb6bae42530f929e9da6fe566a28e7964/src/test/android/testapp/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /src/test/android/testapp/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awslabs/aws-crt-java/479239ddb6bae42530f929e9da6fe566a28e7964/src/test/android/testapp/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /src/test/android/testapp/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awslabs/aws-crt-java/479239ddb6bae42530f929e9da6fe566a28e7964/src/test/android/testapp/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /src/test/android/testapp/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awslabs/aws-crt-java/479239ddb6bae42530f929e9da6fe566a28e7964/src/test/android/testapp/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /src/test/android/testapp/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awslabs/aws-crt-java/479239ddb6bae42530f929e9da6fe566a28e7964/src/test/android/testapp/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /src/test/android/testapp/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awslabs/aws-crt-java/479239ddb6bae42530f929e9da6fe566a28e7964/src/test/android/testapp/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /src/test/android/testapp/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awslabs/aws-crt-java/479239ddb6bae42530f929e9da6fe566a28e7964/src/test/android/testapp/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /src/test/android/testapp/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #6200EE 4 | #3700B3 5 | #03DAC5 6 | 7 | -------------------------------------------------------------------------------- /src/test/android/testapp/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | CRTAndroidTest 3 | 4 | -------------------------------------------------------------------------------- /src/test/android/testapp/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /src/test/java/software/amazon/awssdk/crt/test/ClientBootstrapTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | package software.amazon.awssdk.crt.test; 7 | 8 | import org.junit.Test; 9 | import software.amazon.awssdk.crt.CrtResource; 10 | import software.amazon.awssdk.crt.CrtRuntimeException; 11 | import software.amazon.awssdk.crt.io.ClientBootstrap; 12 | import software.amazon.awssdk.crt.io.EventLoopGroup; 13 | import software.amazon.awssdk.crt.io.HostResolver; 14 | 15 | import java.util.concurrent.ExecutionException; 16 | 17 | import static org.junit.Assert.*; 18 | 19 | public class ClientBootstrapTest extends CrtTestFixture { 20 | public ClientBootstrapTest() {} 21 | 22 | @Test 23 | public void testCreateDestroy() throws ExecutionException, InterruptedException { 24 | EventLoopGroup elg = new EventLoopGroup(1); 25 | HostResolver hostResolver = new HostResolver(elg); 26 | ClientBootstrap bootstrap = new ClientBootstrap(elg, hostResolver); 27 | 28 | assertNotNull(bootstrap); 29 | bootstrap.close(); 30 | bootstrap.getShutdownCompleteFuture().get(); 31 | hostResolver.close(); 32 | elg.close(); 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /src/test/java/software/amazon/awssdk/crt/test/CrtTestContext.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | package software.amazon.awssdk.crt.test; 7 | 8 | // Encapsulates any platform-specific configuration for tests 9 | // TODO remove this. We are going to be using System Properties for tests 10 | public class CrtTestContext { 11 | // Trust store PEM blob 12 | public byte[] trustStore = null; 13 | // IoT Thing certificate for testing 14 | public byte[] iotClientCertificate = null; 15 | // IoT Thing private key for testing 16 | public byte[] iotClientPrivateKey = null; 17 | // IoT Thing ecc certificate for testing 18 | public byte[] iotClientECCCertificate = null; 19 | // IoT Thing ecc private key for testing 20 | public byte[] iotClientECCPrivateKey = null; 21 | // IoT ATS endpoint for testing 22 | public String iotEndpoint = null; 23 | // IoT CA Root 24 | public byte[] iotCARoot = null; 25 | } 26 | -------------------------------------------------------------------------------- /src/test/java/software/amazon/awssdk/crt/test/EccKeyPairTest.java: -------------------------------------------------------------------------------- 1 | package software.amazon.awssdk.crt.test; 2 | 3 | import org.junit.Test; 4 | import software.amazon.awssdk.crt.auth.credentials.Credentials; 5 | import software.amazon.awssdk.crt.cal.EccKeyPair; 6 | 7 | import static org.junit.Assert.assertNotNull; 8 | import static org.junit.Assert.assertTrue; 9 | 10 | public class EccKeyPairTest extends CrtTestFixture { 11 | public EccKeyPairTest() {} 12 | 13 | private static byte[] TEST_ACCESS_KEY_ID = "AKISORANDOMAASORANDOM".getBytes(); 14 | private static byte[] TEST_SECRET_ACCESS_KEY = "q+jcrXGc+0zWN6uzclKVhvMmUsIfRPa4rlRandom".getBytes(); 15 | 16 | static Credentials credentials = new Credentials(TEST_ACCESS_KEY_ID, TEST_SECRET_ACCESS_KEY, null); 17 | 18 | @Test 19 | public void testCreateDestroy() { 20 | try (EccKeyPair keyPair = EccKeyPair.newDeriveFromCredentials(credentials, EccKeyPair.AwsEccCurve.AWS_ECDSA_P256)) { 21 | assertNotNull(keyPair); 22 | } 23 | } 24 | 25 | @Test 26 | public void testSignMessage() { 27 | try (EccKeyPair keyPair = EccKeyPair.newDeriveFromCredentials(credentials, EccKeyPair.AwsEccCurve.AWS_ECDSA_P256)) { 28 | byte[] signatureBytes = keyPair.signMessage("".getBytes()); 29 | assertTrue(signatureBytes.length > 0); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/test/java/software/amazon/awssdk/crt/test/EventLoopGroupTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | package software.amazon.awssdk.crt.test; 7 | 8 | import org.junit.Test; 9 | import static org.junit.Assert.assertNotNull; 10 | import static org.junit.Assert.assertTrue; 11 | import static org.junit.Assert.fail; 12 | import software.amazon.awssdk.crt.*; 13 | import software.amazon.awssdk.crt.io.EventLoopGroup; 14 | 15 | public class EventLoopGroupTest extends CrtTestFixture { 16 | public EventLoopGroupTest() {} 17 | 18 | @Test 19 | public void testCreateDestroy() { 20 | try (EventLoopGroup elg = new EventLoopGroup(1)) { 21 | assertNotNull(elg); 22 | assertTrue(!elg.isNull()); 23 | } catch (CrtRuntimeException ex) { 24 | fail(ex.getMessage()); 25 | } 26 | } 27 | 28 | @Test 29 | public void testCreateDestroyWithCpuGroup() { 30 | try (EventLoopGroup elg = new EventLoopGroup(0,2)) { 31 | assertNotNull(elg); 32 | assertTrue(!elg.isNull()); 33 | } catch (CrtRuntimeException ex) { 34 | fail(ex.getMessage()); 35 | } 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /src/test/java/software/amazon/awssdk/crt/test/FailFastListener.java: -------------------------------------------------------------------------------- 1 | package software.amazon.awssdk.crt.test; 2 | 3 | import org.junit.runner.notification.Failure; 4 | import org.junit.runner.notification.RunListener; 5 | 6 | public class FailFastListener extends RunListener { 7 | public void testFailure(Failure failure) throws Exception { 8 | System.err.println("FAILURE: " + failure); 9 | System.exit(-1); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/test/java/software/amazon/awssdk/crt/test/InitTest.java: -------------------------------------------------------------------------------- 1 | package software.amazon.awssdk.crt.test; 2 | 3 | import org.junit.Test; 4 | 5 | /* 6 | This test exercises a case that used to deadlock the CRT. To properly exercise init, the test must be run by 7 | itself; a successful run when other tests have run doesn't mean anything. 8 | 9 | For CI, we explicitly run this test by itself as part of `.builder/actions/aws_crt_java_test.py` 10 | */ 11 | public class InitTest { 12 | 13 | @Test 14 | public void testConcurrentInitForDeadlock() { 15 | 16 | for (int i = 0; i < 100; i++) { 17 | try { 18 | new Thread(() -> { 19 | try { 20 | Class.forName("software.amazon.awssdk.crt.CRT"); 21 | } catch (ClassNotFoundException e) { 22 | throw new RuntimeException(e); 23 | } 24 | }).start(); 25 | Class.forName("software.amazon.awssdk.crt.CrtResource"); 26 | } catch (Exception e) { 27 | throw new RuntimeException(e); 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/test/java/software/amazon/awssdk/crt/test/JniExceptionTest.java: -------------------------------------------------------------------------------- 1 | package software.amazon.awssdk.crt.test; 2 | 3 | import org.junit.Test; 4 | import software.amazon.awssdk.crt.CRT; 5 | 6 | public class JniExceptionTest extends CrtTestFixture { 7 | public JniExceptionTest() {} 8 | 9 | @Test(expected = RuntimeException.class) 10 | public void testExceptionCheck() { 11 | CRT.checkJniExceptionContract(false); 12 | } 13 | 14 | @Test 15 | public void testExceptionClear() { 16 | CRT.checkJniExceptionContract(true); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/test/java/software/amazon/awssdk/crt/test/PackageInfoTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | package software.amazon.awssdk.crt.test; 7 | 8 | import org.junit.Test; 9 | import org.junit.Assert; 10 | import software.amazon.awssdk.crt.utils.PackageInfo; 11 | 12 | public class PackageInfoTest extends CrtTestFixture { 13 | public PackageInfoTest() {} 14 | 15 | @Test 16 | public void testPackageInfo() { 17 | PackageInfo pkgInfo = new PackageInfo(); 18 | Assert.assertNotEquals("UNKNOWN", pkgInfo.version.toString()); 19 | Assert.assertEquals(0, pkgInfo.version.major); 20 | Assert.assertEquals(0, pkgInfo.version.minor); 21 | Assert.assertEquals(0, pkgInfo.version.patch); 22 | Assert.assertEquals("UNITTEST", pkgInfo.version.tag); 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /src/test/java/software/amazon/awssdk/crt/test/ProcessTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | package software.amazon.awssdk.crt.test; 7 | 8 | import org.junit.Test; 9 | 10 | import static org.junit.Assert.assertEquals; 11 | import static org.junit.Assert.assertTrue; 12 | 13 | import software.amazon.awssdk.crt.CrtRuntimeException; 14 | import software.amazon.awssdk.crt.Process; 15 | 16 | public class ProcessTest extends CrtTestFixture { 17 | public ProcessTest() {} 18 | 19 | @Test 20 | public void testGetPid() { 21 | int pid = Process.getPid(); 22 | assertTrue(pid > 0); 23 | } 24 | 25 | @Test 26 | public void testGetIOHandleLimits() { 27 | long softLimit = Process.getMaxIOHandlesSoftLimit(); 28 | long hardLimit = Process.getMaxIOHandlesHardLimit(); 29 | 30 | assertTrue(softLimit > 0); 31 | assertTrue(hardLimit >= softLimit); 32 | } 33 | 34 | @Test 35 | public void testSetSoftIOHandleLimits() { 36 | long softLimit = Process.getMaxIOHandlesSoftLimit(); 37 | long hardLimit = Process.getMaxIOHandlesHardLimit(); 38 | 39 | assertTrue(softLimit > 0); 40 | assertTrue(hardLimit >= softLimit); 41 | 42 | try { 43 | Process.setMaxIOHandlesSoftLimit(softLimit - 1); 44 | } catch (CrtRuntimeException ex) { 45 | // make sure it's the not-implemented exception if it was thrown. 46 | assertEquals("AWS_ERROR_UNIMPLEMENTED", ex.errorName); 47 | } 48 | } 49 | }; 50 | -------------------------------------------------------------------------------- /src/test/java/software/amazon/awssdk/crt/test/ServerBootstrapTest.java: -------------------------------------------------------------------------------- 1 | package software.amazon.awssdk.crt.test; 2 | 3 | import org.junit.Test; 4 | import software.amazon.awssdk.crt.io.EventLoopGroup; 5 | import software.amazon.awssdk.crt.io.ServerBootstrap; 6 | 7 | import java.util.concurrent.ExecutionException; 8 | 9 | import static org.junit.Assert.assertNotNull; 10 | 11 | public class ServerBootstrapTest extends CrtTestFixture { 12 | public ServerBootstrapTest() {} 13 | 14 | @Test 15 | public void testCreateDestroy() throws ExecutionException, InterruptedException { 16 | EventLoopGroup elg = new EventLoopGroup(1); 17 | ServerBootstrap bootstrap = new ServerBootstrap(elg); 18 | 19 | assertNotNull(bootstrap); 20 | bootstrap.close(); 21 | elg.close(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/test/java/software/amazon/awssdk/crt/test/SystemInfoTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | * SPDX-License-Identifier: Apache-2.0. 4 | */ 5 | 6 | package software.amazon.awssdk.crt.test; 7 | 8 | import org.junit.Test; 9 | 10 | import software.amazon.awssdk.crt.*; 11 | 12 | import static org.junit.Assert.*; 13 | 14 | import org.junit.Assume; 15 | 16 | public class SystemInfoTest extends CrtTestFixture { 17 | public SystemInfoTest() { } 18 | 19 | @Test 20 | public void testCpuIteration() { 21 | int processorCount = SystemInfo.getProcessorCount(); 22 | assertNotEquals(0, processorCount); 23 | 24 | short cpuGroupCount = SystemInfo.getCpuGroupCount(); 25 | assertNotEquals(0, cpuGroupCount); 26 | 27 | int iteratedCpuCount = 0; 28 | for (short i = 0; i < cpuGroupCount; ++i) { 29 | SystemInfo.CpuInfo[] cpus = SystemInfo.getCpuInfoForGroup(i); 30 | assertNotNull(cpus); 31 | assertNotEquals(0, cpus.length); 32 | 33 | for (SystemInfo.CpuInfo cpuInfo : cpus) { 34 | iteratedCpuCount++; 35 | System.out.println(String.format("Found Cpu %d in group %d. Suspected hyper-thread? %s", cpuInfo.cpuId, i, cpuInfo.isSuspectedHyperThread ? "yes" : "no")); 36 | } 37 | } 38 | 39 | assertEquals(processorCount, iteratedCpuCount); 40 | } 41 | 42 | @Test 43 | public void testIsFIPS() { 44 | Assume.assumeTrue(System.getenv("CRT_FIPS") != null); 45 | assertTrue(CRT.isFIPS()); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /utils/Canary/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 4.0.0 6 | 7 | canary.mqtt5 8 | mqtt5 9 | 1.0.0-SNAPSHOT 10 | 11 | 12 | UTF-8 13 | 1.8 14 | 1.8 15 | 16 | 17 | 18 | 19 | software.amazon.awssdk.crt 20 | aws-crt 21 | 1.0.0-SNAPSHOT 22 | 23 | 24 | 25 | 26 | --------------------------------------------------------------------------------